import unittest
from unittest.mock import MagicMock
from app.classes.spec.declaration import EventDeclaration, AssetDeclaration
from app.classes.spec.domain_object import DomainObject
from app.classes.spec.contract_spec_parameter import ContractSpecParameter

from app.classes.pattern_classes.pattern_class import EventPatternClass, PatternClass
from app.src.domain_update_extractor.domain_update_extractor import DomainUpdateExtractor
from app.src.domain_update_extractor.asset_declaration_mapper import IMapAssetDeclarations
from app.src.domain_update_extractor.declaration_mapper import IMapDeclarations
from app.src.domain_update_extractor.domain_model_mapper import IMapDeclarationToDomain
from app.src.domain_update_extractor.contract_parm_mapper import IMapContractParms

from tests.helpers.test_objects import CustomEvents

class DomainUpdateExtractorTests(unittest.TestCase):
    def setUp(self) -> None:
        self.decl_mapper = IMapDeclarations()
        self.domain_mapper = IMapDeclarationToDomain()
        self.csp_mapper = IMapContractParms()

        self.sut = DomainUpdateExtractor(
            self.decl_mapper,
            self.domain_mapper,
            self.csp_mapper
        )

    def test_domain_update_extractor(self):
        asset_decls = [
            AssetDeclaration('a1', 'A1', []),
            AssetDeclaration('a2', 'A2', []),
            EventDeclaration('evt_e1', 'E1',  [])
        ]
        self.decl_mapper.map = MagicMock(return_value=asset_decls)

        domain_obj = DomainObject('a', 'b', [])
        self.domain_mapper.map = MagicMock(return_value=domain_obj)

        csps = [ContractSpecParameter('a','b')]
        self.csp_mapper.map = MagicMock(return_value = csps)

        pattern_class = EventPatternClass()
        pattern_class.nl_event = CustomEvents.paying()

        result = self.sut.extract(pattern_class, None, None)

        self.assertEqual(len(result.declarations), 3)
        self.assertEqual(len(result.domain_objects), 3)
        self.assertEqual(len(result.contract_parms), 1)
        self.assertEqual(result.declarations[2].name, 'evt_e1')
        self.assertEqual(self.decl_mapper.map.call_count, 1)
        self.assertEqual(self.domain_mapper.map.call_count, 3)
        self.assertEqual(self.csp_mapper.map.call_count, 1)

    def test_domain_update_extractor_empty(self):
        self.decl_mapper.map = MagicMock(return_value=[])
        self.domain_mapper.map = MagicMock(return_value=None)
        self.csp_mapper.map = MagicMock(return_value=[])

        pattern_class = PatternClass()
        result = self.sut.extract(pattern_class, None, None)

        self.assertEqual(len(result.declarations), 0)
        self.assertEqual(len(result.domain_objects), 0)
        self.assertEqual(len(result.contract_parms), 0)
        self.assertEqual(self.decl_mapper.map.call_count, 1)
        self.assertEqual(self.domain_mapper.map.call_count, 0)
        self.assertEqual(self.csp_mapper.map.call_count, 1)

if __name__ == '__main__':
    unittest.main()


#A complexidade é O(1), pois as operações de empilhar e desempilhar não dependem do tamanho do vetor.

class Pilha_Dupla:
    def __init__(self, tamanho):
        self.tamanho = tamanho
        self.vetor = [None] * tamanho
        self.topo_pilha1 = -1
        self.topo_pilha2 = tamanho

    def empilhar(self, pilha, valor):
        if pilha == 1:
            if self.topo_pilha1 < self.topo_pilha2 - 1:
                self.topo_pilha1 += 1
                self.vetor[self.topo_pilha1] = valor
            else:
                print("Pilha 1 está cheia.")
        elif pilha == 2:
            if self.topo_pilha2 > self.topo_pilha1 + 1:
                self.topo_pilha2 -= 1
                self.vetor[self.topo_pilha2] = valor
            else:
                print("Pilha 2 está cheia.")
        else:
            print("Pilha inválida.")

    def desempilhar(self, pilha):
        if pilha == 1:
            if self.topo_pilha1 >= 0:
                valor = self.vetor[self.topo_pilha1]
                self.topo_pilha1 -= 1
                return valor
            else:
                print("Pilha 1 está vazia.")
        elif pilha == 2:
            if self.topo_pilha2 < self.tamanho:
                valor = self.vetor[self.topo_pilha2]
                self.topo_pilha2 += 1
                return valor
            else:
                print("Pilha 2 está vazia.")
        else:
            print("Pilha inválida.")

pilha_dupla = Pilha_Dupla(10)
pilha_dupla.empilhar(1, 5)
pilha_dupla.empilhar(2, 10)
pilha_dupla.empilhar(1, 15)
pilha_dupla.empilhar(2, 20)

print(pilha_dupla.desempilhar(1))
print(pilha_dupla.desempilhar(2))

p2 = Pilha_Dupla(6)
p2.empilhar(1,3)
p2.empilhar(2,2)
p2.empilhar(2,3)
p2.empilhar(2,5)
p2.empilhar(2,6)
p2.empilhar(2,9)
print(p2.empilhar(2,0))


"""
In this model, we define a schema for petri nets, and then a subclass of acset
with some convenience methods.
"""
from pathlib import Path

from acsets import (
    CATLAB_SCHEMAS_DIRECTORY,
    HERE,
    JSON_SCHEMAS_DIRECTORY,
    ACSet,
    Attr,
    AttrType,
    Hom,
    Ob,
    Schema,
)

Species = Ob(name="S", title="Species")
Transition = Ob(name="T", title="Transition")
Input = Ob(name="I", title="Input")
Output = Ob(name="O", title="Output")

hom_it = Hom(name="it", dom=Input, codom=Transition, title="Input transition morphism")
hom_is = Hom(name="is", dom=Input, codom=Species, title="Input species morphism")
hom_ot = Hom(name="ot", dom=Output, codom=Transition, title="Output transition morphism")
hom_os = Hom(name="os", dom=Output, codom=Species, title="Output species morphism")

petri_obs = [Species, Transition, Input, Output]
petri_homs = [hom_it, hom_is, hom_ot, hom_os]

Name = AttrType(name="Name", ty=str, title="Name")
Concentration = AttrType(name="Concentration", ty=float, title="Concentration")
Rate = AttrType(name="Rate", ty=float, title="Rate")
Prop = AttrType(name="Prop", ty=dict, title="Property")

attr_sname = Attr(
    name="sname",
    dom=Species,
    codom=Name,
    title="Species name",
    description="An attribute representing the name of a species.",
)
attr_concentration = Attr(
    name="concentration",
    dom=Species,
    codom=Concentration,
    title="Species concentration",
    description="An attribute representing the concentration of a species.",
)
attr_sprop = Attr(
    name="sprop",
    dom=Species,
    codom=Prop,
    title="Species properties",
    description="An attribute representing the properties of a species.",
)
attr_tname = Attr(
    name="tname",
    dom=Transition,
    codom=Name,
    title="Transition name",
    description="An attribute representing the name of a transition.",
)
attr_rate = Attr(
    name="rate",
    dom=Transition,
    codom=Rate,
    title="Transition rate",
    description="An attribute representing the rate of a transition.",
)
attr_tprop = Attr(
    name="tprop",
    dom=Transition,
    codom=Prop,
    title="Transition properties",
    description="An attribute representing the properties of a transition.",
)

labelled_ats = [Name]
labelled_attrs = [attr_sname, attr_tname]

rxn_ats = [Concentration, Rate]
rxn_attrs = [attr_concentration, attr_rate]

prop_ats = [Prop]
prop_attrs = [attr_sprop, attr_tprop]

SchPetriNet = Schema(
    "PetriNet",
    petri_obs,
    petri_homs,
    [],
    [],
)
SchLabelledPetriNet = Schema(
    "LabelledPetriNet", petri_obs, petri_homs, labelled_ats, labelled_attrs
)
SchReactionNet = Schema("ReactionNet", petri_obs, petri_homs, rxn_ats, rxn_attrs)
SchLabelledReactionNet = Schema(
    "LabelledReactionNet", petri_obs, petri_homs, labelled_ats + rxn_ats, labelled_attrs + rxn_attrs
)
SchPropertyPetriNet = Schema("PropertyPetriNet", petri_obs, petri_homs, prop_ats, prop_attrs)
SchPropertyLabelledPetriNet = Schema(
    "PropertyLabelledPetriNet",
    petri_obs,
    petri_homs,
    labelled_ats + prop_ats,
    labelled_attrs + prop_attrs,
)
SchPropertyReactionNet = Schema(
    "PropertyReactionNet", petri_obs, petri_homs, rxn_ats + prop_ats, rxn_attrs + prop_attrs
)
SchPropertyLabelledReactionNet = Schema(
    "PropertyLabelledReactionNet",
    petri_obs,
    petri_homs,
    labelled_ats + rxn_ats + prop_ats,
    labelled_attrs + rxn_attrs + prop_attrs,
)

class Petri(ACSet):
    """
    A subclass of ACSet customized for petri nets.

    .. code-block::

        sir = Petri()
        s,i,r = sir.add_species(3)
        sir.set_subpart(s,attr_sname,"susceptible")
        sir.set_subpart(s,attr_sprop, { "uuid": "dae22e85-d941-4156-b559-d153a44356f3" })
        inf = sir.add_transitions([([s,i],[i,i])])
        sir.set_subpart(inf,attr_tname,"infection")
        sir.set_subpart(inf,attr_tprop, { "uuid": "bba26d0e-3ce5-41e5-ac0e-6be35535d534" })
    """

    def __init__(self, name="Petri", schema=SchPropertyLabelledReactionNet):
        """Initialize a new petri net."""
        super(Petri, self).__init__(schema.name, schema)

    def add_species(self, n: int) -> range:
        """Add `n` number of species to the petri net

        Args:
            n:  The number of species to add to the petri net.

        Returns:
            A range of the indexes of the species that were inserted into the petri net.
        """
        return self.add_parts(Species, n)

    def add_transitions(self, transitions: list[tuple[list[int], list[int]]]) -> range:
        """Add transitions to the petri net

        Args:
            transitions: A list of tuples where each tuple has two items: the first is a list of the input species and the second is a list of the output species.

        Returns:
            A range of the of the indexes of the transitions that were inserted into the petri net.
        """
        ts = self.add_parts(Transition, len(transitions))
        for t, (ins, outs) in zip(ts, transitions):
            for s in ins:
                arc = self.add_part(Input)
                self.set_subpart(arc, hom_it, t)
                self.set_subpart(arc, hom_is, s)
            for s in outs:
                arc = self.add_part(Output)
                self.set_subpart(arc, hom_ot, t)
                self.set_subpart(arc, hom_os, s)
        return ts

if __name__ == "__main__":
    for schema in [
        SchPetriNet,
        SchLabelledPetriNet,
        SchReactionNet,
        SchLabelledReactionNet,
        SchPropertyPetriNet,
        SchPropertyLabelledPetriNet,
        SchPropertyReactionNet,
        SchPropertyLabelledReactionNet,
    ]:
        schema_filename = "{}.json".format(schema.name)
        CATLAB_SCHEMAS_DIRECTORY.joinpath(schema_filename).write_text(
            schema.schema.json(indent=2, ensure_ascii=False, sort_keys=True)
        )
        jsonschema_path = JSON_SCHEMAS_DIRECTORY.joinpath(schema_filename)
        schema.write_schema(
            JSON_SCHEMAS_DIRECTORY.joinpath(jsonschema_path),
            uri="https://raw.githubusercontent.com/AlgebraicJulia/py-acsets/main/src/acsets/{}".format(
                Path(jsonschema_path).relative_to(HERE)
            ),
        )


from collections import Counter
from argparse import ArgumentParser
from tweepy import Cursor
from make_client import make_client

def get_hashtags(tweet: dict) -> list:
    """
    The tweet argument is a dict. So get 'entities' key or return a empty dict.
    This is required for the second .get() to not throw a error where we try to
    get 'hashtags'
    """
    entities = tweet.get('entities', {})
    hashtags = entities.get('hashtags', [])

    return ["#" + tag['text'] for tag in hashtags]

def main():
    hashtags = Counter()
    args = ArgumentParser()
    args.add_argument(
        "username",
        help="username of the profile to parse"
    )
    args.add_argument("-c", "--count", type=int, help="Number of tweets")
    args = args.parse_args()

    client = make_client()
    curr = Cursor(client.user_timeline, screen_name=args.username, count=args.count)

    for page in curr.pages(10):
        for tweet in page:
            hashtags.update(get_hashtags(tweet._json))

    print(hashtags.most_common(20))

if __name__ == "__main__":
    main()


import torch
import torch.nn as nn
import torch.optim as optim
import config
import os
from dataset import MyTestDataset
from generator_model import Generator
from utils import save_test_examples, load_checkpoint
import argparse

def parser():
    parser = argparse.ArgumentParser(description="test.py: Model testing script of White-box Cartoonization. For inference, please refer to inference.py")
    parser.add_argument("--dataroot",default=config.VAL_PHOTO_DIR,
                        help="path to image data test folder. default path:"+f"{config.VAL_PHOTO_DIR}")
    parser.add_argument("--weight_path", default=os.path.join(config.CHECKPOINT_FOLDER, config.LOAD_CHECKPOINT_GEN),
                        help="path to model weight file. default path:"+f"{os.path.join(config.CHECKPOINT_FOLDER, config.LOAD_CHECKPOINT_GEN)}")
    parser.add_argument("--dest_folder",default=config.RESULT_TEST_DIR,
                        help="path to destination folder for saving images. default path:"+f"{config.RESULT_TEST_DIR}")
    parser.add_argument("--sample_size", type=int, default= 50,
                        help="only inference certain number of images. default=50.")
    parser.add_argument('--shuffle', action='store_true',
                        help="shuffle test data")
    parser.add_argument('--concat_img', action='store_true',
                        help="concat input and output images instead of separated save files")
    parser.add_argument('--no_post_processing', action='store_true',
                        help="disable post_processing (not recommended). This will probably cause output to have terrible noise")
    return parser.parse_args()

def check_arguments_errors(args):
    if not os.path.isdir(args.dataroot):
        raise(ValueError("Invalid image data folder path {}".format(os.path.abspath(args.dataroot))))
    if not os.path.isfile(args.weight_path):
        raise(ValueError("Invalid model weight path {}".format(os.path.abspath(args.weight_path))))

def test_fn(args):
    print("Using Device: " + config.DEVICE)
    gen = Generator(img_channels=3).to(config.DEVICE)
    opt_gen = optim.Adam(gen.parameters(), lr=config.LEARNING_RATE, betas=(0.5, 0.999))
    load_checkpoint(gen, opt_gen, config.LEARNING_RATE, path=args.weight_path)
    test_dataset = MyTestDataset(args.dataroot)

    shuffle = True if(args.shuffle) else False
    concat_img = True if(args.concat_img) else False
    post_processing = False if(args.no_post_processing) else True

    print("=> Saving Test outputs")
    print("="*80)
    save_test_examples(gen, test_dataset, dest_folder=args.dest_folder, num_samples=args.sample_size, shuffle=shuffle, concat_image=concat_img, post_processing=post_processing)
    print(f"=> Finished inferencing {args.sample_size} images")
    print("="*80)

if __name__ == "__main__":
    args = parser()
    check_arguments_errors(args)
    test_fn(args)


import numpy as np
import scipy as sp
from quaternion import from_rotation_matrix, quaternion, as_euler_angles, from_euler_angles, as_quat_array
from scipy.spatial.transform import Rotation as R
from matplotlib import pyplot as plt

from rlbench.environment import Environment
from rlbench.action_modes import ArmActionMode, ActionMode
from rlbench.observation_config import ObservationConfig
from rlbench.tasks import *

############################################################
########### TensorForce Includes ###########################
import sys
sys.path.append('../')
sys.path.append(sys.path[0] + '/TensorForceFiles')

import gym
import rlbench.gym
from tensorforce import Agent

from DQN_class import *
from TensorForce_class import *
########### TensorForce Includes ###########################
############################################################

def skew(x):
    return np.array([[0, -x[2], x[1]],
                    [x[2], 0, -x[0]],
                    [-x[1], x[0], 0]])

def sample_normal_pose(pos_scale, rot_scale):
    '''
    Samples a 6D pose from a zero-mean isotropic normal distribution
    '''
    pos = np.random.normal(scale=pos_scale)

    eps = skew(np.random.normal(scale=rot_scale))
    R = sp.linalg.expm(eps)
    quat_wxyz = from_rotation_matrix(R)

    return pos, quat_wxyz

class NoisyObjectPoseSensor:

    def __init__(self, env):
        self._env = env

        self._pos_scale = [0.005] * 3
        self._rot_scale = [0.01]  * 3

    def get_poses(self):
        objs = self._env._scene._active_task.get_base().get_objects_in_tree(exclude_base=True, first_generation_only=False)
        obj_poses = {}

        for obj in objs:
            name = obj.get_name()
            pose = obj.get_pose()

            pos, quat_wxyz = sample_normal_pose(self._pos_scale, self._rot_scale)
            gt_quat_wxyz = quaternion(pose[6], pose[3], pose[4], pose[5])
            perturbed_quat_wxyz = quat_wxyz * gt_quat_wxyz

            # pose[:3] += pos
            # pose[3:] = [perturbed_quat_wxyz.x, perturbed_quat_wxyz.y, perturbed_quat_wxyz.z, perturbed_quat_wxyz.w]

            obj_poses[name] = pose
        return obj_poses

if __name__ == "__main__":
    # action_mode = ActionMode(ArmActionMode.DELTA_EE_POSE_PLAN) # See rlbench/action_modes.py for other action modes
    action_mode = ActionMode(ArmActionMode.ABS_EE_POSE_PLAN) # See rlbench/action_modes.py for other action modes

    env = Environment(action_mode, '', ObservationConfig(), False)
    task = env.get_task(PutGroceriesInCupboard) # available tasks: EmptyContainer, PlayJenga, PutGroceriesInCupboard, SetTheTable

    len_episode = 10

    # agent = TensorForceDQN()
    agent = TensorForceClass(load='rl_models')

    agent.len_episode = len_episode
    obj_pose_sensor = NoisyObjectPoseSensor(env)

    descriptions, obs = task.reset()
    print(descriptions)

    target_name = 'sugar'
    episode_num =0
    rews = []
    save_freq = 20

    while True:
        episode_num += 1
        total_reward = 0
        obj_poses = obj_pose_sensor.get_poses()
        target_state = list(obj_poses[target_name])
        target_state[2] += 0.1

        best_reward = 0
        for i in range(len_episode):
            # Getting noisy object poses
            obj_poses = obj_pose_sensor.get_poses()

            # Getting various fields from obs
            current_joints = obs.joint_positions
            gripper_pose = obs.gripper_pose
            rgb = obs.wrist_rgb
            depth = obs.wrist_depth
            mask = obs.wrist_mask
            agent.has_object = len(task._robot.gripper._grasped_objects) > 0

            actions = agent.act(obs,obj_poses)

            try:
                obs, reward, terminal = task.step(actions)

                ### Check current distance
                agent.dist_after_action = np.linalg.norm(target_state[:3] - obs.gripper_pose[:3])

                ### Calculate reward
                reward, terminal = agent.calculateReward()

            except:
                reward = -agent.dist_before_action*5
                terminal = False

            ## Observe results
            agent.agent.observe(terminal=terminal, reward=reward)
            total_reward += reward

            if terminal:
                break

            print('Iteration: %i, Reward: %.1f' %(i, reward))

        print('Episode: %i, Average Reward: %.1f' %(episode_num,total_reward))
        rews.append(total_reward)
        print('Reset')
        descriptions, obs = task.reset()
        agent.agent.reset()

        if episode_num % save_freq == save_freq - 1: agent.agent.save(directory='rl_models')

    env.shutdown()
    agent.agent.close()


import sys
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import cross_validate
from sklearn.svm import SVR
from RegressionMetrics import RegressorMetrics
from numpy import arange
from timeit import default_timer as timer

# from numba import jit, cuda , float32
# @jit(target ="cuda")
# @cuda.jit
def gen(x):
    out = []
    out.append(x)
    while(x < 1):
        x = x * 10
        out.append(x)

    x = 2
    out.append(x)
    while(x <= 10000):
        x = x * 2
        out.append(x)

    return out
# def float_range(start, stop, step):
#   while start < stop:
#     yield float(start)
#     start += decimal.Decimal(step)

# @jit(target ="cuda")
# @cuda.jit
def svmRbf(data, labels, nof ,file , filename):
    start = timer()
    out = gen(0.00000001)
    params = {
        # 'C': out,
        'C': [0.1, 0.5, 1, 5, 10, 20],
        'gamma': arange(0.1 , 10.0 , 0.1),
        'kernel': ['rbf']
    }
    clf = GridSearchCV(SVR(), params, n_jobs=-1, cv=nof)
    clf.fit(data, labels)
    best_parameters = clf.best_params_
    c = best_parameters['C']
    gamma = best_parameters['gamma']

    model = SVR(C=c,kernel='rbf' , gamma= gamma)
    # cvs = cross_val_score(model, data, labels, cv=nof)
    # print(cvs)
    # print(cvs.mean() , "\t" , cvs.std())
    r = RegressorMetrics()
    r.set_predictorName("SVR_rbf")
    r.set_contin(False)
    r.set_DatasetName(filename)
    bestparameters = 'C= ' +str(c) + ' gamma= '+str(gamma)
    r.set_best(bestparameters)
    r.PrintbestParameters()

    cv_results = cross_validate(model, data, labels, cv=nof, scoring=r.scorer, return_train_score = True)
    r.Print("SVR_rbf")
    r.Print("test")
    r.PrintResults("MAE" , cv_results['test_MAE'])
    r.PrintResults("RMAE" , cv_results['test_RMAE'])
    r.PrintResults("MSE" , cv_results['test_MSE'])
    r.PrintResults("RMSE" , cv_results['test_RMSE'])
    r.PrintResults("RS" , cv_results['test_RS'])
    r.Print("train")
    r.PrintResults("MAE" , cv_results['train_MAE'])
    r.PrintResults("RMAE" , cv_results['train_RMAE'])
    r.PrintResults("MSE" , cv_results['train_MSE'])
    r.PrintResults("RMSE" , cv_results['train_RMSE'])
    r.PrintResults("RS" , cv_results['train_RS'])
    print("time:", timer()-start)

    # file.write(str(cv_results['test_MAE']))
    # file.write(str(cv_results['test_RMAE']))
    # file.write(str(cv_results['test_MSE']))
    # file.write(str(cv_results['test_RMSE']))
    # file.write(str(cv_results['test_RS']))


#!/usr/bin/env python

'''Plot relative battery lifes of regulated and deregulated approaches as
functions of initial voltage and footprint based on the following assumptions:
  1) Equal footprints (twice the area allowed for deregulated)
  2) The workload is that requiring all the deregulated cores at minimal voltage.
'''

# Justify vmin with DRAM low.
vmin = 1.8
bat_capacity = 600.0 * 1E-3 * 60.0 * 60.0 * 4 # Ws
conv_eff = 0.85
parallel_eff = 0.85
reg_system_r = 5.0 # Ohm
leakage = 0.00
cutout = 0.85

import math
import shutil
import os
import sys

def frange(a, b, inc):
	return (a + i * inc for i in range(int(math.ceil((b - a) / inc))))

def actual_work(proc):
	return proc ** parallel_eff

def actual_proc(work):
	return math.ceil(work ** (1.0 / parallel_eff))

class Multicore(object):
	time_step = 2.0

	def __init__(self, bat, proc_cnt, tot_r, work_rate):
		# Work rate is for all processors at 1 volt
		self.bat = bat
		self.proc_cnt = proc_cnt
		self.tot_r = tot_r
		self.work_rate = work_rate
		self.leakage_i = leakage * bat.voltage() / tot_r
		self.run_time_s = 0.0
		while self.functioning():
			cap_step = self.power() * self.time_step
			self.bat.deplete_capacity(cap_step)
			self.run_time_s += self.time_step

class RegMC(Multicore):
	def __init__(self, bat, proc_cnt, tot_r, work_rate, conv_eff):
		self.conv_eff = conv_eff
		self.outvolt = work_rate / actual_work(proc_cnt)
		Multicore.__init__(self, bat, proc_cnt, tot_r, work_rate)

	def functioning(self):
		return self.bat.cap > 0.0 and self.bat.voltage() * cutout > self.outvolt

	def power(self):
		leak_p = self.leakage_i * self.outvolt
		dyn_p = self.outvolt ** 2.0 / self.tot_r / conv_eff
#		print leak_p / dyn_p
		return leak_p + dyn_p

class DeregMC(Multicore):
	def __init__(self, bat, proc_cnt, tot_r, work_rate, vmin):
		self.vmin = vmin
		Multicore.__init__(self, bat, proc_cnt, tot_r, work_rate)

	def functioning(self):
		return self.bat.cap > 0.0 and self.bat.voltage() > self.vmin

	def power(self):
		proc = actual_proc(self.work_rate / self.bat.voltage())
#		print proc, self.proc_cnt
		proc_rat = proc / self.proc_cnt
		leak_p = self.leakage_i * self.bat.voltage() * proc_rat
		dyn_p = self.bat.voltage() ** 2.0 / self.tot_r * proc_rat
#		print leak_p / dyn_p
		return leak_p + dyn_p

def fname(bname, bat_type_i, val, suffix):
	return bname + str(bat_type_i) + ('a%.2f' % val) + '.' + suffix

cmp_min = {}
cmp_max = {}

def gen_data(dereg_reg_area_ratio):
	cmp_min[dereg_reg_area_ratio] = 0.0
	cmp_max[dereg_reg_area_ratio] = 0.0
	for bat_type_i in range(len(bat_types)):
		reg_f = open(fname('reg', bat_type_i, dereg_reg_area_ratio, 'data'), 'w')
		dereg_f = open(fname('dereg', bat_type_i, dereg_reg_area_ratio, 'data'), 'w')
		cmp_f = open(fname('cmp', bat_type_i, dereg_reg_area_ratio, 'data'), 'w')
		for dereg_proc_cnt in range(1, 17):
			reg_proc_cnt = int(dereg_proc_cnt / dereg_reg_area_ratio)
			if reg_proc_cnt == 0:
				continue
			work_rate = actual_work(dereg_proc_cnt) * vmin
			bat_type = bat_types[bat_type_i]
			reg = RegMC(bat_type(bat_capacity), reg_proc_cnt, reg_system_r,
				work_rate, conv_eff)
			if reg.run_time_s != 0:
				dereg = DeregMC(bat_type(bat_capacity), dereg_proc_cnt,
					reg_system_r / dereg_reg_area_ratio, work_rate, vmin)
				reg_f.write('%d %d %f\n' % (reg_proc_cnt, bat_type_i,
					reg.run_time_s / 60.0))
				dereg_f.write('%d %d %f\n' % (dereg_proc_cnt, bat_type_i,
					dereg.run_time_s / 60.0))
				val = 100.0 * (dereg.run_time_s - reg.run_time_s) / reg.run_time_s
				cmp_f.write('%d %f\n' % (dereg_proc_cnt, val))
				cmp_min[dereg_reg_area_ratio] = \
					min(cmp_min[dereg_reg_area_ratio], val)
				cmp_max[dereg_reg_area_ratio] = \
					max(cmp_max[dereg_reg_area_ratio], val)
		reg_f.write('\n\n')
		dereg_f.write('\n\n')
		cmp_f.write('\n\n')

# Plot the discharge curves
for bti in range(len(bat_types)):
	f = file('discharge%d.data' % bti, 'w')
	for x, y in bat_types[bti].table:
		f.write('%e %e\n' % (x * 100.0, y))
	f.close()

f = file('discharge.gp', 'w')
f.write('''set terminal postscript eps enhanced
#set title 'Battery discharge curves'
set xlabel 'Remaining capacity (%)'
set xrange [100:0]
set ylabel 'Voltage (V)'
''')
all_plt = ', \\\n'.join("'discharge%d.data' w l t '%s'" % (i, bat_types[i].name)
	for i in range(len(bat_types)))
f.write('plot ' + all_plt + '\n')
f.close()

os.system('gnuplot < discharge.gp > discharge.eps')

for dereg_reg_area_ratio in frange(1.0, 1.5, 0.05):
	gen_data(dereg_reg_area_ratio)
	gpfile = 'cmp' + ('%.2f' % dereg_reg_area_ratio) + '.gp'
	shutil.copyfile('cmp.gp', gpfile)
	f = file(gpfile, 'a')
	f.write('plot ')
	f.write(', \\\n'.join("'" + fname('cmp', i, dereg_reg_area_ratio, 'data') +
		"' w l t '" + bat_types[i].name + "'"
		for i in range(len(bat_types))))
	f.write('\n')
	f.close()
	os.system('gnuplot < ' + gpfile + ' > ' +
		'cmp' + ('%.2f' % dereg_reg_area_ratio) + '.eps')


"""Match WebScraper."""

import csv
import logging
import pdb
import sqlite3
from datetime import datetime
# from collections import namedtuple
# from threading import Thread
from os.path import isfile
# from selenium.webdriver.firefox.options import Options
from time import ctime, sleep

from bs4 import BeautifulSoup
from selenium.common.exceptions import ElementClickInterceptedException
from selenium.webdriver import Chrome
from selenium.webdriver.common.keys import Keys

FORMAT = '%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(message)s'

logging.basicConfig(format=FORMAT, level=logging.DEBUG, filename='match_logs.log')

logger = logging.getLogger("football_match_logger")
logger.warning("Football Match Logger")
logger.warning("-"*80)
logger.warning("Starting at : " + datetime.now().strftime("%d:%m:%Y $H:%M:%S"))
logger.warning("-"*80)

class MatchesDBAdapter():
    def __init__(self):
        self.db_connection = sqlite3.connect('football_matches.db')
        self.cursor = self.db_connection.cursor()
        self.create_matches_table_query = '''
            CREATE TABLE IF NOT EXISTS matches
            (id INTEGER PRIMARY KEY,
             is_stats_scraped INTEGER DEFAULT 0,
             team1 TEXT NOT NULL,
             team2 TEXT NOT NULL,
             startDate timestamp,
             scraped_at timestamp,
             match_stats_link TEXT,
             tople_left TEXT,
             tople_right TEXT,
             kormer_left TEXT,
             kormer_right TEXT,
             gol_left TEXT,
             gol_right TEXT,
             kirmizi_left TEXT,
             kirmizi_right TEXT,
             orta_left TEXT,
             orta_right TEXT,
             CONSTRAINT unique_matches UNIQUE(team1,team2,startDate));
            '''

        self.cursor.execute(self.create_matches_table_query)
        self.db_connection.commit()
        logger.info("Match Table Created")

        self.insert_matches_query = '''
            INSERT INTO 'matches'
            (team1, team2 , startDate, tople_left, tople_right, kormer_left, kormer_right, gol_left, gol_right, kirmize_left, kirmizi_right, orta_left, orta_right, scraped_at, match_stats_link) VALUES
            (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
            '''

        self.insert_matches_basic_query = '''
            INSERT INTO 'matches'
            (team1, team2 , startDate, scraped_at, match_stats_link) VALUES
            (?, ?, ?, ?, ?);
            '''

    def populate_data(self, row_data):
        logger.info("Stats Details populated")
        self.cursor.execute(self.insert_matches_query, row_data)
        self.db_connection.commit()

    def populate_data_basic(self, row_data):
        logger.info("Basic details populated")
        self.cursor.execute(self.insert_matches_basic_query, row_data)
        self.db_connection.commit()

class MatchScraper():
    def __init__(self):
        self.base_url = 'https://www.mackolik.com/futbol/canli-sonuclar'
        self.driver = Chrome()
        self.default_sleep_interval = 3 # In seconds
        self.database_adapter = MatchesDBAdapter()

    def clean_up(self):
        self.driver.close()

    def start_scraping(self):
        print("Match Scraping started.....")
        self.driver.get(self.base_url)
        # sleep(self.default_sleep_interval)

        matches = self.driver.find_elements_by_xpath('//div[contains(@class, "widget-livescore__title")]')
        match_links = set()
        print("Orginal Matches : ", len(matches))

        for match in matches:
            anchor =  match.find_element_by_xpath('..').find_element_by_xpath('.//a')
            print("Anchor : ", anchor.get_attribute('href'))
            match_links.add(anchor.get_attribute('href'))

        print("Match Links Found ...")
        print('\n'.join(match_links))

        for match_link in match_links:
            print("matching link : ", match_link)
            # print(match.text)
            # anchor =  match.find_element_by_xpath('..').find_element_by_xpath('.//a')
            # print(anchor.get_attribute('href'))
            self.driver.get(match_link)
            sleep(self.default_sleep_interval)
            # main_window = self.driver.current_window_handle
            scraped_at = datetime.now()
            self.driver.find_element_by_partial_link_text('FIKSTÜR').click()
            sleep(self.default_sleep_interval)
            # print("Here")
            ol = self.driver.find_elements_by_xpath('//ol[contains(@class, "p0c-competition-match-list__days")]')

            for i in ol:
                print(i.tag_name)
                for j in i.find_elements_by_xpath('li'):
                    print(j.tag_name)
                    date_str = j.find_element_by_xpath('div')
                    print(date_str)
                    try:
                        # Needs improvement
                        print(date_str.text.split(' '))
                    except Exception as e:
                        print(e)

                    date_str = date_str.text.split(' ')[1]
                    print(datetime.strptime(date_str, '%d.%m.%Y'))
                    for k in j.find_elements_by_xpath('ol/li'):
                        print('1_1', k.tag_name, k.text, "1_1")
                        try:
                            split_text = k.text.split('\n')
                            date_time_str = date_str + ' '+ split_text[0].strip()
                            print(datetime.strptime(date_time_str, '%d.%m.%Y %H:%M'))
                            date = datetime.strptime(date_time_str, '%d.%m.%Y %H:%M')

                        except ValueError as e:
                            date = datetime.strptime(date_str, '%d.%m.%Y')
                        team1 = split_text[1].strip()
                        team2 = split_text[3].strip()
                        match_stats_link = k.find_element_by_xpath('//a/span[@data-dateformat="time"]').find_element_by_xpath('..').get_attribute('href')

                        data = (team1, team2, date, scraped_at, match_stats_link)
                        self.database_adapter.populate_data_basic(data)
            self.driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w')
        self.clean_up()
        print("Match Scraping completed.....")

    def scrape(self):
        try:
            self.start_scraping()
        except Exception as e:
            print("Error : ", str(e))
            logging.critical("Scraping halted ...!!!!!!!!!!!!!!")
            logging.critical(str(e))
            # Uncomment the line to close the browser in the end in case of error
            # self.driver.quit()

if __name__ == '__main__':
    # exit()
    match_scraper = MatchScraper()
    match_scraper.scrape()


from decimal import Decimal
from rest_framework.serializers import ModelSerializer, ReadOnlyField

from apps.biscuit.models.biscuit import Biscuit, PriceList, ReturnBiscuit
from apps.warehouse.models import WareHouseBiscuit

class BiscuitModelSerializer(ModelSerializer):
    class Meta:
        model = Biscuit
        fields = "__all__"

    def update(self, instance, validated_data):
        instance.name = validated_data.get('name', instance.name)
        instance.description = validated_data.get('description', instance.description)
        instance.price = validated_data.get('price', instance.price)
        instance.save()
        obj = PriceList.objects.filter(biscuit__id=instance.id).first()
        obj.price = validated_data.get('price', instance.price)
        obj.save()
        return instance

class BiscuitCostSerializer(ModelSerializer):
    biscuit = BiscuitModelSerializer(read_only=True, many=False)

    class Meta:
        model = PriceList
        fields = [
            'id',
            'biscuit',
            'price',
            'currency',
            'created_date',
            'modified_date'
        ]

class ReturnDetailBiscuitCostSerializer(ModelSerializer):
    biscuit = BiscuitModelSerializer(read_only=True, many=False)
    client_first_name = ReadOnlyField(source='client.first_name')
    client_last_name = ReadOnlyField(source='client.last_name')

    class Meta:
        model = ReturnBiscuit
        fields = [
            'id',
            'biscuit',
            'comment',
            'quantity',
            'created_date',
            'modified_date',
            'client',
            'client_first_name',
            'client_last_name',
        ]

class ReturnBiscuitSerializer(ModelSerializer):
    class Meta:
        model = ReturnBiscuit
        fields = "__all__"

    def create(self, validated_data):
        biscuit_id = validated_data.get('biscuit')
        quantity = validated_data.get('quantity')
        ware_house_biscuit = WareHouseBiscuit.objects.filter(biscuit_id=biscuit_id).first()
        ware_house_biscuit.add_quantity(Decimal(quantity))
        ware_house_biscuit.set_total_price()
        ware_house_biscuit.set_average_price()
        ware_house_biscuit.save()
        return super().create(validated_data)


import os

from django.shortcuts import render, HttpResponse
from django import forms
from app01.utils.bootstrap import BootStrapForm, BootStrapModelForm
from app01 import models
from django.conf import settings

def upload_list(request):
    if request.method == "GET":
        return render(request, 'upload_list.html')
    # 获取文件对象
    file_object = request.FILES.get("avatar")
    # 根据获取文件名file_object.name
    f = open(file_object.name, mode='wb')
    # 获取文件内容
    for chunk in file_object.chunks():
        f.write(chunk)
    f.close()
    return HttpResponse("....")

class UpForm(BootStrapForm):
    bootstrap_exclude_fields = ['img']

    name = forms.CharField(label="姓名")
    age = forms.IntegerField(label="年龄")
    img = forms.FileField(label="头像")

def upload_form(request):
    title = "Form上传"
    if request.method == "GET":
        form = UpForm()
        return render(request, 'upload_form.html', {"form": form, "title": title})
    # data表单，files文件
    form = UpForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        # print(form.cleaned_data)
        # 读取到内容，处理每个字段的数据
        # 读取图片的内容，写入到文件将中并获取文件夹路径
        image_object = form.cleaned_data.get("img")
        # 路径的分隔符再windows和linux中是不一样的，我们就需要使用os拼接路径
        # 静态static:由于用户访问直接获取的是数据库图片路径，不是真正的图片路径(多了一个app01)，我们就把app01换成http://127.0.0.1:8000/
        # db_file_path = os.path.join("static", "img", image_object.name)  # 数据库存储路径
        # file_path = os.path.join("app01", db_file_path)  # 图片存储路径
        # 动态media,绝对路径:settings.MEDIA_ROOT
        media_path = os.path.join(settings.MEDIA_ROOT, image_object.name)  # 数据库存储路径
        # 动态media,相对路径:"media"
        media_path = os.path.join("media", image_object.name)  # 数据库存储路径
        f = open(media_path, mode='wb')
        for chunk in image_object.chunks():
            f.write(chunk)
        f.close()
        # 将图片路径存储到数据库中
        models.Boss.objects.create(
            name=form.cleaned_data['name'],
            age=form.cleaned_data['age'],
            # 存储img为图片路径
            img=media_path,
        )
        return HttpResponse("...")
    return render(request, 'upload_form.html', {"form": form, "title": title})

class UpModelForm(BootStrapModelForm):
    bootstrap_exclude_fields = ['img']

    class Meta:
        model = models.City
        fields = "__all__"

def upload_modal_form(request):
    """ 上传文件和数据（modelForm）"""
    title = "ModelForm上传文件"
    if request.method == "GET":
        form = UpModelForm()
        return render(request, 'upload_form.html', {"form": form, 'title': title})
    form = UpModelForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        # 对于文件：自动保存(路径再创建的数据库中)
        # 字段 + 上传路径写入到数据库
        form.save()
        return HttpResponse("成功")
    return render(request, 'upload_form.html', {"form": form, 'title': title})


from bs4 import BeautifulSoup as bs
import requests
import selenium
import time
from splinter import Browser
import pandas as pd
import json

#############################
# Initialize selenium
#############################

executable_path = {'executable_path': '/usr/bin/chromedriver'}
browser = Browser('chrome', **executable_path, headless=True)

#############################
# Scrape NASA.gov
#############################

def nasa():
    try:
        NASAurl = 'https://mars.nasa.gov/news'
        browser.visit(NASAurl)

        html = browser.html
        soup = bs(html, 'html.parser')

        newsTitle = soup.find('div', class_='image_and_description_container')\
                        .find('div', class_='list_text')\
                        .find('div', class_='content_title')\
                        .find('a')\
                        .text

        newsP = soup.find('div', class_='image_and_description_container')\
                    .find('div', class_='list_text')\
                    .find('div', class_='article_teaser_body')\
                    .text

        return newsTitle, newsP
    except:
        return None, None

#############################
# Scrape JPL.NASA.gov
#############################

def jpl():
    try:
        JPLurl = 'https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars'

        browser.visit(JPLurl)

        browser.click_link_by_partial_text('FULL IMAGE')

        time.sleep(1)

        html = browser.html
        soup = bs(html, 'html.parser')

        imageLink = soup.find('img', class_='fancybox-image')['src']
        featuredImageURL = 'https://www.jpl.nasa.gov' + imageLink
        return featuredImageURL
    except:
        return None

#############################
# Scrape Twitter
#############################

def twitter():
    try:
        Twitterurl = 'https://twitter.com/marswxreport?lang=en'

        browser.visit(Twitterurl)
        html = browser.html
        soup = bs(html, 'html.parser')

        weatherTweet = soup.find('p', class_='tweet-text').text
        return weatherTweet
    except:
        return None

#############################
# Scrape Space-Facts
#############################

def spacefacts():
    try:
        MarsFactsurl = 'https://space-facts.com/mars'
        tables = pd.read_html(MarsFactsurl)

        #earthcompare = tables[0]
        marsfacts    = tables[1]

        marsfactshtml = marsfacts.to_html()
        return marsfactshtml
    except:
        return None

#############################
# Scrape USGS
#############################

def usgs():
    try:
        USGSurl =\
            'https://astrogeology.usgs.gov/search/' + \
            'results?q=hemisphere+enhanced&c1=target&v1=Mars'

        browser.visit(USGSurl)
        html = browser.html
        soup = bs(html, 'html.parser')

        links = soup.find('div', class_='results').find_all('a')
        image_dict = {}

        lwt = [link for link in links if link.text]

        for link in lwt:
            text = link.text
            url  = 'https://astrogeology.usgs.gov' + link['href']

            browser.visit(url)
            html = browser.html
            soup = bs(html, 'html.parser')

            dl_links = soup.find('div', class_='downloads').find_all('a')

            for dl_link in dl_links:
                if dl_link.text == 'Original':
                    img_link = dl_link['href']
                    image_dict[text] = img_link

        return image_dict
    except:
        return None

def Scrape():
    newsTitle, newsP = nasa()
    featuredImageURL = jpl()
    weatherTweet = twitter()
    marsfactshtml = spacefacts()
    image_dict = usgs()

    scrape_dict = {
        'newsTitle': newsTitle,
        'newsP': newsP,
        'featuredImageURL': featuredImageURL,
        'weatherTweet': weatherTweet,
        'marsfactshtml': marsfactshtml,
        'image_dict': image_dict
    }

    return scrape_dict


# -*- coding: utf-8 -*-
"""
Created on Sun Oct 17 22:10:35 2010

@author: -
"""
import numpy
from enthought.mayavi import mlab

x, y = numpy.mgrid[0:3:1,0:3:1]
s = mlab.surf(x, y, numpy.asarray(x*0.1, 'd'))
#
for i in range(10):
    s.mlab_source.scalars = numpy.asarray(x*0.1*(i+1), 'd')
#
# Produce some nice data.
n_mer, n_long = 6, 11
pi = numpy.pi
dphi = pi/1000.0
phi = numpy.arange(0.0, 2*pi + 0.5*dphi, dphi, 'd')
mu = phi*n_mer
x = numpy.cos(mu)*(1+numpy.cos(n_long*mu/n_mer)*0.5)
y = numpy.sin(mu)*(1+numpy.cos(n_long*mu/n_mer)*0.5)
z = numpy.sin(n_long*mu/n_mer)*0.5

# View it.
l = mlab.plot3d(x, y, z, numpy.sin(mu), tube_radius=0.025, colormap='Spectral')

# Now animate the data.
ms = l.mlab_source
for i in range(10):
    x = numpy.cos(mu)*(1+numpy.cos(n_long*mu/n_mer +
                                    numpy.pi*(i+1)/5.)*0.5)
    scalars = numpy.sin(mu + numpy.pi*(i+1)/5)
    ms.set(x=x, scalars=scalars)


# -*- coding: UTF-8 -*-

from imgfactory import ImgFactory

# init
factory = ImgFactory( (248, 682), (200, 200) )

# show all the img name in folder "bg"
print( factory.listDir("/data/irene_bgs") )

# get the font object
font1 = factory.getFont("fonts/WCL-01.ttf", 50)
font2 = factory.getFont("fonts/WCL-02.ttf", 40)
font3 = factory.getFont("fonts/Pacifico.ttf", 50)

# get the domain color of bg and fg
bgDomain = factory.getDomainColor("/data/irene_bgs/b001.png")
fgDomain = factory.getDomainColor("/data/prod_imgs_nb/1997134.png")
dctDomain = factory.getDomainColor("/data/irene_dcts/bubble-d-01.png")
print(bgDomain, fgDomain, dctDomain)

# generate numpy array of bg, fg and dct
bg = factory.readBg("/data/irene_bgs/b001.png")
print(bg.shape)
fg = factory.readFg("/data/prod_imgs_nb/1997134.png")
fg3ch = factory.bgra2Bgr(fg)
fg1ch = factory.bgra2Gray(fg)
print(fg.shape, fg3ch.shape, fg1ch.shape)
dct = factory.readDct("/data/irene_dcts/bubble-d-01.png")
print(dct.shape)

# change the color of bg according to fg
renderedBg = factory.renderImg(bg, bgDomain, fgDomain, 0)

# conbine the segments and add text
testImg = factory.combineImg(renderedBg, dct, fg, 0., -0.6)
testImg = factory.addText(testImg, "包包出清特價", font1, (0., 0.3, 0.), -0.8, -0.1)
testImg = factory.addText(testImg, "買一送一", font2, (0., 0.3, 0.), -0.2, 0.1)
testImg = factory.addText(testImg, "$300", font3, (0., 0.3, 0.), 0.1, 0.4)

# diff color demo
bgs = []
dcts = []
rgbs = []
for c in range(5):
    bgs.append( factory.renderImg(bg, bgDomain, fgDomain, c) )
    dcts.append( factory.renderImg(dct, dctDomain, fgDomain, c) )
    rgbs.append( factory.renderRGB(fgDomain, c) )
styleDicts = [
    {"bg": 0, "dct": 1, "text": 3},
    {"bg": 0, "dct": 2, "text": 3},
    {"bg": 1, "dct": 0, "text": 4},
    {"bg": 1, "dct": 2, "text": 4}]
for idx, styleDict in enumerate(styleDicts):
    tmpImg = factory.combineImg(bgs[ styleDict["bg"] ], dcts[ styleDict["dct"] ], fg, 0., -0.6)
    tmpImg = factory.addText(tmpImg, "Best Bag Forever", font3, rgbs[ styleDict["text"] ], -0.3, -0.1)
    factory.dumpImg(tmpImg, "/web/public/images/colormap" + str(idx + 1) + ".png")

# dump to file
factory.dumpImg(factory.resizeImg( testImg, (40, 95) ), "/web/public/images/tmp2.png")

# test only font
factory = ImgFactory( (248, 682), (200, 200) )
fg = factory.readFg("/data/prod_imgs_nb/1997134.png")
bg = factory.readBg("/data/irene_bgs/b001.png")
dct = factory.readDct("/data/irene_dcts/bubble-d-01.png")
img = factory.combineImg(bg, dct, fg, 0., -0.6)
font = factory.getFont("fonts/Pacifico.ttf", 50)
tmp = factory.getTextImg("Best Beg Forever", font, (0., 0.2, 0.8))
img = factory.addTextImg(img, tmp, 0, 0.3)
factory.dumpImg(img, "/web/public/images/font.png")


# encoding:utf-8
from flask import Flask,request
import json
from threading import Thread
import threading
import time
import sys
import sqlite3
import os

app=Flask(__name__)
####回复文本格式##########
re={}
result={}
result["type"]="text"
result["content"]=""
re["error_code"]=0
re["error_msg"]=""
re["result"]=result
dic={'温度':'temperature','湿度':'humidity','光照':'light','二氧化碳':'co2_simulation','声音':'noise'}
##########意图对应的语音回复文本字典############
response={'AC1_OC_OPEN':'请稍等，正在为您打开空调',
'AC1_OC_CLOSE':'请稍等，正在为您关闭空调',
'AC1_TEMP_UP':'正在帮您升高空调温度，请稍等',
'AC1_TEMP_DOWN':'正在帮您降低空调温度，请稍等',
'AC1_WSPEED_UP':'正在帮您提高空调风速，请稍等',
'AC1_WSPEED_DOWN':'正在帮您降低空调风速，请稍等',
'AC1_SLEEP_OPEN':'好的，正在为您打开睡眠模式，请稍等',
'AC1_SLEEP_CLOSE':'好的，正在为您关闭睡眠模式，请稍等',
'AC1_TIMER_CLOSE':'好的，正在为您取消空调定时，请稍等'}
##############词槽标准化字典#############
normal={'高':'0','中':'1','低':'2','制冷':'0','制热':'1','送风':'2','自动':'3','除湿':'4','关':'close','开':'open','平衡':'0','环保':'1','极致':'2',
'16度':'16','17度':'17','18度':'18','19度':'19','20度':'20','21度':'21','22度':'22','23度':'23','24度':'24','25度':'25',
'26度':'26','27度':'27','28度':'28','29度':'29','30度':'30','降低':'lower','热':'lower','升高':'higher','冷':'higher',
'半小时':'0.5','一小时':'1.0','一个半小时':'1.5','两个小时':'2.0','两个半小时':'2.5','三个小时':'3.0','温度':'0','湿度':'1','声音':'2','光照':'3','二氧化碳':'4'}
class Response:
	def __init__(self,intent,nom_word):
		self.re=re
		self.intent=intent
		self.nom_word=nom_word
	def json_resp(self,intent,nom_word):
		if intent in response.keys():
			re["result"]["content"]=response[intent]
		elif intent=="AC1_TEMP_TO":
			re["result"]["content"]="好的，正在为您将空调设置为"+nom_word+"，请稍等"
		elif intent=="AC1_WSPEED_TO":
			re["result"]["content"]="好的，正在为您调节风速为"+nom_word+"，请稍等"
		elif intent=="AC1_TIMER_SET":
			if nom_word=="开"or nom_word=="":
				re["result"]["content"]="好的，正在为您设置空调定时，定时时间为默认值半小时"
			else:
				re["result"]["content"]="好的，正在为您设置空调定时，定时时间为"+nom_word
		elif intent=="AC1_COMMOD_SELECT"or intent=="AC1_SMARTMOD_SELECT":
			re["result"]["content"]="好的，正在为您调节到"+nom_word+"模式，请稍等"
		elif intent=="ROOM1_ENV_INFO_QUERY":
			conn = sqlite3.connect("db.sqlite3")
			c = conn.cursor()
			c.execute('SELECT '+dic[nom_word]+' FROM myhome_nodedata ORDER BY id desc')#选择查询信息的最新值
			query_result=c.fetchone()[0]					#取出查询项对应数据
			re["result"]["content"]="您当前的室内"+nom_word+"为"+str(query_result)
		else:
			re["result"]["content"]="请求失败，请重试"
		return re

@app.route("/unit/callback",methods=['POST'])
def callback():
	#print(request.headers)
	#print(request.data)
	dic=json.loads(str(request.data,encoding='utf-8'))
	intent=dic["response"]["schema"]["intent"]
	nom_word=dic["response"]["schema"]["slots"][0]["normalized_word"]
	exp1=Response(intent,nom_word)

	if os.path.exists("db.sqlite3"):
		conn = sqlite3.connect("db.sqlite3")
		c = conn.cursor()
	else:
		conn = sqlite3.connect("db.sqlite3")
		c = conn.cursor()
		c.execute('''CREATE TABLE myhome_commands(ID integer NOT NULL PRIMARY KEY AUTOINCREMENT,INTENT text NOT NULL ,SLOTS text NOT NULL)''')#若命令表单不存在则创建表单
		c.execute('INSERT INTO myhome_commands VALUES(1,"0","0")')				#插入意图和归一化词槽
	c.execute("UPDATE myhome_commands SET INTENT=?,SLOTS=? where ID=1",(intent,normal[nom_word]))
	conn.commit()
	conn.close()
	json_re=exp1.json_resp(intent,nom_word)#获得答复数据
	json_re=json.dumps(re)
	#print(json_re)
	return json_re

if __name__=='__main__':
	app.run(host='172.20.10.12',port=9999,debug=True)


from dotenv import load_dotenv
import datetime as dt
import os
import telebot
import json

load_dotenv()
BOT_TOKEN = os.environ.get('BOT_TOKEN')
bot = telebot.TeleBot(BOT_TOKEN)

COMMANDS = [
    {
        "name": 'start',
        "description": 'Restart the bot'
    },
    {
        "name": 'predict',
        "description": 'Get prediction for today'
    },
    {
        "name": 'day_prediction',
        "description": 'Get prediction for selected day'
    }
]

bot.set_my_commands(
    commands=[telebot.types.BotCommand(
        command["name"], command["description"]) for command in COMMANDS]
)

with open('probability_week.json', 'r') as prob_file:
    prob_data = json.load(prob_file)

weekdays = ['Monday', 'Tuesday', 'Wednesday',
            'Thursday', 'Friday', 'Saturday', 'Sunday']

@bot.message_handler(commands=[command["name"] for command in COMMANDS])
def exchange_command(message):
    if (message.text == '/start'):
        bot.send_message(
            message.chat.id, 'Glory to UkraineðŸ‡ºðŸ‡¦! I can predict air raid alerts in Kyiv for you!ðŸ¥°')

        commands_str = ''
        for command in COMMANDS:
            if (command["name"] == "start"):
                continue
            commands_str += f'/{command["name"]} - {command["description"]}\n'

        bot.send_message(
            message.chat.id,
            f'Here are the list of commands:\n{commands_str}',
            parse_mode='HTML')

    elif (message.text == '/predict'):
        curr_weekday = dt.datetime.now().weekday()

        keyboard = telebot.types.InlineKeyboardMarkup()
        keyboard.row(
            telebot.types.InlineKeyboardButton(
                'Show for hours', callback_data=f'hour_day-{curr_weekday}')
        )

        day = weekdays[curr_weekday]
        day_prob = "{:.2f}".format(
            round(prob_data[curr_weekday]["day_prob"] * 100, 2))

        bot.send_message(message.chat.id,
                         f'Alert probability for {day}: {day_prob}%',
                         reply_markup=keyboard, parse_mode='HTML')

    elif (message.text == '/day_prediction'):
        keyboard = telebot.types.InlineKeyboardMarkup()

        for weekday in weekdays:
            keyboard.row(
                telebot.types.InlineKeyboardButton(
                    weekday, callback_data=f'day-{weekdays.index(weekday)}')
            )

        bot.send_message(message.chat.id, 'Select a day:',
                         reply_markup=keyboard)

@bot.callback_query_handler(func=lambda call: True)
def iq_callback(query):
    keyboard = telebot.types.InlineKeyboardMarkup()
    data = query.data
    if (data.startswith('day-')):
        day_id = int(data[-1])
        day = weekdays[day_id]
        day_prob = "{:.2f}".format(
            round(prob_data[day_id]["day_prob"] * 100, 2))

        keyboard.row(
            telebot.types.InlineKeyboardButton(
                'Show for hours', callback_data=f'hour_day-{day_id}')
        )

        bot.send_message(query.message.chat.id, f'Alert probability for {day}: {day_prob}%',
                         reply_markup=keyboard, parse_mode='HTML')

    elif (data.startswith('hour_day-')):
        day_id = int(data[-1])
        day = weekdays[day_id]

        bot.send_message(query.message.chat.id,
                         f'Alert probability for {day} hours: ')

        str_hours = ''
        cnt = 0
        for hour_prob in prob_data[day_id]["hours_prob"]:
            if (hour_prob == 0):
                cnt += 1
                continue
            hour_string = '{:02d}:00'.format(cnt)
            hour_prob_string = "{:.2f}".format(round(hour_prob * 100, 2))
            str_hours += hour_string + \
                f': {hour_prob_string}%\n'
            cnt += 1
        bot.send_message(query.message.chat.id,
                         str_hours, parse_mode='HTML')

bot.infinity_polling()


import sys
import socket
import unittest
import threading
import traceback

import servers

DEFAULT_CLIENTS = 10

class Client(object):

    def __init__(self, host=None, port=None):
        super(Client, self).__init__()
        if host is None:
            host = "localhost"
        if port is None:
            port = servers.DEFAULT_PORT
        self._sock = socket.socket()
        self._sock.connect((host, port))

    def cookie(self):
        self._sock.send("cookie")
        server_cookie = self._sock.recv(1024)
        return server_cookie

    def ping(self):
        self._sock.send("ping")
        assert self._sock.recv(1024) == "pong"

    def drop(self):
        self._sock.send("drop")
        assert self._sock.recv(1024) == "okay"
        self._sock.close()

class ClientThread(threading.Thread):

    def __init__(self, **kwargs):
        super(ClientThread, self).__init__()
        self._client = Client(**kwargs)
        self._cookie = None
        self._exception = None
        self.daemon = True
        self.start()

    def run(self):
        try:
            self._client.ping()
            self._cookie = self._client.cookie()
            self._client.drop()
        except Exception as e:
            self._exception = e

    def verify(self, valid_cookies):
        self.join()
        if self._exception:
            raise self._exception
        assert self._cookie in valid_cookies

class Clients(object):

    def __init__(self, N=None, host=None, port=None):
        super(Clients, self).__init__()
        if N is None:
            N = DEFAULT_CLIENTS
        self._clients = map(lambda x: ClientThread(host=host, port=port), range(N))

    def verify(self, valid_cookies):
        for c in self._clients:
            c.verify(valid_cookies)


from torch import nn
import torch

import numpy as np

class SIREN(nn.Module):

    def __init__(self, in_features, hidden_features, hidden_layers, first_omega_0, hidden_omega_0):
        super().__init__()

        self.net = []

        self.net.append(
            SineLayerLinear(
                in_features=in_features,
                out_features=hidden_features,
                is_first=True,
                omega_0=first_omega_0,
            )
        )

        for i in range(hidden_layers):
            self.net.append(
                SineLayerLinear(
                    in_features=hidden_features, out_features=hidden_features, is_first=False,
                    omega_0=hidden_omega_0
                )
            )

        self.net = nn.Sequential(*self.net)

    def forward(self, x):
        """ Propagate the coordinates through SIREN.
        """
        x = self.net(x)
        return x

class SineLayerBase(nn.Module):

    def __init__(self, in_features, out_features, bias, is_first, omega_0):
        super().__init__()

        self.omega_0 = omega_0
        self.is_first = is_first

        self.in_features = in_features
        self.out_features = out_features

        self.bias = bias
        self.is_first = is_first

    def init_weights(self):
        with torch.no_grad():
            if self.is_first:
                self.linear.weight.uniform_(-1 / self.in_features, 1 / self.in_features)
            else:
                self.linear.weight.uniform_(-np.sqrt(6 / self.in_features) / self.omega_0,
                                            np.sqrt(6 / self.in_features) / self.omega_0)
                # Important! Bias is not defined in original SIREN implementation
                if self.linear.bias is not None:
                    # self.linear.bias.data.uniform_(-1.0, 1.0)
                    self.linear.bias.data.fill_(0)

    def forward(self, x):
        return torch.sin(self.omega_0 * self.linear(x))

class SineLayerLinear(SineLayerBase):

    def __init__(self, in_features, omega_0, out_features, bias=True, is_first=False):
        super(SineLayerLinear, self).__init__(
            in_features=in_features,
            out_features=out_features,
            bias=bias,
            is_first=is_first,
            omega_0=omega_0
        )

        self.linear = nn.Linear(in_features, out_features, bias=bias)
        self.init_weights()


import pygame as pg

class Button(pg.sprite.Sprite):

    def __init__(self, x, y, color):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((30, 30))
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y


import wfdb
import numpy as np

# features array:
#
# (0 = no = negative = front)
# (1 = yes = positive = end)
#
# 0     parity = number of previous deliveries,
# 1     maternal age,
# 2     previous abortions,
# 3     weight,
# 4     hypertension,
# 5     diabetes,
# 6     smoker
# 7     bleeding first trimester,
# 8     bleeding second trimester,
# 9     funneling,
# 10    placental position,

# 6+ minutes
def get_features(records):
    """
    get the feature vector from the record
    string array to int array, if not, drop the record

    :param records: wfdb records to check
    :return: numpy arrays with all 15 features, and gestation period
    """
    features_set = []
    output_set = []
    canceled_index_list = []
    for (num, record) in enumerate(records):
        signals, fields = wfdb.rdsamp(record.record_name,pb_dir='tpehgdb/tpehgdb')
        features = np.empty(15, dtype=float)
        good_record_flag = True
        output = 1
        # index of features array
        i = 0
        for item in (fields['comments']):
            if "None" in item:
                # append canceled index
                canceled_index_list.append(num)
                good_record_flag = False
                break
            else:
                # good record
                if "Gestation" in item:
                    # output
                    output = (item.split()[1])
                if "Parity" in item:
                    features[i] = (item.split()[1])
                    i += 1
                if "Age" in item:
                    features[i] = (item.split()[1])
                    i += 1
                if "Abortions" in item:
                    features[i] = (item.split()[1])
                    i += 1
                if "Weight" in item:
                    features[i] = (item.split()[1])
                    i += 1
                if "Hypertension" in item:
                    if "no" in item:
                        features[i] = 0
                    else:
                        features[i] = 1
                    i += 1
                if "Diabetes" in item:
                    if "no" in item:
                        features[i] = 0
                    else:
                        features[i] = 1
                    i += 1
                if "Smoker" in item:
                    if "no" in item:
                        features[i] = 0
                    else:
                        features[i] = 1
                    i += 1
                if "Bleeding_first_trimester" in item:
                    if "no" in item:
                        features[i] = 0
                    else:
                        features[i] = 1
                    i += 1
                if "Bleeding_second_trimester" in item:
                    if "no" in item:
                        features[i] = 0
                    else:
                        features[i] = 1
                    i += 1
                if "Funneling" in item:
                    if "negative" in item:
                        features[i] = 0
                    else:
                        features[i] = 1
                    i += 1
                if "Placental_position" in item:
                    if "front" in item:
                        features[i] = 0
                    else:
                        features[i] = 1
                    i += 1
        if (good_record_flag):
            features_set.append(features)
            output_set.append(output)

    # arrays should have the same number of rows (number of records kept)
    features_array = np.empty(shape=(len(features_set),11), dtype=float)
    outputs_array = np.empty(shape=(len(output_set), 1), dtype=float)
    # convert list to ndarray
    for (i, feature_array) in enumerate(features_set):
        features_array[i] = feature_array[:-4]
    for (i, output_array) in enumerate(output_set):
        outputs_array[i] = output_array
    return features_array, outputs_array, canceled_index_list

# test preprocessing
if __name__ == "__main__":
    # record1 = wfdb.rdrecord('tpehgdb/tpehg1132',pb_dir='tpehgdb/tpehgdb') # dropped
    record2 = wfdb.rdrecord('tpehgdb/tpehg1134',pb_dir='tpehgdb/tpehgdb')
    r = []
    # r.append(record1)
    r.append(record2)
    f, o, a = get_features(r)
    for item in np.nditer(f):
        print((item))
    print(o[0])
    # signals, fields = wfdb.rdsamp(record.record_name,pb_dir='tpehgdb/tpehgdb')
    # print((fields['comments']))   # list


from functools import partial
import time
from interp.ui.attribution_backend import AttributionBackend
from interp.ui.very_named_tensor import LazyVeryNamedTensor, VeryNamedTensor
from typing import Any
import asyncio
import websockets
import json
from interp.model.model_loading import load_model
from interp.encoding import get_callback_result, callables_table, msgpack_encode
import threading
from threading import Lock

from IPython.core.display import display, HTML
from typing import *

served_things: Dict[str, Any] = {}
thread = None
lock = Lock()
sockets = []

async def handler(websocket):
    global sockets
    print("handler")
    this_obj = {"websocket": websocket, "name": None}
    sockets.append(this_obj)
    async for buf in websocket:
        msg = json.loads(buf)
        kind = msg.get("kind")
        print(kind)
        if kind == "init":
            pass
        elif kind == "nameStartup":
            name = msg["name"]
            print("name", name)
            this_obj["name"] = name
            with lock:
                thing = served_things.get(name, None)
            await websocket.send(msgpack_encode({"kind": "nameStartup", "data": thing}))
        elif kind == "callback":
            enc = msgpack_encode(get_callback_result(msg))
            await websocket.send(enc)
        else:
            print("Unrecognized message: ", msg)

def loop_in_thread(loop, port):
    print("started")

    asyncio.set_event_loop(loop)
    loop.run_until_complete(websockets.serve(handler, "localhost", port))
    loop.run_forever()

async def init(port=6789):
    global thread
    port = str(port)
    loop = asyncio.new_event_loop()
    t = threading.Thread(target=loop_in_thread, args=(loop, port))
    t.start()
    thread = t
    print(
        "Composable UI initialized! Make sure you've run `npm install` and `npm run start` in /interp/app before using"
    )

async def show_tensors(*lvnts, name="untitled"):
    lvnts = [lvnt.to_lvnt() if not isinstance(lvnt, LazyVeryNamedTensor) else lvnt for lvnt in lvnts]
    with lock:
        did_exist = name in served_things
        served_things[name] = lvnts
    if did_exist:
        encoded = msgpack_encode({"kind": "nameStartup", "data": lvnts})
        try:
            await [socket for socket in sockets if socket["name"] == name][0]["websocket"].send(encoded)
        except:
            pass
    link = f"http://127.0.0.1:3000/#/tensors/{name}"
    return display(
        HTML(f'
Link
')
    )

async def show_fns(*lvnt_makers, name="untitled"):
    with lock:
        did_exist = name in served_things
        served_things[name] = lvnt_makers
    link = f"http://127.0.0.1:3000/#/functions/{name}"
    if did_exist:
        await [socket for socket in sockets if socket["name"] == name][0]["websocket"].send(
            msgpack_encode({"kind": "nameStartup", "data": lvnt_makers})
        )

    return display(
        HTML(f'
Link
')
    )

async def show_attribution(model, params, tokenizer, name="untitled"):
    func = partial(AttributionBackend, model, params, tokenizer)
    with lock:
        did_exist = name in served_things
        served_things[name] = func
    if did_exist:
        await [socket for socket in sockets if socket["name"] == name][0]["websocket"].send(
            msgpack_encode({"kind": "nameStartup", "data": func})
        )
    link = f"http://127.0.0.1:3000/#/attribution/{name}"
    return display(
        HTML(f'
Link
')
    )


import os
import sys
import random
import math
import numpy as np
import skimage.io
import matplotlib
import matplotlib.pyplot as plt
import cv2
import time
import glob
import argparse
from mrcnn.config import Config
from datetime import datetime
from scipy.misc import imsave
##########################################################################
parser = argparse.ArgumentParser(description='Resize images in a folder')
parser.add_argument('--input',    '-i', help='input image folder', required=True)
args = parser.parse_args()
# Validate parameters
input_path = os.path.abspath(args.input)
if not os.path.isdir(args.input):
    print('--input ({}) must be a folder.'.format(args.input))
    sys.exit(1)

##########################################################################
# Root directory of the project
ROOT_DIR = os.getcwd()

# Import Mask RCNN
sys.path.append(ROOT_DIR)  # To find local version of the library
from mrcnn import utils
import mrcnn.model as modellib
from mrcnn import visualize
# Import COCO config
# sys.path.append(os.path.join(ROOT_DIR, "samples/coco/"))  # To find local version
# from samples.coco import coco

# Directory to save logs and trained model
MODEL_DIR = os.path.join(ROOT_DIR, "model_save")
##########################################################################
# Local path to trained weights file
# EVAL_MODEL_PATH = os.path.join(MODEL_DIR,"maskrcnn_config20200814T1659/mask_rcnn_maskrcnn_config_0187.h5")
#EVAL_MODEL_PATH=input_path
for root, _, basenames in os.walk(input_path):
        for basename in basenames:
            basename_check=basename.split('.')[1]
            if(basename_check=='h5'):
                EVAL_MODEL_PATH=os.path.join(input_path,basename)
model_basename=os.path.basename(EVAL_MODEL_PATH)
model_name=model_basename.split('.')[0]
print('model from == ',EVAL_MODEL_PATH)
print('===========================================================================================================================')
# Download COCO trained weights from Releases if needed
if not os.path.exists(EVAL_MODEL_PATH):
    utils.download_trained_weights(EVAL_MODEL_PATH)
    print("cuiwei***********************")

# Directory of images to run detection on
IMAGE_DIR = os.path.join(ROOT_DIR, "./datasets/Data640/eval_image_640x640_nospace/")
##########################################################################
class ShapesConfig(Config):
    """Configuration for training on the toy shapes dataset.
    Derives from the base Config class and overrides values specific
    to the toy shapes dataset.
    """
    # Give the configuration a recognizable name
    NAME = "MaskRCNN_config"

    # Train on 1 GPU and 8 images per GPU. We can put multiple images on each
    # GPU because the images are small. Batch size is 8 (GPUs * images/GPU).
    GPU_COUNT = 1
    IMAGES_PER_GPU = 1

    # Number of classes (including background)
    NUM_CLASSES = 1 + 24  # background + 1 shapes + 1 not_defined

    # Use small images for faster training. Set the limits of the small side
    # the large side, and that determines the image shape.
    IMAGE_MIN_DIM = 512
    IMAGE_MAX_DIM = 640

    # Use smaller anchors because our image and objects are small
    RPN_ANCHOR_SCALES = (40,80,160,320,640)  # anchor side in pixels

    # Reduce training ROIs per image because the images are small and have
    # few objects. Aim to allow ROI sampling to pick 33% positive ROIs.
    TRAIN_ROIS_PER_IMAGE =100

    # Use a small epoch since the data is simple
    STEPS_PER_EPOCH = 1

    # use small validation steps since the epoch is small
    VALIDATION_STEPS = 50

    # Non-maximum suppression threshold for detection
    #DETECTION_NMS_THRESHOLD = 0.3
##########################################################################
#import train_tongue
#class InferenceConfig(coco.CocoConfig):
class InferenceConfig(ShapesConfig):
    # Set batch size to 1 since we'll be running inference on
    # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU
    GPU_COUNT = 1
    IMAGES_PER_GPU = 1

config = InferenceConfig()
model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)

# Create model object in inference mode.
model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)
# Load weights trained on MS-COCO
model.load_weights(EVAL_MODEL_PATH, by_name=True)

# COCO Class names
# Index of the class in the list is its ID. For example, to get ID of
# the teddy bear class, use: class_names.index('teddy bear')
#class_names = ['BG', 'person']
class_names=['_background_',
             'cocacola',
             'cashewnuts',
             'M_MBIG',
             'M_MSMALL',
             'Hot-Chili-Squid-Flavor',
             'Original-Flavor',
             'Thai-Spicy-Mixed-Nuts',
             'Pon-De-Strawberry-Honey',
             'Pon-de-Strawberry',
             'Pon-De-Double-Chocolate',
             'Old-Fashioned',
             'Pon-De-Soybean',
             'Pringles',
             'TARO-FISH-SNACK',
             'SALTED-PEANUTS',
             'MANDARIN',
             'SPEARMINT',
             'Choco-Old-Fashioned',
             'Pon-De-Chocolate',
             'Fried-Seaweed',
             'Pon-De-Yogurt',
             'Strawberry-Ring',
             'Sugar-Ring'
            ]
##########################################################################
# Load a random image from the images folder
file_names = next(os.walk(IMAGE_DIR))[2]
#random_image_name=random.choice(file_names)
count=1
for eval_image in file_names:
    print('eval image... ',count)
    choice_eval_image_path=os.path.join(IMAGE_DIR,eval_image)
    image = skimage.io.imread(choice_eval_image_path)
    results = model.detect([image], verbose=1)
    r = results[0]
    visualize.display_instances(eval_image,image, r['rois'], r['masks'], r['class_ids'],
                            class_names, r['scores'])
    count+=1
print('===========================================================================================================================')
'''
a=datetime.now()
# Run detection
results = model.detect([image], verbose=1)
b=datetime.now()
# Visualize results
print("shijian",(b-a).seconds)
r = results[0]

#print('r == ',r)
#display_instances in visualize.py lines 83
visualize.display_instances(random_image_name,image, r['rois'], r['masks'], r['class_ids'],
                            class_names, r['scores'])
'''


# D - Cylinder
# https://atcoder.jp/contests/abc247/tasks/abc247_d
# ランレングス符号化

from collections import deque

que = deque()
Q = int(input())
for i in range(Q):
    query = list(map(int, input().split()))
    if query[0] == 1:
        que.append(query[1])
        que.append(query[2])
    else:
        ans = 0
        val = que.popleft()
        num = que.popleft()

        while query[1] != 0:
            if num > query[1]:
                num -= query[1]
                ans += val * query[1]
                query[1] = 0
                que.appendleft(num)
                que.appendleft(val)
            elif num == query[1]:
                ans += val * num
                query[1] = 0
            else:
                ans += val * num
                query[1] -= num
                val = que.popleft()
                num = que.popleft()
        print(ans)


import socket
import threading
import service

if __name__ == '__main__':
    # 初始化socket
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 绑定IP地址和端口
    server.bind(("localhost", 8888))
    # 设置最大监听数
    server.listen(15)
    # 设置一个字典，用来保存每一个客户端的连接 和 身份信息
    print("服务器已启动。。。。")
    client_number = 0
    socket_mapping = {}
    # 开启准备等待获取客户端的链接
    while True:
        sc, addr = server.accept()
        # print(sc)

        # 为每一个客户端开启一个线程、保证程序的高效运行
        lock = threading.Lock()
        threading.Thread(target=service.get_client_info, args=(sc, socket_mapping, lock)).start()
        client_number += 1
        print(f'已经有{client_number}个客户端连接到服务器')


from analysis.hitmiss import convolve_match, convolve_match_series
import numpy as np

img = np.array([
    [0, 0],
    [1, 1],
    [1, 1]
], dtype=np.bool)

match = np.array([
    [0, 0, 0],
    [0, 1, 1],
    [0, 1, 0]
], dtype=np.uint8)

image = np.array([
#    0  1  2  3  4
    [0, 0, 0, 0, 0], # 0
    [0, 0, 0, 0, 0], # 1
    [0, 0, 0, 0, 0], # 2
    [0, 0, 0, 0, 0], # 3
    [0, 0, 0, 0, 0], # 4
    [0, 0, 0, 0, 0], # 5
    [0, 0, 0, 0, 0], # 6
    [0, 0, 0, 0, 0]  # 7
], dtype=np.uint8)

# print(convolve_match(img, match, 0, 1, 3, 2))
# get the width and height of the scanning region (we scan from outer edge to inner edge in a circular pattern)
start_row = 0
start_col = 0
rows, cols = image.shape
middle_row = int(rows / 2.0)
middle_col = int(cols / 2.0)

# determine width offset
if start_col >= middle_col:
    offset_col = cols - (start_col + 1)
else:
    offset_col = start_col
# determine height offset
if start_row >= middle_row:
    offset_row = rows - (start_row + 1)
else:
    offset_row = start_row

# let's get current step in the loop (step being the iteration of inner loop)
cur_step = 0
if offset_col >= offset_row and start_row < middle_row:  # more cols completed
    if start_col >= middle_col and offset_col == offset_row:
        direction = 1  # we're in the right corner let's switch direction
    else:
        direction = 0  # top row (for the rest)
    cur_step = offset_row
elif offset_col > offset_row and start_row >= middle_row:
    if start_col < middle_col and offset_col == offset_row:
        direction = 3  # left column let's switch direction
    else:
        direction = 2  # bottom row
    cur_step = offset_row
elif offset_row >= offset_col and start_col >= middle_col:
    if start_row >= middle_row and offset_col == offset_row:
        direction = 2  # finished right column let's move left
    else:
        direction = 1  # right col
    cur_step = offset_col
elif offset_row >= offset_col and start_col < middle_col:
    direction = 3  # left col
    cur_step = offset_col
else:
    raise Exception('odd loop combination for start position')

# set current loop width and height
width = cols - (cur_step * 2)
height = rows - (cur_step * 2)
cur_col = start_col
cur_row = start_row

# for our "starting position" we need to handle a couple special cases of iteration
scanned = []

while width >= 0 and height >= 0:
    offset_step = cur_step + 1
    for cur_col in range(cur_col, cols - offset_step):
        scanned.append((cur_col, cur_row))
    cur_col += 1
    for cur_row in range(cur_row, rows - offset_step):
        scanned.append((cur_col, cur_row))
    cur_row += 1
    for cur_col in range(cols - offset_step, cur_step, -1):
        scanned.append((cur_col, cur_row))
    cur_col -= 1
    for cur_row in range(rows - offset_step, offset_step, -1):
        scanned.append((cur_col, cur_row))
    cur_row -= 1

    # shift step
    cur_step += 1
    width = cols - (cur_step * 2)
    height = rows - (cur_step * 2)

sup_scan = []
for row in range(rows):
    for col in range(cols):
        sup_scan.append((col, row))

print(set(sup_scan) ^ set(scanned))

# keep iterating until we run out
"""
has_pixels = True
while has_pixels:
    if direction == 0:

for row in range(start_row, rows):
    for col in range(start_loc.x, cols):
        if image[row, col] == search:
            loc.x = col
            loc.y = row
            return <int> 1
"""

print('middle', (middle_row, middle_col))
print('offset', (offset_row, offset_col), 'direction', direction)
print('step', cur_step)
print(width, height)


from typing import Optional, Union

import torch
import torch.nn as nn
import torch.nn.functional as F
import torchaudio
from pyannote.core.utils.generators import pairwise

from pyannote.audio.core.model import Model
from pyannote.audio.core.task import Task
from pyannote.audio.utils.params import merge_dict

class SSeRiouSS(Model):
    """Self-Supervised Representation for Speaker Segmentation

    wav2vec > LSTM > Feed forward > Classifier

    Parameters
    ----------
    sample_rate : int, optional
        Audio sample rate. Defaults to 16kHz (16000).
    num_channels : int, optional
        Number of channels. Defaults to mono (1).
    wav2vec: dict or str, optional
        Defaults to "WAVLM_BASE".
    wav2vec_layer: int, optional
        Index of layer to use as input to the LSTM.
        Defaults (-1) to use average of all layers (with learnable weights).
    lstm : dict, optional
        Keyword arguments passed to the LSTM layer.
        Defaults to {"hidden_size": 128, "num_layers": 4, "bidirectional": True},
        i.e. two bidirectional layers with 128 units each.
        Set "monolithic" to False to split monolithic multi-layer LSTM into multiple mono-layer LSTMs.
        This may proove useful for probing LSTM internals.
    linear : dict, optional
        Keyword arugments used to initialize linear layers
        Defaults to {"hidden_size": 128, "num_layers": 2},
        i.e. two linear layers with 128 units each.
    """

    WAV2VEC_DEFAULTS = "WAVLM_BASE"

    LSTM_DEFAULTS = {
        "hidden_size": 128,
        "num_layers": 4,
        "bidirectional": True,
        "monolithic": True,
        "dropout": 0.0,
    }
    LINEAR_DEFAULTS = {"hidden_size": 128, "num_layers": 2}

    def __init__(
        self,
        wav2vec: Union[dict, str] = None,
        wav2vec_layer: int = -1,
        lstm: dict = None,
        linear: dict = None,
        sample_rate: int = 16000,
        num_channels: int = 1,
        task: Optional[Task] = None,
    ):
        super().__init__(sample_rate=sample_rate, num_channels=num_channels, task=task)

        if isinstance(wav2vec, str):
            # `wav2vec` is one of the supported pipelines from torchaudio (e.g. "WAVLM_BASE")
            if hasattr(torchaudio.pipelines, wav2vec):
                bundle = getattr(torchaudio.pipelines, wav2vec)
                if sample_rate != bundle._sample_rate:
                    raise ValueError(
                        f"Expected {bundle._sample_rate}Hz, found {sample_rate}Hz."
                    )
                wav2vec_dim = bundle._params["encoder_embed_dim"]
                wav2vec_num_layers = bundle._params["encoder_num_layers"]
                self.wav2vec = bundle.get_model()

            # `wav2vec` is a path to a self-supervised representation checkpoint
            else:
                _checkpoint = torch.load(wav2vec)
                wav2vec = _checkpoint.pop("config")
                self.wav2vec = torchaudio.models.wav2vec2_model(**wav2vec)
                state_dict = _checkpoint.pop("state_dict")
                self.wav2vec.load_state_dict(state_dict)
                wav2vec_dim = wav2vec["encoder_embed_dim"]
                wav2vec_num_layers = wav2vec["encoder_num_layers"]

        # `wav2vec` is a config dictionary understood by `wav2vec2_model`
        # this branch is typically used by Model.from_pretrained(...)
        elif isinstance(wav2vec, dict):
            self.wav2vec = torchaudio.models.wav2vec2_model(**wav2vec)
            wav2vec_dim = wav2vec["encoder_embed_dim"]
            wav2vec_num_layers = wav2vec["encoder_num_layers"]

        if wav2vec_layer < 0:
            self.wav2vec_weights = nn.Parameter(
                data=torch.ones(wav2vec_num_layers), requires_grad=True
            )

        lstm = merge_dict(self.LSTM_DEFAULTS, lstm)
        lstm["batch_first"] = True
        linear = merge_dict(self.LINEAR_DEFAULTS, linear)

        self.save_hyperparameters("wav2vec", "wav2vec_layer", "lstm", "linear")

        monolithic = lstm["monolithic"]
        if monolithic:
            multi_layer_lstm = dict(lstm)
            del multi_layer_lstm["monolithic"]
            self.lstm = nn.LSTM(wav2vec_dim, **multi_layer_lstm)

        else:
            num_layers = lstm["num_layers"]
            if num_layers > 1:
                self.dropout = nn.Dropout(p=lstm["dropout"])

            one_layer_lstm = dict(lstm)
            one_layer_lstm["num_layers"] = 1
            one_layer_lstm["dropout"] = 0.0
            del one_layer_lstm["monolithic"]

            self.lstm = nn.ModuleList(
                [
                    nn.LSTM(
                        wav2vec_dim
                        if i == 0
                        else lstm["hidden_size"] * (2 if lstm["bidirectional"] else 1),
                        **one_layer_lstm,
                    )
                    for i in range(num_layers)
                ]
            )

        if linear["num_layers"] < 1:
            return

        lstm_out_features: int = self.hparams.lstm["hidden_size"] * (
            2 if self.hparams.lstm["bidirectional"] else 1
        )
        self.linear = nn.ModuleList(
            [
                nn.Linear(in_features, out_features)
                for in_features, out_features in pairwise(
                    [
                        lstm_out_features,
                    ]
                    + [self.hparams.linear["hidden_size"]]
                    * self.hparams.linear["num_layers"]
                )
            ]
        )

    def build(self):
        if self.hparams.linear["num_layers"] > 0:
            in_features = self.hparams.linear["hidden_size"]
        else:
            in_features = self.hparams.lstm["hidden_size"] * (
                2 if self.hparams.lstm["bidirectional"] else 1
            )

        if isinstance(self.specifications, tuple):
            raise ValueError("SSeRiouSS model does not support multi-tasking.")

        if self.specifications.powerset:
            out_features = self.specifications.num_powerset_classes
        else:
            out_features = len(self.specifications.classes)

        self.classifier = nn.Linear(in_features, out_features)
        self.activation = self.default_activation()

    def forward(self, waveforms: torch.Tensor) -> torch.Tensor:
        """Pass forward

        Parameters
        ----------
        waveforms : (batch, channel, sample)

        Returns
        -------
        scores : (batch, frame, classes)
        """

        num_layers = (
            None if self.hparams.wav2vec_layer < 0 else self.hparams.wav2vec_layer
        )

        with torch.no_grad():
            outputs, _ = self.wav2vec.extract_features(
                waveforms.squeeze(1), num_layers=num_layers
            )

        if num_layers is None:
            outputs = torch.stack(outputs, dim=-1) @ F.softmax(
                self.wav2vec_weights, dim=0
            )
        else:
            outputs = outputs[-1]

        if self.hparams.lstm["monolithic"]:
            outputs, _ = self.lstm(outputs)
        else:
            for i, lstm in enumerate(self.lstm):
                outputs, _ = lstm(outputs)
                if i + 1 < self.hparams.lstm["num_layers"]:
                    outputs = self.dropout(outputs)

        if self.hparams.linear["num_layers"] > 0:
            for linear in self.linear:
                outputs = F.leaky_relu(linear(outputs))

        return self.activation(self.classifier(outputs))


from django.test import TestCase
from django.urls import reverse
from final_exam_project.rent_a_car_web.models import Car

class CarsPageViewTest(TestCase):
    def test_cars_page_view(self):
        self.car1 = Car.objects.create(make='Toyota', car_model='Corolla', horsepower=200, image='toyota.jpg', price=50)
        self.car2 = Car.objects.create(make='Honda', car_model='Civic', horsepower=180, image='honda.jpg', price=45)

        response = self.client.get(reverse('catalogue_page'))

        self.assertEqual(response.status_code, 200)

        self.assertTemplateUsed(response, 'catalogue_page.html')

        self.assertIn('cars', response.context)

        cars_in_context = response.context['cars']

        self.assertQuerysetEqual(cars_in_context, Car.objects.all(), ordered=False)


from tensorflow.python.keras.layers import Flatten, Conv2D, MaxPool2D, Dense, Reshape, Dropout, LSTM, ReLU, BatchNormalization, Bidirectional
import tensorflow as tf

tf = tf.compat.v1

def prepare_model_settings(label_count, sample_rate, clip_duration_ms,
                           window_size_ms, window_stride_ms):
    """Calculates common settings needed for all models.

    Args:
    label_count: How many classes are to be recognized.
    sample_rate: Number of audio samples per second.
    clip_duration_ms: Length of each audio clip to be analyzed.
    window_size_ms: Duration of frequency analysis window.
    window_stride_ms: How far to move in time between frequency windows.

    Returns:
    Dictionary containing common settings.
    """
    from my_signal import feature_length
    desired_samples = int(sample_rate * clip_duration_ms / 1000)
    window_size_samples = int(sample_rate * window_size_ms / 1000)
    window_stride_samples = int(sample_rate * window_stride_ms / 1000)
    length_minus_window = (desired_samples - window_size_samples)
    if length_minus_window < 0:
        spectrogram_length = 0
    else:
        spectrogram_length = 1 + int(length_minus_window / window_stride_samples)
    feature_length = window_size_samples // 2 + 1
    fingerprint_size = feature_length * spectrogram_length
    return {
        'desired_samples': desired_samples,
        'window_size_samples': window_size_samples,
        'window_stride_samples': window_stride_samples,
        'spectrogram_length': spectrogram_length,
        'feature_length': feature_length,
        'fingerprint_size': fingerprint_size,
        'label_count': label_count,
        'sample_rate': sample_rate,
    }

def load_variables_from_checkpoint(sess, start_checkpoint):
    """Utility function to centralize checkpoint restoration.

    Args:
    sess: TensorFlow session.
    start_checkpoint: Path to saved checkpoint on disk.
    """
    saver = tf.train.Saver(tf.global_variables())
    saver.restore(sess, start_checkpoint)