from flask import Flask
from configuration import Configuration
from models import db, Product, ProductCategory, Category, Order, Request
from redis import Redis
from flask_jwt_extended import JWTManager
from sqlalchemy import asc, func

app = Flask(__name__)
app.config.from_object(Configuration)
jwt = JWTManager(app)

def main():
    while True:
        try:
            with Redis(host=Configuration.REDIS_HOST) as redis:
                while True:
                    podaci = redis.blpop(Configuration.REDIS_PRODUCTS_LIST)[1].decode().split(",")
                    kategorije = podaci[0].split("|")
                    ime = podaci[1]
                    kolicina = int(podaci[2])
                    cena = float(podaci[3])

                    # print(str(podaci))
                    with app.app_context():
                        proizvod = Product.query.filter(Product.name == ime).first()
                        if(proizvod):
                            postojece = ProductCategory.query.join(Category).with_entities(Category.name).filter(ProductCategory.productId == proizvod.id).all()
                            postojece = [p[0] for p in postojece]
                            if(set(kategorije) == set(postojece)):
                                proizvod.price = (proizvod.price*proizvod.amount + cena*kolicina)/(proizvod.amount + kolicina)
                                proizvod.amount += kolicina

                                db.session.commit()
                                ordIds = Order.query.join(Request).with_entities(Order.id, Request.id).filter(
                                    Order.status == "PENDING",
                                    Request.productId == proizvod.id,
                                    Request.received < Request.requested
                                ).group_by(Order.id, Request.id).order_by(asc(Order.id)).all()
                                for o in ordIds:
                                    order = Order.query.filter(Order.id == o[0]).first()
                                    req = Request.query.filter(Request.id == o[1]).first()
                                    num = Request.query.with_entities(func.count("*")).filter(
                                        Request.orderId == order.id,
                                        Request.received < Request.requested
                                    ).all()

                                    cnt = req.requested - req.received
                                    if (cnt <= proizvod.amount):
                                        proizvod.amount -= cnt
                                        req.received += cnt
                                        if (num[0][0] == 1):
                                            order.status = "COMPLETE"
                                    else:
                                        req.received += proizvod.amount
                                        proizvod.amount = 0
                                    db.session.commit()
                                    if (proizvod.amount == 0):
                                        break
                            else:
                                continue
                        else:
                            noviProizvod = Product(name=ime, price=cena, amount=kolicina)
                            db.session.add(noviProizvod)
                            db.session.commit()

                            for kat in kategorije:
                                novaKategorija = Category.query.filter(Category.name == kat).first()
                                if(not novaKategorija):
                                    novaKategorija = Category(name=kat)
                                    db.session.add(novaKategorija)
                                    db.session.commit()

                                noviLink = ProductCategory(productId=noviProizvod.id, categoryId=novaKategorija.id)
                                db.session.add(noviLink)
                                db.session.commit()
        except Exception as error:
            print(error, flush=True)

if(__name__ == "__main__"):
    db.init_app(app)
    main()


from flask import Flask
from flask_restful import Api

from rest_api.resources.meeting import MeetingV1
from rest_api.db import db

app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
app.config['PROPOGATE_EXCEPTIONS'] = True
app.secret_key = 'indypy_secret'   # This should not be defined in the file and kept secret for a real site

api = Api(app)

@app.before_first_request
def create_tables():
    db.create_all()

api.add_resource(MeetingV1, '/api/v1/meetings', '/api/v1/meetings/<string:meeting_date>')


"""Handler for mediate-grant message."""

from .....messaging.base_handler import BaseHandler, HandlerException
from .....messaging.request_context import RequestContext
from .....messaging.responder import BaseResponder
from .....multitenant.base import BaseMultitenantManager
from .....storage.error import StorageNotFoundError

from ..manager import MediationManager
from ..messages.mediate_grant import MediationGrant
from ..models.mediation_record import MediationRecord

class MediationGrantHandler(BaseHandler):
    """Handler for mediate-grant message."""

    async def handle(self, context: RequestContext, responder: BaseResponder):
        """Handle mediate-grant message."""
        self._logger.debug(
            "%s called with context %s", self.__class__.__name__, context
        )
        assert isinstance(context.message, MediationGrant)

        if not context.connection_ready:
            raise HandlerException("Received mediation grant from inactive connection")

        profile = context.profile
        mgr = MediationManager(profile)
        try:
            async with profile.session() as session:
                record = await MediationRecord.retrieve_by_connection_id(
                    session, context.connection_record.connection_id
                )
            await mgr.request_granted(record, context.message)

            # Multitenancy setup
            multitenant_mgr = profile.inject_or(BaseMultitenantManager)
            wallet_id = profile.settings.get("wallet.id")

            if multitenant_mgr and wallet_id:
                base_mediation_record = await multitenant_mgr.get_default_mediator()

                # If we have a base mediator and sub wallet mediator
                # we need to register the base mediator routing key at the
                # sub wallet mediator
                if base_mediation_record:
                    # Last routing key needs to be registered at the mediator
                    keylist_updates = await mgr.add_key(
                        base_mediation_record.routing_keys[-1]
                    )

                    await responder.send(
                        keylist_updates,
                        connection_id=context.connection_record.connection_id,
                    )

            # Set to default if metadata set on connection to do so
            async with profile.session() as session:
                mediationRecord = await context.connection_record.metadata_get(
                    session, MediationManager.SET_TO_DEFAULT_ON_GRANTED
                )

            if mediationRecord:
                await mgr.set_default_mediator(record)

        except StorageNotFoundError as err:
            raise HandlerException(
                "Received mediation grant from connection from which mediation "
                "has not been requested."
            ) from err


from db import db
import datetime

class LabModel(db.Model):
    __tablename__ = 'labs'

    id = db.Column(db.Integer, autoincrement=True)
    name = db.Column(db.String(80), primary_key=True)
    full_name = db.Column(db.String(80))
    address_1 = db.Column(db.String(80))
    address_2 = db.Column(db.String(80))
    phone_no = db.Column(db.String(12))
    fax = db.Column(db.String(80))
    website = db.Column(db.String(80))
    CLIA = db.Column(db.String(80))
    director_name = db.Column(db.String(80))
    logo = db.Column(db.String(80))
    supervisor_name = db.Column(db.String(80))
    approved_by = db.Column(db.String(80))
    email = db.Column(db.String(80))
    created_at = db.Column(db.DateTime, default=datetime.datetime.utcnow)

    def __init__(self, name, full_name, address1, address2, phone_no,
                 fax, email, website, CLIA, director_name, logo,
                 approved_by, supervisor_name
                ):
        self.name = name
        self.full_name = full_name
        self.address_1 = address1
        self.address_2 = address2
        self.phone_no = phone_no
        self.fax = fax
        self.website = website
        self.CLIA = CLIA
        self.director_name = director_name
        self.logo = logo
        self.supervisor_name = supervisor_name
        self.approved_by = approved_by
        self.email = email

    def json(self):
        return {"id": self.id,
                "name": self.name,
                "full_name": self.full_name,
                "address1": self.address_1,
                "address2": self.address_2,
                "phone_no": self.phone_no,
                "fax": self.fax,
                "CLIA": self.CLIA,
                "director_name": self.director_name,
                "log": self.logo,
                "supervisor_name": self.supervisor_name,
                "approved_by": self.approved_by,
                "email": self.email,
                "website": self.website,
                "created_at": self.created_at.strftime("%Y/%m/%d %H:%M:%S")
                }

    @classmethod
    def find_by_labname(cls, lab_name):
        return cls.query.filter_by(name=lab_name).first() # SELECT * FROM items WHERE name=name LIMIT 1

    @classmethod
    def find_by_labname_and_id(cls, lab_id, name):
        return cls.query.filter_by(id=lab_id, name=name).first()

    def save_to_db(self): # It can handle update and insert into the database
        db.session.add(self)
        db.session.commit()

    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()

    @classmethod
    def get_all_labs(cls):
        return [x.json() for x in cls.query.order_by(cls.created_at.desc()).all()]


import cupy as cp
import numpy as np
import string

from .fusion_manager import FusionBase

def add_color_kernel(
    width, height,
):
    add_color_kernel = cp.ElementwiseKernel(
        in_params="raw T p, raw U R, raw U t, raw W pcl_chan, raw W map_lay, raw W pcl_channels",
        out_params="raw V color_map",
        preamble=string.Template(
            """
            __device__ int get_map_idx(int idx, int layer_n) {
                const int layer = ${width} * ${height};
                return layer * layer_n + idx;
            }
            __device__ unsigned int get_r(unsigned int color){
                unsigned int red = 0xFF0000;
                unsigned int reds = (color & red) >> 16;
                return reds;
            }
            __device__ unsigned int get_g(unsigned int color){
                unsigned int green = 0xFF00;
                unsigned int greens = (color & green) >> 8;
                return greens;
            }
            __device__ unsigned int get_b(unsigned int color){
                unsigned int blue = 0xFF;
                unsigned int blues = ( color & blue);
                return blues;
            }
            """
        ).substitute(width=width, height=height),
        operation=string.Template(
            """
            U id = floorf(i/pcl_channels[1]);
            int layer = i % pcl_channels[1];
            U idx = p[id * pcl_channels[0]];
            U valid = p[id * pcl_channels[0] + 1];
            U inside = p[id * pcl_channels[0] + 2];
            if (valid && inside){
                    unsigned int color = __float_as_uint(p[id * pcl_channels[0] + pcl_chan[layer]]);
                    atomicAdd(&color_map[get_map_idx(idx, layer*3)], get_r(color));
                    atomicAdd(&color_map[get_map_idx(idx, layer*3+1)], get_g(color));
                    atomicAdd(&color_map[get_map_idx(idx, layer*3 + 2)], get_b(color));
                    atomicAdd(&color_map[get_map_idx(idx, pcl_channels[1]*3)], 1);
            }
            """
        ).substitute(width=width),
        name="add_color_kernel",
    )
    return add_color_kernel

def color_average_kernel(
    width, height,
):
    color_average_kernel = cp.ElementwiseKernel(
        in_params="raw V color_map, raw W pcl_chan, raw W map_lay, raw W pcl_channels",
        out_params="raw U map",
        preamble=string.Template(
            """
            __device__ int get_map_idx(int idx, int layer_n) {
                const int layer = ${width} * ${height};
                return layer * layer_n + idx;
            }
            __device__ unsigned int get_r(unsigned int color){
                unsigned int red = 0xFF0000;
                unsigned int reds = (color & red) >> 16;
                return reds;
            }
            __device__ unsigned int get_g(unsigned int color){
                unsigned int green = 0xFF00;
                unsigned int greens = (color & green) >> 8;
                return greens;
            }
            __device__ unsigned int get_b(unsigned int color){
                unsigned int blue = 0xFF;
                unsigned int blues = (color & blue);
                return blues;
            }
            """
        ).substitute(width=width, height=height),
        operation=string.Template(
            """
            U id = floorf(i/pcl_channels[1]);
            int layer = i % pcl_channels[1];
            unsigned int cnt = color_map[get_map_idx(id, pcl_channels[1]*3)];
            if (cnt>0){
                    // U prev_color = map[get_map_idx(id, map_lay[layer])];
                    unsigned int r = color_map[get_map_idx(id, layer*3)]/(1*cnt);
                    unsigned int g = color_map[get_map_idx(id, layer*3+1)]/(1*cnt);
                    unsigned int b = color_map[get_map_idx(id, layer*3+2)]/(1*cnt);
                    //if (prev_color>=0){
                    //    unsigned int prev_r = get_r(prev_color);
                    //    unsigned int prev_g = get_g(prev_color);
                    //    unsigned int prev_b = get_b(prev_color);
                    //    unsigned int r = prev_r/2 + color_map[get_map_idx(i, layer*3)]/(2*cnt);
                    //    unsigned int g = prev_g/2 + color_map[get_map_idx(i, layer*3+1)]/(2*cnt);
                    //    unsigned int b = prev_b/2 + color_map[get_map_idx(i, layer*3+2)]/(2*cnt);
                    //}
                    unsigned int rgb = (r<<16) + (g << 8) + b;
                    float rgb_ = __uint_as_float(rgb);
                    map[get_map_idx(id,  map_lay[layer])] = rgb_;
            }
            """
        ).substitute(),
        name="color_average_kernel",
    )
    return color_average_kernel

class Color(FusionBase):
    def __init__(self, params, *args, **kwargs):
        # super().__init__(fusion_params, *args, **kwargs)
        # print("Initialize fusion kernel")
        self.name = "pointcloud_color"
        self.cell_n = params.cell_n
        self.resolution = params.resolution

        self.add_color_kernel = add_color_kernel(params.cell_n, params.cell_n,)
        self.color_average_kernel = color_average_kernel(self.cell_n, self.cell_n)

    def __call__(self, points_all, R, t, pcl_ids, layer_ids, elevation_map, semantic_map, new_map, *args):
        self.color_map = cp.zeros((1 + 3 * layer_ids.shape[0], self.cell_n, self.cell_n), dtype=cp.uint32,)

        points_all = points_all.astype(cp.float32)
        self.add_color_kernel(
            points_all,
            R,
            t,
            pcl_ids,
            layer_ids,
            cp.array([points_all.shape[1], pcl_ids.shape[0]], dtype=cp.int32),
            self.color_map,
            size=(points_all.shape[0]),
        )
        self.color_average_kernel(
            self.color_map,
            pcl_ids,
            layer_ids,
            cp.array([points_all.shape[1], pcl_ids.shape[0]], dtype=cp.int32),
            semantic_map,
            size=(self.cell_n * self.cell_n),
        )


import numpy as np
from pathlib import Path
import pickle
import yaml
import sys
import scipy.optimize as syopt
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
from matplotlib import rcParams

from analysis import stats
from analysis.bootstrap import bootstrap
from analysis.formatting import err_brackets
from analysis import fitfunc as ff

from common import read_pickle
from common import fit_value
from common import fit_value3
from common import read_correlators
from common import read_correlators2
from common import make_matrices
from common import gevp

from params import params

_metadata = {"Author": "Mischa Batelaan", "Creator": __file__}
_colors = [
    "#377eb8",
    "#4daf4a",
    "#f781bf",
    "#a65628",
    "#ff7f00",
    "#984ea3",
    "#999999",
    "#e41a1c",
    "#dede00",
]
_markers = ["s", "o", "^", "*", "v", ">", "<", "s", "s"]
# From the theta tuning:
m_N = 0.4179255
m_S = 0.4641829

def plot_matrix(fitlist, plotdir, name):
    weights = np.array([i["weight"] for i in fitlist])
    x_coord = np.array([i["x"][0] for i in fitlist])
    y_coord = np.array([i["x"][-1] for i in fitlist])

    # print(max(weights))
    argument_w = np.argmax(weights)
    # print(argument_w)

    # print(fitlist[argument_w]["x"][0])
    # print(fitlist[argument_w]["x"][-1])
    # print(fitlist[argument_w]["redchisq"])

    # Find the unique values of tmin and tmax to make a grid showing the reduced chi-squared values.
    unique_x = np.unique(x_coord)
    unique_y = np.unique(y_coord)
    min_x = np.min(x_coord)
    min_y = np.min(y_coord)
    plot_x = np.append(unique_x, unique_x[-1] + 1)
    plot_y = np.append(unique_y, unique_y[-1] + 1)

    # print(f"\n\n{unique_x}")
    # print(f"{min_x}")
    # print(f"{unique_y}")
    # print(f"{min_y}")

    # matrix = np.zeros((len(unique_x), len(unique_y)))
    matrix = np.full((len(unique_x), len(unique_y)), np.nan)
    for i, x in enumerate(x_coord):
        matrix[x - min_x, y_coord[i] - min_y] = fitlist[i]["redchisq"]
    plt.figure(figsize=(5, 4))
    mat = plt.pcolormesh(plot_x, plot_y, matrix.T, cmap="RdBu", vmin=0.0, vmax=2)
    plt.colorbar(mat, label=r"$\chi^2_{\textrm{dof}}$")
    plt.xlabel(r"$t_{\textrm{min}}$")
    plt.ylabel(r"$t_{\textrm{max}}$")
    plt.savefig(plotdir / (f"chisq_matrix_time_" + name + ".pdf"), metadata=_metadata)
    plt.close()

    # matrix = np.zeros((len(unique_x), len(unique_y)))
    matrix = np.full((len(unique_x), len(unique_y)), np.nan)
    for i, x in enumerate(x_coord):
        matrix[x - min_x, y_coord[i] - min_y] = fitlist[i]["weight"]
    plt.figure(figsize=(5, 4))
    mat = plt.pcolormesh(
        plot_x, plot_y, matrix.T, cmap="GnBu" #, vmin=0.0, vmax=np.max(matrix)
    )
    plt.colorbar(mat, label="weight")
    plt.xlabel(r"$t_{\textrm{min}}$")
    plt.ylabel(r"$t_{\textrm{max}}$")
    plt.savefig(plotdir / (f"weights_matrix_time_" + name + ".pdf"), metadata=_metadata)
    plt.close()

    # matrix = np.zeros((len(unique_x), len(unique_y)))
    matrix = np.full((len(unique_x), len(unique_y)), np.nan)
    for i, x in enumerate(x_coord):
        matrix[x - min_x, y_coord[i] - min_y] = np.average(fitlist[i]["param"][:, 1])
    plt.figure(figsize=(5, 4))
    mat = plt.pcolormesh(
        plot_x, plot_y, matrix.T, cmap="GnBu" #, vmin=0.4, vmax=np.max(matrix)
    )
    plt.colorbar(mat, label="energy")
    plt.xlabel(r"$t_{\textrm{min}}$")
    plt.ylabel(r"$t_{\textrm{max}}$")
    plt.savefig(plotdir / (f"energy_matrix_time_" + name + ".pdf"), metadata=_metadata)
    plt.close()
    return

def weighted_avg_1_2_exp(fitlist_1exp, fitlist_2exp, print=False, tmax_choice=None):
    """Take two lists of dictionaries, one for a fit using the one-exponential function and one using a two-exponential function, Return the weighted average of the energies across these fits"""

    if tmax_choice:
        tmax_1exp = np.array([i["x"][-1] for i in fitlist_1exp])
        tmin_1exp = np.array([i["x"][0] for i in fitlist_1exp])
        indices = np.where(tmax_1exp == tmax_choice)
        indices = indices[0][np.where(3 < tmin_1exp[indices])]
        indices = indices[np.where(16 > tmin_1exp[indices])]
        fitlist_1exp = [fitlist_1exp[index] for index in indices]

        if len(fitlist_2exp)>0:
            tmax_2exp = np.array([i["x"][-1] for i in fitlist_2exp])
            tmin_2exp = np.array([i["x"][0] for i in fitlist_2exp])
            indices_2exp = np.where(tmax_2exp == tmax_choice)
            indices_2exp = indices_2exp[0][np.where(tmin_2exp[indices_2exp] < 4)]
            fitlist_2exp = [fitlist_2exp[index] for index in indices_2exp]

    dE_1exp = np.std([i["param"][:, 1] for i in fitlist_1exp], axis=1)
    dof_1exp = np.array([i["dof"] for i in fitlist_1exp])
    chisq_1exp = np.array([i["chisq"] for i in fitlist_1exp])

    if len(fitlist_2exp)>0:
        dE_2exp = np.std([i["param"][:, 1] for i in fitlist_2exp], axis=1)
        dof_2exp = np.array([i["dof"] for i in fitlist_2exp])
        chisq_2exp = np.array([i["chisq"] for i in fitlist_2exp])
        dof_list = np.append(dof_1exp, dof_2exp)
        chisq_list = np.append(chisq_1exp, chisq_2exp)
        dE_list = np.append(dE_1exp, dE_2exp)
        energies_comb = np.append(
            np.array([i["param"][:, 1] for i in fitlist_1exp]),
            np.array([i["param"][:, 1] for i in fitlist_2exp]),
            axis=0,
        )

    else:
        dof_list = dof_1exp
        chisq_list = chisq_1exp
        dE_list = dE_1exp
        energies_comb = np.array([i["param"][:, 1] for i in fitlist_1exp])

    fitweights = np.array(
        stats.fitweights(
            dof_list,
            chisq_list,
            dE_list,
        )
    )

    weighted_energy = np.dot(fitweights, energies_comb)

    # Rescale the bootstrap error to include the systematic error
    E_avg = np.average(weighted_energy)
    E_staterr = np.std(weighted_energy)
    E_systerr = np.sqrt(
        np.dot(
            fitweights,
            np.array([(E_avg - np.average(energy)) ** 2 for energy in energies_comb]),
        )
    )
    E_comberr = np.sqrt(E_staterr**2 + E_systerr**2)
    for ival, value in enumerate(weighted_energy):
        weighted_energy[ival] = E_avg + (value - E_avg) * E_comberr / E_staterr

    if print:
        print(
            f"\n+++++\nweighted energy = {err_brackets(np.average(weighted_energy), np.std(weighted_energy))}\n+++++"
        )
    return weighted_energy, fitweights

def weighted_avg(fitlist_1exp, fitlist_2exp, plotdir, name, tmax_choice=24, tminmin_1exp=3, tminmax_1exp=16, tminmin_2exp=0, tminmax_2exp=4):
    print("\n")

    tmax_1exp = np.array([i["x"][-1] for i in fitlist_1exp])
    tmin_1exp = np.array([i["x"][0] for i in fitlist_1exp])
    indices = np.where(tmax_1exp == tmax_choice)
    indices = indices[0][np.where(tminmin_1exp < tmin_1exp[indices])]
    indices = indices[np.where(tminmax_1exp > tmin_1exp[indices])]
    tmax_ = tmax_1exp[indices]
    tmin_ = tmin_1exp[indices]
    reduced_fitlist_1exp = [fitlist_1exp[index] for index in indices]

    tmax_2exp = np.array([i["x"][-1] for i in fitlist_2exp])
    tmin_2exp = np.array([i["x"][0] for i in fitlist_2exp])
    indices_2exp = np.where(tmax_2exp == tmax_choice)
    indices_2exp = indices_2exp[0][np.where(tminmin_2exp < tmin_2exp[indices_2exp])]
    indices_2exp = indices_2exp[np.where(tminmax_2exp > tmin_2exp[indices_2exp])]
    tmin_2 = tmin_2exp[indices_2exp]
    reduced_fitlist_2exp = [fitlist_2exp[index] for index in indices_2exp]

    weighted_energy, fitweights = weighted_avg_1_2_exp(reduced_fitlist_1exp, reduced_fitlist_2exp, print=False)

    weights = fitweights[: len(reduced_fitlist_1exp)]
    weights_2 = fitweights[len(reduced_fitlist_1exp) :]

    energies_1exp = np.array([i["param"][:, 1] for i in reduced_fitlist_1exp])
    energies_avg = np.average(energies_1exp, axis=1)
    energies_std = np.std(energies_1exp, axis=1)
    weights_ = weights

    if len(reduced_fitlist_2exp)>0:
        energies_2exp = np.array([i["param"][:, 1] for i in reduced_fitlist_2exp])
        energies_avg_2 = np.average(energies_2exp, axis=1)
        energies_std_2 = np.std(energies_2exp, axis=1)
        weights_2 = weights_2

    # fig, ax1 = plt.subplots(figsize=(5, 4))
    fig, ax1 = plt.subplots(figsize=(7, 5))
    ax1.errorbar(
        tmin_,
        energies_avg,
        energies_std,
        fmt="s",
        label=r"1-exp",
        color=_colors[0],
        capsize=4,
        elinewidth=1,
        markerfacecolor="none",
    )
    if len(reduced_fitlist_2exp)>0:
        ax1.errorbar(
            tmin_2,
            energies_avg_2,
            energies_std_2,
            fmt="s",
            label=r"2-exp",
            color=_colors[1],
            capsize=4,
            elinewidth=1,
            markerfacecolor="none",
        )
    ax1.fill_between(
        np.arange(-1, 20),
        np.ones(21) * (np.average(weighted_energy) - np.std(weighted_energy)),
        np.ones(21) * (np.average(weighted_energy) + np.std(weighted_energy)),
        color="r",
        alpha=0.4,
        linewidth=0,
        label=rf"$E={err_brackets(np.average(weighted_energy), np.std(weighted_energy))}$",
    )
    ax1.set_xlabel(r"$t_{\textrm{min}}$")
    ax1.set_ylabel(r"$E$")
    ax1.set_xlim(0, tmin_[-1] + 1)

    ax2 = ax1.twinx()
    ax2.bar(tmin_, weights_, color=_colors[0], alpha=0.3)
    ax2.bar(tmin_2, weights_2, color=_colors[1], alpha=0.3)
    ax2.set_ylabel(r"$\textrm{Weights}$")

    # ax1.legend(fontsize="xx-small", framealpha=1, facecolor='blue')
    # fig.legend(fontsize="xx-small", framealpha=0.8, loc="upper right")
    fig.legend(fontsize="x-small", framealpha=1)
    fig.savefig(plotdir / ("tmin_energies_weights_" + name + ".pdf"), metadata=_metadata)
    return

def main():
    """Plot the chi-squared values and weights of a range of time fitting windows

    Read the data from a pickle file and plot it as a color plot on a matrix
    """

    plt.style.use("./mystyle.txt")

    pars = params(0)  # Get the parameters for this lattice

    # Read in the directory data from the yaml file if one is given
    if len(sys.argv) == 2:
        config_file = sys.argv[1]
    else:
        config_file = "data_dir_theta2.yaml"
    print("Reading directories from: ", config_file)

    with open(config_file) as f:
        config = yaml.safe_load(f)
    # Set parameters to defaults defined in another YAML file
    with open("defaults.yaml") as f:
        defaults = yaml.safe_load(f)
    for key, value in defaults.items():
        config.setdefault(key, value)

    pickledir_k1 = Path(config["pickle_dir1"])
    pickledir_k2 = Path(config["pickle_dir2"])
    plotdir = Path(config["analysis_dir"]) / Path("plots")
    datadir = Path(config["analysis_dir"]) / Path("data")
    plotdir.mkdir(parents=True, exist_ok=True)
    datadir.mkdir(parents=True, exist_ok=True)

    with open(datadir / (f"time_window_loop_nucl_1exp.pkl"), "rb") as file_in:
        fitlist_nucl_1exp = pickle.load(file_in)
    with open(datadir / (f"time_window_loop_nucl_2exp.pkl"), "rb") as file_in:
        fitlist_nucl_2exp = pickle.load(file_in)

    with open(
        "/scratch/usr/hhpmbate/chroma_3pt/32x64/b5p50kp121040kp120620/six_point_fn_qmax/analysis/data/time_window_loop_sigma_1exp.pkl",
        "rb",
    ) as file_in:
        fitlist_sigma_1exp = pickle.load(file_in)
    with open(
        "/scratch/usr/hhpmbate/chroma_3pt/32x64/b5p50kp121040kp120620/six_point_fn_qmax/analysis/data/time_window_loop_sigma_2exp.pkl",
        "rb",
    ) as file_in:
        fitlist_sigma_2exp = pickle.load(file_in)

    with open(
            datadir / (f"time_window_loop_nucldivsigma_1exp.pkl"), "rb"
    ) as file_in:
        fitlist_nucldivsigma_1exp = pickle.load(file_in)
    with open(
            datadir / (f"time_window_loop_nucldivsigma_2exp.pkl"), "rb"
    ) as file_in:
        fitlist_nucldivsigma_2exp = pickle.load(file_in)

    with open(datadir / (f"time_window_loop_lambda_small.pkl"), "rb") as file_in:
        fitlist_small = pickle.load(file_in)
    with open(datadir / (f"time_window_loop_lambda_large.pkl"), "rb") as file_in:
        fitlist_large = pickle.load(file_in)

    # ===== Nucleon data =====
    weights_nucl = np.array([i["weight"] for i in fitlist_nucl_1exp])
    weights_nucl_2 = np.array([i["weight"] for i in fitlist_nucl_2exp])
    high_weight_nucl = np.argmax(weights_nucl)
    # print(fitlist_nucl_1exp[high_weight_nucl]["redchisq"])
    nucl_t_range = np.arange(
        fitlist_nucl_1exp[high_weight_nucl]["x"][0],
        fitlist_nucl_1exp[high_weight_nucl]["x"][-1] + 1,
    )
    print(f"\nnucl_t_range = {nucl_t_range}")
    # print("redchisq", fitlist_nucl_1exp[high_weight_nucl]["redchisq"])
    # print("maxweight",max(weights_nucl))
    print("max: redchisq = ", fitlist_nucl_1exp[high_weight_nucl]["redchisq"])
    print("max: range = ", fitlist_nucl_1exp[high_weight_nucl]["x"])

    # ===== Sigma data =====
    weights_sigma = np.array([i["weight"] for i in fitlist_sigma_1exp])
    high_weight_sigma = np.argmax(weights_sigma)
    sigma_t_range = np.arange(
        fitlist_sigma_1exp[high_weight_sigma]["x"][0],
        fitlist_sigma_1exp[high_weight_sigma]["x"][-1] + 1,
    )
    print(f"\nsigma_t_range = {sigma_t_range}")
    # print(fitlist_sigma_1exp[high_weight_sigma]["redchisq"])
    # print("maxweight",max(weights_sigma))
    print("max: redchisq = ", fitlist_sigma_1exp[high_weight_sigma]["redchisq"])
    print("max: range = ", fitlist_sigma_1exp[high_weight_sigma]["x"])
    # print("max-1: redchisq = ", fitlist_sigma_1exp[high_weight_sigma-1]["redchisq"])
    # print("max-1: range = ", fitlist_sigma_1exp[high_weight_sigma-1]["x"])
    # print("max-2: redchisq = ", fitlist_sigma_1exp[high_weight_sigma-2]["redchisq"])
    # print("max-2: range = ", fitlist_sigma_1exp[high_weight_sigma-2]["x"])
    # print("max-3: redchisq = ", fitlist_sigma_1exp[high_weight_sigma-3]["redchisq"])
    # print("max-3: weight = ", fitlist_sigma_1exp[high_weight_sigma-3]["weight"])
    # print("max-3: range = ", fitlist_sigma_1exp[high_weight_sigma-3]["x"])

    weights_small = np.array([i["weight"] for i in fitlist_small])
    high_weight_small = np.argmax(weights_small)
    weights_large = np.array([i["weight"] for i in fitlist_large])
    high_weight_large = np.argmax(weights_large)
    ratio_t_range = np.arange(
        min(
            fitlist_small[high_weight_small]["x"][0],
            fitlist_large[high_weight_large]["x"][0],
        ),
        fitlist_large[high_weight_large]["x"][-1] + 1,
    )
    print(f"\nratio_t_range = {ratio_t_range}")
    # print(fitlist_small[high_weight_small]["redchisq"])
    # print("maxweight",max(weights_small))
    # print(fitlist_large[high_weight_large]["redchisq"])
    # print("maxweight",max(weights_large))

    print(f"small: {fitlist_small[high_weight_small]['x']}")
    print(f"large: {fitlist_large[high_weight_large]['x']}")
    print("max: redchisq = ", fitlist_small[high_weight_small]["redchisq"])
    print("max: range = ", fitlist_small[high_weight_small]["x"])
    # print("max-1: redchisq = ", fitlist_small[high_weight_small-1]["redchisq"])
    # print("max-1: range = ", fitlist_small[high_weight_small-1]["x"])
    # print("max-2: redchisq = ", fitlist_small[high_weight_small-2]["redchisq"])
    # print("max-2: range = ", fitlist_small[high_weight_small-2]["x"])
    # print("max-3: redchisq = ", fitlist_small[high_weight_small-3]["redchisq"])
    # print("max-3: range = ", fitlist_small[high_weight_small-3]["x"])

    print("\nmax: redchisq = ", fitlist_large[high_weight_large]["redchisq"])
    print("max: range = ", fitlist_large[high_weight_large]["x"])

    plot_matrix(fitlist_nucl_1exp, plotdir, "nucl_1exp")
    plot_matrix(fitlist_nucl_2exp, plotdir, "nucl_2exp")
    plot_matrix(fitlist_sigma_1exp, plotdir, "sigma_1exp")
    plot_matrix(fitlist_sigma_2exp, plotdir, "sigma_2exp")

    weighted_avg(fitlist_nucl_1exp, fitlist_nucl_2exp, plotdir, "nucl", tmax_choice=config["tmax_nucl"])
    weighted_avg(fitlist_sigma_1exp, fitlist_sigma_2exp, plotdir, "sigma", tmax_choice=config["tmax_sigma"])

    # ===== Nucleon divided by sigma data =====
    weights_nucldivsigma = np.array([i["weight"] for i in fitlist_nucldivsigma_1exp])
    weights_nucldivsigma_2 = np.array([i["weight"] for i in fitlist_nucldivsigma_2exp])
    high_weight_nucldivsigma = np.argmax(weights_nucldivsigma)
    nucldivsigma_t_range = np.arange(
        fitlist_nucldivsigma_1exp[high_weight_nucldivsigma]["x"][0],
        fitlist_nucldivsigma_1exp[high_weight_nucldivsigma]["x"][-1] + 1,
    )
    print(f"\nnucldivsigma_t_range = {nucldivsigma_t_range}")
    print("max: redchisq = ", fitlist_nucldivsigma_1exp[high_weight_nucldivsigma]["redchisq"])
    print("max: range = ", fitlist_nucldivsigma_1exp[high_weight_nucldivsigma]["x"])

    weighted_avg(fitlist_nucldivsigma_1exp, fitlist_nucldivsigma_2exp, plotdir, "nucldivsigma", tmax_choice=config["tmax_nucl"], tminmin_2exp = 2, tminmax_2exp = 2, tminmin_1exp=1, tminmax_1exp=15)

if __name__ == "__main__":
    main()


import json
import logging

import datasets
from tqdm import tqdm
import click

from pathlib import Path

from datasets import load_dataset
import evaluate
from transformers import AutoTokenizer, AutoModelForSequenceClassification, TrainingArguments, Trainer, pipeline
import transformers
import code
import torch
from models import get_model
from sklearn.metrics import (
    accuracy_score,
    precision_score,
    recall_score,
    f1_score
)

import numpy as np

transformers.logging.set_verbosity_info()
metric = evaluate.load("accuracy")

def _load_dataset(dataset_path, data_name, checkpoint, validate=False, training=True):
    """
    return: tokenizer, train, validation, test
    """
    tokenizer = AutoTokenizer.from_pretrained(checkpoint)
    f_label = datasets.ClassLabel(num_classes=2, names=["non-violent", 'violent'])

    def tokenize_function(examples):
        return tokenizer(examples["text"], return_tensors="pt", padding="max_length", truncation=True)

    dataset_test = load_dataset("json", data_files=str((dataset_path / f"{data_name}-test.jsonl").resolve()))
    dataset_test = dataset_test.cast_column('label', f_label)
    dataset_test.set_format("torch")
    tokenized_data_test = (dataset_test.map(tokenize_function, batched=True, remove_columns=['id', 'text']))

    if training:
        dataset_train = load_dataset("json", data_files={"train": str((dataset_path / f"{data_name}-train.jsonl").resolve())})
        f_label = datasets.ClassLabel(num_classes=2, names=["non-violent", 'violent'])
        dataset_train = dataset_train.cast_column('label', f_label)
        dataset_train.set_format("torch")

        if validate:
            dataset_train = dataset_train["train"].train_test_split(test_size=0.1, stratify_by_column="label")

        tokenized_data_train = (dataset_train.map(tokenize_function, batched=True, remove_columns=['id', 'text']))

        return tokenizer, tokenized_data_train["train"], tokenized_data_test['train'], \
               tokenized_data_train["test"] if validate else None

    return tokenizer, None, tokenized_data_test['train'], None

def _evaluate(eval_pred):
    logits, labels = eval_pred
    predictions = np.argmax(logits, axis=-1)
    return metric.compute(predictions=predictions, references=labels)

def run_experiment(dataset_path: str, sample_name: str, checkpoint: str, savepoint: str, epochs=20, batches=4,
                   lr=0.0005, model_type='longformer', validate=True):
    logging.warning("load dataset and tokenizer")
    dataset_path = Path(dataset_path)
    tok, ds_train, ds_test, ds_validation = _load_dataset(dataset_path, sample_name, checkpoint)
    logging.warning("start model training")

    num_labels = 2

    # TODO https://huggingface.co/docs/transformers/v4.24.0/en/main_classes/trainer#transformers.TrainingArguments
    # Params following https://github.com/amazon-science/efficient-longdoc-classification
    args = TrainingArguments(
        output_dir=savepoint,
        evaluation_strategy="epoch",
        save_strategy="epoch",
        learning_rate=lr,
        per_device_train_batch_size=batches,
        per_device_eval_batch_size=batches,
        num_train_epochs=epochs,
        load_best_model_at_end=True,
        metric_for_best_model='accuracy',
        push_to_hub=False,
        report_to="wandb",
        run_name=f"violence-{model_type}-{sample_name}")

    model = get_model(checkpoint, num_labels, model_type)
    trainer = Trainer(model=model, args=args,
                      train_dataset=ds_train, eval_dataset=ds_test,
                      tokenizer=tok, compute_metrics=_evaluate)

    trainer.evaluate()

    # TODO https://colab.research.google.com/github/huggingface/notebooks/blob/master/examples/text_classification.ipynb#scrollTo=NboJ7kDOIrJq
    # best_run = trainer.hyperparameter_search(n_trials=10, direction="maximize")
    # logging.info(f"best parameters found: {best_run.hyperparameters.items()}")
    # for n, v in best_run.hyperparameters.items():
    #     setattr(trainer.args, n, v)
    trainer.train()

    logging.warning("save trained model")
    trainer.save_model(savepoint)

    predictions = trainer.predict(ds_test)

    results = getattr(predictions, "metrics")
    open(f"{savepoint}/results.json", 'w').write(json.dumps(results))
    return savepoint

def make_and_save_predictions(dataset_path: str, name: str, model_checkpoint: str, tokenizer_checkpoint: str,
                              savepoint: str):
    logging.warning("load dataset")
    f_label = datasets.ClassLabel(num_classes=2, names=["non-violent", 'violent'])
    tokenizer_kwargs = {'padding': True, 'truncation': True}

    dataset_test = load_dataset("json", data_files=f"{dataset_path}/{name}-test.jsonl")
    dataset_test = dataset_test.cast_column('label', f_label)
    dataset_test.set_format("torch")

    logging.warning("load pipeline")
    tokenizer = AutoTokenizer.from_pretrained(tokenizer_checkpoint)

    classifier = pipeline(model=model_checkpoint, tokenizer=tokenizer, task="text-classification",
                          device="cuda:0")

    def add_length(example):
        return {"length": len(example["text"].split(" "))}

    def classify(examples):
        return {"prediction": classifier(examples["text"], **tokenizer_kwargs)}

    logging.warning("make predictions")
    dataset_with_length = dataset_test.map(add_length)
    dataset_with_predictions = dataset_with_length.map(classify, batched=True, batch_size=32, remove_columns=["text"])
    for split, data in dataset_with_predictions.items():
        data.to_json(f"{savepoint}/predictions-{split}.jsonl")

    ## Evaluation of results
    ds_test = dataset_with_predictions["train"]
    truth = ds_test["label"]
    predictions = [1 if p["label"] == "LABEL_1" else 0 for p in ds_test["prediction"]]

    def _scores(t, p):
        return {"f1": round(f1_score(t, p), 3), "p": round(precision_score(t, p), 3),
                "r": round(recall_score(t, p), 3), "acc": round(accuracy_score(t, p), 3)}

    results = _scores(truth, predictions)

    for lower, upper in {(0, 512), (512, 4096), (4096, 16000), (16000, 10e+5)}:
        results[f"{lower}-{upper}"] = _scores([t for t, l in zip(truth, ds_test["length"]) if lower < l <= upper],
                                              [p for p, l in zip(predictions, ds_test["length"]) if lower < l <= upper])

    open(f"{savepoint}/prediction-metrics.json", 'w').write(json.dumps(results))

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

@click.option('-d', '--dataset-dir', type=click.Path(exists=True), help="Path where the xxx-train.jsonl and xxx-test.jsonl is.")
@click.option('-n', '--name', type=click.STRING, default='develop', help="base name of the sample (i.e. `random-balanced`)")
@click.option('-m', '--model_type', type=click.STRING, default='longformer', help="which model to use (see models.py)")
@click.option('-s', '--savepoint', type=click.Path(), help="Path to save the model in.")
@click.option('--epochs', type=click.INT, default=20, help="Number of training epochs")
@click.option('--batches', type=click.INT, default=4, help="Batch size")
@click.option('--lr', type=click.FLOAT, default=0.0005, help="Initial learning rate")
@cli.command()
def run(dataset_dir, name, model_type, savepoint, epochs, batches, lr):
    """
    This is the CLI interface to train the model .

      python3 /mnt/ceph/storage/data-tmp/2022/mike4537/trigger-warning-classification/standalone-classifiers/longformer_experiments.py run \
        -n "random-balanced" \
        -d "/mnt/ceph/storage/data-in-progress/data-research/computational-ethics/trigger-warnings/jsonl_datasets/v3-arr23/normal" \
        -s "/mnt/ceph/storage/data-in-progress/data-research/computational-ethics/trigger-warnings/violence-classification/classification-results/arr23-submission/longformer/random-balanced"
    """
    Path(savepoint).mkdir(parents=True, exist_ok=True)

    if model_type == 'longformer':
        checkpoint = 'allenai/longformer-base-4096'
    else:
        checkpoint = "bert-base-uncased"

    run_experiment(dataset_dir, name, checkpoint, savepoint, epochs=epochs, batches=batches, lr=lr, model_type=model_type)
    print(f"trained model at {savepoint}")

@click.option('-c', '--checkpoint', type=click.STRING, default='allenai/longformer-base-4096', help="base checkpoint for model and tokenized")
@click.option('-d', '--dataset-dir', type=click.Path(exists=True), help="Path where the training.jsonl and validation.jsonl is.")
@click.option('-s', '--savepoint', type=click.Path(), help="Path to save the model in.")
@click.option('--epochs', type=click.INT, default=3, help="Path to save the model in.")
@cli.command()
def hyperparameters(checkpoint, dataset_dir, savepoint, epochs):
    """ TODO hyperparameter sweep (cf. the comments in the train loop). May also be a flag in the run method.  """
    pass

@click.option('-c', '--checkpoint', type=click.STRING, help="checkpoint to load")
@click.option('-n', '--name', type=click.STRING, default='develop', help="base name of the sample (i.e. `random-balanced`)")
@click.option('-d', '--dataset-dir', type=click.Path(exists=True), help="Path where the training.jsonl and validation.jsonl is.")
@click.option('-s', '--savepoint', type=click.Path(), help="Path to save the predictions in.")
@click.option('-m', '--model_type', type=click.STRING, default='longformer', help="which model to use (see models.py)")
@cli.command()
def predict(checkpoint, name, dataset_dir, savepoint, model_type):
    """
    How to run `predict` from cli (example):

         python3 /mnt/ceph/storage/data-tmp/2022/mike4537/trigger-warning-classification/standalone-classifiers/longformer_experiments.py predict \
            -n "tag-frequency-balanced" \
            -c "/mnt/ceph/storage/data-in-progress/data-research/computational-ethics/trigger-warnings/violence-classification/classification-results/arr23-submission/longformer/tag-frequency-balanced" \
            -d "/mnt/ceph/storage/data-in-progress/data-research/computational-ethics/trigger-warnings/jsonl_datasets/v3-arr23/normal" \
            -s "/mnt/ceph/storage/data-in-progress/data-research/computational-ethics/trigger-warnings/violence-classification/classification-results/arr23-submission/longformer/tag-frequency-balanced"
    """
    Path(savepoint).mkdir(parents=True, exist_ok=True)

    if model_type == 'longformer':
        tokenizer_checkpoint = 'allenai/longformer-base-4096'
    else:
        tokenizer_checkpoint = "bert-base-uncased"
    make_and_save_predictions(dataset_dir, name, checkpoint, tokenizer_checkpoint, savepoint)

if __name__ == "__main__":
    cli()


from collections import deque

N = int(input())

graph = []
for _ in range(N):
    graph.append(list(map(int, input())))

dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]

def BFS(x, y):
    queue = deque()
    queue.append((x, y))
    graph[x][y] = 0
    cnt = 1
    while queue:
        x, y = queue.popleft()
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]

            if nx < 0 or nx >= N or ny < 0 or ny >= N:
                continue

            if graph[nx][ny] == 1:
                graph[nx][ny] = 0
                queue.append((nx, ny))
                cnt += 1
    return cnt

cnt_lst = []
for i in range(N):
    for j in range(N):
        if graph[i][j] == 1:
            cnt_lst.append(BFS(i,j))

cnt_lst.sort()
print(len(cnt_lst))
for i in cnt_lst:
    print(i)


# import re
# hand = open('short')
# for line in hand:
#     line = line.rstrip()
#     x = re.findall('[a-zA-Z0-9]\S+@\S+[a-zA-Z]', line)
#     if len(x) > 0:
#         print(x)
# import re
# hand = open('zx.txt')
# lst = list()
# for line in hand:
#     line = line.rstrip()
#     x = re.findall('New Revision: ([0-9]+)', line)
#     if len(x) > 0:
#         num = int(x[0])
#         lst.append(num)
# ave = sum(lst)/len(lst)
# print(int(ave))
# import re
# hand = open('regex_sum_1427517.txt')
# lst = list()
# for line in hand:
#     line = line.rstrip()
#     x = re.findall('([0-9]+)', line)
#     if len(x) > 0:
#         num = [int(a) for a in x]
#         for i in num:
#             lst.append(i)
# print(sum(lst))
# import socket
# url = input('enter url: ').split('/')
# mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# mysock.connect((url[2], 80))
# cmd = 'GET http://data.pr4e.org/romeo.txt HTTP/1.0\r\n\r\n'.encode()
# mysock.send(cmd)
# count = 0
# while True:
#     data = mysock.recv(3000)
#     if len(data) < 1:
#         break
#     print(data.decode(),end='')
#     datas = data.decode()
#     num = datas.replace(' ','')
#     print(len(num))
#
# mysock.close()
# import urllib.request, urllib.parse, urllib.error
# fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
# while True:
#     data = fhand.read()
#     if len(data) < 1:
#         break
#     print(data.decode(),end='')
#     datas = data.decode()
#     num = datas.replace(' ','')
#     print(len(num))
from urllib.request import urlopen
from bs4 import BeautifulSoup
import ssl

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = input('Enter - ')
html = urlopen(url, context=ctx).read()
soup = BeautifulSoup(html, "html.parser")

# Retrieve all of the anchor tags
tags = soup('a')
for tag in tags:
    # Look at the parts of a tag
    print('TAG:', tag)
    print('URL:', tag.get('href', None))
    print('Contents:', tag.contents[0])
    print('Attrs:', tag.attrs)


# multiplication of 2 binary numbers using grade school technique
from binary_addition import binary_sum

def binary_number_input(msg):
    while True:
        x = input(msg)
        found = True
        for i in x:
            if i != '0' and i != '1':
                found = False
                print ("Bad binary input! Plz try again..")
                break
        if found:
            return x

def binary_mult(x, y):
    y = y[::-1]
    index = 0
    ilist = []
    for i in y:
        if i == '1':
            s = "0" * index
            z = x + s
            ilist.append(z)
        index += 1
    # for n in ilist:
    #    print (n)
    ans = "0"
    for n in ilist:
        ans = binary_sum(ans, n)
    print ("x * y = ", ans)

def main():
    x = binary_number_input("First Binary Number X: ")
    y = binary_number_input("Second Binary Number Y: ")
    binary_mult(x, y)

if __name__ == '__main__':
    main()


import sys
sys.path.append("../minesweeper")

import unittest
# import thread
import threading
import time
import game
from gameWindow import *
import PySimpleGUI as psg

class MyTestCase(unittest.TestCase):
   def test_1(self):
        gameWindow = GameWindow()
        thread = threading.Thread(target=game.Game(gameWindow).startGame)
        thread.start()
        time.sleep(1)

        gameWindow._window["-N-"].update(8)
        gameWindow._window["-M-"].update(8)
        gameWindow._window["-BOMBS-"].update(12)
        gameWindow._window["-START-"].click()

        time.sleep(1)

        layout = gameWindow._board.getLayout().getMap()

        count = 0
        for n in range(0, 8):
            if(count == 5):
                break
            for m in range(0, 8):
                if(layout[n][m] != -1):
                    gameWindow._board.lClick(int(n), int(m))
                    gameWindow.parseVisuals()
                else:
                    gameWindow._board.rClick(int(n), int(m))
                    gameWindow.parseVisuals()
                count += 1
                if(count == 5):
                    break

        # PySimpleGui uses gameLoop and doesn't really close in any other ways.
        # Calling .close() method only closes the window and leaves infinite loop hanging on a separate thread

        gameWindow._window.close()
        time.sleep(3)

        gameWindow = GameWindow()
        thread2 = threading.Thread(target=game.Game(gameWindow).startGame)
        thread2.start()
        time.sleep(3)

        gameWindow._window["-N-"].update(8)
        gameWindow._window["-M-"].update(8)
        gameWindow._window["-BOMBS-"].update(12)
        time.sleep(2)
        gameWindow._window["-START-"].click()

        for n in range(0, 8):
            for m in range(0, 8):
                self.assertTrue(gameWindow._window["{} {}".format(n, m)].get_text() == " ")

        self.assertTrue(gameWindow._window["-FLAGS-"].get_text() == "0")

        return

unittest.main()


# -*- coding: utf-8 -*-
from django.urls import path,re_path
from finweb import views

urlpatterns =[
             path(r'',views.index,name='index'),
             path('register/',views.register,name='register'),
             path('login/',views.user_login,name='login'),
            #  path('rules/',views.rules,name='rules'),
             path('changepassword/',views.changepassword,name='changepassword'),
             path('changeinfo/',views.changeinfo,name='changeinfo'),
             path('logout/',views.user_logout,name='logout'),
             path('get_index_data/',views.get_index_data,name='get_index_data'),
             path('get_span_data/',views.get_span_data,name='get_span_data'),
             path('get_stocks_data/',views.get_stocks_data,name='get_stocks_data'),
             path('stocks_to_info/',views.stocks_to_info,name='stocks_to_info'),
             path('delete_stocks/',views.delete_stocks,name='delete_stocks'),
             path('add_stocks_toport/',views.add_stocks_toport,name='add_stocks_toport'),
             path('userinfo/',views.userinfo,name='userinfo'),
             path('quant/',views.quant,name='quant'), #量化投资
             path('operate/',views.operate,name='operate'),#股票操作
             path('stocks/',views.stocks,name='stocks'),#我的自选股
             path('portfolio/',views.portfolio,name='portfolio'),#我的投资组合
             path('add_portfolio/',views.add_portfolio,name='add_portfolio'),#创建投资组合
             path('port_to_info',views.port_to_info,name='port_to_info'),#跳转
             path('delete_stocks_inp/',views.delete_stocks_inp,name='delete_stocks_inp'),#删除组合中的股票
             path('delete_portfolio/',views.delete_portfolio,name='delete_portfolio'),#删除组合
             path('stockinfo/',views.stockinfo,name='stockinfo'),#个股信息页面
             path('get_info_stockdata/',views.get_info_stockdata,name='get_info_stockdata'),#个股信息页面上更新span
             path('get_info_kdata/',views.get_info_kdata,name='get_info_kdata'),#个股信息页面上获取k线数据
             path('get_info_search/',views.get_info_search,name='get_info_search'),#个股信息页面搜索
             path('addto_stocks/',views.addto_stocks,name='addto_stocks'),#个股信息,添加到自选股
            #  path('indicator/',views.indicator,name='indicator'),#技术指标
            #  path('get_macd/',views.get_macd,name='get_macd'), #获得MACD指标图像
            #  path('get_adx/',views.get_adx,name='get_adx'), #获得ADX指标图像
            #  path('get_sma/',views.get_sma,name='get_sma'), #获得SMA指标图像
            #  path('get_bbands/',views.get_bbands,name='get_bbands'), #获得BBands指标图像
             path('get_quant_data/',views.get_quant_data,name='get_quant_data'),#选择组合
            #  path('factor_analysis/',views.factor_analysis,name='factor_analysis'),#多因子分析
             path('stock_ratio/',views.stock_ratio,name='stock_ratio'), #资产配置
             path('get_stock_ratio/',views.get_stock_ratio,name='get_stock_ratio'),
             path('revenue_test/',views.revenue_test,name='revenue_test'),#收益回测
             path('fin_data/',views.fin_data,name='fin_data'),
             path('notices/',views.notices,name='notices'),
             path('candle1/',views.candle1,name='candle1'),#test
             path('news_test/',views.news_test,name='news_test'),#test
             path('candle/',views.candle,name='candle'),#test
             path('echarts/',views.echarts,name='echarts'), #test
             path('test/',views.test,name='test'), #test
]


import sys
import os
import json
import struct
import re
import subprocess
import shutil
import string

#constants
TAGS = {
    0x5: "color",
    0xB: "name",
    0xF: "voice",
    0x6: "size",
    0xC: "item",
    0xD: "button",
}

names = {
    1: "Veigue",
    2: "Mao",
    3: "Eugene",
    4: "Annie",
    5: "Tytree",
    6: "Hilda",
    7: "Claire_Agarte",
    8: "Agarte_Claire",
    9: "Annie (NPC)",
    0x1FFF: "OnScreenChar",
}

colors = {
    1: "Blue",
    2: "Red",
    3: "Purple",
    4: "Green",
    5: "Cyan",
    6: "Yellow",
    7: "White",
}

PRINTABLE_CHARS = "".join(
    (string.digits, string.ascii_letters, string.punctuation, " ")
)

COMMON_TAG = r"(<\w+:?\w+>)"
HEX_TAG = r"(\{[0-9A-F]{2}\})"

pointer_start = 0x1870
pointer_end = 0x1C40

text_start = 0x3961
text_end = 0x3ED8

def mkdir(name):
    try: os.mkdir(name)
    except: pass

#############################################
#                                           #
#             Extract Function              #
#                                           #
#############################################

def extract_missions():
    print("Extracting Mission Strings...")
    mkdir('Mission_txt/')
    print("Directory Made")

    json_file = open('tor_tbl.json', 'r')
    json_data = json.load(json_file)
    json_file.close()

    name = "00023_0000d"
    f = open("00023/00023_0000d.unknown", 'rb')

    miss_file = open('miss.json', 'w')
    miss_data = {}

    text_pointers = []
    addrs = []

    f.seek(pointer_start)

    while f.tell() < pointer_end:
        addr = struct.unpack('<L', f.read(4))[0]
        if text_start <= addr <= text_end:
            addrs.append(f.tell() - 4)
            text_pointers.append(addr)
        else:
            continue

    o = open("Mission_txt/" + name + ".txt", "w", encoding="utf-8")

    miss_data[name] = []

    for i in range(len(text_pointers)):
        f.seek(text_pointers[i] - 1, 0)
        b = f.read(1)
        if b != b"\x00":
            continue
        miss_data[name].append(addrs[i])
        b = f.read(1)
        while b != b"\x00":
            b = ord(b)
            if (b >= 0x99 and b <= 0x9F) or (b >= 0xE0 and b <= 0xEB):
                c = (b << 8) + ord(f.read(1))
                # if str(c) not in json_data.keys():
                #    json_data[str(c)] = char_index[decode(c)]
                o.write(json_data[str(c)])
            elif b == 0x1:
                o.write("\n")
            elif b in (0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xB, 0xC, 0xD, 0xE, 0xF):
                b2 = struct.unpack("<L", f.read(4))[0]
                if b in TAGS:
                    tag_name = TAGS.get(b)
                    tag_param = None
                    if (tag_name + "s") in globals():
                        tag_param = eval("%ss.get(b2, None)" % tag_name)
                    if tag_param != None:
                        o.write("<%s>" % tag_param)
                    else:
                        o.write("<%s:%08X>" % (tag_name, b2))
                else:
                    o.write("<%02X:%08X>" % (b, b2))
            elif chr(b) in PRINTABLE_CHARS:
                o.write(chr(b))
            elif b >= 0xA1 and b < 0xE0:
                o.write(struct.pack("B", b).decode("cp932"))
            elif b in (0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19):
                o.write("{%02X}" % b)
                next_b = b""
                while next_b != b"\x80":
                    next_b = f.read(1)
                    o.write("{%02X}" % ord(next_b))
            elif b == 0x81:
                next_b = f.read(1)
                if next_b == b"\x40":
                    o.write("　")
                else:
                    o.write("{%02X}" % b)
                    o.write("{%02X}" % ord(next_b))
            else:
                o.write("{%02X}" % b)
            b = f.read(1)
        o.write("\n[ENDBLOCK]\n")
    f.close()
    o.close()

    json.dump(miss_data, miss_file, indent=4)

#############################################
#                                           #
#             Reinsert Function             #
#                                           #
#############################################

def insert_missions():
    print("Reinserting Mission Strings...")
    json_file = open("TOR_TBL.json", "r")
    miss_json = open("miss.json", "r")
    table = json.load(json_file)
    miss_data = json.load(miss_json)
    json_file.close()
    miss_json.close()

    itable = dict([[i, struct.pack(">H", int(j))] for j, i in table.items()])
    itags = dict([[i, j] for j, i in TAGS.items()])
    inames = dict([[i, j] for j, i in names.items()])
    icolors = dict([[i, j] for j, i in colors.items()])
    unames = []
    for i in names.values():
        nam = "<" + str(i) + ">"
        unames.append(nam)
    ucolors = []
    for i in colors.values():
        col = "<" + str(i) + ">"
        ucolors.append(col)

    mkdir("mission_new/")

    for name in os.listdir("mission_txt/"):
        f = open("mission_txt/" + name, "r", encoding="utf8")
        name = name[:-4]
        e = open("00023/00023_0000d.unknown", "rb")
        o = open("mission_new/" + name + '.unknown', "wb")

        txts = []
        sizes = []
        txt = bytearray()

        for line in f:
            line = line.strip("\x0A")
            if len(line) > 0:
                if line[0] == "#":
                    continue
            if line == "[ENDBLOCK]":
                if len(line) == 0:
                    txts.append(b"\x00")
                else:
                    txts.append(txt[:-1] + b"\x00")
                sizes.append(len(txt))
                txt = bytearray()
            else:
                string_hex = re.split(HEX_TAG, line)
                string_hex = [sh for sh in string_hex if sh]
                for s in string_hex:
                    if re.match(HEX_TAG, s):
                        txt += struct.pack("B", int(s[1:3], 16))
                    else:
                        s_com = re.split(COMMON_TAG, s)
                        s_com = [sc for sc in s_com if sc]
                        for c in s_com:
                            if re.match(COMMON_TAG, c):
                                if ":" in c:
                                    split = c.split(":")
                                    if split[0][1:] in itags.keys():
                                        txt += struct.pack("B", itags[split[0][1:]])
                                        txt += struct.pack("<I", int(split[1][:8], 16))
                                    else:
                                        txt += struct.pack("B", int(split[0][1:], 16))
                                        txt += struct.pack("<I", int(split[1][:8], 16))
                                if c in unames:
                                    txt += struct.pack("B", 0xB)
                                    txt += struct.pack("<I", inames[c[1:-1]])
                                if c in ucolors:
                                    txt += struct.pack("B", 0x5)
                                    txt += struct.pack("<I", icolors[c[1:-1]])
                            else:
                                for c2 in c:
                                    if c2 in itable.keys():
                                        txt += itable[c2]
                                    else:
                                        txt += c2.encode("cp932")
                txt += b"\x01"

        f.close()

        if sum(sizes) >= 0x577:
            print("Error: Length of Text Block is Too Long. \n Text Block must be no larger than 1406 bytes \n in length unless you want your precious \n strings to get overwritten!")
            continue
        e.seek(0, 0)
        header = e.read(text_start)
        o.write(header + b"\x00")
        e.close()

        pos = 0x3961
        for i in range(len(txts)):
            o.seek(miss_data[name][i], 0)
            o.write(struct.pack("<L", pos))
            pos += sizes[i]

        o.seek(text_start, 0)

        for t in txts:
            o.write(t)
        o.close()

if __name__ == '__main__':
    if sys.argv[1] == 'help':
        print("Tales of Rebirth Panic Dreamer Mission Strings Extraction/Reinsertion tool. \n By SymphoniaLauren.\n Usage: \n py tor_mission.py extract missions -- extracts mission strings. \n py tor_mission.py insert missions -- inserts missions strings.")
    if sys.argv[1] == 'extract' and sys.argv[2] == 'missions':
        extract_missions()
    if sys.argv[1] == 'insert' and sys.argv[2] == 'missions':
        insert_missions()
    else:
        sys.exit(1)


import os

from setuptools import setup, find_packages, Extension, Command
from setuptools.command.build_ext import build_ext
from setuptools.command.install_scripts import install_scripts
from setuptools.errors import SetupError

with open('requirements.txt') as f:
    required_dependencies = f.read().splitlines()
    external_dependencies = []
    for dependency in required_dependencies:
        if dependency[0:2] == '-e':
            repo_name = dependency.split('=')[-1]
            repo_url = dependency[3:]
            external_dependencies.append('{} @ {}'.format(repo_name, repo_url))
        else:
            external_dependencies.append(dependency)

def get_extensions():
    uncompress = Extension('scilpy.tractograms.uncompress',
                           ['scilpy/tractograms/uncompress.pyx'])
    quick_tools = Extension('scilpy.tractanalysis.quick_tools',
                            ['scilpy/tractanalysis/quick_tools.pyx'])
    grid_intersections = Extension('scilpy.tractanalysis.grid_intersections',
                                   ['scilpy/tractanalysis/grid_intersections.pyx'])
    streamlines_metrics = Extension('scilpy.tractanalysis.streamlines_metrics',
                                    ['scilpy/tractanalysis/streamlines_metrics.pyx'])
    return [uncompress, quick_tools, grid_intersections, streamlines_metrics]

class CustomBuildExtCommand(build_ext):
    """ build_ext command to use when numpy headers are needed. """

    def run(self):
        # Now that the requirements are installed, get everything from numpy
        from Cython.Build import cythonize
        from numpy import get_include

        # Add everything requires for build
        self.swig_opts = None
        self.include_dirs = [get_include()]
        self.distribution.ext_modules[:] = cythonize(
            self.distribution.ext_modules)

        # Call original build_ext command
        build_ext.finalize_options(self)
        build_ext.run(self)

# Get the requiered python version
PYTHON_VERSION = ""
with open('.python-version') as f:
    py_version = f.readline().strip("\n").split(".")
    py_major = py_version[0]
    py_minor = py_version[1]
    py_micro = "*"
    py_extra = None
    if len(py_version) > 2:
        py_micro = py_version[2]
    if len(py_version) > 3:
        py_extra = py_version[3]

    PYTHON_VERSION = ".".join([py_major, py_minor, py_micro])
    if py_extra:
        PYTHON_VERSION = ".".join([PYTHON_VERSION, py_extra])

    PYTHON_VERSION = "".join(["==", PYTHON_VERSION])

# Get version and release info, which is all stored in scilpy/version.py
ver_file = os.path.join('scilpy', 'version.py')
with open(ver_file) as f:
    exec(f.read())

opts = dict(name=NAME,
            maintainer=MAINTAINER,
            maintainer_email=MAINTAINER_EMAIL,
            description=DESCRIPTION,
            long_description=LONG_DESCRIPTION,
            url=URL,
            download_url=DOWNLOAD_URL,
            license=LICENSE,
            classifiers=CLASSIFIERS,
            author=AUTHOR,
            author_email=AUTHOR_EMAIL,
            platforms=PLATFORMS,
            version=VERSION,
            packages=find_packages(),
            cmdclass={
                'build_ext': CustomBuildExtCommand
            },
            ext_modules=get_extensions(),
            python_requires=PYTHON_VERSION,
            setup_requires=['cython', 'numpy'],
            install_requires=external_dependencies,
            entry_points={
                'console_scripts': ["{}=scripts.{}:main".format(
                    os.path.basename(s),
                    os.path.basename(s).split(".")[0]) for s in SCRIPTS] +
                ["{}=scripts.legacy.{}:main".format(
                    os.path.basename(s),
                    os.path.basename(s).split(".")[0]) for s in LEGACY_SCRIPTS]
            },
            data_files=[('data/LUT',
                         ["data/LUT/freesurfer_desikan_killiany.json",
                          "data/LUT/freesurfer_subcortical.json",
                          "data/LUT/dk_aggregate_structures.json"])],
            include_package_data=True)

setup(**opts)


import sys
import os
import os.path as osp
import argparse
import numpy as np
import cv2
import math
import torch
import torchvision.transforms as transforms
from torch.nn.parallel.data_parallel import DataParallel
import torch.backends.cudnn as cudnn

sys.path.insert(0, osp.join(r'Your file storage path ', 'main'))
sys.path.insert(0, osp.join(r'Your file storage path', 'data'))
sys.path.insert(0, osp.join(r'Your file storage path', 'common'))
sys.path.insert(0, osp.join(r'Your file storage path', 'nets'))
sys.path.insert(0, osp.join(r'Your file storage path', 'utils1'))
from config import cfg
from model import get_pose_net
from pose_utils import process_bbox
from dataset import generate_patch_image

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--gpu', type=str, default='0', dest='gpu_ids')
    parser.add_argument('--test_epoch', type=str, default='18', dest='test_epoch')
    args = parser.parse_args()

    # test gpus
    if not args.gpu_ids:
        assert 0, "Please set proper gpu ids"

    if '-' in args.gpu_ids:
        gpus = args.gpu_ids.split('-')
        gpus[0] = 0 if not gpus[0].isdigit() else int(gpus[0])
        gpus[1] = len(mem_info()) if not gpus[1].isdigit() else int(gpus[1]) + 1
        args.gpu_ids = ','.join(map(lambda x: str(x), list(range(*gpus))))

    assert args.test_epoch, 'Test epoch is required.'
    return args

# argument parsing
args = parse_args()
cfg.set_args(args.gpu_ids)
cudnn.benchmark = True

# snapshot load
model_path = r'Your model storage path' % int(args.test_epoch)
assert osp.exists(model_path), 'Cannot find model at ' + model_path
print('Load checkpoint from {}'.format(model_path))
model = get_pose_net(cfg, False)
model = DataParallel(model).cuda()
ckpt = torch.load(model_path)
model.load_state_dict(ckpt['network'])
model.eval()

def rootnet(img, bboxlist):
# prepare input image
    transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize(mean=cfg.pixel_mean, std=cfg.pixel_std)])
    original_img = img
    original_img_height, original_img_width = original_img.shape[:2]

    bbox_list = bboxlist
    person_num = len(bbox_list)
    root_list = []
    # normalized camera intrinsics
    focal = [1500, 1500]  # x-axis, y-axis
    for n in range(person_num):
        bbox = process_bbox(np.array(bbox_list[n]), original_img_width, original_img_height)
        img, img2bb_trans = generate_patch_image(original_img, bbox, False, 0.0)
        img = transform(img).cuda()[None, :, :, :]
        k_value = np.array(
            [math.sqrt(cfg.bbox_real[0] * cfg.bbox_real[1] * focal[0] * focal[1] / (bbox[2] * bbox[3]))]).astype(np.float32)
        k_value = torch.FloatTensor([k_value]).cuda()[None, :]

        # forward
        with torch.no_grad():
            root_3d = model(img, k_value)  # x,y: pixel, z: root-relative depth (mm)
        img = img[0].cpu().numpy()
        root_3d = root_3d[0].cpu().numpy()

        # save output in 2D space (x,y: pixel)
        vis_img = img.copy()
        vis_img = vis_img * np.array(cfg.pixel_std).reshape(3, 1, 1) + np.array(cfg.pixel_mean).reshape(3, 1, 1)
        vis_img = vis_img.astype(np.uint8)
        vis_img = vis_img[::-1, :, :]
        vis_img = np.transpose(vis_img, (1, 2, 0)).copy()
        vis_root = np.zeros((2))
        vis_root[0] = root_3d[0] / cfg.output_shape[1] * cfg.input_shape[1]
        vis_root[1] = root_3d[1] / cfg.output_shape[0] * cfg.input_shape[0]
        cv2.circle(vis_img, (int(vis_root[0]), int(vis_root[1])), radius=5, color=(0, 255, 0), thickness=-1,
                   lineType=cv2.LINE_AA)
        root_list.append(root_3d[2])
    return root_list


from scapy.all import *
import loadnotebook
a=0
def getAddress(address):
    global a
    capture = sniff(count=5)
    for p in capture:
        if (readpcap(p) == 1):
             print("Harmfull Packet!")
        elif (readpcap(p) == 0):
         print("Benign")
        a = dir(p)

    wrpcap("hackathon.pcap", capture)

def readpcap(pkt):
    return loadnotebook.predict(pkt)

getAddress("www.freerobux.com")


# # 시간초과
# import sys
# input = sys.stdin.readline
# sys.setrecursionlimit(10000)

# T = int(input())

# def fibonacci(n):
#     if n == 0:
#         return [1, 0]
#     elif n == 1:
#         return [0, 1]
#     else:           # 각 인덱스의 합을 출력하는 함수
#         return [fibonacci(n-1)[i] + fibonacci(n-2)[i] for i in range(2)]

# for _ in range(T):
#     tmp = int(input())
#     print(fibonacci(tmp))

# # 시간초과 - 문제: 메모리에 저장해둬서 했던 작업 반복하지 않게 해야함
# import sys
# input = sys.stdin.readline

# T = int(input())

# def f1(n):
#     if n == 0:
#         return 1
#     elif n == 1:
#         return 0
#     else:
#         return f1(n-1) + f1(n-2)

# def f2(n):
#     if n == 0:
#         return 0
#     elif n == 1:
#         return 1
#     else:
#         return f2(n-1) + f2(n-2)

# for _ in range(T):
#     tmp = int(input())
#     print(f1(tmp), f2(tmp))

# 블로그 풀이 - 했던 행위를 메모리에 넣고, 또 다시 반복하지 않음
import sys
input = sys.stdin.readline

T = int(input())
zero = [1, 0, 1]
one = [0, 1, 1]

def fibonacci(n):
    length = len(zero)                          # 지금까지 완성된 길이만큼 적는다.
    if n >= length:                             # 그것보다 더 크다면,
        for i in range(length, n+1):            # 지금까지 완성된 것 이후의 값을 채워 넣는다.
            zero.append(zero[i-1] + zero[i-2])
            one.append(one[i-1] + one[i-2])
    return zero[n], one[n]

for _ in range(T):
    print(*fibonacci(int(input())))

'''
f(0) = 0				        1 0
f(1) = 1				        0 1
f(2) = 0+1			            1 1
f(3) = 2 = 1+(0+1)			    1 2
f(4) = 3 = (0+1)+1+(0+1)		2 3
f(5) = 5 = 1 *2  + (0+1) * 3	3 5
f(6) = 8				        5 8
'''


# Игра Крестики-нолики с графическим интерфейсом
# с помощью tkinter
# импорт всех необходимых библиотек
import random
import tkinter
from tkinter import *
from functools import partial
from tkinter import messagebox
from copy import deepcopy
import array as arr

import RSP
from RSP import *

button = []
# Создает пустую доску
global board
board = [[" " for x in range(3)] for y in range(3)]

# Проверить l(O/X) выиграл матч или нет по правилам игры
def winner(b, l):
    return ((b[0][0] == l and b[0][1] == l and b[0][2] == l) or
            (b[1][0] == l and b[1][1] == l and b[1][2] == l) or
            (b[2][0] == l and b[2][1] == l and b[2][2] == l) or
            (b[0][0] == l and b[1][0] == l and b[2][0] == l) or
            (b[0][1] == l and b[1][1] == l and b[2][1] == l) or
            (b[0][2] == l and b[1][2] == l and b[2][2] == l) or
            (b[0][0] == l and b[1][1] == l and b[2][2] == l) or
            (b[0][2] == l and b[1][1] == l and b[2][0] == l))

# текст на кнопке во время игры с другим игроком
def get_text(i, j, gb, l1, l2):
    if board[i][j] == ' ':
        if l1['state'] == ACTIVE:
            l1.config(state=DISABLED)
            l2.config(state=ACTIVE)
            board[i][j] = "X"
        else:
            l2.config(state=DISABLED)
            l1.config(state=ACTIVE)
            board[i][j] = "O"
        button[i][j].config(text=board[i][j])
    if winner(board, "X"):
        gb.destroy()
        box = messagebox.showinfo("Победа", "Игрок 1 выиграл")

    elif winner(board, "O"):
        gb.destroy()
        box = messagebox.showinfo("Победа", "Игрок 2 выиграл")

    elif (isfull()):
        gb.destroy()
        box = messagebox.showinfo("Ничья", "Ничья")

# Проверяем, может ли игрок нажать на кнопку или нет
def isfree(i, j):
    return board[i][j] == " "

# Проверяем, заполнена доска или нет
def isfull():
    flag = True
    for i in board:
        if (i.count(' ') > 0):
            flag = False
    return flag

# Создайте графический интерфейс игрового поля для игры вместе с другим игроком
def gameboard_pl(game_board, l1, l2):
    for i in range(3):
        m = 3 + i
        button.append(i)
        button[i] = []
        for j in range(3):
            n = j
            button[i].append(j)
            get_t = partial(get_text, i, j, game_board, l1, l2)
            button[i][j] = Button(
                game_board, bd=5, command=get_t, height=4, width=8, state=DISABLED)
            button[i][j].grid(row=m, column=n)

# Инициализировать игровое поле для игры с другим игроком
def withplayer(game_board1):
    game_board1.destroy()
    global game_board, button
    game_board = Tk()
    game_board.resizable(width=False, height=False)
    game_board.title("Крестики-нолики")
    l1 = Button(game_board, text="Игрок 1 : X", width=10)
    l2 = Button(game_board, text="Игрок 2 : O", width=10)
    choose_pl = Button(game_board, text="Кто ходит первый?", width=20, command=lambda: (
    game_board.withdraw(), choose_pl.grid_forget(), RSP.RSPplay(game_board, button, l1, l2)))
    choose_pl.grid(row=2, columnspan=3)
    gameboard_pl(game_board, l1, l2)
    game_board.mainloop()

# главная функция
def play():
    menu = Tk()
    menu.geometry("325x113")
    menu.title("Крестики-нолики")
    wpl = partial(withplayer, menu)

    head = Button(menu, text="---Добро пожаловать---",
                  activeforeground='red',
                  activebackground="yellow", bg="grey",
                  fg="black", width=500, font='summer', bd=5)

    B2 = Button(menu, text="Многопользовательский режим", command=wpl,
                activeforeground='red',
                activebackground="yellow", bg="gray", fg="black",
                width=500, font='summer', bd=5)

    B3 = Button(menu, text="Выход", command=menu.quit,
                activeforeground='red',
                activebackground="yellow", bg="grey", fg="black",
                width=500, font='summer', bd=5)
    head.pack(side='top')
    B2.pack(side='top')
    B3.pack(side='top')
    menu.mainloop()

if __name__ == '__main__':
    play()
    SystemExit(1)


from sqlalchemy import desc
from db_config import db
from .error import RecordNotFound
from datetime import datetime

class BaseRepo:
    @classmethod
    def model(cls):
        raise NotImplementedError

    @classmethod
    def entity(cls):
        raise NotImplementedError

    @classmethod
    def create(cls, **kwargs):
        record = cls.model()(**kwargs)
        db.session.add(record)
        db.session.commit()

        if record:
            return record
        else:
            raise Exception

    @classmethod
    def find(cls, **kwargs):
        record = cls.model().query.filter_by(**kwargs).first()

        # should raise an error if no record
        if record:
            return record
        raise RecordNotFound()

    @classmethod
    def find_all(cls, **kwargs):
        records = cls.model().query.filter_by(**kwargs).all()
        return records

    @classmethod
    def update(cls, id, **kwargs):
        result = (
            db.session.query(cls.model())
            .filter_by(id=id)
            .update(
                kwargs,
            )
        )

        # rescue exception here
        db.session.commit()
        return cls.find(id=id)

    @classmethod
    def delete(cls, id):
        result = (
            db.session.query(cls.model())
            .filter_by(id=id)
            .update(
                {"disabled_at": datetime.now()},
            )
        )

        # rescue exception here
        db.session.commit()
        return cls.find(id=id)

    @classmethod
    def paginate(cls, page=1, per_page=20, **kwargs):
        query = (
            cls.model()
            .query.filter_by(**kwargs)
            .order_by(desc(cls.model().id))
            .paginate(page, per_page)
        )
        return query.items, query.total  # probably expensice to run total


# -*- coding: utf-8 -*-
# @Author: MirrorAi
# @Date:   2020-01-10 21:50:37
# @Last Modified by:   MirroAi
# @Last Modified time: 2020-01-10 21:56:02

# 列表排序及连接

def run():

    l1 = []
    for i in input("请输入数组1，如1,2,3,4：").split(","):
        l1.append(int(i))

    l2 = []
    for i in input("请输入数组2：").split(","):
        l2.append(int(i))

    print("数组1排序后为", sorted(l1))
    print("数组2排序后为", sorted(l2))
    print("数组1、数组2连接后为", l1+l2)

if __name__ == "__main__":
    run()


import os
import shutil

import pyblish.api
import clique
import nuke
from openpype.hosts.nuke import api as napi
from openpype.pipeline import publish
from openpype.lib import collect_frames

class NukeRenderLocal(publish.Extractor,
                      publish.ColormanagedPyblishPluginMixin):
    """Render the current Nuke composition locally.

    Extract the result of savers by starting a comp render
    This will run the local render of Fusion.

    Allows to use last published frames and overwrite only specific ones
    (set in instance.data.get("frames_to_fix"))
    """

    order = pyblish.api.ExtractorOrder
    label = "Render Local"
    hosts = ["nuke"]
    families = ["render.local", "prerender.local", "image.local"]

    def process(self, instance):
        child_nodes = (
            instance.data.get("transientData", {}).get("childNodes")
            or instance
        )

        node = None
        for x in child_nodes:
            if x.Class() == "Write":
                node = x

        self.log.debug("instance collected: {}".format(instance.data))

        node_subset_name = instance.data.get("name", None)

        first_frame = instance.data.get("frameStartHandle", None)
        last_frame = instance.data.get("frameEndHandle", None)

        filenames = []
        node_file = node["file"]
        # Collect expected filepaths for each frame
        # - for cases that output is still image is first created set of
        #   paths which is then sorted and converted to list
        expected_paths = list(sorted({
            node_file.evaluate(frame)
            for frame in range(first_frame, last_frame + 1)
        }))
        # Extract only filenames for representation
        filenames.extend([
            os.path.basename(filepath)
            for filepath in expected_paths
        ])

        # Ensure output directory exists.
        out_dir = os.path.dirname(expected_paths[0])
        if not os.path.exists(out_dir):
            os.makedirs(out_dir)

        frames_to_render = [(first_frame, last_frame)]

        frames_to_fix = instance.data.get("frames_to_fix")
        if instance.data.get("last_version_published_files") and frames_to_fix:
            frames_to_render = self._get_frames_to_render(frames_to_fix)
            anatomy = instance.context.data["anatomy"]
            self._copy_last_published(anatomy, instance, out_dir,
                                      filenames)

        for render_first_frame, render_last_frame in frames_to_render:

            self.log.info("Starting render")
            self.log.info("Start frame: {}".format(render_first_frame))
            self.log.info("End frame: {}".format(render_last_frame))

            # Render frames
            nuke.execute(
                str(node_subset_name),
                int(render_first_frame),
                int(render_last_frame)
            )

        ext = node["file_type"].value()
        colorspace = napi.get_colorspace_from_node(node)

        if "representations" not in instance.data:
            instance.data["representations"] = []

        if len(filenames) == 1:
            repre = {
                'name': ext,
                'ext': ext,
                'files': filenames[0],
                "stagingDir": out_dir
            }
        else:
            repre = {
                'name': ext,
                'ext': ext,
                'frameStart': (
                    "{{:0>{}}}"
                    .format(len(str(last_frame)))
                    .format(first_frame)
                ),
                'files': filenames,
                "stagingDir": out_dir
            }

        # inject colorspace data
        self.set_representation_colorspace(
            repre, instance.context,
            colorspace=colorspace
        )

        instance.data["representations"].append(repre)

        self.log.debug("Extracted instance '{0}' to: {1}".format(
            instance.name,
            out_dir
        ))

        families = instance.data["families"]
        # redefinition of families
        if "render.local" in families:
            instance.data['family'] = 'render'
            families.remove('render.local')
            families.insert(0, "render2d")
            instance.data["anatomyData"]["family"] = "render"
        elif "prerender.local" in families:
            instance.data['family'] = 'prerender'
            families.remove('prerender.local')
            families.insert(0, "prerender")
            instance.data["anatomyData"]["family"] = "prerender"
        elif "image.local" in families:
            instance.data['family'] = 'image'
            families.remove('image.local')
            instance.data["anatomyData"]["family"] = "image"
        instance.data["families"] = families

        collections, remainder = clique.assemble(filenames)
        self.log.debug('collections: {}'.format(str(collections)))

        if collections:
            collection = collections[0]
            instance.data['collection'] = collection

        self.log.info('Finished render')

        self.log.debug("_ instance.data: {}".format(instance.data))

    def _copy_last_published(self, anatomy, instance, out_dir,
                             expected_filenames):
        """Copies last published files to temporary out_dir.

        These are base of files which will be extended/fixed for specific
        frames.
        Renames published file to expected file name based on frame, eg.
        test_project_test_asset_subset_v005.1001.exr > new_render.1001.exr
        """
        last_published = instance.data["last_version_published_files"]
        last_published_and_frames = collect_frames(last_published)

        expected_and_frames = collect_frames(expected_filenames)
        frames_and_expected = {v: k for k, v in expected_and_frames.items()}
        for file_path, frame in last_published_and_frames.items():
            file_path = anatomy.fill_root(file_path)
            if not os.path.exists(file_path):
                continue
            target_file_name = frames_and_expected.get(frame)
            if not target_file_name:
                continue

            out_path = os.path.join(out_dir, target_file_name)
            self.log.debug("Copying '{}' -> '{}'".format(file_path, out_path))
            shutil.copy(file_path, out_path)

            # TODO shouldn't this be uncommented
            # instance.context.data["cleanupFullPaths"].append(out_path)

    def _get_frames_to_render(self, frames_to_fix):
        """Return list of frame range tuples to render

        Args:
            frames_to_fix (str): specific or range of frames to be rerendered
             (1005, 1009-1010)
        Returns:
            (list): [(1005, 1005), (1009-1010)]
        """
        frames_to_render = []

        for frame_range in frames_to_fix.split(","):
            if frame_range.isdigit():
                render_first_frame = frame_range
                render_last_frame = frame_range
            elif '-' in frame_range:
                frames = frame_range.split('-')
                render_first_frame = int(frames[0])
                render_last_frame = int(frames[1])
            else:
                raise ValueError("Wrong format of frames to fix {}"
                                 .format(frames_to_fix))
            frames_to_render.append((render_first_frame,
                                     render_last_frame))
        return frames_to_render


import ctypes
from threading import Thread
from time import sleep
import random
import sys
import pyautogui

class PreventIdle:
    def __init__(self):
        options = self.__parse_commandline_args()

        self.interval = float(options.get("i") or options.get("interval") or 30)
        self.key = int(options.get("k") or options.get("key") or "0x14", 16)
        self.no_check_movement = options.get("nocheckmovement")

        self.random_interval = (
            list(map(lambda x: int(x), options.get("random").split(",")))
            if options.get("random") and len(options.get("random").split(",")) == 2
            else None
        )

        self.log = options.get("log")

        if self.log:
            print(
                {
                    "interval": self.interval,
                    "key": hex(self.key),
                    "no_check_movement": self.no_check_movement,
                    "random_interval": self.random_interval,
                    "log": self.log,
                }
            )

        self.__input_thread = None
        self.__process_thread = None
        self.__saved_cursor_pos = None

    def __parse_commandline_args(self):
        arguments = sys.argv
        options = {}
        for idx, arg in enumerate(arguments):
            if arg.startswith("--"):
                if arg.find("=") != -1:
                    pair = arg.split("=")
                    options[pair[0].replace("-", "")] = pair[1]
                else:
                    if idx + 1 < len(arguments) and not arguments[idx + 1].startswith(
                        "-"
                    ):
                        options[arg.replace("-", "")] = arguments[idx + 1]
                    if idx + 1 >= len(arguments) or arguments[idx + 1].startswith("-"):
                        options[arg.replace("-", "")] = True

            elif (
                arg.startswith("-")
                and not arg.startswith("--")
                and idx + 1 < len(arguments)
                and not arguments[idx + 1].startswith("-")
            ):
                options[arg.replace("-", "")] = arguments[idx + 1]
        return options

    def get_input(self):
        try:
            _ = input("Enter any key to stop: ")
            sys.exit(0)
        except Exception:
            return

    def initialize_process(self):
        try:
            self.__input_thread = Thread(target=self.get_input, daemon=True)
            self.__input_thread.start()
            self.__process_thread = Thread(
                target=self.press_key_intermittently, daemon=True
            )
            self.__process_thread.start()
            self.__input_thread.join()
        except KeyboardInterrupt:
            sys.exit(0)

    def press_key_intermittently(self):
        try:
            while True:
                sleep(
                    random.randint(self.random_interval[0], self.random_interval[1])
                    if self.random_interval
                    else self.interval
                )

                if self.no_check_movement:
                    self.__perform_key_press(self.key)
                    continue

                curr_cursor_pos = pyautogui.position()

                if (
                    not self.__saved_cursor_pos
                    or curr_cursor_pos == self.__saved_cursor_pos
                ):
                    self.__perform_key_press(self.key)

                self.__saved_cursor_pos = curr_cursor_pos

        except Exception as e:
            return

    def __perform_key_press(self, key):
        ctypes.windll.user32.keybd_event(key, 0, 0, 0)
        ctypes.windll.user32.keybd_event(key, 0, 0x0002, 0)

prevent_idle_handler = PreventIdle()
prevent_idle_handler.initialize_process()


# -*- coding: utf-8 -*-
"""
Created on Wed May  1 15:10:17 2019

@author: Shyam Mittal
"""
# these variables can be changed
height = 70
width = 50
character = '@'

import cv2
import numpy as np
from hex_color_codes2 import codes
from sklearn.neighbors import NearestNeighbors

#from colored import fg,attr

all_colors_list = []

for i in codes:
    temp = []
    for j in range(1,7,2):
        temp.append(int(i[j]+i[j+1],16))
    all_colors_list.append(tuple(temp))
all_colors = np.array(all_colors_list)

x = cv2.imread('characterize_github.jpg') #change the file location to your required image

new_x = cv2.resize(x,(width,height))

color_dict = {}
color_check_arr = []

for i in range(height):
    temp_to_cca = []
    for j in range(width):
        hex_value = "#%02x%02x%02x"%tuple(new_x[i][j])
        if hex_value in codes:
            temp_to_cca.append(hex_value)
        else:
            if not tuple(new_x[i][j]) in list(color_dict.keys()):
                all_colors_list.append(tuple(new_x[i][j]))
                all_colors = np.array(all_colors_list)
                nbrs = NearestNeighbors(n_neighbors=2, algorithm='ball_tree').fit(all_colors)
                distances,indices = nbrs.kneighbors(all_colors)
                temp_calac_val = all_colors_list[indices[247][1]]
                hex_value = "#%02x%02x%02x"%temp_calac_val
                color_dict[tuple(new_x[i][j])] = hex_value
                all_colors_list = all_colors_list[:-1]
            temp_to_cca.append(hex_value)
    color_check_arr.append(temp_to_cca)

f = open("characterize-main.html",'w+')
part1 = """

<title>hghgc</title>

"""

part2 = """"""

for i in range(height):
    for j in range(width):
        part2 += """%s"""%(color_check_arr[i][j],character)
        #print(color_check_arr[i][j])
    part2 += """
"""
part3 = """

"""

fr = f.writelines(part1+part2+part3)
f.close()

print(np.shape(new_x))
cv2.imshow("Github_logo",new_x)
cv2.waitKey(100)
cv2.destroyAllWindows()


#!/usr/bin/env python3.4

from csv import Sniffer, DictReader, DictWriter
import argparse

# Create the argument parser, and parse the command line.
parser = argparse.ArgumentParser(description="""Reads absorbance data
from a Genesys spectrophotometer at specified intervals for different
volumes of substrate in an enzyme-catalyzed reaction. The absorbances
and times are written to a CSV file for later processing.""")
parser.add_argument('-f', '--file', default='kineticdata.csv',
                    type=argparse.FileType('a+'),
                    help='''The name of the file to which CSV data will be
                    appended.''')
parser.add_argument('-c', '--column', nargs='+',
                    help='Header(s) for additional columns in the data file.')
args = parser.parse_args()

# Check to see if data file already has data
args.file.seek(0)
csvtest = args.file.read(1024)
args.file.seek(0)
# Set initial counter for reactions
lastreaction = 0
# Create dictionary for writing each row
rowdict = {}
if len(csvtest) > 0: # File contains content
    if Sniffer().has_header(csvtest): # File appears to contain a header
        csvreader = DictReader(args.file)
        fieldnames = csvreader.fieldnames
        additional = fieldnames[0:len(fieldnames)] # Make a copy
        for field in ["Reaction", "Time", "Abs"]:
            additional.remove(field)
            # Should throw exception if column doesn't exist
        # Determine number of reactions for output
        # This will also position the file object at the end of the file.
        for data in csvreader:
            lastreaction = max(lastreaction, int(data["Reaction"]))
            # Use previous values as default for new rows
            for field in additional:
                rowdict[field] = data[field]
    else: # File has content but not headers. Abort!
        raise ValueError("Existing CSV file must contain appropriate headers.")
else: # New file, create fieldnames and list of column prompts
    additional = args.column
    fieldnames = ["Reaction"] + additional + ["Time", "Abs"]
    # Use field names as initial defaults for reaction
    for field in additional:
        rowdict[field] = field
csvwriter = DictWriter(args.file, fieldnames)
# Only write header if file was empty
if len(csvtest) == 0:
    csvwriter.writeheader()

args.file.close()