import numba
import numpy as np
import scipy.sparse as sps
import scipy.sparse.linalg as spsl
import scipy.special as spec

import warnings

from quantum_systems import BasisSet

from quantum_systems.quantum_dots.one_dim.one_dim_qd import _shielded_coulomb
from quantum_systems.quantum_dots.one_dim.one_dim_potentials import (
    HOPotential,
    DWPotential,
    DWPotentialSmooth,
    SymmetricDWPotential,
    AsymmetricDWPotential,
    GaussianPotential,
    AtomicPotential,
)

class ODSincDVR(BasisSet):
    """Create matrix elements and grid representation of sinc-dvr basis
    functions, to exploit sparsity in coulomb operator

    Parameters
    ----------
    l : int
        Number of sinc-dvr functions
    grid_length : int or float
        Space over which to model wavefunction
    a : float, default 0.25
        Screening parameter in the shielded Coulomb interation.
    alpha : float, default 1.0
        Strength parameter in the shielded Coulomb interaction.
    beta : float, default 0.0
        Strength parameter of the non-dipole term in the laser interaction matrix.
    """

    HOPotential = HOPotential
    DWPotential = DWPotential
    DWPotentialSmooth = DWPotentialSmooth
    SymmetricDWPotential = SymmetricDWPotential
    AsymmetricDWPotential = AsymmetricDWPotential
    GaussianPotential = GaussianPotential
    AtomicPotential = AtomicPotential

    def __init__(
        self,
        l,
        grid_length,
        a=0.25,
        alpha=1.0,
        beta=0,
        potential=None,
        u_repr="2d",
        **kwargs,
    ):
        # for backwards compatibility:
        # u_repr = "sparse" if kwargs.pop("sparse_u", False) else u_repr

        if u_repr not in ("2d", "4d"):
            raise ValueError("Invalid u_repr value: '{}'".format(u_repr))

        super().__init__(l, dim=1, **kwargs)

        self.alpha = alpha
        self.a = a
        self.beta = beta

        self.grid_length = grid_length

        self.grid = np.linspace(-self.grid_length, self.grid_length, self.l)
        self.num_grid_points = self.l

        if potential is None:
            omega = (
                0.25  # Default frequency corresponding to Zanghellini article
            )
            potential = HOPotential(omega)

        self.potential = potential

        self.setup_basis(u_repr)

    @property
    def sparse_repr(self):
        return self.u_repr == "2d"

    @property
    def u_repr(self):
        if np.ndim(self.u) == 2:
            return "2d"
        if np.ndim(self.u) == 4:
            return "4d"
        return "unknown"

    def setup_basis(self, u_repr):
        self.dx = self.grid[1] - self.grid[0]

        self.h = np.zeros((self.l, self.l), dtype=np.complex128)

        # create multi_dim index for speedy calculations
        ind = np.arange(self.l)
        diff_grid = ind[:, None] - ind

        # mask diagonal to edit offdiagonal elements
        mask = np.ones(self.h.shape, dtype=bool)
        np.fill_diagonal(mask, 0)
        self.h[mask] = (-1.0) ** diff_grid[mask] / (
            self.dx**2 * diff_grid[mask] ** 2
        )
        # fill diagonal
        self.h[ind, ind] = np.pi**2 / (6 * self.dx**2)
        self.h[ind, ind] += self.potential(self.grid)

        self.s = self.construct_s()
        self.spf = self.construct_sinc_grid()

        self.u = self.construct_coulomb_elements(u_repr)

        self.construct_position_integrals()
        self.cast_to_complex()

    def set_u_repr(self, new_repr):
        """Switches representation of coloumb matrix elements between 2d and 4d"""
        coords0 = np.arange(self.l**2) % self.l
        coords1 = np.arange(self.l**2) // self.l

        if new_repr == self.u_repr:
            print("u repr is already {}, doing nothing".format(new_repr))
        elif new_repr == "4d":
            new_u = np.zeros(
                (self.l, self.l, self.l, self.l), dtype=self.u.dtype
            )
            new_u[coords0, coords1, coords0, coords1] = self.u[coords0, coords1]
        elif new_repr == "2d":
            new_u = np.zeros((self.l, self.l), dtype=self.u.dtype)
            new_u[coords0, coords1] = self.u[coords0, coords1, coords0, coords1]
        else:
            raise ValueError(
                "'{}' is not a valid representation".format(new_repr)
            )

    def construct_sinc_grid(self):
        x = self.grid
        return 1 / np.sqrt(self.dx) * np.sinc((x - x[:, None]) / self.dx)

    def construct_position_integrals(self):
        self.position = np.zeros((1, self.l, self.l), dtype=self.spf.dtype)
        self.position[0] = np.diag(self.grid + self.beta * self.grid**2)

    def construct_coulomb_elements(self, u_repr="4d"):
        """Computes Sinc-DVR matrix elements of onebody operator h and two-body
        operator u."""
        x = self.grid

        coords = []
        data = []
        for p in range(self.l):
            for q in range(self.l):
                data.append(_shielded_coulomb(x[p], x[q], self.alpha, self.a))
                coords.append((p, q))
        coords = np.array(coords).T
        data = np.array(data)

        if u_repr == "2d":
            self.u = np.zeros((self.l, self.l))
            self.u[coords[0], coords[1]] = data
        else:
            self.u = np.zeros((self.l, self.l, self.l, self.l))
            self.u[coords[0], coords[1], coords[0], coords[1]] = data
        return self.u

    def construct_s(self):
        return np.eye(self.l)

    def change_to_general_orbital_basis(self, anti_symmetrize=True):
        if anti_symmetrize and self.u_repr == "2d":
            if self.l > 100:
                warnings.warn(
                    "Warning, l large. Change to gos with anti_symmetrize=True forces 4d u."
                )

            self.set_u_repr("4d")
        return super().change_to_general_orbital_basis(
            anti_symmetrize=anti_symmetrize
        )

    def change_module(self, np):
        if self.sparse_repr:
            self.np = np
            warnings.warn(
                "change_module not implemented for sparse u, doing nothing"
            )
        else:
            return super().change_module(np)

    @staticmethod
    def add_spin_two_body(u, np):
        """Class method overwriting the static method of BasisSet."""
        if np.ndim(u) == 2:
            # spin symmetry is equal to dvr symmetry, meaning that the total matrix of
            # spatial and spin elements is doubled with every element kept
            return np.kron(u, np.ones((2, 2)))
        else:
            return super(ODSincDVR, ODSincDVR).add_spin_two_body(u, np)

    @staticmethod
    def anti_symmetrize_u(_u):
        if len(np.shape(_u)) == 2:
            return _u  # _u.transpose((0, 1))[:,::-1]
        else:
            return super(ODSincDVR, ODSincDVR).anti_symmetrize_u(_u)

    def transform_two_body_elements(
        self, u, C, np, anti_symmetrize=False, C_tilde=None
    ):
        """Class method overwriting the static method of BasisSet. Returns a 4d
        u_prime in numpy format, and allows for direct antisymmetrization of transformed
        elements, to compensate for lack of antisymmetrization in 2d representation of u.
        """
        if self.u_repr == "2d":
            if C_tilde is None:
                C_tilde = C.conj().T
            # get the 2d matrix of nonzero values
            if self.u_repr == "2d":
                _u = u
            else:
                _u = np.zeros(u.shape[:2])
                _u[u.coords[0], u.coords[1]] = u.data
            u_prime = np.einsum(
                "bs,ar,qb,pa,ab->pqrs",
                C,
                C,
                C_tilde,
                C_tilde,
                _u,
                optimize=True,
            )
            if anti_symmetrize:
                u_prime -= np.einsum(
                    "br,as,qb,pa,ab->pqrs",
                    C,
                    C,
                    C_tilde,
                    C_tilde,
                    _u,
                    optimize=True,
                )
            return u_prime
        else:
            assert (
                not anti_symmetrize
            ), "antisymmetrize only valid for sparse storage of u"
            # call static method of superclass
            return super(ODSincDVR, ODSincDVR).transform_two_body_elements(
                u, C, np, C_tilde
            )

    def change_basis(self, *args, **kwargs):
        super().change_basis(*args, **kwargs)


import requests
from bs4 import BeautifulSoup
from flask import Flask, render_template, request, redirect, url_for
import time
import random

app = Flask(__name__, template_folder=r"C:\Users\adamk\gitpractice\practice\wiki")

def wiki_article(article):
    # get wikipage of a specific article
    url = 'https://en.wikipedia.org/wiki/' + article
    webpage_response = requests.get(url)
    webpage = webpage_response.content
    soup = BeautifulSoup(webpage, "html.parser")
    return soup, url

def get_first_img_src(soup):
    # get first SIGNIFICANT image with width bigger than 50
    for n in range(5):
        img = soup.find_all("img")[n]
        img_width = img.get('width')
        if int(img_width) > 50:
            img_src = img.get('src')
            return img_src
    # no big img found, return first
    img_src = soup.img.get('src')
    return img_src

def get_categories(soup):
    # get soup categories
    try:
        categories_data = soup.select('.mw-normal-catlinks > ul')[0]
    except IndexError:
        return ["No tags available"]
    categories = (categories_data.get_text('|')).split('|')
    return categories

def related_to_categories(subject, categories):
    subject = subject.lower()
    for category in categories:
        if subject in category.lower():
            return True
    return False

def get_head(soup):
    # get heading
    return soup.select("#firstHeading")[0].string

def get_paragraph_text(soup):
    # get first SIGNIFICANT paragraph (longer than 20)
    n = 0
    p = soup.select('.mw-parser-output > p')[n]
    p_text = p.get_text()
    while len(p_text) < 20:
        n += 1
        p = soup.select('.mw-parser-output > p')[n]
        p_text = p.get_text()
    return p_text

def rand_article():
    rand_url = "https://en.wikipedia.org/wiki/Special:Random"
    webpage_response = requests.get(rand_url)
    webpage = webpage_response.content
    soup = BeautifulSoup(webpage, "html.parser")
    return soup

def rand_article_by_category(subject):
    rand_url = "https://en.wikipedia.org/wiki/Special:RandomInCategory/" + subject.replace(" ", "_")
    print("rand url: ", rand_url)
    webpage_response = requests.get(rand_url)
    webpage = webpage_response.content
    soup = BeautifulSoup(webpage, "html.parser")
    return soup

def generate_url_by_head(head):
    url = 'https://en.wikipedia.org/wiki/' + head.replace(" ", "_")
    return url

def get_sub_pages(soup):
    pages = soup.select(".mw-category-group > ul > li > a")
    return pages

def rand_inner_page(soup):
    pages = get_sub_pages(soup)
    try:
        ran_page = random.choice(pages)
    except IndexError:
        raise NameError("Category has no subpages")
    page_url = ran_page['href']
    article = "https://en.wikipedia.org" + page_url
    return wiki_article(article)

def is_category(head):
    if head == "Random page in category":
        raise NameError('No such category')
    elif "Category:" in head:
        return True
    return False

@app.route("/", methods=["POST", "GET"])
def random_page():
    subject = request.form.get("subject")
    t0 = time.perf_counter()
    if subject is None:
        return render_template("index.html")
    else:
        soup = rand_article_by_category(subject)
        head = get_head(soup)
        print("First head: " ,head)
        if is_category(head):
            #entered a sub category
            soup, wiki_url = rand_inner_page(soup)
            print("wiki url: ", wiki_url)
        else:
            wiki_url = generate_url_by_head(head)
            print("else wikiurl: ", wiki_url)

        categories = get_categories(soup)
        img_src = get_first_img_src(soup)
        text = get_paragraph_text(soup)
        t1 = time.perf_counter()
        elapsed_time = round(t1-t0, 2)
        return render_template("index.html", head=head, img_src=img_src,
                               categories=categories, text=text,
                               wiki_url=wiki_url, elapsed_time=elapsed_time)

@app.route("/<string:article>", methods=["POST", "GET"])
def index(article):
    soup, wiki_url = wiki_article(article)
    head = get_head(soup)
    img_src = get_first_img_src(soup)
    text = get_paragraph_text(soup)
    categories = get_categories(soup)
    return render_template("index.html", head=head, img_src=img_src,
                           categories=categories, text=text, wiki_url=wiki_url)

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

'''
webpage_response = requests.get("https://en.wikipedia.org/wiki/Category:Economic_history")
webpage = webpage_response.content
soup = BeautifulSoup(webpage, "html.parser")
#print(get_head(soup))
#print(get_paragraph_text(soup))
#print(get_categories(soup))

def get_sub_categories(soup):
    sub_categories = soup.select(".CategoryTreeItem > a")
    return sub_categories

def page_or_sub_category(soup):
    pages = get_sub_pages(soup)
    sub_categories = get_sub_categories(soup)
    if random.randint(0,1) == 0:
        #50% precent chance
        chosen_articles = pages
    else:
        chosen_sub_category = random.choice(sub_categories)
        sub_category_url = "https://en.wikipedia.org" + chosen_sub_category.['href']
        webpage_response = requests.get(sub_category_url)
        webpage = webpage_response.content
        sub_soup = BeautifulSoup(webpage, "html.parser")
        chosen_articles = get_sub_pages(sub_soup)
'''


#! /usr/bin/python3
from itertools import product
import ipaddress
from bitstring import BitArray
from collections import Counter
import iota.harness.api as api
import iota.test.iris.utils.iperf as iperf
import iota.test.utils.naples_host as host
import iota.test.iris.config.workload.api as wl_api
import pdb
import iota.harness.infra.utils.toeplitz as toeplitz
from iota.harness.infra.utils.toeplitz import *

def generate_flows(tc, num_flows, num_queues):
    queue_used = Counter()
    port_used = set()
    hash_mask = (1 << 7) - 1

    for q in range(num_queues):
        queue_used[q] = 0

    for server_port, client_port in product(range(10000, 19999), range(20000, 29999)):

        if server_port in port_used or client_port in port_used:
            continue

        hdr = (tc.server_ip,tc.client_ip, server_port, client_port)
        flow_hash = toeplitz.toeplitz_hash(toeplitz.toeplitz_input(*hdr, rss_type_num=tc.rss_enum),
                                          BitArray(bytes=toeplitz.toeplitz_symmetric_key))

        queue = (flow_hash & hash_mask) % num_queues
        if queue_used[queue] != num_flows:
            queue_used[queue] += 1
            yield (queue, server_port, client_port)

        port_used.add(client_port)
        port_used.add(server_port)

        if all(queue_used[q] == num_flows for q in queue_used):
            return api.types.status.SUCCESS

    else:
        api.Logger.info(f"Queue used: {queue_used}")
        api.Logger.error("Not enough combinations to generate all flows!")
        return api.types.status.FAILURE

def send_iperf_cmd(tc, client_port, server_port, test_packet_count):
    """
    send iperf to the receiving node
    use specific client/server ports to sensure packets land in the desired queue
    """
    serverReq = None
    clientReq = None

    serverReq = api.Trigger_CreateExecuteCommandsRequest(serial=False)
    clientReq = api.Trigger_CreateExecuteCommandsRequest(serial=False)

    cmd_descr = f"Server: [({tc.server.workload_name})({tc.server_ip})] <--> Client: [({tc.client.workload_name})({tc.client_ip})]"
    tc.cmd_descr.append(cmd_descr)

    server_cmd = None
    client_cmd = None

    server_cmd = iperf.ServerCmd(server_port)
    client_cmd = iperf.ClientCmd(tc.server_ip, server_port, time=10, proto=tc.proto, jsonOut=True,
                                ipproto=tc.tc_ip_proto, num_of_streams=tc.num_sessions,
                                client_ip=tc.client_ip, client_port=client_port, packet_count=test_packet_count,
                                bandwidth='10m')

    tc.server_cmds.append(server_cmd)
    tc.client_cmds.append(client_cmd)
    api.Logger.info(f"Iperf:  Server [{tc.server.node_name}.{tc.server.interface}]")
    api.Logger.info(f"        Client [{tc.client.node_name}.{tc.client.interface}]")

    api.Trigger_AddCommand(serverReq, tc.server.node_name, tc.server.workload_name,
                           server_cmd, background=True)

    api.Trigger_AddCommand(clientReq, tc.client.node_name, tc.client.workload_name,
                           client_cmd)

    server_resp = api.Trigger(serverReq)
    #Sleep for some time as bg may not have been started.
    time.sleep(10)

    tc.iperf_client_resp = api.Trigger(clientReq)
    api.Trigger_TerminateAllCommands(server_resp)

    return api.types.status.SUCCESS

def trigger_iperf(tc, num_queues):
    num_flows = 1
    test_packet_count = 10000
    queue = []
    tc.server_cmds = []
    tc.client_cmds = []
    tc.cmd_descr = []
    tc.failed_queues = []

    # get the client and server port numbers, based on hash and ip addr.
    for queue, server_port, client_port in generate_flows(tc, num_flows, num_queues):
        api.Logger.info(f"------- RSS for: queue ---> {queue} -------")

        # collect stats before the test
        stats_before_test = get_rx_queue_stats(tc)
        if len(stats_before_test) == 0:
            return api.types.status.FAILURE

        # send iperf, generate traffic on a specific queues
        send_iperf_cmd(tc, client_port, server_port, test_packet_count)

        if verify_iperf(tc) is api.types.status.SUCCESS:
            stats_after_test = get_rx_queue_stats(tc)
            # test if the packets landed in the right queue
            # if RSS is disabled, expect all traffic to land on queue [0]
            if (tc.iterators.rss == 'disabled'): current_stats = stats_after_test[0] - stats_before_test[0]
            else: current_stats = stats_after_test[queue] - stats_before_test[queue]

            if  current_stats < test_packet_count:
                    api.Logger.error (f"RSS Failed for queue [{queue}]")
                    tc.failed_queues.append (queue)
        else: return api.types.status.FAILURE

    return api.types.status.SUCCESS

def verify_iperf(tc):
    """
    Verifies iperf command output
    Handles exceptions
    Returns Success/Failure
    """

    conn_timedout = 0
    control_socker_err = 0
    for idx, cmd in enumerate(tc.iperf_client_resp.commands):
        api.Logger.info(tc.cmd_descr[idx])
        api.Logger.info("Server cmd  %s" % (tc.server_cmds[idx]))
        api.Logger.info("Client cmd %s" % (tc.client_cmds[idx]))
        if cmd.exit_code != 0:
            api.Logger.error("Iperf client exited with error")
            if iperf.ConnectionTimedout(cmd.stdout):
                api.Logger.error("Connection timeout, ignoring for now")
                conn_timedout = conn_timedout + 1
                continue
            if iperf.ControlSocketClosed(cmd.stdout):
                api.Logger.error("Control socket cloned, ignoring for now")
                control_socker_err = control_socker_err + 1
                continue
            if iperf.ServerTerminated(cmd.stdout):
                api.Logger.error("Iperf server terminated")
                return api.types.status.FAILURE
            if not iperf.Success(cmd.stdout):
                api.Logger.error("Iperf failed", iperf.Error(cmd.stdout))
                return api.types.status.FAILURE

    if conn_timedout > 0:
        api.Logger.info("Number of connection timeouts : {}".format(conn_timedout))
    if control_socker_err > 0:
        api.Logger.info("Number of control socket errors : {}".format(control_socker_err))

    api.Logger.info("Iperf test successfull")

    return api.types.status.SUCCESS

def get_rx_queue_stats(tc):
    """
    get stats for all RX queues from the interface under test
    """
    queue_stats = []

    get_rx_queue_stats_cmd= f"ethtool -S  {tc.server.parent_interface} | awk '/rx_._pkts|rx_.._pkts/ {{ print $2 }}'"
    req = api.Trigger_CreateExecuteCommandsRequest()

    api.Trigger_AddHostCommand(req, tc.server.node_name, get_rx_queue_stats_cmd)
    resp = api.Trigger(req)

    if resp is None:
        api.Logger.error(f"Failed to get que stats info from interface {tc.server.parent_interface}" )
        return queue_stats

    cmd = resp.commands.pop()

    if cmd.exit_code != 0:
        api.Logger.error(f"Error in {get_rx_queue_stats_cmd}")
        return queue_stats

    if cmd.stdout == "":
        api.Logger.error(f"Error in {get_rx_queue_stats_cmd} ")
        api.Logger.error(f"Queue Stats: {queue_stats}")
        return queue_stats

    # split stdout by lines to get the stat values
    # make sure all values are a min of zero
    queue_stats = cmd.stdout.splitlines()
    for i in range(len(queue_stats)):
        if queue_stats[i] == '': queue_stats[i] = '0'

    # convert to a list of ints
    queue_stats = list(map(int,queue_stats))
    api.Logger.info (f"Queue Stats for {tc.server.parent_interface}: {queue_stats}")

    return queue_stats

def Setup(tc):

    #map iterators from IOTA infra to the enum for the toeplitz utilitys
    iterators = {'tcp4' : RSS.IPV4_TCP,  'udp4':RSS.IPV4_UDP , 'tcp6' : RSS.IPV6_TCP, \
                 'udp6':RSS.IPV6_UDP, 'ip6':RSS.IPV6,  'ip4tcp':RSS.IPV4, 'ip4udp':RSS.IPV4, 'ip6tcp':RSS.IPV6, 'ip6udp':RSS.IPV6}
    tc.rss_enum = iterators.get(tc.iterators.rxflowhash, "none")

    # iperf options for iterators
    # IPv4 vs IPv6 iterator
    ip_proto_iterators = {'tcp4' : 'v4',  'udp4':'v4' , 'tcp6' : 'v6', 'udp6':'v6', 'ip4tcp':'v4', \
                         'ip4udp':'v4', 'ip6tcp':'v6', 'ip6udp':'v6'}
    tc.tc_ip_proto = ip_proto_iterators.get(tc.iterators.rxflowhash, "none")

    # UDP vs TCP iterator
    proto_iterators = {'tcp4' : 'tcp',  'udp4':'udp' , 'tcp6':'tcp', 'udp6':'udp', 'ip4tcp':'tcp',
                       'ip4udp':'udp', 'ip6tcp':'tcp', 'ip6udp':'udp'}
    tc.proto = proto_iterators.get(tc.iterators.rxflowhash, "none")

    if tc.proto  == "none" or tc.tc_ip_proto == "none " or tc.rss_enum == "none":
        api.Logger.error ( f"Not able to map the iterators. Iterator:{tc.iterators.rxflowhash} tc_ip_proto: {tc.tc_ip_proto}, proto: {tc.proto}, tc.rss_enum: {tc.rss_enum}")
        return api.types.status.FAILURE

    # number of sessions iterator
    tc.num_sessions = int(getattr(tc.args, "num_sessions", 1))

    # log which iterration is in progress:
    api.Logger.info (f"=============== %s ===============" % tc.rss_enum)
    api.Logger.info(f"ip_proto:{tc.tc_ip_proto}, proto: {tc.proto}, rss: {tc.iterators.rss}, iperf_sessions: {tc.num_sessions}")

    #TODO: Is this different ?
    #tc.nodes = api.GetNaplesHostnames()
    tc.nodes = api.GetWorkloadNodeHostnames()
    tc.os = api.GetNodeOs(tc.nodes[0])
    if tc.os == 'freebsd':
        return api.types.status.SUCCESS

    # Identify the receiving node (testing RSS)
    # This will be the client node for iPerf
    # All configuration, and testing and verification will be done on this node
    for n in tc.nodes:
        if api.IsNaplesNode(n):
            api.Logger.info(f"Found Naples Node: [{n}]")
            ReceiveNode = n
            break
    else:
        api.Logger.error(f"Failed to find a Naples Node!")
        return api.types.status.FAILURE

    # Get workload pars for iperf sessions
    workload_pairs = api.GetRemoteWorkloadPairs()
    if len(workload_pairs) == 0:
        api.Logger.info("Skipping Testcase due to no workload pairs.")
        tc.skip = True

    # assign client/server node based on selected Receiving Node
    for pair in workload_pairs:
        if ReceiveNode == pair[0].node_name:
            tc.client = pair[1]
            tc.server = pair[0]
        else:
            tc.client = pair[0]
            tc.server = pair[1]
        break

    # unload driver, to clear stats (server node only)
    # Re-add workloads
    if host.UnloadDriver(tc.os, tc.server.node_name, "all") is api.types.status.FAILURE:
        return api.types.status.FAILURE
    if host.LoadDriver(tc.os, tc.server.node_name) is api.types.status.FAILURE:
        return api.types.status.FAILURE
    wl_api.ReAddWorkloads(tc.server.node_name)

    if tc.tc_ip_proto is 'v6':
        tc.server_ip = ipaddress.ip_address(tc.server.ipv6_address)
        tc.server_ip = str(tc.server_ip.exploded)

        tc.client_ip = ipaddress.ip_address(tc.client.ipv6_address)
        tc.client_ip = str(tc.client_ip.exploded)
    else:
        tc.server_ip = tc.server.ip_address
        tc.client_ip = tc.client.ip_address

    return api.types.status.SUCCESS

def Trigger(tc):
    get_queues = "grep -c processor /proc/cpuinfo"
    #get_queues = f"ethtool -l {tc.client.parent_interface} | grep -m 1 Combined | awk '/Combined:/' | awk '{{print $2}}'"
    api.Logger.info(get_queues)

    # TODO: FreeBSD logic is to be implemented
    if tc.os == 'freebsd':
        return api.types.status.SUCCESS

    # discover a number of cores on the server node
    req = api.Trigger_CreateExecuteCommandsRequest()
    api.Trigger_AddHostCommand(req, tc.server.node_name, get_queues)
    resp = api.Trigger(req)

    if resp is None:
        api.Logger.error(f"Failed to get queue count from {tc.server.node_name} \
                                                  -{tc.server.parent_interface}")
        return api.types.status.FAILURE

    cmd = resp.commands.pop()

    if cmd.exit_code != 0:
        api.Logger.error(f"Error in {get_queues}")
        api.PrintCommandResults(cmd)
        return api.types.status.FAILURE

    # number of queues is min of Naples Max or Test Case Max
    num_queues = tc.args.maxqueues
    num_queues = min(tc.args.maxqueues, int(cmd.stdout.strip()))

    req = api.Trigger_CreateExecuteCommandsRequest()

    if tc.iterators.rss == 'disabled':
        # disable RSS hashing
        init_rss_cmd = f"ethtool -K {tc.server.parent_interface} rxhash off"

    else:
        # enable RSS hashing
        enable_rss_cmd = f"ethtool -K {tc.server.parent_interface} rxhash on"
        api.Trigger_AddHostCommand(req, tc.server.node_name, enable_rss_cmd)
        # init hash key and num of queues
        key = ':'.join([hex(x)[2:] for x in toeplitz_symmetric_key])
        init_rss_cmd =  f"ethtool -X {tc.server.parent_interface} hfunc toeplitz hkey {key} equal {num_queues}"

    api.Logger.info(f"{init_rss_cmd}")
    api.Trigger_AddHostCommand(req, tc.server.node_name, init_rss_cmd)

    resp = api.Trigger(req)

    if resp is None:
        api.Logger.error(f"Failed to initialize RSS on host {n}, interface{tc.server.parent_interface} ")
        return api.types.status.FAILURE

    for cmd in resp.commands:
        api.PrintCommandResults(cmd)
        if cmd.exit_code != 0:
            api.Logger.error(f"Error in {enable_rss_cmd}")
            api.PrintCommandResults(cmd)
            return api.types.status.FAILURE

    api.Logger.info(f"Total Queues: {num_queues}")

    return trigger_iperf(tc, num_queues)

def Verify(tc):
    if tc.failed_queues:
        api.Logger.error ("The following queues failed in this iteration: %s" % ', '.join(map(str, tc.failed_queues)))
        return api.types.status.FAILURE

    return api.types.status.SUCCESS


import re
import requests
import base64

from bs4 import BeautifulSoup
from analytics.models import *
from urlparse import urlparse

class ParseChannel:

    def __init__(self):
        self.homeUrl = "https://www.youtube.com"

    def initialize_db(self):
        data = requests.get(self.homeUrl)
        soup = BeautifulSoup(data.text)
        links = soup.find_all('a', href=re.compile('/channel/'))
        distinct_ids = []
        for link in set(link.get('href') for link in links):
            channel_id = str(link).lstrip('/channel/')
            distinct_ids.append(channel_id)
            # print "Saving Channel Id -> " + channel_id
            obj = ChannelDetails(ch_id=channel_id)
            obj.save()

    def insert_details(self):
        # status = ChannelDetails.objects.filter(status=False)
        for x in ChannelDetails.objects.filter(status=False)[:10]:
            # data = requests.get(str(x.about_url))
            soup = BeautifulSoup(requests.get(str(x.about_url)).text)
            image = soup.find('img', class_="channel-header-profile-image")
            # print "img_url1 ->", str(image['src'])
            try:
                img_url = 'https:' + str(image['src'])
                # print "img_url ->", img_url
                response = requests.get(img_url)
                x.pic = base64.b64encode(response.content)
            except:
                img_url = str(image['src'])
                # print "img_url ->", img_url
                response = requests.get(img_url)
                x.pic = base64.b64encode(response.content)
            try:
                x.name = soup.find('a', class_="branded-page-header-title-link").string
                # name = name.string
            except:
                x.name = None
            stats = soup.find_all('span', class_="about-stat")
            x.subscriber = 0
            if len(stats) > 1:
                x.subscriber = "".join(str(stats[0].b.string).split(","))
                if int(x.subscriber) > 400:
                    x.subs_limit = True
            try:
                x.date_joined = stats[-1].string
            except:
                x.date_joined = None
            x.views = 0
            if len(stats) > 2:
                x.views = "".join(str(stats[1].b.string).split(","))
            links = soup.find_all('a', class_="about-channel-link")
            x.twitter_link = None
            x.fb_link = None
            for link in links:
                try:
                    if 'Twitter' in str(link['title']):
                        # print "twit-> ", str(link['href'])
                        x.twitter_link = str(link['href'])
                except:
                    pass
                try:
                    if 'Facebook' in str(link['title']):
                        # print "fb_link-> ", str(link['href'])
                        x.fb_link = str(link['href'])
                except:
                    pass
            try:
                x.country = str(soup.find('span', class_="country-inline").string).strip()
                # country = str(country.string).strip()
            except:
                x.country = "others"
            # print "country -------------->>>>>>>>>>" , country
            # x.name = name
            # x.pic = img_url
            # x.views = views
            # x.subscriber = subscriber
            # x.fb_link = fb_link
            # x.twitter_link = twit_link
            # x.twitter_link = twit_link
            # x.date_joined = date
            x.status = True
            # x.country = country
            x.save()
        if len(ChannelDetails.objects.filter(status=False)) == 0:
            return False
        else:
            return True

    def fetch_channels(self):
        # fetched = ChannelDetails.objects.filter(fetched = False)
        for p in ChannelDetails.objects.filter(fetched = False)[:10]:
            # print "url", p.channels_url
            # print "id-> " , p.ch_id
            # data = requests.get(str(p.channels_url))
            # soup = BeautifulSoup(requests.get(str(p.channels_url)).text)
            # links = BeautifulSoup(requests.get(str(p.channels_url)).text).find_all('a', href=re.compile('/channel/'))
            distinct_ids = []
            for link in set(link.get('href') for link in BeautifulSoup(requests.get(str(p.channels_url)).text).find_all('a', href=re.compile('/channel/'))):
                parsed = urlparse(link)
                channel_id = str(parsed.path).lstrip('/channel/').split("/")
                # channel_id = channel_id.split("/")
                if len(channel_id) == 1:
                    channel_id = channel_id[0]
                    distinct_ids.append(channel_id)
                    distinct_ids = list(set(distinct_ids))
            p.fetched = True
            p.save()
            for q in distinct_ids:
                try:
                    obj = ChannelDetails(ch_id=q)
                    obj.save()
                except:
                    pass
        if len(ChannelDetails.objects.filter(fetched=False)) == 0:
            return False
        else:
            return True

    def infinite_loop(self):
        status = ChannelDetails.objects.filter(status=False)
        fetched = ChannelDetails.objects.filter(fetched = False)
        if len(status) == 0 and len(fetched) == 0:
            return False
        else:
            return True

    def filldb_loop(self):
        status = ChannelDetails.objects.filter(status=False)
        fetched = ChannelDetails.objects.filter(fetched = False)
        if len(status) == 0 and len(fetched) == 0:
            return False
        else:
            return True


# 89. k Sum
# 中文English
# Given n distinct positive integers, integer k (k <= n) and a number target.
#
# Find k numbers where sum is target. Calculate how many solutions there are?
#
# 样例
# Example 1
#
# Input:
# List = [1,2,3,4]
# k = 2
# target = 5
# Output: 2
# Explanation: 1 + 4 = 2 + 3 = 5
# Example 2
#
# Input:
# List = [1,2,3,4,5]
# k = 3
# target = 6
# Output: 1
# Explanation: There is only one method. 1 + 2 + 3 = 6

class Solution:
    """
    @param A: An integer array
    @param k: A positive integer (k <= length(A))
    @param target: An integer
    @return: An integer
    """

    # write your code here
    # 有多少种方法让背包装满。
    # 看最后一个数A_n-1 是否选入这K个数
    # 情况一：A_n-1不选入：需要在前n-1个数中选K个数，使得它们的和是target.
    # 情况二：A_n-1选入：需要在前n-1个数中选K-1个数，使得他们的和是target - A_n-1

    # f[i][k][s] 表示有多少种方法可以在前i个数中选出k个，使得它们的和是s。
    # dp[i][k][s] = number of ways to use the first 'i' numbers in A, select 'k' of them, to sum to target 's'

    def kSum(self, A, k, target):
        n = len(A)
        num_numbs = k
        dp = [[[None] * (target + 1) for _ in range(k + 1)] for _ in range(n + 1)]

        for i in range(0, n + 1):
            for k in range(num_numbs + 1):
                for s in range(0, target + 1):
                    if i == 0 and k == 0 and s == 0:
                        dp[i][k][s] = 1
                        continue
                    if i == 0:
                        dp[i][k][s] = 0
                        continue

                    # not use the ith number A[i-1]
                    dp[i][k][s] = dp[i - 1][k][s]
                    # use the ith number A[i-1]
                    if k > 0 and s - A[i - 1] >= 0:
                        dp[i][k][s] += dp[i - 1][k - 1][s - A[i - 1]]

        return dp[n][num_numbs][target]

A = [1, 2, 3, 4]
k = 2
target = 5
sol = Solution()
sol.kSum(A, k, target)


import collections
import datetime
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px
from sklearn.decomposition import PCA
from sklearn.cluster import MeanShift, DBSCAN, KMeans

percetanges = ['1day%', 'GC%', 'TT%', 'sprint%', 'climber%']
n_comp = 3

# PCA on points per specialty
def pca_analysis_on_points(save=False):
    riders_info = classify_points()
    riders_points = riders_info[percetanges]

    pca = PCA(n_components=n_comp)
    pca.fit(riders_points)
    print('Variance ratio', pca.explained_variance_ratio_) # first 3 accounts for 93%

    # Corelation matrix
    corr = riders_points.corr()
    fig = px.imshow(corr, color_continuous_scale='RdBu')
    fig.update_layout(title_text="Correlation matrix")
    fig.show()
    if save:
        fig.write_image('reports/figures/corr_matrix.png')
        # fig.write_html("reports/figures/riders_points_corr.html")

    # Eigenvector bar plot
    eigenvectors = np.abs(pca.components_)
    print(eigenvectors)
    ind = np.arange(len(percetanges))
    width = 0.25
    for i in range(n_comp):
        print(i)
        plt.bar(ind+i*width, eigenvectors[i], width, label=f'ev{i}')

    plt.xticks(ind+width/2, percetanges)
    plt.legend()
    plt.xlabel('Point percentage')
    plt.ylabel('Eigenvector components')
    plt.tight_layout()
    if save:
        plt.savefig('reports/figures/riders_points_pca_eigenvectors.png')
    plt.show()

    # 3D clustering
    principalComponents = pca.fit_transform(riders_points)
    riders_points_pca = pd.DataFrame(data=principalComponents, columns=['pca1', 'pca2', 'pca3'])

    # clustering = MeanShift().fit(riders_points_pca)
    # clustering = DBSCAN().fit(riders_points_pca)
    clustering = KMeans(n_clusters=3).fit(riders_points_pca)
    clustering_freq = collections.Counter(clustering.labels_)
    print('Clustering freq:', clustering_freq)

    riders_points_pca_labelled = pd.concat((riders_points_pca, pd.DataFrame(clustering.labels_, columns=['cluster'])), axis=1)

    fig = px.scatter_3d(riders_points_pca_labelled, x='pca1', y='pca2', z='pca3', color='cluster')
    fig.update_layout(title_text="3D PCA plot of riders points (variance ratio: 93% for the first 3)")
    fig.show()
    if save:
        fig.write_html("reports/figures/riders_PCA.html")

# Age, Weight, Height
def pca_analysis_on_figure(save=False):
    riders_info = pd.read_csv('data/processed/riders_info_cleaned.csv')
    this_year = datetime.date.today().year

    # Find age
    riders_info['DOB'] = pd.to_datetime(riders_info['DOB'])
    riders_info['age'] = this_year - riders_info['DOB'].dt.year
    riders_info = riders_info[['age', 'weight', 'height']]

    clustering = KMeans(n_clusters=3).fit(riders_info)
    clustering_freq = collections.Counter(clustering.labels_)
    print('Clustering freq:', clustering_freq)

    riders_info_labelled = pd.concat((riders_info, pd.DataFrame(clustering.labels_, columns=['cluster'])), axis=1)

    # 3d plot
    fig = px.scatter_3d(riders_info_labelled, x='height', y='weight', z='age', color='cluster')
    fig.update_layout(title_text="Age, weight and height of riders")
    fig.show()
    if save:
        fig.write_html("reports/figures/riders_awh.html")

# Points per specialty
def classify_points(plot=False):
    riders_info = pd.read_csv('data/processed/riders_info_cleaned.csv')
    riders_info['total'] = riders_info['one day races'] + riders_info['GC'] + riders_info['TT'] + riders_info['sprint'] + riders_info['climber']

    min_total = 50 # flexible
    riders_info = riders_info[riders_info['total'] > min_total]

    riders_info['1day%'] = riders_info['one day races'] / riders_info['total']
    riders_info['GC%'] = riders_info['GC'] / riders_info['total']
    riders_info['TT%'] = riders_info['TT'] / riders_info['total']
    riders_info['sprint%'] = riders_info['sprint'] / riders_info['total']
    riders_info['climber%'] = riders_info['climber'] / riders_info['total']

    # sort by total points
    riders_info = riders_info.sort_values(by='total', ascending=False)

    # hist of total point
    if plot:
        print(riders_info.head()[['name', 'total', '1day%', 'GC%', 'TT%', 'sprint%', 'climber%']])
        riders_info.hist(column='total', bins=1000)
        plt.show()

    return riders_info

if __name__ == "__main__":
    pca_analysis_on_points(save=True)
    # pca_analysis_on_figure()


# Create the first example
# Functionalities:
# 1.create windows, create label widget

from os import path
import os
from tkinter import *
from tkinter import scrolledtext
from tkinter import filedialog
from tkinter import Menu
from tkinter import messagebox,ttk
from tkinter.ttk import Combobox,Radiobutton
from tkinter.ttk import Checkbutton,Progressbar

window = Tk()
window.title("Example one")
window.geometry('900x800')

lbl = Label(window,text='Label 1',padx=50,pady=10,bg='red')
# without calling the grid function for label, it won't show up
lbl.grid(column=0,row=0)

# create textbox using Tkinter Entry class
txt = Entry(window,width=10)
txt.grid(column=1,row=0)

# add a area to show the botton clicked event
show1= Label(window,text='show area two')
# without calling the grid function for label, it won't show up
show1.grid(column=2,row=0)
# add a function to handle button click event
def clicked():
    show1.configure(text='The input is:' + txt.get())
# add a button,and change backgroud and foreground
btn = Button(window,text='Click Me',bg='orange',fg='red',command=clicked)
btn.grid(column=3,row=0)

# add a area to show the combobox selected event
show2= Label(window,text='Show Area',bg='green',fg='red')
show2.grid(column=0,row=1)
# add a combobox widget
combo = Combobox(window)
combo['values'] = (1,2,'name',4,5,'Text')
combo.current(2) # set the selected item
combo.grid(column=1,row=1)
# show the selected results
show2.configure(text='The select is:' +combo.get())

# add a checkbotton widget

# set check state,method one
# chk_state = IntVar()
# chk_state.set(0) # uncheck
# chk_state.set(1) # check

# set check state,method 2
chk_state = BooleanVar()
chk_state.set(True) # set check state
chk = Checkbutton(window,text='Choose',var=chk_state)
chk.grid(column=0,row=3)

# add a area to show the combobox selected event
show3= Label(window,text='Show Area',bg='white',fg='red')
show3.grid(column=3,row=4)
# handle event function
def rad1_event():
    show3.configure(text='first')
def rad2_event():
    show3.configure(text='second')
def rad3_event():
    show3.configure(text='third')
# add radio buttons widgets
rad1 = Radiobutton(window,text='first',value=1,command=rad1_event)
rad2 = Radiobutton(window,text='second',value=2,command=rad2_event)
rad3 = Radiobutton(window,text='third',value=3,command=rad3_event)
rad1.grid(column=0,row=4)
rad2.grid(column=1,row=4)
rad3.grid(column=2,row=4)

# add a ScrolledText widget
s_txt = scrolledtext.ScrolledText(window,width=40,height=10)
s_txt.grid(column=0,row=5)
s_txt.insert(INSERT,'you text goes here')

# add a messagebox
# there are also have messagebox.askquestion,messagebox.askyesno,
# messagebox.askyesnocancel,messagebox.okcancel,messagebox.askretrycancel
def show_info():
    messagebox.showinfo('Message title','Message info content')
btn = Button(window,text='showinfo',bg='orange',fg='red',command=show_info)
btn.grid(column=1,row=6)

def show_warning():
    messagebox.showwarning('Message title','Message warning content')
btn = Button(window,text='showwarning',bg='orange',fg='red',command=show_warning)
btn.grid(column=2,row=6)

def show_error():
    messagebox.showerror('Message title','Message error content')
btn = Button(window,text='showerror',bg='orange',fg='red',command=show_error)
btn.grid(column=3,row=6)

# add a SpinBox,and set default value
var = IntVar()
var.set(9)
spin = Spinbox(window,from_=0,to=20,width=5,textvariable=var)
spin.grid(column=0,row=7)

# add another SpinBox
spin = Spinbox(window,values=(2,5,16),width=10)
spin.grid(column=1,row=7)

# add a Progressbar widget
style = ttk.Style()
style.theme_use('default')
style.configure('black.Horizontal.TProgressbar',background='blue')
bar = Progressbar(window,length=200,style='black.Horizontal.TProgressbar')
bar['value'] = 70
bar.grid(column=0,row=8)

# add filedialog
def get_file():
    #print(os.getcwd()) # the current path
    file_ = filedialog.askopenfilename(initialdir=os.getcwd(),\
            filetypes=(('Text files','*.txt'),('Python file','*.py'),\
            ('all files','*.*')))
    print('the file is:' + file_)

btn = Button(window,text='get file',bg='orange',fg='red',command=get_file)
btn.grid(column=0,row=9)

# add menu
menu = Menu(window)
# diable the dashed line, which will show the menu items in a small separate windows
#new_item = Menu(menu,tearoff=0)
def menu_event():
    messagebox.showinfo('Message title','Message info content')

new_item = Menu(menu)
new_item.add_command(label='has an event',command=menu_event)
new_item.add_command(label='NEW_2')
new_item.add_separator()
new_item.add_command(label='NEW_3')
menu.add_cascade(label='File',menu=new_item)
window.configure(menu=menu)

window.mainloop()


'''
Example: s1: 'horse'
         s2: 'ros'

Case1: Inserting a Character

Now if we have to match the strings by insertions, what would we do?:

We would have placed an ‘s’ at index 5 of S1.
Suppose i now point to s at index 5 of S1 and j points are already pointing to s at index j of S2.
Now, we hit the condition, where characters do match. (as mentioned in case 1).
Therefore, we will decrement i and j by 1. They will now point to index 4 and 1 respectively.

Now, the number of operations we did were only 1 (inserting s at index 5) but do we need to really insert the ‘s’ at index 5 and modify the string? The answer is simply NO. As we see that inserting a character (here ‘s’ at index 5), we will eventually get to the third step. So we can just return 1+ f(i,j-1) as i remains there only after insertion and j decrements by 1. We can say that we have hypothetically inserted character s.

Case 2: Deleting a character

Consider the same example,

We can simply delete the character at index 4 and check from the next index.

Now, j remains at its original index and we decrement i by 1. We perform 1 operation, therefore we will recursively call 1+f(i-1,j).

Case3: Replacing a character

Consider the same example,

If we replace the character ‘e’ at index 4 of S1 with ‘s’, we have matched both the characters ourselves. We again hit the case of character matching, therefore we decrement both i and j by 1. As the number of operations performed is 1, we will return 1+f(i-1,j-1).

To summarise, these are the three choices we have in case characters don’t match:

return 1+f(i-1,j) // Insertion of character.
return 1+f(i,j-1) // Deletion of character.
return 1+f(i-1,j-1) // Replacement of character.
'''

#Recursion
#Time Complexity: O(2^(m+n))
#Space Complexity: O(m+n)
class Solution1:
    def minDistance(self, word1: str, word2: str) -> int:
        def solve(i,j):
            if i==0:
                return j
            if j==0:
                return i
            if word1[i-1]==word2[j-1]:
                return solve(i-1,j-1)
            else:
                return 1 + min(solve(i,j-1),solve(i-1,j),solve(i-1,j-1))
        m,n=len(word1),len(word2)
        return solve(m,n)

#Memoization (Top-Down)
#Time Complexity: O(m*n)
#Space Complexity: O(m+n) + O(m*n)
class Solution2:
    def minDistance(self, word1: str, word2: str) -> int:
        def solve(i,j):
            if i==0:
                return j
            if j==0:
                return i
            if dp[i][j]!=-1:
                return dp[i][j]
            if word1[i-1]==word2[j-1]:
                dp[i][j]=solve(i-1,j-1)
                return dp[i][j]
            else:
                dp[i][j]=1 + min(solve(i,j-1),solve(i-1,j),solve(i-1,j-1))
                return dp[i][j]
        m,n=len(word1),len(word2)
        dp=[[-1 for j in range(n+1)] for i in range(m+1)]
        return solve(m,n)

class Solution3:
    def minDistance(self, word1: str, word2: str) -> int:
        m,n = len(word1),len(word2)
        dp = [[0 for j in range(n+1)] for i in range(m+1)]
        for i in range(m+1):
            dp[i][0] = i
        for j in range(n+1):
            dp[0][j] = j
        for i in range(1,m+1):
            for j in range(1,n+1):
                if word1[i-1] == word2[j-1]:
                    dp[i][j] = dp[i-1][j-1]
                else:
                    dp[i][j] = 1 + min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1])
        return dp[m][n]

#Space Optimization
#Time Complexity: O(m*n)
#Space Complexity: O(n)
class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        m,n = len(word1),len(word2)
        prev=[0]*(n+1)
        curr=[0]*(n+1)
        for j in range(n+1):
            prev[j]=j
        for i in range(1,m+1):
            curr[0]=i
            for j in range(1,n+1):
                if word1[i-1] == word2[j-1]:
                    curr[j] = prev[j-1]
                else:
                    curr[j] = 1 + min(prev[j-1], prev[j], curr[j-1])
            prev=curr[:]
        return prev[n]

# https://zhuanlan.zhihu.com/p/553078167
# 动态规划三部曲  1)dp数组含义  2)初始值  3)状态转移方程
# dp[i][j]定义为 word1前i个字符转换到word2前j个字符所需的最少操作数
#   | '' | r | o | s
# ''| 0  | 1 | 2 | 3
# h | 1  |
# o | 2  |
# r | 3  |
# s | 4  |
# e | 5  |
# dp[0][j]的含义: 从''转换为'',r,ro,ros所需的最少操作数
# dp[i][0]的含义: 从'',h,ho,hor,hors,horse转换为''所需的最少操作数
# dp[i][j] = dp[i-1][j-1] if word1[i-1]==word2[j-1] else min(dp[i-1][j-1]+1,dp[i-1][j]+1,dp[i][j-1]+1)
def editDistance(word1, word2):
    m,n = len(word1),len(word2)
    dp = [[0]*(n+1) for _ in range(m+1)]
    for i in range(m+1):
        for j in range(n+1):
            if i==0 or j==0:
                dp[i][j] = i if j==0 else j
            else:
                dp[i][j] = dp[i-1][j-1] if word1[i-1]==word2[j-1] else min(dp[i-1][j-1]+1,dp[i-1][j]+1,dp[i][j-1]+1)
    return dp[m][n]

from functools import lru_cache
def edit_distance(word1, word2):
    m, n = len(word1), len(word2)

    @lru_cache(None)
    def dp(i,j):
        if i>=m: return n-j
        if j>=n: return m-i
        if word1[i] == word2[j]: return dp(i+1, j+1)
        return min(dp(i,j+1), dp(i+1,j), dp(i+1,j+1)) + 1

    return dp(0,0)


class Solution:
	def maxSquare(self, matrix):
		tmp = [0] * len(matrix[0])
		MAX = 0
		for row in range(len(matrix)):
			for col in range(len(matrix[0])):
				if matrix[row][col] == 0:
					tmp[col] = 0
				else:
					tmp[col] += 1
			MAX = max(MAX, self.maxEdge(tmp[::]))
		return MAX ** 2

	def maxEdge(self, heights):
		# print(heights)
		heights.append(0)
		MAX = 0
		stack = [-1]
		for i in range(len(heights)):
			h = heights[i]
			while h < heights[stack[-1]]:
				H = heights[stack.pop()]
				W = i - stack[-1] - 1
				MAX = max(MAX, min(H, W))
			stack.append(i)
		return MAX

matrix = [[1,0,1,0,0], [1,0,1,1,1], [1,1,1,1,1], [1,0,0,1,0]]

inst = Solution()
print(inst.maxSquare(matrix))


# AHA imports
import magma as m
import fault

# svreal imports
from .common import *
from svreal import (real2fixed, real2recfn, fixed2real, recfn2real,
                    DEF_HARD_FLOAT_WIDTH)

def pytest_generate_tests(metafunc):
    pytest_sim_params(metafunc)
    pytest_real_type_params(metafunc)

def test_sync_rom(simulator, real_type, abs_tol=0.001):
    # determine formatting
    if real_type == RealType.HardFloat:
        width = DEF_HARD_FLOAT_WIDTH
        conv_func = real2recfn
        inv_func = recfn2real
    else:
        width = 18
        exponent = -12
        def conv_func(x):
            return real2fixed(x, exp=exponent, width=width, treat_as_unsigned=True)
        def inv_func(x):
            return fixed2real(x, exp=exponent, width=width, treat_as_unsigned=True)

    # write the lookup table
    expct = [1.23, -2.34, 3.45, -4.56]
    path_to_mem = get_file(f'test_sync_rom_{real_type.value.lower()}.mem').resolve()
    with open(path_to_mem, 'w') as f:
        for elem in expct:
            line = conv_func(elem)  # format input as an integer
            line = bin(line)  # convert to binary string
            line = line.replace('0b', '')  # strip the beginning '0b'
            line = line.rjust(width, '0')  # pad to the right width
            f.write(line + '\n')

    # verify the lookup table
    with open(path_to_mem, 'r') as f:
        for elem in expct:
            line = f.readline()  # read the next line
            line = line.strip()  # remove whitespace
            line = int(line, 2)  # convert to an integer
            meas = inv_func(line)  # convert to a real number
            assert abs(elem-meas) <= abs_tol, 'Lookup table verification failed'

    # declare circuit
    class dut(m.Circuit):
        io = m.IO(
            addr=m.In(m.Bits[2]),
            out=fault.RealOut,
            clk=m.ClockIn,
            ce=m.BitIn
        )
        name='test_sync_rom'

    # define the test
    t = SvrealTester(dut, dut.clk)

    # initialize
    t.poke(dut.clk, 0)
    t.poke(dut.ce, 1)
    t.poke(dut.addr, 0)
    t.eval()

    # check output values
    for k in range(4):
        t.poke(dut.addr, k)
        t.eval()
        t.step(2)
        t.expect(dut.out, expct[k], abs_tol=abs_tol)

    # disable clock enable and walk through addresses
    t.poke(dut.ce, 0)
    t.eval()
    for k in range(4):
        t.poke(dut.addr, k)
        t.eval()
        t.step(2)
        t.expect(dut.out, expct[-1], abs_tol=abs_tol)

    # run the test
    t.compile_and_run(
        get_file('test_sync_rom.sv'),
        simulator=simulator,
        real_type=real_type,
        defines={'PATH_TO_MEM': f'"{path_to_mem}"'}
    )


import os
from os import listdir
from os.path import isfile, join

# scan apps and include them

FichList = [ f for f in os.listdir('./app') if( os.path.isfile(os.path.join('./app',f)) == False) ]

# make the apps.hpp file

file_app = """
#ifndef APPS_HPP
#define APPS_HPP

#include "../widgets/gauss.hpp"
#include "../system/files/files.hpp"

class App
{
    public:
    virtual void launch() = 0;
    virtual String getName() = 0;
    virtual String getLogo() = 0;
    Window* window = nullptr;
};

bool watchDogCall()
{
    return true;
}

#define while(condition) while(watchDogCall() && condition)
#define appEvent static void

"""

for f in FichList:
    file_app += "#include \""+f+"/"+f+".hpp\"\n"

file_app += "#define NB_APPS " + str(len(FichList))
file_app += "\nApp *application[NB_APPS] = {\n"

for f in FichList:
    file_app += "nullptr,"

file_app = file_app[0:len(file_app)-1]

file_app += "\n};\n"

file_app += """
void allocateApp(int index)
{
    switch (index)
    {
"""

i=0

for f in FichList:
    file_app += "       case "+str(i)+": application["+str(i)+"] = new "+f+"; break;\n"
    i+=1

file_app += """
    }
}

"""

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

file_app += """
void destroyApp(int index)
{
    switch (index)
    {
"""

i=0

for f in FichList:
    file_app += "       case "+str(i)+": delete application["+str(i)+"]; break;\n"
    i+=1

file_app += """
    }
}

"""

########

file_app += """
void runApp(int index)
{
    allocateApp(index);
    if(application[index]!=nullptr) application[index]->launch();
    else Serial.println("invalid app index:" + String(index));
    destroyApp(int(index));
    //vTaskDelete(0);
}

#endif /* APPS_HPP */
"""

fichier = open('./app/apps.hpp', "w")
fichier.write(file_app)
fichier.close()

os.system('arduino --upload PAXOS_7.ino')


# -*- coding: utf-8 -*-
"""
Created on Wed Aug  8 20:26:54 2018

@author: simon.suthers
"""

from scipy import signal
import matplotlib.pyplot as plt
from scipy.io import wavfile
import numpy as np
from math import ceil

file1 = "./signal1.wav"
file2 = "./signal2.wav"

#%% Play wav file

import winsound

winsound.PlaySound(file1, winsound.SND_FILENAME|winsound.SND_ASYNC)

#%% Join 2 wav files together
#Make sure all 3 wav files are the same length
#Pad all 3 wav files to the nearest second

#Read 2 wav files
sample_rate1, samples1 = wavfile.read(file1)
sample_rate2, samples2 = wavfile.read(file2)

#Find length of longest signal
maxlength = max(len(samples1),len(samples1))

#Pad each signal to the length of the longest signal
samples1 = np.pad(samples1, (0, maxlength - len(samples1)), 'constant', constant_values=(0))
samples2 = np.pad(samples2, (0, maxlength - len(samples2)), 'constant', constant_values=(0))

#combine series together
mixed_series = samples1 + samples2

#Pad 3 wav files to whole number of seconds
extrapadding = (ceil(len(mixed_series) / sample_rate1) * sample_rate1) - len(mixed_series)
mixed_series = np.pad(mixed_series, (0,extrapadding), 'constant', constant_values=(0))
samples1 = np.pad(samples1, (0,extrapadding), 'constant', constant_values=(0))
samples2 = np.pad(samples2, (0,extrapadding), 'constant', constant_values=(0))

#%% Save combined wav file and play it

#Save combined series to wav file
wavfile.write('./mixed_series.wav', sample_rate1, np.asarray(mixed_series, dtype=np.int16))

#play sound
winsound.PlaySound('./mixed_series.wav', winsound.SND_FILENAME|winsound.SND_ASYNC)

#%% Show 3 wav files in plot

#Create x axis of time
x = np.arange(0, (len(mixed_series) / sample_rate1), (1 / sample_rate1))

#Show wav file on chart
fig = plt.figure()
fig, (ax1, ax2) = plt.subplots(2, figsize=(6,5), sharey=True)

ax1.plot(x, mixed_series, color="green", alpha = 0.8)
ax1.set(title='Mixture wav files', ylabel='Amplitude')
ax1.legend(['Combined signals'])

ax2.plot(x, samples1, color="blue", alpha = 0.5)
ax2.plot(x, samples2, color="red", alpha = 0.5)
ax2.set(xlabel='Time [sec]', ylabel='Amplitude')
ax2.legend(['Signal 1', 'Signal 2'])

fig.savefig("mixturesignals.png", bbox_inches="tight")
plt.show()
plt.close(fig)

#%% Compute the STFT of the 3 wav files

#Length of each segment. Defaults to 256. Set to 0.05 of a second
nperseg = sample_rate1 / 50

#Get stft of 3 wav files
f1, t1, Zsamples1 = signal.stft(samples1, fs=sample_rate1, nperseg=nperseg)
f2, t2, Zsamples2 = signal.stft(samples2, fs=sample_rate1, nperseg=nperseg)
fmixed, tmixed, Zmixed_series = signal.stft(mixed_series, fs=sample_rate1, nperseg=nperseg)

#%% Plot magnitude of 3 wav files

# Plot Spectrogram
fig = plt.figure()
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(10,3), sharey=True)

ax1.pcolormesh(tmixed, fmixed, np.abs(Zmixed_series))
ax1.set(title='Mixture signal', xlabel='Time [sec]', ylabel='Frequency [Hz]')

ax2.pcolormesh(t1, f1, np.abs(Zsamples1))
ax2.set(title='Signal 1', xlabel='Time [sec]')

ax3.pcolormesh(t2, f2, np.abs(Zsamples2))
ax3.set(title='Signal 2', xlabel='Time [sec]')

plt.tight_layout()
fig.savefig("spectrograms.png", bbox_inches="tight")
plt.show()
plt.close(fig)

#%% Create mask and apply it to the signal
# Create IBM for signal 1 by calculating SNR of signal 1 vs mixture signal

#Choose sample to create mask for
Zsample = Zsamples2
sample = samples2

#Calculate signal to noise ratio of clean signal versus combined signal
snr = np.divide(np.abs(Zsample), np.abs(Zmixed_series))
#round snr to 0 or 1 to create binary mask
mask = np.around(snr, 0)

#convert all nan in mask to 1 (it shouldnt matter if this is 0 or 1)
mask[np.isnan(mask)] = 1

#replace all values over 1 with 1
mask[mask > 1] = 1

#check to see what maximum value in array is
np.amax(mask)

#Element-wise multiply mask with mixed signal t-f signal
Zsamplesmaked = np.multiply(Zmixed_series, mask)

#%% Show mask

fig = plt.figure()
plt.imshow(mask, cmap='Greys', interpolation='none')

fig.savefig("mask.png", bbox_inches="tight")
plt.show()
plt.close(fig)

#%% convert back to a time series via inverse STFT

_, samplesrec = signal.istft(Zsamplesmaked, sample_rate1)

#%% Compare the original wav with recovered wav

fig = plt.figure()
plt.plot(x, sample, color="red", alpha = 0.6)
plt.plot(x, samplesrec, color="blue", alpha = 0.4)
plt.xlabel('Time [sec]')
plt.ylabel('Signal')
plt.legend(['Original', 'Recovered via STFT'])
fig.savefig("recoverdsignal.png", bbox_inches="tight")
plt.show()
plt.close(fig)

#%% Save recovered wav file and play it

#Save combined series to wav file
wavfile.write('./recovered.wav', sample_rate1, np.asarray(samplesrec, dtype=np.int16))

#play sound
winsound.PlaySound('./recovered.wav', winsound.SND_FILENAME|winsound.SND_ASYNC)


from functools import reduce
import operator as op
def nCr(n,r):
    numerator=reduce(op.mul,range(n,n-r,-1))
    denominator=reduce(op.mul,range(1,r+1))
    return numerator//denominator

p=1.09/(1+1.09)
q=1/(1+1.09)
ans=0
for i in range(3,7):
    ans+=nCr(6,i)*pow(p,i)*pow(q,6-i)
print(round(ans,3))

10 Days of Statistics/Binomial Distribution I/Solution.py


from nonebot.matcher import Matcher
from nonebot.permission import SUPERUSER
from nonebot import get_driver, on_command
from nonebot.plugin import require
from nonebot.rule import to_me
from nonebot.adapters.onebot.v11.message import Message
from nonebot.typing import T_State
from nonebot.params import Arg, Depends, CommandArg
from nonebot.log import logger
from .config import Config
import traceback
from sqlite3 import IntegrityError
from typing import Union
from uuid import uuid4
from nonebot import get_driver

export = require("nonebot_plugin_navicat")

global_config = get_driver().config
plugin_config = Config.parse_obj(get_driver().config)

class BlackList:
    data = []

    async def fresh(self):
        self.data = []
        try:
            query = "SELECT * FROM BLACKLIST"
            rows = await export.sqlite_pool.fetch_all(query=query)
            for col in rows:
                id = int(col[1])
                self.data.append(id)
        except:
            traceback.print_exc()

b = BlackList()
driver = get_driver()

@driver.on_startup
async def _():
    await b.fresh()

def parse_int(key: str):
    """解析数字，并将结果存入 state 中"""

    async def _key_parser(
            matcher: Matcher, state: T_State, a_input: Union[int, Message] = Arg(key)
    ):
        print(f"运行 parse_int, key: {key}")
        if isinstance(a_input, int):
            return

        plaintext = a_input.extract_plain_text()
        if not plaintext.isdigit():
            await matcher.reject_arg(key, "请只输入数字，不然我没法理解呢！")
        state[key] = int(plaintext)

    return _key_parser

add_blacklist = on_command(cmd="add_blacklist", rule=to_me(), permission=SUPERUSER, priority=10, block=True)

@add_blacklist.handle()
async def _(state: T_State, args: Message = CommandArg()):
    plaintext = args.extract_plain_text()
    if plaintext.isdigit():
        state["id"] = int(plaintext)

@add_blacklist.got("id", "请输入一个需封禁的qq用户id", parameterless=[Depends(parse_int("id"))])
async def _(id: Union[int, str, Message] = Arg()):
    if isinstance(id, Message):
        id = id.extract_plain_text()
    if isinstance(id, str):
        if id.isdigit():
            id = int(id)
        else:
            await add_blacklist.reject("ERROR：qq用户id非正确格式")
            logger.opt(colors=True).error("<y>qq用户id非正确格式</y>")
    try:
        query = "INSERT INTO BLACKLIST(UUID, ID) VALUES (:UUID, :ID)"
        values = {"UUID": str(uuid4()), "ID": id}
        await export.sqlite_pool.execute(query=query, values=values)
    except IntegrityError:
        traceback.print_exc()
        logger.opt(colors=True).error("<y>出现重复qq</y>")
        await add_blacklist.finish("ERROR: 出现重复qq")
    except:
        logger.opt(colors=True).error("<y>数据库出现问题</y>")
        traceback.print_exc()
        await add_blacklist.finish("ERROR: 数据库出现问题")
    await add_blacklist.send("用户" + str(id) + "已被封禁")
    await b.fresh()

del_blacklist = on_command(cmd="del_blacklist", rule=to_me(), permission=SUPERUSER, priority=10, block=True)

@del_blacklist.handle()
async def _(state: T_State, args: Message = CommandArg()):
    plaintext = args.extract_plain_text()
    if plaintext.isdigit():
        state["id"] = int(plaintext)

@del_blacklist.got("id", "请输入一个需解除封禁的qq用户id", parameterless=[Depends(parse_int("id"))])
async def _(id: Union[int, str, Message] = Arg()):
    if isinstance(id, Message):
        id = id.extract_plain_text()
    if isinstance(id, str):
        if id.isdigit():
            id = int(id)
        else:
            await add_blacklist.reject("ERROR：qq用户id非正确格式")
            logger.opt(colors=True).error("<y>qq用户id非正确格式</y>")
    try:
        query = "DELETE FROM BLACKLIST WHERE ID = :ID"
        values = {"ID": id}
        await export.sqlite_pool.execute(query=query, values=values)
    except IntegrityError:
        traceback.print_exc()
        logger.opt(colors=True).error("<y>此用户未被封禁</y>")
        await add_blacklist.finish("ERROR: 此用户未被封禁")
    except:
        logger.opt(colors=True).error("<y>数据库出现问题</y>")
        await add_blacklist.finish("ERROR: 数据库出现问题")
    await del_blacklist.send("用户" + str(id) + "已被解除封禁")
    await b.fresh()

show_blacklist = on_command(cmd="show_blacklist", rule=to_me(), permission=SUPERUSER, priority=10, block=True)

@show_blacklist.handle()
async def _():
    msg = ''
    for user in b.data:
        msg += str(user)+'\n'
    await show_blacklist.finish(message=msg)


import argparse
import random
import os
from tkinter import *
import tkinter as tk
from PIL import Image, ImageTk
import tkinter.filedialog

seq = [ 1, 2, 3, 4, 5, 6, 7, 8, 9]
mask= [ 1 ,   3,    5,    7,    9]

def binary_convert(n):
	binary_1=1
	binary = [x for x in seq if (n>>(x-1))&binary_1 ]
	return binary

def get_random(list, n):
	#random.seed('DIP')
	ran = random.sample(list, n)
	return ran

def setk(k):
	if k == 1:
		return 0, 0
	if k == 2:
		return 1, 0
	if k == 3:
		return 2, 0
	if k == 4:
		return 0, 1
	if k == 5:
		return 1, 1
	if k == 6:
		return 2, 1
	if k == 7:
		return 0, 2
	if k == 8:
		return 1, 2
	if k == 9:
		return 2, 2

if __name__ == '__main__':
        class Application(tk.Frame):
                def __init__(self, master):
                        self.master = master
                        self.initWidgets()

                def initWidgets(self):
                        self.master.FM1 = Frame(self.master)
                        self.master.FM1.pack(side=LEFT, fill=BOTH, expand=YES)
                        self.master.FM1.fm11 = Frame(self.master.FM1)
                        self.master.FM1.fm11.pack(side=TOP, fill=BOTH, expand=YES)
                        self.master.FM1.fm11.secretname = Label(self.master.FM1.fm11, text="機密圖")
                        self.master.FM1.fm11.secretname.pack(side=LEFT)
                        self.master.FM1.fm11.path = Label(self.master.FM1.fm11)
                        self.master.FM1.fm11.choosebutton = Button(self.master.FM1.fm11, text="選擇檔案", command=self.choose_secret)
                        self.master.FM1.fm11.choosebutton.pack(side=RIGHT)

                        self.master.FM1.fm12 = Frame(self.master.FM1)
                        self.master.FM1.fm12.pack(side=TOP, fill=BOTH, expand=YES)
                        self.master.FM1.fm12.imagelabel = Label(self.master.FM1.fm12)
                        self.master.FM1.fm12.imagelabel.pack(side=LEFT)

                        self.master.FM1.fm13 = Frame(self.master.FM1)
                        self.master.FM1.fm13.pack(side=TOP, fill=BOTH, expand=YES)
                        self.master.FM1.fm13.text = Label(self.master.FM1.fm13, text = "機密圖為須透過解密才能得到的隱藏圖")
                        self.master.FM1.fm13.text.pack(side=TOP)

                        self.master.FM1.fm15 = Frame(self.master.FM1)
                        self.master.FM1.fm15.pack(side=TOP, fill=BOTH, expand=YES)
                        self.master.FM1.fm15.text = Label(self.master.FM1.fm15, text = "機密圖和兩張偽裝圖的長寬皆須相同")
                        self.master.FM1.fm15.text.pack(side=TOP)

                        self.master.FM1.fm14 = Frame(self.master.FM1)
                        self.master.FM1.fm14.pack(side=TOP, fill=BOTH, expand=YES)
                        self.master.FM1.fm14.button = Button(self.master.FM1.fm14, text="生成分享圖", command=self.make_output)
                        self.master.FM1.fm14.button.pack(side=RIGHT)

                        self.master.FM2 = Frame(self.master)
                        self.master.FM2.pack(side=LEFT, fill=BOTH, expand=YES)
                        self.master.FM2.fm21 = Frame(self.master.FM2)
                        self.master.FM2.fm21.pack(side = TOP, fill=BOTH, expand=YES)
                        self.master.FM2.fm21.fakename_1 = Label(self.master.FM2.fm21, text = "偽裝圖1")
                        self.master.FM2.fm21.fakename_1.pack(side=LEFT)
                        self.master.FM2.fm21.path = Label(self.master.FM2.fm21)
                        self.master.FM2.fm21.choosebutton = Button(self.master.FM2.fm21, text="選擇檔案", command=self.choose_fake1)
                        self.master.FM2.fm21.choosebutton.pack(side=RIGHT)

                        self.master.FM2.fm22 = Frame(self.master.FM2)
                        self.master.FM2.fm22.pack(side=TOP, fill=BOTH, expand=YES)
                        self.master.FM2.fm22.imagelabel = Label(self.master.FM2.fm22)
                        self.master.FM2.fm22.imagelabel.pack(side=LEFT)

                        self.master.FM2.fm23 = Frame(self.master.FM2)
                        self.master.FM2.fm23.pack(side=TOP, fill=BOTH, expand=YES)
                        self.master.FM2.fm23.fakename_2 = Label(self.master.FM2.fm23, text = "偽裝圖2")
                        self.master.FM2.fm23.fakename_2.pack(side = LEFT)
                        self.master.FM2.fm23.path = Label(self.master.FM2.fm23)
                        self.master.FM2.fm23.choosebutton = Button(self.master.FM2.fm23, text="選擇檔案", command=self.choose_fake2)
                        self.master.FM2.fm23.choosebutton.pack(side=RIGHT)

                        self.master.FM2.fm24 = Frame(self.master.FM2)
                        self.master.FM2.fm24.pack(side=TOP, fill=BOTH, expand=YES)
                        self.master.FM2.fm24.imagelabel = Label(self.master.FM2.fm24)
                        self.master.FM2.fm24.imagelabel.pack(side=LEFT)

                        self.master.FM3 = Frame(self.master)
                        self.master.FM3.pack(side=LEFT, fill=BOTH, expand=YES)
                        self.master.FM3.fm31 = Frame(self.master.FM3)
                        self.master.FM3.fm31.pack(side=TOP, fill=BOTH, expand=YES)
                        self.master.FM3.fm31.sharename_1 = Label(self.master.FM3.fm31, text = "分享圖1")
                        self.master.FM3.fm31.sharename_1.pack(side=LEFT)
                        self.master.FM3.fm31.save = Button(self.master.FM3.fm31, text="儲存分享圖1", command=self.save_1)
                        self.master.FM3.fm31.save.pack(side=RIGHT)

                        self.master.FM3.fm32 = Frame(self.master.FM3)
                        self.master.FM3.fm32.pack(side=TOP, fill=BOTH, expand=YES)
                        self.master.FM3.fm32.imagelabel = Label(self.master.FM3.fm32)
                        self.master.FM3.fm32.imagelabel.pack(side=LEFT)

                        self.master.FM3.fm33 = Frame(self.master.FM3)
                        self.master.FM3.fm33.pack(side=TOP, fill=BOTH, expand=YES)
                        self.master.FM3.fm33.sharename_2 = Label(self.master.FM3.fm33, text = "分享圖2")
                        self.master.FM3.fm33.sharename_2.pack(side=LEFT)
                        self.master.FM3.fm33.save = Button(self.master.FM3.fm33, text="儲存分享圖2", command=self.save_2)
                        self.master.FM3.fm33.save.pack(side=RIGHT)

                        self.master.FM3.fm34 = Frame(self.master.FM3)
                        self.master.FM3.fm34.pack(side=TOP, fill=BOTH, expand=YES)
                        self.master.FM3.fm34.imagelabel = Label(self.master.FM3.fm34)
                        self.master.FM3.fm34.imagelabel.pack(side=LEFT)

                def choose_secret(self):
                        default_dir = r"\Users\scl971009\Desktop\desktop\DIP\final project\DIP-final---visual-cryptography"
                        fname = tkinter.filedialog.askopenfilename(title=u"", initialdir=(os.path.expanduser(default_dir)))
                        self.master.FM1.fm11.path.configure(text=fname)
                        self.master.FM1.fm11.path.text=fname
                        img = Image.open(fname)
                        width, height = img.size
                        img = img.convert("RGB")
                        resized = img.resize((320, 320*height//width), Image.ANTIALIAS)
                        imgr = ImageTk.PhotoImage(resized)
                        self.master.FM1.fm12.imagelabel.configure(image = imgr)
                        self.master.FM1.fm12.imagelabel.image = imgr

                def choose_fake1(self):
                        default_dir = r"\Users\scl971009\Desktop\desktop\DIP\final project\DIP-final---visual-cryptography"
                        fname = tkinter.filedialog.askopenfilename(title=u"", initialdir=(os.path.expanduser(default_dir)))
                        self.master.FM2.fm21.path.configure(text=fname)
                        self.master.FM2.fm21.path.text=fname
                        img = Image.open(fname)
                        width, height = img.size
                        img = img.convert("RGB")
                        resized = img.resize((320, 320*height//width), Image.ANTIALIAS)
                        imgr = ImageTk.PhotoImage(resized)
                        self.master.FM2.fm22.imagelabel.configure(image = imgr)
                        self.master.FM2.fm22.imagelabel.image = imgr

                def choose_fake2(self):
                        default_dir = r"\Users\scl971009\Desktop\desktop\DIP\final project\DIP-final---visual-cryptography"
                        fname = tkinter.filedialog.askopenfilename(title=u"", initialdir=(os.path.expanduser(default_dir)))
                        self.master.FM2.fm23.path.configure(text=fname)
                        self.master.FM2.fm23.path.text=fname
                        img = Image.open(fname)
                        width, height = img.size
                        img = img.convert("RGB")
                        resized = img.resize((320, 320*height//width), Image.ANTIALIAS)
                        imgr = ImageTk.PhotoImage(resized)
                        self.master.FM2.fm24.imagelabel.configure(image = imgr)
                        self.master.FM2.fm24.imagelabel.image = imgr

                def make_output(self):
                        original_share1 = Image.open(self.master.FM2.fm21.path.text)
                        original_share1 = original_share1.convert("RGB")
                        original_s1_pixels = original_share1.load()

                        original_share2 = Image.open(self.master.FM2.fm23.path.text)
                        original_share2 = original_share2.convert("RGB")
                        original_s2_pixels = original_share2.load()

                        secret = Image.open(self.master.FM1.fm11.path.text)
                        secret = secret.convert("RGB")
                        se_pixels = secret.load()

                        share1 = Image.new("RGB", (original_share1.size[0] * 3, original_share1.size[1] * 3))
                        s1_pixels = share1.load()

                        share2 = Image.new("RGB", (original_share2.size[0] * 3, original_share2.size[1] * 3))
                        s2_pixels = share2.load()

                        for i in range(original_share1.size[0]):
                                for j in range(original_share1.size[1]):
                                        s1=[0, 0, 0]
                                        s2=[0, 0, 0]
                                        list1=[[], [], []]
                                        list2=[[], [], []]
                                        for r in range(3):
                                                s=binary_convert(se_pixels[i, j][r])
                                                s_inv=[x for x in seq if ((x not in s) and (x != 9))]
                                                if len(s_inv)/2 >= 1:
                                                        list1[r]=get_random(s_inv, int(len(s_inv)/2))
                                                list2[r]=[x for x in s_inv if x not in list1[r]]
                                                for x in s:
                                                        list1[r].append(x)
                                                        list2[r].append(x)

                                        for k in seq:
                                                m,n=setk(k)
					#print(se_pixels[i,j][r],s)
				#v=get_random(randomseq,1)

                                                for r in range(3):
                                                        if k in list1[r]:
                                                                s1[r] = original_s1_pixels[i,j][r]
                                                        else :
                                                                s1[r] = original_s1_pixels[i,j][r]-1
                                                                if s1[r]<0:
                                                                        s1[r]=2
                                                        if k in list2[r]:
                                                                s2[r] = original_s2_pixels[i,j][r]
                                                        else :
                                                                s2[r] = original_s2_pixels[i,j][r]-1
                                                                if s2[r]<0:
                                                                        s2[r]=2

                                                s1_pixels[ i*3 + m , j*3 + n ]=(s1[0],s1[1],s1[2])
                                                s2_pixels[ i*3 + m , j*3 + n ]=(s2[0],s2[1],s2[2])

                        self.master.FM2.fm22.image = share1
                        self.master.FM3.fm32.image = share2
                        width, height = original_share1.size
                        height = 320*height//width
                        width1, height1 = share1.size
                        resized1 = share1.resize((height*width1//height1, height),Image.ANTIALIAS)
                        imgr1 = ImageTk.PhotoImage(resized1)
                        self.master.FM3.fm32.imagelabel.configure(image=imgr1)
                        self.master.FM3.fm32.imagelabel.image=imgr1
                        width2, height2 = share2.size
                        resized2 = share2.resize((height*width1//height1, height),Image.ANTIALIAS)
                        imgr2 = ImageTk.PhotoImage(resized2)
                        self.master.FM3.fm34.imagelabel.configure(image=imgr2)
                        self.master.FM3.fm34.imagelabel.image=imgr2

                def save_1(self):
                        image = self.master.FM2.fm22.image
                        default_dir = r"\Users\scl971009\Desktop\desktop\DIP\final project\DIP-final---visual-cryptography"
                        toSave = tkinter.filedialog.asksaveasfile(mode='wb',defaultextension='.png')
                        image.save(toSave)

                def save_2(self):
                        image = self.master.FM3.fm32.image
                        default_dir = r"\Users\scl971009\Desktop\desktop\DIP\final project\DIP-final---visual-cryptography"
                        toSave = tkinter.filedialog.asksaveasfile(mode='wb',defaultextension='.png')
                        image.save(toSave)

        root = tk.Tk()
        root.title("加密3")
        app = Application(root)
        root.mainloop()


import os
import time
def main():
    while True:
        try:
            command=input("What app do you want to open? ")
            time.sleep(1)
            os.startfile(command)
        except:
            print("You entered the app's name incorrectly.")
            break
        answer = input("Do you want to set a time limit? ")
        if answer=="yes".lower():
            time_limit=int(input("How many minutes do you want to spend on your app? "))
            time.sleep(time_limit*60)
            os.system("taskkill/im "+command+ ".exe")
            break
        elif answer=="no".lower():
            print("Have fun!")
            break
        else:
            print("Wrong input!")
            break
main()


def run():
    number: int = int(input())
    # arr = {}
    arr = [list(map(int, input().split())) for i in range(number)]
    # arr = {i: list(map(int, input().split())) for i in range(number)}
    # arr = dict(sorted(arr.items(), key=lambda x: x[1][1], reverse=1))
    arr = list(sorted(arr, key=lambda x: x[1], reverse=1))
    arr1 = [0 for i in range(number)]
    tantrum = 0
    for i, j in enumerate(arr):
        aux = False
        if(arr1[int(j[0]/10)] == 0):
            arr1[int(j[0]/10)] = j
            aux = True
        else:
            n = (int(j[0]/10))-1
            while(n >= 0):
                if(arr1[n] == 0):
                    arr1[n] = j
                    aux = True
                    break
                n -= 1
        if aux == False:
            arr1.insert(number-1, j)
            tantrum += j[1]

    print(tantrum)

if __name__ == '__main__':
    iter = int(input())
    for i in range(iter):
        run()


def order():
    my_menu ={"wings": 0,"cookies": 0,"spring rolls": 0,"salmon": 0,"steak": 0,"meat tornado": 0,"a literal garden": 0,
    "ice cream": 0,"cake": 0,"pie": 0,
        "coffee": 0,"tea": 0,"unicorn tears": 0
    }
    res = input("> if you want to order type any things or \"quit\" to exit ")
    final_order = {}
    count_of_order = 0
    while res != "quit":
        order = input("> ").lower()

        if order == "quit":
            print("Your order contains")
            for key, value in final_order.items():
                print(key, ' : ', value+1)
            print("thank you and Good Bye")
            break
        if order in  my_menu:
            final_order.update({f"{order}": my_menu[order]})
            new_order = order
            count_of_order +=1
            my_menu[order] +=1
            print(f"{my_menu[order]} of {new_order} have been added yo your meal ")
        else :
            print("This dish is not in the menu")

print("****************************************")
print("**     welcome to the Sankes Cafe!    **")
print("**     Please see our menu below.     **")
print("** ")
print("** To quit at any time, type \"quit\"  **")
print("****************************************")
format_menu= """Appetizers
----------
Wings
Cookies
Spring Rolls

Entrees
-------
Salmon
Steak
Meat Tornado
A Literal Garden

Desserts
--------
Ice Cream
Cake
Pie

Drinks
------
Coffee
Tea
Unicorn Tears
***********************************
** What would you like to order? **
***********************************
"""
print(format_menu)
order()


import os
import random as rnd

from PIL import Image, ImageFilter, ImageStat
import numpy as np
from pandas import array
from engine import distorsion_generator
import cv2
def getbackgroundImage(foreground, backgroundList):

    backgroundFile = rnd.choice(backgroundList)
    background = Image.open(backgroundFile)
    if foreground.mode != background.mode:
        foreground = foreground.convert(background.mode)
    fwidth,fheight = foreground.size
    bwidth,bheight = background.size
    if bwidth>fwidth and bheight>fheight:
        top = rnd.randint(0,bheight-fheight)
        left = rnd.randint(0,bwidth-fwidth)
        background = background.crop((left, top, left+fwidth, top+fheight))
    else:
        background = background.resize(foreground.size)
    return background

class FakeformularDataGenerator(object):
    @classmethod
    def generate_from_tuple(cls, t):
        """
            Same as generate, but takes all parameters as one tuple
        """

        cls.generate(*t)

    @classmethod
    def generate(
        cls, foreImage, backgroundList,
        skewing_angle,
        random_skew, blur,random_blur, distorsion_type,
        distorsion_orientation, margins,
        image_mode="RGB",
    ):
        image = None

        margin_top, margin_left, margin_bottom, margin_right = margins
        horizontal_margin = margin_left + margin_right
        vertical_margin = margin_top + margin_bottom

        ##########################S
        # get foreground image #
        ##########################
        image = cv2.imread(foreImage)
        mask = 255-image
        mask = np.where(mask>175,255,0)
        mask = Image.fromarray(mask.astype(np.uint8))
        image = Image.fromarray(image)

        random_angle = rnd.randint(0 - skewing_angle, skewing_angle)

        rotated_img = image.rotate(
            skewing_angle if not random_skew else random_angle, expand=1
        )
        rotated_mask = mask.rotate(
            skewing_angle if not random_skew else random_angle, expand=1
        )

        #############################
        # Apply distorsion to image #
        #############################
        if distorsion_type == 0:
            distorted_img = rotated_img  # Mind = blown
            distorted_mask = rotated_mask
        elif distorsion_type == 1:
            distorted_img, distorted_mask = distorsion_generator.sin(
                rotated_img,
                rotated_mask,
                vertical=(distorsion_orientation == 0 or distorsion_orientation == 2),
                horizontal=(distorsion_orientation == 1 or distorsion_orientation == 2),
            )
        elif distorsion_type == 2:
            distorted_img, distorted_mask = distorsion_generator.cos(
                rotated_img,
                rotated_mask,
                vertical=(distorsion_orientation == 0 or distorsion_orientation == 2),
                horizontal=(distorsion_orientation == 1 or distorsion_orientation == 2),
            )
        else:
            distorted_img, distorted_mask = distorsion_generator.random(
                rotated_img,
                rotated_mask,
                vertical=(distorsion_orientation == 0 or distorsion_orientation == 2),
                horizontal=(distorsion_orientation == 1 or distorsion_orientation == 2),
            )

        #############################
        # Generate background image #
        #############################

        background_img =getbackgroundImage(
                distorted_img, backgroundList
            )

        #############################
        # Place text with alignment #
        #############################

        new_text_width, _ = distorted_img.size

        background_img.paste(distorted_img, (margin_left, margin_top), distorted_mask.convert("L"))
        #background_img.paste(image, (margin_left, margin_top), mask.convert("L"))

        #######################
        # Apply gaussian blur #
        #######################

        gaussian_filter = ImageFilter.GaussianBlur(
            radius=blur if not random_blur else rnd.randint(0, blur)
        )
        final_image = background_img.filter(gaussian_filter)

        ############################################
        # Change image mode (RGB, grayscale, etc.) #
        ############################################

        final_image = final_image.convert(image_mode)

        return final_image


from config.db import db

class Confgiuration():

    def __init__(self, likeCount, retweetCount, viewCount, inKeywords, outKeywords, user):
        self.likeCount = likeCount
        self.retweetCount = retweetCount
        self.viewCount = viewCount
        self.inKeywords = inKeywords
        self.outKeywords = outKeywords
        self.user = user

    def __str__(self):
        return f" >>>  Confgiuration({self.likeCount},{self.retweetCount})"

    def __repr__(self):
        rep = 'Confgiuration(' + self.likeCount + ',' + \
            str(self.retweetCount) + ')'
        return rep

    def serialize(self):
        return {
            '_id': str(self._id),
            'likeCount': self.likeCount,
            'retweetCount': self.retweetCount,
            'viewCount': self.viewCount,
            'inKeywords': self.inKeywords,
            'outKeywords': self.outKeywords,
            'user': self.user,

        }

    def toDictionary(self):
        return {
            'likeCount': self.likeCount,
            'retweetCount': self.retweetCount,
            'viewCount': self.viewCount,
            'inKeywords': self.inKeywords,
            'outKeywords': self.outKeywords,
            'user': self.user,

        }


from web3 import Web3
import os

# Networks setup
web3_local_rinkeby = Web3(Web3.HTTPProvider('http://127.0.0.1:8888'))
web3_arbitrum_rinkeby = Web3(Web3.HTTPProvider('https://rinkeby.arbitrum.io/rpc'))

# Arbitrum TheLootBox contract setup
addr_lootbox_arbitrum = os.environ.get("TEST_NET_ARBITRUM_LOOTBOX")
addr_lootbox_arbitrum_abi = os.environ.get("TEST_NET_ARBITRUM_LOOTBOX_ABI")
addr_lootbox_factory_rinkeby = os.environ.get("LOOTBOX_FACTORY_CONTRACT_RINKEBY")
addr_lootbox_factory_rinkeby_abi = os.environ.get("TEST_NET_RINKEBY_LOOTBOX_FACTORY_ABI")
lootbox_contract_arbitrum = web3_arbitrum_rinkeby.eth.contract(address=addr_lootbox_arbitrum,
                                                               abi=addr_lootbox_arbitrum_abi)
lootbox_contract_rinkeby = web3_local_rinkeby.eth.contract(address=addr_lootbox_factory_rinkeby,
                                                           abi=addr_lootbox_factory_rinkeby_abi)

# TheLootBox bundle contract setup
addr_lootbox_bundle_arbitrum = os.environ.get("TEST_NET_ARBITRUM_LOOTBOX_BUNDLE_CONTRACT")
addr_lootbox_arbitrum_abi_v2 = os.environ.get("TEST_NET_ARBITRUM_LOOTBOX_ABI_V2")
lootbox_contract_arbitrum_bundle = web3_arbitrum_rinkeby.eth.contract(address=addr_lootbox_bundle_arbitrum,
                                                                      abi=addr_lootbox_arbitrum_abi_v2)

# DAI contract setup
dai_abi = os.environ.get("DAI_ABI")
addr_dai = os.environ.get("DAI_ADDR")
dai_contract_rinkeby = web3_local_rinkeby.eth.contract(address=addr_dai, abi=dai_abi)

# Dev setup
dev = os.environ.get("DEV")
key = os.environ.get('ARBITRUM_PRIVATE_KEY')
gas_price = web3_arbitrum_rinkeby.eth.gasPrice


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

# # Ans 1.

# In[16]:

def getrange(fibfun):
    def fibseries():
        print("Enter the range of Fibonacci Series")
        end = int(input("Enter ending no: "))
        fibfun(end)
    return fibseries

# In[17]:

@getrange
def fibonacciSeries(ending):
    starting = 0
    num = 0
    first = 1
    for i in range(ending):
        print("Fibonacci Series :", num)
        starting = first
        first = num
        num = starting + first

# In[18]:

fibonacciSeries()

# # Ans 2)

# In[60]:

file = open("Day8-AA","w")
file.write("Hey there!, How are you")
file.close()

# In[61]:

file = open("Day8-AA","r")
fileData = file.read()
print(fileData)
file.close()

# In[62]:

file = open("Day8-AA","a")
file.write("?")
file.close()

# In[63]:

file = open("Day8-AA","r")
fileData = file.read()
print(fileData)
file.close()

# In[64]:

file = open("Day8-AA", "r")
try :
    file.write("I am fine thankyou")
except :
    print("File is opened in read only mode, not writable!!!")
fileData = file.read()
print(fileData)
file.close()

# In[ ]:


import numpy as np

def printt(patch):
    for row in patch:
        s=""
        for col in row:
            if col:
                s+='#'
            else:
                s+='.'
        print(s)
    print()

def GetInput(filename):
    arr1=[]
    arr2=[]
    mode='start'
    with open(filename) as f:
        lines = f.readlines()
    for line in lines:
        if line=='\n':
            mode='end'
            continue
        line=line.strip()
        if mode=='start':
            for ch in line:
                if ch=='.':
                    arr1.append(0)
                else:
                    arr1.append(1)
        else:
            tmp=[]
            for ch in line:
                if ch=='.':
                    tmp.append(0)
                else:
                    tmp.append(1)
            arr2.append(tmp)
    return np.array(arr1).astype(np.int32), np.array(arr2).astype(np.int32)

def pad_with(vector, pad_width, iaxis, kwargs):
    pad_value = kwargs.get('padder', 10)
    vector[:pad_width[0]] = pad_value
    vector[-pad_width[1]:] = pad_value

import copy
def ApplyConvolution(patch,iecode,padval):
    patch=np.pad(patch,3,pad_with,padder=padval)
    #printt(patch)
    target=copy.deepcopy(patch)
    m=patch.shape[0]
    n=patch.shape[1]
    for row in np.arange(1,m-1,1):
        for col in np.arange(1,n-1,1):
            if row==4 and col==4:
                k=0
            string=""
            string+=str(patch[row-1][col-1])
            string+=str(patch[row-1][col])
            string+=str(patch[row-1][col+1])
            string+=str(patch[row][col-1])
            string+=str(patch[row][col])
            string+=str(patch[row][col+1])
            string+=str(patch[row+1][col-1])
            string+=str(patch[row+1][col])
            string+=str(patch[row+1][col+1])
            index=int(string,2)
            target[row][col]=iecode[index]
    if True:#padval==0:
        k=2
        return target[k:-k,k:-k]
    else:
        return target

steps=50
iecode, patch = GetInput("input20.txt")
patch=np.pad(patch,3,pad_with,padder=0)

#printt(patch)
for i in range(steps):
    print('step ',i+1)
    padval=0
    if (i%2!=0) and iecode[0]==1 and iecode[-1]==0:
        padval=1
    patch = ApplyConvolution(patch,iecode,padval)
    #printt(patch)
print(patch.sum())