# This is the file that implements a flask server to do inferences. It's the file that you will modify to
# implement the scoring for your own algorithm.

from __future__ import print_function

import os
import json
import pickle
import sys
import signal
import traceback

import flask

import math
import numpy as np
import mxnet as mx
from mxnet import nd
from mxnet.gluon.data.vision import transforms
import gluoncv as gcv
from gluoncv.data.transforms import image as timage

prefix = '/opt/ml/'
model_path = os.path.join(prefix, 'model')
artifact_file = os.path.join(model_path, 'artifact.json')
model_name = None
with open(artifact_file) as json_file:
    artifact = json.load(json_file)
    model_name = artifact['model_name']
if not model_name:
    raise RuntimeError('Unable to determine saved model name')

# A singleton for holding the model. This simply loads the model and holds it.
# It has a predict function that does a prediction based on the model and the input data.

class ScoringService(object):
    model = None                # Where we keep the model when it's loaded

    @classmethod
    def get_model(cls):
        """Get the model object for this instance, loading it if it's not already loaded."""
        if cls.model == None:
            model = gcv.model_zoo.get_model(model_name, pretrained=False, pretrained_base=False)
            model.load_parameters(os.path.join(model_path, 'model.params'), allow_missing=True)
            model.hybridize()
            cls.model = model
        return cls.model

    @classmethod
    def predict(cls, input):
        """For the input, do the predictions and return them.
        """
        clf = cls.get_model()
        output = clf(input)[0]
        predict = mx.nd.squeeze(mx.nd.argmax(output, 1)).asnumpy().astype('int32')
        return predict

# The flask app for serving predictions
app = flask.Flask(__name__)

@app.route('/ping', methods=['GET'])
def ping():
    """Determine if the container is working and healthy. In this sample container, we declare
    it healthy if we can load the model successfully."""
    health = ScoringService.get_model() is not None  # You can insert a health check here

    status = 200 if health else 404
    return flask.Response(response='\n', status=status, mimetype='application/json')

@app.route('/invocations', methods=['POST'])
def transformation():
    """Do an inference on a single batch of data. In this sample server, we take image data, decode
    image to raw frame, and apply prediction.
    """
    def preprocess(raw_image_buf, size=480,
               mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)):
        orig_image = mx.img.imdecode(raw_image_buf)
        img = timage.imresize(orig_image, size, size)
        img = mx.nd.image.to_tensor(img)
        img = mx.nd.image.normalize(img, mean=mean, std=std)
        return img.expand_dims(0), orig_image

    if flask.request.content_type in ['image/jpeg', 'image/png']:
        raw = flask.request.data
        data, orig_image = preprocess(raw)
    else:
        return flask.Response(response='This predictor only supports image data, {}'.format(flask.request.content_type), status=415, mimetype='text/plain')

    print('Invoked with {} records'.format(data.shape[0]))

    # Do the prediction
    pred = ScoringService.predict(data)

    # Convert from output to readable text
    if model_name == 'fastscnn_citys':
        classes = ('road', 'sidewalk', 'building', 'wall', 'fence', 'pole', 'traffic light', 'traffic sign', 'vegetation', 'terrain', 'sky', 'person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle', 'bicyle')
    else:
        classes = ScoringService.get_model().classes
    result = json.dumps({'prediction': pred.tolist(), 'classes': classes})
    return flask.Response(response=result, status=200, mimetype='application/json')


###############################################################################
# Auxiliary
#   Non-specific functions needed by routines
###############################################################################
import os
import warnings
import numpy as np
import matplotlib.colors as mcolors
warnings.filterwarnings("ignore")

def isnotebook():
    try:
        shell = get_ipython().__class__.__name__
        if shell == 'ZMQInteractiveShell':
            return True
        elif shell == 'TerminalInteractiveShell':
            return False
        else:
            return False
    except NameError:
        return False

def padList(lst, n):
    lst.extend([None] * n)
    lst = lst[:n]
    return lst

def removeBanned(lastfmData, bans, label='Artist'):
    return lastfmData[~lastfmData[label].isin(bans)]

def replace(dataframe, replacementDict, columnNames):
    (df, repDict, col) = (dataframe, replacementDict, columnNames)
    cats = sorted(list(repDict.keys()))
    for cat in cats:
        repSet = repDict[cat]
        df.loc[df[col[0]].isin(repSet), col[1]] = cat
    return df

def makeFolder(path):
    if not os.path.exists(path):
        try:
            os.mkdir(path)
        except OSError:
            raise OSError(
                "Can't create destination directory (%s)!" % (path)
            )

def colorPaletteFromHexList(clist):
    c = mcolors.ColorConverter().to_rgba
    clrs = [c(i) for i in clist]
    rvb = mcolors.LinearSegmentedColormap.from_list("", clrs)
    return rvb

def rollingAverage(x, w):
    return np.convolve(x, np.ones(w), 'valid') / w


#import random will make sure that the 'random' module is present.
import random

# ASCII art representing rock, paper and scissors, tagged with variables so we can use them later.
rock = '''
    _______
---'   ____)
      (_____)
      (_____)
      (____)
---.__(___)
'''

paper = '''
    _______
---'   ____)____
          ______)
          _______)
         _______)
---.__________)
'''

scissors = '''
    _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)
'''
# User input, int function makes sure input gets stores as an integer
user_choice = int(input("What do you choose? \nType 0 for Rock, 1 for Paper or 2 for Scissors. \n"))

# Makes the choices into a list, so that the computer can choose a random one from this list
choices = [rock, paper, scissors]

#Computer will take from 'choices' list and choose one at random. We store the result in a variable.
computer_choice = random.choice(choices)

# Depending on the users choice we need to print out the corresponding ASCII art
if user_choice == 0:
  print(rock)
elif user_choice == 1:
  print(paper)
elif user_choice == 2:
  print(scissors)
# if user chooses an invalid number below will be printed
else:
  print("Please pick a valid number.")

# Prints out the computer choice as long as user typed a valid number
if user_choice >= 0 and user_choice < 3:
  print(f"Computer chose: \n {computer_choice}")

# Draw statements, maybe not the most readable or efficent way to solve this, but it works
if user_choice == 0 and computer_choice == rock:
  print("It's a draw.")
elif user_choice == 1 and computer_choice == paper:
  print("It's a draw.")
elif user_choice == 2 and computer_choice == scissors:
  print("It's a draw.")

# Win statements
if user_choice == 0 and computer_choice == scissors:
  print("You win!")
elif user_choice == 1 and computer_choice == rock:
  print("You win!")
elif user_choice == 2 and computer_choice == paper:
  print("You win!")

#Lose statements
if user_choice == 0 and computer_choice == paper:
  print("You lose!")
elif user_choice == 1 and computer_choice == scissors:
  print("You lose!")
elif user_choice == 2 and computer_choice == rock:
  print("You lose!")

  # A more efficent solution: https://replit.com/@appbrewery/rock-paper-scissors-debugged-end


import pygame, random
from pygame.locals import *

def on_grid_random():
    x = random.randint(0, 590)
    y = random.randint(0, 590)
    return x // 10 * 10, y // 10 * 10

def collision(c1, c2):
    return (c1[0] == c2[0]) and (c1[1] == c2[1])

UP = 0
RIGHT = 1
DOWN = 2
LEFT = 3

pygame.init()
screen = pygame.display.set_mode((800, 800))
pygame.display.set_caption('Cobrinha')

cobrinha = [(300, 300), (310, 300), (320, 300)]
cobrinha_skin = pygame.Surface((10, 10))
cobrinha_skin.fill((0, 255, 255))

apple_pos = on_grid_random()
apple = pygame.Surface((10, 10))
apple.fill((255, 255, 255))

my_direction = LEFT

clock = pygame.time.Clock()

while True:
    clock.tick(15)
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()

        if event.type == KEYDOWN:
            if event.key == K_UP:
                my_direction = UP
        if event.type == KEYDOWN:
            if event.key == K_DOWN:
                my_direction = DOWN
        if event.type == KEYDOWN:
            if event.key == K_LEFT:
                my_direction = LEFT
        if event.type == KEYDOWN:
            if event.key == K_RIGHT:
                my_direction = RIGHT

    if collision(cobrinha[0], apple_pos):
        apple_pos = on_grid_random()
        cobrinha.append((0, 0))

    for i in range(len(cobrinha) - 1, 0, -1):
        cobrinha[i] = (cobrinha[i - 1][0], cobrinha[i - 1][1])

    if my_direction == UP:
        cobrinha[0] = (cobrinha[0][0], cobrinha[0][1] - 10)
    if my_direction == DOWN:
        cobrinha[0] = (cobrinha[0][0], cobrinha[0][1] + 10)
    if my_direction == RIGHT:
        cobrinha[0] = (cobrinha[0][0] + 10, cobrinha[0][1])
    if my_direction == LEFT:
        cobrinha[0] = (cobrinha[0][0] - 10, cobrinha[0][1])

    screen.fill((0, 0, 0))
    screen.blit(apple, apple_pos)
    for pos in cobrinha:
        screen.blit(cobrinha_skin, pos)

    pygame.display.update()


import happybase as hb
import zmq
import base64
import time
import sys
import os

#### CONFIG
hbase_url = '10.1.94.57'
hbase_table = 'image_cache'
temp_img_path = './temp-dir/img.jpg'
seg_service_port = 5561
output_hbase_table = 'rgirdhar-CMU-segmentation'
seg_fpath = '../temp-dir/result.jpg'
loc_fpath = '../temp-dir/locResult.txt'
bin_image_key_name = 'image:binary'
START_ID = '00103C5B9425A40D806D2D1D7D0D2AF8CEF4D303'
###########

last_print_time = -1
def tic_toc_print(str):
  global last_print_time
  if time.time() - last_print_time > 1:
    sys.stdout.write(str)
    last_print_time = time.time()

def refineBox(bbox):
  OFFSET = (256 -227) / 2
  return [str(float(el) + OFFSET) for el in bbox]

# set up hbase
conn = hb.Connection(hbase_url)
tab = conn.table(hbase_table)
out_tab = conn.table(output_hbase_table)
# set up zmq
context = zmq.Context()
socket = context.socket(zmq.REQ)
socket.connect('tcp://localhost:%d' % seg_service_port)

total_time_elap = 0
nitem = 0
for key,data in tab.scan(START_ID, batch_size=300):
  start_time = time.time()
  # get image
  #raw_img = base64.b64decode(data['image:orig'])
  if bin_image_key_name not in data:
    continue
  raw_img = data[bin_image_key_name]
  f = open(temp_img_path, 'wb')
  f.write(raw_img)
  f.close()
  if len(raw_img) == 0:
    continue
  # run segmentation
  socket.send(os.path.realpath(temp_img_path) + '\0')
  socket.recv()
  f = open(seg_fpath)
  seg_output = base64.b64encode(f.read())
  f.close()
  f = open(loc_fpath)
  loc_output = refineBox(f.read().strip().split(' ')[1:])
  f.close()
  #writing it out
  out_tab.put(key, {'seg:orig' : seg_output,
      'loc:xmin' : loc_output[0],
      'loc:ymin' : loc_output[1],
      'loc:xmax' : loc_output[2],
      'loc:ymax' : loc_output[3]})

  end_time = time.time()
  time_elap = end_time - start_time
  total_time_elap += time_elap
  nitem += 1
  tic_toc_print('Done till %d (key=%s). Elapsed %f sec\n Avg time %f sec\n' % (nitem, key, time_elap, total_time_elap / nitem))


from odoo import models, fields, api, _
from odoo.exceptions import Warning as UserError

from odoo.addons.l10n_br_base.tools import fiscal

class L10nbrAccountDocumentRelated(models.Model):
    _name = 'l10n_br_account_product.document.related'

    invoice_id = fields.Many2one(
        comodel_name='account.invoice',
        string=u'Documento Fiscal',
        ondelete='cascade',
        index=True)

    invoice_related_id = fields.Many2one(
        comodel_name='account.invoice',
        string=u'Documento Fiscal',
        ondelete='cascade',
        index=True)

    document_type = fields.Selection(
        selection=[('nf', 'NF'),
                   ('nfe', 'NF-e'),
                   ('cte', 'CT-e'),
                   ('nfrural', 'NF Produtor'),
                   ('cf', 'Cupom Fiscal')],
        string=u'Tipo Documento',
        required=True)

    access_key = fields.Char(
        string=u'Chave de Acesso',
        size=44)

    serie = fields.Char(
        string=u'Série',
        size=12)

    number = fields.Char(
        string=u'Número',
        size=32)

    state_id = fields.Many2one(
        comodel_name='res.country.state',
        string=u'Estado',
        domain="[('country_id.code', '=', 'BR')]")

    cnpj_cpf = fields.Char(
        string=u'CNPJ/CPF',
        size=18)

    cpfcnpj_type = fields.Selection(
        selection=[('cpf', 'CPF'),
                   ('cnpj', 'CNPJ')],
        string=u'Tipo Doc.',
        default='cnpj')

    inscr_est = fields.Char(
        string='Inscr. Estadual/RG',
        size=16)

    date = fields.Date(
        string='Data')

    fiscal_document_id = fields.Many2one(
        comodel_name='l10n_br_account.fiscal.document',
        string='Documento')

    @api.one
    @api.constrains('cnpj_cpf')
    def _check_cnpj_cpf(self):
        check_cnpj_cpf = True

        if self.cnpj_cpf:
            if self.cpfcnpj_type == 'cnpj':
                if not fiscal.validate_cnpj(self.cnpj_cpf):
                    check_cnpj_cpf = False
            elif not fiscal.validate_cpf(self.cnpj_cpf):
                check_cnpj_cpf = False
        if not check_cnpj_cpf:
            raise UserError(
                _(u'CNPJ/CPF do documento relacionado é invalido!'))

    @api.one
    @api.constrains('inscr_est')
    def _check_ie(self):
        """Checks if company register number in field insc_est is valid,
        this method call others methods because this validation is State wise

        :Return: True or False.

        :Parameters:
            - 'cr': Database cursor.
            - 'uid': Current user’s ID for security checks.
            - 'ids': List of partner objects IDs.
        """
        check_ie = True

        if self.inscr_est or self.inscr_est != 'ISENTO':
            uf = self.state_id and self.state_id.code.lower() or ''
            try:
                mod = __import__('openerp.addons.l10n_br_base.tools.fiscal',
                                 globals(), locals(), 'fiscal')

                validate = getattr(mod, 'validate_ie_%s' % uf)
                if not validate(self.inscr_est):
                    check_ie = False
            except AttributeError:
                if not fiscal.validate_ie_param(uf, self.inscr_est):
                    check_ie = False

        if not check_ie:
            raise UserError(
                _(u'Inscrição Estadual do documento fiscal inválida!'))

    @api.onchange('invoice_related_id')
    def _onchange_invoice_related_id(self):
        related = self.invoice_related_id
        if not related and not related.fiscal_document_id:
            return False

        if related.fiscal_document_id.code == '01':
            self.document_type = 'nf'
        elif related.fiscal_document_id.code == '04':
            self.document_type = 'nfrural'
        elif related.fiscal_document_id.code == '55':
            self.document_type = 'nfe'
        elif related.fiscal_document_id.code == '57':
            self.document_type = 'cte'
        elif related.fiscal_document_id.code in ('2B', '2C', '2D'):
            self.document_type = 'cf'
        else:
            self.document_type = False

        if related.fiscal_document_id.code in ('55', '57'):
            self.access_key = related.nfe_access_key
            self.serie = False
            self.number = False
            self.state_id = False
            self.cnpj_cpf = False
            self.cpfcnpj_type = False
            self.date = False
            self.fiscal_document_id = False
            self.inscr_est = False

        if related.fiscal_document_id.code in ('01', '04'):
            self.access_key = False
            if related.issuer == '0':
                self.serie = related.document_serie_id and \
                    related.document_serie_id.code or False
            else:
                self.serie = related.vendor_serie

            self.number = related.fiscal_number
            self.state_id = related.partner_id and \
                related.partner_id.state_id and \
                related.partner_id.state_id.id or False
            self.cnpj_cpf = related.partner_id and \
                related.partner_id.cnpj_cpf or False

            if related.partner_id.is_company:
                self.cpfcnpj_type = 'cnpj'
            else:
                self.cpfcnpj_type = 'cpf'

            self.date = related.date_invoice
            self.fiscal_document_id = \
                related.fiscal_document_id and \
                related.fiscal_document_id.id or False

        if related.fiscal_document_id.code == '04':
            self.inscr_est = related.partner_id and \
                related.partner_id.inscr_est or False

    @api.onchange('cnpj_cpf', 'cpfcnpj_type')
    def _onchange_mask_cnpj_cpf(self):
        country = 'BR'
        is_company = True

        if self.cpfcnpj_type == 'cpf':
            is_company = False

        cpf_cnpj = fiscal.format_cpf_cnpj(self.cnpj_cpf, country, is_company)

        self.cnpj_cpf = cpf_cnpj


import requests
from urllib.parse import urlencode
import os
from hashlib import md5

headers = {
    'cookie': '__tasessionId=ampozol5g1563806844189; tt_webid=671649' +
    '9234256455175; WEATHER_CITY=%E5%8C%97%E4%BA%AC; UM_distinctid=16c' +
    '1a26e5e12df-040ada0c1d8081-c343162-100200-16c1a26e5e428c; CNZZDAT' +
    'A1259612802=945869726-1563806204-https%253A%252F%252Fwww.google.c' +
    'om%252F%7C1563806204; tt_webid=6716499234256455175; csrftoken=46' +
    'a41d4141000920aea9354904736a2d; s_v_web_id=2b8f7242614ce9f3dd7cbf' +
    '26d932530d',
    'host': 'www.toutiao.com',
    'referer': 'https://www.toutiao.com/search/?keyword=%E8%A1%97%E6%8B%8D',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit' +
    '/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36',
    'x-requested-with': 'XMLHttpRequest'
}

def get_page(offset):
    params = {
        'aid': '24',
        'app_name': 'web_search',
        'offset': offset,
        'format': 'json',
        'keyword': '街拍',
        'autoload': 'true',
        'count': '20',
        'en_qc': '1',
        'cur_tab': '1',
        'from': 'search_tab',
        'pd': 'synthesis',
        'timestamp': '1563782026489'
    }
    url = 'https://www.toutiao.com/api/search/content/?' + urlencode(params)
    print(url)
    try:
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            print('suc_1')
            # print(response.json())
            return response.json()
    except requests.ConnectionError:
        return None

def get_images(json):
    if json.get('data'):
        for item in json.get('data'):
            title = item.get('title')
            images = item.get('image_list')
            if images:
                for image in images:
                    print('suc_2')
                    yield {
                        'image': image.get('url'),
                        'title': title
                    }
    else:
        print('data is none')

def save_image(item):
    if not os.path.exists(item.get('title')):
        os.mkdir(item.get('title'))
    try:
        print('suc_3')
        response = requests.get(item.get('image'))
        if response.status_code == 200:
            file_path = '{0}/{1}.{2}'.format(
                item.get('title'),
                md5(response.content).hexdigest(), 'jpg')
            if not os.path.exists(file_path):
                with open(file_path, 'wb') as f:
                    f.write(response.content)
    except requests.ConnectionError:
        print('Failed to save Image')

def main(offset):
    json = get_page(offset)
    for item in get_images(json):
        save_image(item)

if __name__ == '__main__':
    groups = [x * 20 for x in range(1, 5)]
    os.chdir('../weibo_ajax/images')    # 提前切换到图片存放目录
    for val in groups:
        main(val)


# Tuples

## Task
## Given an integer, n, and n space-separated integers as input, create a tuple,t ,
## n of those  integers. Then compute and print the result of hash(t).
##
## Sample Input 0
##
## 2
## 1 2
## Sample Output 0
##
## 3713081631934410656

# Main

if __name__ == '__main__':
    n = int(input())
    integer_list = map(int, input().split())
    t = tuple(integer_list)
    print(hash(t))


#! usr/bin/python3

"""
This Program encrypts and decrypts messages
"""

import pyperclip

def Cipher():
    try:

        # mode ="encrypt" # or decrypt
        mode = input("Do you want to \" encrypt \" or \" decrypt\" ? >>")

        message=input("Insert the Message you want to {} >>".format(mode))

        #encrypting and decrypting key
        key = int(input("Please insert your {} key >>".format(mode)))

        LETTERS= "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

        translated=''

        message= message.upper()

        for symbol in message:
            if symbol in LETTERS:
                num=LETTERS.find(symbol)
                if mode=="encrypt":
                    num=num+key
                elif mode=="decrypt":
                    num=num-key
                if  num >= len(LETTERS):
                    num= num- len(LETTERS)
                elif num < 0:
                    num= num + len(LETTERS)
                translated= translated + LETTERS[num]
            else:
                translated=translated + symbol

        print("")
        print("*****************************************")
        print("The {}ed message is: ".format(mode))
        print (translated)

        pyperclip.copy(translated)
    except:
        print("Check what you inputted")
        Cipher()

Cipher()


class Map(object):
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.map = None

        self._reset_map()

    def _reset_map(self):
        self.map = [[' ' for __ in range(self.width)] for _ in range(self.height)]
        for i in range(self.width):
            self.map[0][i] = '>'
            self.map[-1][i] = '<'
        for i in range(self.height):
            self.map[i][0] = '^'
            self.map[i][-1] = 'v'

    def make_lst(self, snake, candy):
        self._reset_map()
        for coor in snake.body:
            self.map[coor[0]][coor[1]] = '@'

        if candy.current_candy is not None:
            current_candy = candy.current_candy
            self.map[current_candy[0]][current_candy[1]] = '@' if candy.candy_eaten else '*'


from django.urls import include, path
from rest_framework import routers

from core.views import ProductViewSet, UserViewSet, ContactViewSet, SupplierStatisticView,\
    SupplierListCreateAPIView, SupplierUpdateDeleteAPIView

app_name = "core"

router = routers.SimpleRouter()

router.register(r"product", ProductViewSet, basename='product')
router.register(r"user", UserViewSet, basename='user')
router.register(r"contact", ContactViewSet, basename='contact')

urlpatterns = [
    path("", include(router.urls)),
    path('debt', SupplierStatisticView.as_view(), name='debt'),
    path('supplier/', SupplierListCreateAPIView.as_view(), name='supplier_list'),
    path('supplier_update/<int:pk>/', SupplierUpdateDeleteAPIView.as_view(), name='supplier_update_delete'),
]


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os

import numpy as np

from tensorflow.python import keras
from tensorflow.python.eager import context
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import test_util
from tensorflow.python.keras import keras_parameterized
from tensorflow.python.keras import model_subclassing_test_util as model_util
from tensorflow.python.keras import testing_utils
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import embedding_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.platform import test
from tensorflow.python.training.tracking import data_structures

try:
  import h5py  # pylint:disable=g-import-not-at-top
except ImportError:
  h5py = None

@keras_parameterized.run_all_keras_modes
class ModelSubclassingTest(keras_parameterized.TestCase):

  def test_custom_build(self):
    class DummyModel(keras.Model):

      def __init__(self):
        super(DummyModel, self).__init__()
        self.dense1 = keras.layers.Dense(32, activation='relu')
        self.uses_custom_build = False

      def call(self, inputs):
        return self.dense1(inputs)

      def build(self, input_shape):
        self.uses_custom_build = True

    test_model = DummyModel()
    dummy_data = array_ops.ones((32, 50))
    test_model(dummy_data)
    self.assertTrue(test_model.uses_custom_build, 'Model should use user '
                                                  'defined build when called.')

  def test_attribute_conflict_error(self):

    class ModelWithProperty(keras.Model):

      @property
      def read_only(self):
        return 1.

    m = ModelWithProperty()
    with self.assertRaisesRegexp(AttributeError, 'read_only'):
      m.read_only = 2.

  def test_custom_build_with_fit(self):

    class DummyModel(keras.Model):

      def __init__(self):
        super(DummyModel, self).__init__()
        self.layer1 = keras.layers.Dense(10, activation='relu')

      def build(self, input_shape):
        self.layer2 = keras.layers.Dense(1, activation='relu')

      def call(self, inputs):
        return self.layer2(self.layer1(inputs))

    model = DummyModel()
    model.compile(
        'sgd',
        'mse',
        run_eagerly=testing_utils.should_run_eagerly(),
        experimental_run_tf_function=testing_utils.should_run_tf_function())
    model.fit(np.ones((10, 10)), np.ones((10, 1)), batch_size=2, epochs=2)
    self.assertLen(model.layers, 2)
    self.assertLen(model.trainable_variables, 4)

  def test_invalid_input_shape_build(self):
    num_classes = 2
    input_dim = 50

    model = model_util.SimpleTestModel(
        num_classes=num_classes, use_dp=True, use_bn=True)

    self.assertFalse(model.built, 'Model should not have been built')
    self.assertFalse(model.weights, ('Model should have no weights since it '
                                     'has not been built.'))
    with self.assertRaisesRegexp(
        ValueError, 'input shape is not one of the valid types'):
      model.build(input_shape=tensor_shape.Dimension(input_dim))

  def test_embed_dtype_with_subclass_build(self):
    class Embedding(keras.layers.Layer):
      """An Embedding layer."""

      def __init__(self, vocab_size, embedding_dim, **kwargs):
        super(Embedding, self).__init__(**kwargs)
        self.vocab_size = vocab_size
        self.embedding_dim = embedding_dim

      def build(self, _):
        self.embedding = self.add_variable(
            'embedding_kernel',
            shape=[self.vocab_size, self.embedding_dim],
            dtype=np.float32,
            initializer=init_ops.random_uniform_initializer(-0.1, 0.1),
            trainable=True)

      def call(self, x):
        return embedding_ops.embedding_lookup(self.embedding, x)

    class EmbedModel(keras.Model):

      def __init__(self, vocab_size, embed_size):
        super(EmbedModel, self).__init__()
        self.embed1 = Embedding(vocab_size, embed_size)

      def call(self, inputs):
        return self.embed1(inputs)

    model = EmbedModel(100, 20)
    self.assertFalse(model.built, 'Model should not have been built')
    self.assertFalse(model.weights, ('Model should have no weights since it '
                                     'has not been built.'))
    with self.assertRaisesRegexp(
        ValueError, 'if your layers do not support float type inputs'):
      model.build(input_shape=(35, 20))

  def test_single_time_step_rnn_build(self):
    dim = 4
    timesteps = 1
    batch_input_shape = (None, timesteps, dim)
    units = 3

    class SimpleRNNModel(keras.Model):

      def __init__(self):
        super(SimpleRNNModel, self).__init__()
        self.lstm = keras.layers.LSTM(units)

      def call(self, inputs):
        return self.lstm(inputs)

    model = SimpleRNNModel()
    self.assertFalse(model.built, 'Model should not have been built')
    self.assertFalse(model.weights, ('Model should have no weights since it '
                                     'has not been built.'))
    model.build(batch_input_shape)
    self.assertTrue(model.weights, ('Model should have weights now that it '
                                    'has been properly built.'))
    self.assertTrue(model.built, 'Model should be built after calling `build`.')
    model(array_ops.ones((32, timesteps, dim)))

  def test_single_io_subclass_build(self):
    num_classes = 2
    input_dim = 50
    batch_size = None

    model = model_util.SimpleTestModel(
        num_classes=num_classes, use_dp=True, use_bn=True)

    self.assertFalse(model.built, 'Model should not have been built')
    self.assertFalse(model.weights, ('Model should have no weights since it '
                                     'has not been built.'))
    model.build(input_shape=(batch_size, input_dim))
    self.assertTrue(model.weights, ('Model should have weights now that it '
                                    'has been properly built.'))
    self.assertTrue(model.built, 'Model should be built after calling `build`.')
    model(array_ops.ones((32, input_dim)))

  def test_single_io_dimension_subclass_build(self):
    num_classes = 2
    input_dim = tensor_shape.Dimension(50)
    batch_size = tensor_shape.Dimension(None)

    model = model_util.SimpleTestModel(
        num_classes=num_classes, use_dp=True, use_bn=True)

    self.assertFalse(model.built, 'Model should not have been built')
    self.assertFalse(model.weights, ('Model should have no weights since it '
                                     'has not been built.'))
    model.build(input_shape=(batch_size, input_dim))
    self.assertTrue(model.weights, ('Model should have weights now that it '
                                    'has been properly built.'))
    self.assertTrue(model.built, 'Model should be built after calling `build`.')
    model(array_ops.ones((32, input_dim)))

  def test_multidim_io_subclass_build(self):
    num_classes = 10
    # Input size, e.g. image
    batch_size = 32
    input_shape = (32, 32, 3)

    model = model_util.SimpleConvTestModel(num_classes)
    self.assertFalse(model.built, 'Model should not have been built')
    self.assertFalse(model.weights, ('Model should have no weights since it '
                                     'has not been built.'))
    batch_input_shape = (batch_size,) + input_shape
    model.build(input_shape=batch_input_shape)
    self.assertTrue(model.weights, ('Model should have weights now that it '
                                    'has been properly built.'))
    self.assertTrue(model.built, 'Model should be built after calling `build`.')

    model(array_ops.ones(batch_input_shape))

  def test_tensorshape_io_subclass_build(self):
    num_classes = 10
    # Input size, e.g. image
    batch_size = None
    input_shape = (32, 32, 3)

    model = model_util.SimpleConvTestModel(num_classes)
    self.assertFalse(model.built, 'Model should not have been built')
    self.assertFalse(model.weights, ('Model should have no weights since it '
                                     'has not been built.'))
    model.build(
        input_shape=tensor_shape.TensorShape((batch_size,) + input_shape))
    self.assertTrue(model.weights, ('Model should have weights now that it '
                                    'has been properly built.'))
    self.assertTrue(model.built, 'Model should be built after calling `build`.')

    model(array_ops.ones((32,) + input_shape))

  def test_subclass_save_model(self):
    num_classes = 10
    # Input size, e.g. image
    batch_size = None
    input_shape = (32, 32, 3)

    model = model_util.SimpleConvTestModel(num_classes)
    self.assertFalse(model.built, 'Model should not have been built')
    self.assertFalse(model.weights, ('Model should have no weights since it '
                                     'has not been built.'))
    model.build(
        input_shape=tensor_shape.TensorShape((batch_size,) + input_shape))
    self.assertTrue(model.weights, ('Model should have weights now that it '
                                    'has been properly built.'))
    self.assertTrue(model.built, 'Model should be built after calling `build`.')
    weights = model.get_weights()

    tf_format_name = os.path.join(self.get_temp_dir(), 'ckpt')
    model.save_weights(tf_format_name)
    if h5py is not None:
      hdf5_format_name = os.path.join(self.get_temp_dir(), 'weights.h5')
      model.save_weights(hdf5_format_name)

    model = model_util.SimpleConvTestModel(num_classes)
    model.build(
        input_shape=tensor_shape.TensorShape((batch_size,) + input_shape))
    if h5py is not None:
      model.load_weights(hdf5_format_name)
      self.assertAllClose(weights, model.get_weights())
    model.load_weights(tf_format_name)
    self.assertAllClose(weights, model.get_weights())

  def test_multi_io_subclass_build(self):
    batch_size = None
    num_samples = 1000
    input_dim = 50
    model = model_util.MultiIOTestModel()
    self.assertFalse(model.built, 'Model should not have been built')
    self.assertFalse(model.weights, ('Model should have no weights since it '
                                     'has not been built.'))
    batch_input_shape = tensor_shape.TensorShape((batch_size, input_dim))
    model.build(
        input_shape=[batch_input_shape, batch_input_shape])
    self.assertTrue(model.weights, ('Model should have weights now that it '
                                    'has been properly built.'))
    self.assertTrue(model.built, 'Model should be built after calling `build`.')
    x1 = array_ops.ones((num_samples, input_dim))
    x2 = array_ops.ones((num_samples, input_dim))
    model([x1, x2])

  def test_summary(self):

    class ToString(object):

      def __init__(self):
        self.contents = ''

      def __call__(self, msg):
        self.contents += msg + '\n'

    # Single-io
    model = model_util.SimpleTestModel(num_classes=4, use_bn=True, use_dp=True)
    model._set_inputs(np.ones((3, 4)))  # need to build model first
    print_fn = ToString()
    model.summary(print_fn=print_fn)
    self.assertTrue('Trainable params: 356' in print_fn.contents)

    # Multi-io
    model = model_util.MultiIOTestModel(
        num_classes=(5, 6), use_bn=True, use_dp=True)
    model._set_inputs([np.ones((3, 4)),
                       np.ones((3, 4))])  # need to build model first
    print_fn = ToString()
    model.summary(print_fn=print_fn)
    self.assertTrue('Trainable params: 587' in print_fn.contents)

  def test_no_dependency(self):
    class Foo(keras.Model):

      def __init__(self):
        super(Foo, self).__init__()
        self.isdep = keras.layers.Dense(1)
        self.notdep = data_structures.NoDependency(keras.layers.Dense(2))
        self.notdep_var = data_structures.NoDependency(
            resource_variable_ops.ResourceVariable(1., name='notdep_var'))

    m = Foo()
    self.assertEqual([m.isdep, m.notdep], m.layers)
    self.assertEqual(1, len(m._checkpoint_dependencies))
    self.assertIs(m.isdep, m._checkpoint_dependencies[0].ref)
    self.assertEqual('notdep_var:0', m.notdep_var.name)

  def test_extra_variable(self):

    class ExtraVar(keras.Model):

      def __init__(self):
        super(ExtraVar, self).__init__()
        self.dense = keras.layers.Dense(1)
        self.var = resource_variable_ops.ResourceVariable(1.)
        self.not_trainable_var = resource_variable_ops.ResourceVariable(
            2., trainable=False)

      def call(self, inputs):
        return self.dense(inputs + self.var)

    m = ExtraVar()
    self.assertTrue(m.trainable)
    self.assertEqual([m.dense], m.layers)
    self.assertEqual([m.var, m.not_trainable_var], m.variables)
    self.assertEqual([m.var], m.trainable_variables)
    self.assertEqual([m.not_trainable_var], m.non_trainable_variables)
    self.assertLen(m.get_weights(), 2)
    m.trainable = False
    self.assertEqual([m.var, m.not_trainable_var], m.variables)
    self.assertEqual([], m.trainable_variables)
    self.assertEqual([m.var, m.not_trainable_var], m.non_trainable_variables)
    self.assertLen(m.get_weights(), 2)
    m.trainable = True

    m(array_ops.ones([1, 1]))

    self.assertEqual([m.dense.kernel, m.dense.bias], m.dense.variables)
    self.assertEqual([m.dense.kernel, m.dense.bias], m.dense.weights)

    self.assertLen(m.get_weights(), 4)
    self.assertEqual([m.dense.kernel, m.dense.bias, m.var, m.not_trainable_var],
                     m.variables)
    self.assertEqual([m.dense.kernel, m.dense.bias, m.var],
                     m.trainable_variables)
    self.assertEqual([m.not_trainable_var], m.non_trainable_variables)

    m.dense.trainable = False
    self.assertEqual(
        [m.dense.kernel, m.dense.bias, m.var, m.not_trainable_var],
        m.variables)
    self.assertEqual([m.var], m.trainable_variables)
    self.assertEqual([m.dense.kernel, m.dense.bias, m.not_trainable_var],
                     m.non_trainable_variables)
    self.assertLen(m.get_weights(), 4)

  def test_add_weight_in_model(self):

    class MyModel(keras.Model):

      def __init__(self):
        super(MyModel, self).__init__()
        self.b = self.add_weight('bias', (10,))
        self.c = self.add_weight('bias2', (10,), trainable=False)

      def call(self, inputs):
        return inputs + self.b + self.c

    x = ops.convert_to_tensor(np.ones((10, 10), 'float32'))
    model = MyModel()
    model(x)
    self.assertEqual(1, len(model.trainable_weights))
    self.assertEqual(1, len(model.non_trainable_weights))
    self.assertEqual(2, len(model.weights))

    class MyModelCustomBuild(keras.Model):

      def build(self, input_shape):
        self.b = self.add_weight('bias', (10,))
        self.c = self.add_weight('bias2', (10,), trainable=False)

      def call(self, inputs):
        return inputs + self.b + self.c

    x = ops.convert_to_tensor(np.ones((10, 10), 'float32'))
    model = MyModelCustomBuild()
    model(x)
    self.assertEqual(1, len(model.trainable_weights))
    self.assertEqual(1, len(model.non_trainable_weights))
    self.assertEqual(2, len(model.weights))

  def test_add_update_in_model(self):

    class MyModel(keras.Model):

      def __init__(self):
        super(MyModel, self).__init__()
        self.b = self.add_weight('bias', (10,))
        self.c = self.add_weight('bias2', (10,))

      def call(self, inputs):
        # Unconditional
        self.add_update(self.b.assign(self.b * 2))
        # Conditional
        self.add_update(self.c.assign(inputs[1, :]), inputs)
        return inputs + self.b + self.c

    x = ops.convert_to_tensor(np.ones((10, 10), 'float32'))
    model = MyModel()
    model(x)

    if context.executing_eagerly():
      self.assertEqual(0, len(model.updates))
    else:
      self.assertEqual(2, len(model.updates))
      self.assertEqual(1, len(model.get_updates_for(None)))
      self.assertEqual(1, len(model.get_updates_for(x)))

class GraphSpecificModelSubclassingTests(test.TestCase):

  @test_util.run_deprecated_v1
  def test_single_io_workflow_with_tensors(self):
    num_classes = 2
    num_samples = 10
    input_dim = 50

    with self.cached_session():
      model = model_util.SimpleTestModel(
          num_classes=num_classes, use_dp=True, use_bn=True)
      model.compile(loss='mse', optimizer='rmsprop')

      x = array_ops.ones((num_samples, input_dim))
      y = array_ops.zeros((num_samples, num_classes))

      model.fit(x, y, epochs=2, steps_per_epoch=10, verbose=0)
      _ = model.evaluate(steps=10, verbose=0)

  @test_util.run_deprecated_v1
  def test_multi_io_workflow_with_tensors(self):
    num_classes = (2, 3)
    num_samples = 10
    input_dim = 50

    with self.cached_session():
      model = model_util.MultiIOTestModel(
          num_classes=num_classes, use_dp=True, use_bn=True)
      model.compile(loss='mse', optimizer='rmsprop')

      x1 = array_ops.ones((num_samples, input_dim))
      x2 = array_ops.ones((num_samples, input_dim))
      y1 = array_ops.zeros((num_samples, num_classes[0]))
      y2 = array_ops.zeros((num_samples, num_classes[1]))

      model.fit([x1, x2], [y1, y2], epochs=2, steps_per_epoch=10, verbose=0)
      _ = model.evaluate(steps=10, verbose=0)

  @test_util.run_deprecated_v1
  def test_updates_and_losses_for_nested_models_in_subclassed_model(self):

    # Case 1: deferred-build sequential nested in subclass.
    class TestModel1(keras.Model):

      def __init__(self):
        super(TestModel1, self).__init__()
        self.fc = keras.layers.Dense(10, input_shape=(784,),
                                     activity_regularizer='l1')
        self.bn = keras.Sequential([keras.layers.BatchNormalization(axis=1)])

      def call(self, x):
        return self.bn(self.fc(x))

    with self.cached_session():
      model = TestModel1()

      x = array_ops.ones(shape=[100, 784], dtype='float32')
      model(x)
      self.assertEqual(len(model.get_updates_for(x)), 2)
      self.assertEqual(len(model.get_losses_for(x)), 1)

    # Case 2: placeholder-sequential nested in subclass.
    class TestModel2(keras.Model):

      def __init__(self):
        super(TestModel2, self).__init__()
        self.fc = keras.layers.Dense(10, input_shape=(784,),
                                     activity_regularizer='l1')
        self.bn = keras.Sequential(
            [keras.layers.BatchNormalization(axis=1, input_shape=(10,))])

      def call(self, x):
        return self.bn(self.fc(x))

    with self.cached_session():
      model = TestModel2()

      x = array_ops.ones(shape=[100, 784], dtype='float32')
      model(x)
      self.assertEqual(len(model.get_updates_for(x)), 2)
      self.assertEqual(len(model.get_losses_for(x)), 1)

    # Case 3: functional-API model nested in subclass.
    inputs = keras.Input((10,))
    outputs = keras.layers.BatchNormalization(axis=1)(inputs)
    bn = keras.Model(inputs, outputs)

    class TestModel3(keras.Model):

      def __init__(self):
        super(TestModel3, self).__init__()
        self.fc = keras.layers.Dense(10, input_shape=(784,),
                                     activity_regularizer='l1')
        self.bn = bn

      def call(self, x):
        return self.bn(self.fc(x))

    with self.cached_session():
      model = TestModel3()

      x = array_ops.ones(shape=[100, 784], dtype='float32')
      model(x)
      self.assertEqual(len(model.get_updates_for(x)), 2)
      self.assertEqual(len(model.get_losses_for(x)), 1)

  @test_util.run_deprecated_v1
  def test_multi_io_workflow_with_numpy_arrays_and_custom_placeholders(self):
    num_classes = (2, 3)
    num_samples = 1000
    input_dim = 50

    with self.cached_session():
      model = model_util.MultiIOTestModel(
          num_classes=num_classes, use_dp=True, use_bn=True)
      model.compile(loss='mse', optimizer='rmsprop')

      x1 = np.ones((num_samples, input_dim))
      x2 = np.ones((num_samples, input_dim))
      y1 = np.zeros((num_samples, num_classes[0]))
      y2 = np.zeros((num_samples, num_classes[1]))

      x2_placeholder = array_ops.placeholder(
          dtype='float32', shape=(None, input_dim))
      model._set_inputs([x1, x2_placeholder])

      model.fit([x1, x2], [y1, y2], epochs=2, batch_size=32, verbose=0)
      _ = model.evaluate([x1, x2], [y1, y2], verbose=0)

@test_util.run_all_in_graph_and_eager_modes
class CustomCallSignatureTests(test.TestCase):

  def test_no_inputs_in_signature(self):
    model = model_util.CustomCallModel()
    first = array_ops.ones([2, 3])
    second = array_ops.ones([2, 5])
    output = model(first, second)
    self.evaluate([v.initializer for v in model.variables])
    expected_output = self.evaluate(model.dense1(first) + model.dense2(second))
    self.assertAllClose(expected_output, self.evaluate(output))
    output = model(first, second, fiddle_with_output='yes')
    self.assertAllClose(10. * expected_output, self.evaluate(output))
    output = model(first, second=second, training=False)
    self.assertAllClose(expected_output, self.evaluate(output))

  def test_training_args_call_build(self):
    input_dim = 2

    model = model_util.TrainingNoDefaultModel()
    self.assertFalse(model.built, 'Model should not have been built')
    self.assertFalse(model.weights, ('Model should have no weights since it '
                                     'has not been built.'))
    model.build((None, input_dim))
    self.assertTrue(model.weights, ('Model should have weights now that it '
                                    'has been properly built.'))
    self.assertTrue(model.built, 'Model should be built after calling `build`.')

  def test_training_and_mask_args_call_build(self):
    input_dim = 2

    model = model_util.TrainingMaskingModel()
    self.assertFalse(model.built, 'Model should not have been built')
    self.assertFalse(model.weights, ('Model should have no weights since it '
                                     'has not been built.'))
    model.build((None, input_dim))
    self.assertTrue(model.weights, ('Model should have weights now that it '
                                    'has been properly built.'))
    self.assertTrue(model.built, 'Model should be built after calling `build`.')

  def test_custom_call_kwargs_and_build(self):
    first_input_shape = (2, 3)
    second_input_shape = (2, 5)

    model = model_util.CustomCallModel()
    self.assertFalse(model.built, 'Model should not have been built')
    self.assertFalse(model.weights, ('Model should have no weights since it '
                                     'has not been built.'))
    with self.assertRaisesRegexp(
        ValueError, 'cannot build your model if it has positional'):
      model.build(input_shape=[first_input_shape, second_input_shape])

  def test_kwargs_in_signature(self):

    class HasKwargs(keras.Model):

      def call(self, x, y=3, **kwargs):
        return x

    model = HasKwargs()
    arg = array_ops.ones([1])
    model(arg, a=3)
    if not context.executing_eagerly():
      self.assertEqual(len(model.inputs), 1)

  @test_util.assert_no_new_tensors
  @test_util.assert_no_garbage_created
  def test_training_no_default(self):
    if not context.executing_eagerly():
      self.skipTest('b/138307499')
    model = model_util.TrainingNoDefaultModel()
    arg = array_ops.ones([1, 1])
    model(arg, True)

  def test_positional_arg_in_call(self):

    class ModelWithPositionalArgs(keras.Model):

      def call(self, x, x2, x3=None):
        return x + x2

    x = np.ones((10, 1))
    y = np.ones((10, 1))
    m = ModelWithPositionalArgs()
    m.compile('sgd', 'mse')
    with self.assertRaisesRegexp(ValueError, r'Models passed to `fit`'):
      m.fit(x, y, batch_size=2)
    with self.assertRaisesRegexp(ValueError, r'Models passed to `evaluate`'):
      m.evaluate(x, y, batch_size=2)
    with self.assertRaisesRegexp(ValueError, r'Models passed to `predict`'):
      m.predict(x, batch_size=2)
    with self.assertRaisesRegexp(ValueError,
                                 r'Models passed to `train_on_batch`'):
      m.train_on_batch(x, y)
    with self.assertRaisesRegexp(ValueError,
                                 r'Models passed to `test_on_batch`'):
      m.test_on_batch(x, y)
    with self.assertRaisesRegexp(ValueError,
                                 r'Models passed to `predict_on_batch`'):
      m.predict_on_batch(x)

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


from common.device_command import CommandUtil
from common.log import Log
from common.utils import Utils

import os
import time
from enum import Enum
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtTest import *
from com.dtmilano.android.viewclient import ViewClient
# from com.dtmilano.android.adb.adbclient import AdbClient

ONBOARDING_TIMEOUT = 600
REMOVING_TIMEOUT = 120
# start onboarding
ONBOARDING_ADD_BUTTON = 0
ONBOARDING_ADDITIONAL_ADD_BUTTON = 1
ONBOARDING_MANUAL_PAIRING_CODE_BOTTON = 2
ONBOARDING_MANUAL_PAIRING_CODE_TEXTBOX = 3
ONBOARDING_MANUAL_PAIRING_CODE_INPUT_DONE = 4
ONBOARDING_CONTINUE_BUTTON = 5
ONBOARDING_NO_MATTER_CERT_DEVICE_SKIP_BUTTON = 6
ONBOARDING_MATTER_DEVICE_NAME_CHANGE = 7
ONBOARDING_MATTER_DEVICE_NAME_CHANGE_DONE = 8
ONBOARDING_DONE_BACK_TO_FIRST_SCREEN = 9
# remove device
REMOVE_START = 30
REMOVE_BUTTON = 31
REMOVE_DONE = 32
# error capture
ERROR_CHECK_LAYOUT = 40
# words
ERROR_OCCUR_KOR = 90
ERROR_OCCUR_ENG = 91
ADD_DEVICE_KOR = 92
ADD_DEVICE_ENG = 93
REMOVE_BUTTON_KOR = 94
REMOVE_BUTTON_ENG = 95

class STOnboardingResult():
    ONBOARDING_FAILURE = 0
    ONBOARDING_SUCCESS = 1
    REMOVING_FAILURE = 2
    REMOVING_SUCCESS = 3
    REMOVED_PHONE = 4

    result_message = {
        ONBOARDING_FAILURE : "Onboarding failed",
        ONBOARDING_SUCCESS : "Onboarding success",
        REMOVING_FAILURE : "Removing failed",
        REMOVING_SUCCESS : "Removing success",
        REMOVED_PHONE : "Removed phone"
    }

    @classmethod
    def is_onboarding_result(cls, r):
        if r == cls.ONBOARDING_FAILURE or r == cls.ONBOARDING_SUCCESS:
            return True
        return False

    @classmethod
    def is_removing_result(cls, r):
        if r == cls.REMOVING_FAILURE or r == cls.REMOVING_SUCCESS:
            return True
        return False

    @classmethod
    def get_result_msg(cls, result):
        return cls.result_message.get(result, "")

class AutoDeviceState():
    IDLE = 0
    CONNECTING_PHONE = 1
    ONBOARDING = 2
    REMOVING = 3

## Dialog class ##
class simpleDlg(QDialog):

    ## Initialize Dialog ##
    def __init__(self, title, content):
        super(simpleDlg, self).__init__()
        self.app = QErrorMessage()
        self.app.showMessage(content)
        self.app.setWindowModality(Qt.WindowModal)
        self.app.setWindowTitle(title)
        self.app.exec()

    def no_device_dialog():
        simpleDlg("No device is selected",
                                "Check the device for onboarding")
        Log.print("Error: No device is selected for onboarding.")

    def one_device_dialog():
        simpleDlg("Wrong input",
                "Only one device can use Auto onboarding repeat test!!")
        Log.print("only one device can use Auto onboarding repeat test!!")

    def no_phone_dialog():
        err = simpleDlg("Error",
                "Can't work auto-onboarding because the phone is not connected")
        err.setWindowModality(Qt.NonModal)
        Log.print("Can't work auto-onboarding because the phone is not connected")

## Automation of devices ##
class autoDevice(QThread):
    update_onboarding_state = pyqtSignal(int, str, str)

    ## Initialize autodevice ##
    def __init__(self, parent):
        super().__init__()
        self.parent = parent
        self.device = None
        self.serialno = None
        self.vc = None
        self.running = False
        self.device_name = None
        self.comport = None
        self.device_num = None
        self.is_request = dict()
        self.debug = False
        # Log.print("autoDevice")

    ## Run autodevice ##
    def run(self):
        self.running = True
        self.step = AutoDeviceState.IDLE
        self.is_request.clear()
        while self.running:
            if self.step == AutoDeviceState.CONNECTING_PHONE:
                if self.try_connect_phone():
                    self.step = AutoDeviceState.ONBOARDING
                    continue
                self.step = AutoDeviceState.IDLE
            elif self.step == AutoDeviceState.ONBOARDING:
                self.auto_onboarding_device()
                self.step = AutoDeviceState.IDLE
            elif self.step == AutoDeviceState.REMOVING:
                self.auto_remove_device()
                self.step = AutoDeviceState.IDLE
            QTest.qWait(1000)

    ## Check device available for auto-onboarding ##
    def check_auto_available(self):
        if Utils.check_connectable():
            return True
        else:
            simpleDlg.no_phone_dialog()
            return False

    ## Check device running state ##
    def is_running(self):
        return self.running

    ## Try to connect to phone ##
    def try_connect_phone(self):
        result = False
        if self.check_auto_available():
            try:
                (self.device, self.serialno) = ViewClient.connectToDeviceOrExit()
                self.vc = ViewClient(self.device, self.serialno)
                self.device.reconnect = True
            except RuntimeError as e:
                Log.print("connect error", e)
            else:
                Log.print("adb is connected")
                result = True
        return result

    ## Check device connection state ##
    def is_connected(self):
        if self.device and self.vc:
            return True
        else:
            return False

    ## Request onboarding ##
    def request_onboarding(self, comport, device_num, code, device_id):
        if self.step != AutoDeviceState.IDLE:
            Log.print(f'working on something else  step : {self.step}')
            return False
        if True in self.is_request.values():
            Log.print(f'working on something else is_request {self.is_request}')
            return False
        self.is_request[device_num] = True
        self.comport = comport
        self.device_num = device_num
        self.device_id = device_id
        self.pairing_code = code
        if not self.is_connected():
            self.step = AutoDeviceState.CONNECTING_PHONE
        else:
            self.step = AutoDeviceState.ONBOARDING
        return True

    ## Update onboarding status of device ##
    def auto_onboarding_device(self):
        self.device_name = f"{CommandUtil.get_device_type_by_device_id(self.device_id)}-{self.device_num}"
        self.count = 0
        if self.auto_onboarding():
            Log.print("onboarding success!")
            self.update_onboarding_state.emit(
                STOnboardingResult.ONBOARDING_SUCCESS, self.comport, self.device_num)
            self.is_request[self.device_num] = False
        else:
            if not self.is_connected():
                Log.print("onboarding failed due to adb problem")
            else:
                Log.print("onboarding failed..")
                self.update_onboarding_state.emit(
                    STOnboardingResult.ONBOARDING_FAILURE, self.comport, self.device_num)
            if self.device_num in self.is_request:
                del self.is_request[self.device_num]

    ## auto onboarding ##
    def auto_onboarding(self):
        start_time = time.time()
        stair = ONBOARDING_ADD_BUTTON
        while self.running:
            # Log.print(f"auto_onboarding step {self.step} device_num {self.device_num}")
            if True not in self.is_request.values():
                return False
            obj = self.get_obj(str(stair))
            if obj and stair == ONBOARDING_ADDITIONAL_ADD_BUTTON:
                if obj.getText() in [self.get_smartthings_view_id(ADD_DEVICE_KOR),
                                     self.get_smartthings_view_id(ADD_DEVICE_ENG)]:
                    if self.debug == True:
                        Log.print(
                            f"stair::ONBOARDING_ADDITIONAL_ADD_BUTTON, obj={obj}")
                    obj.touch()
                    stair += 1
            elif not obj and stair == ONBOARDING_ADDITIONAL_ADD_BUTTON:
                obj = self.get_obj(str(stair), True)
                if obj:
                    if self.debug == True:
                        Log.print(
                            f"stair::ONBOARDING_ADDITIONAL_ADD_BUTTON, obj={obj}")
                    obj.touch()
                    stair += 1
                else:
                    obj = self.get_obj(
                        str(ONBOARDING_MANUAL_PAIRING_CODE_BOTTON))
                    if obj:
                        if self.debug == True:
                            Log.print(
                                f"stair::ONBOARDING_MANUAL_PAIRING_CODE_BOTTON, obj={obj}")
                        obj.touch()
                        stair += 2
            elif obj and stair == ONBOARDING_MANUAL_PAIRING_CODE_TEXTBOX:
                if self.debug == True:
                    Log.print(
                        f"stair::ONBOARDING_MANUAL_PAIRING_CODE_TEXTBOX, obj={obj}")
                obj.type(self.pairing_code)
                stair += 1
            elif obj and stair == ONBOARDING_MATTER_DEVICE_NAME_CHANGE:
                if self.debug == True:
                    Log.print(
                        f"stair::ONBOARDING_MATTER_DEVICE_NAME_CHANGE, obj={obj}")
                obj.setText(self.device_name)
                stair += 1
            elif obj and stair == ONBOARDING_MATTER_DEVICE_NAME_CHANGE_DONE:
                if self.debug == True:
                    Log.print(
                        f"stair::ONBOARDING_MATTER_DEVICE_NAME_CHANGE_DONE, obj={obj}")
                if self.device.isKeyboardShown():
                    self.device.press("BACK")
                    if self.debug == True:
                        Log.print(
                            f"stair::ONBOARDING_MATTER_DEVICE_NAME_CHANGE_DONE, keyboard down")
                    QTest.qWait(2000)
                obj.touch()
                QTest.qWait(12000)
                stair += 1
            elif stair == ONBOARDING_DONE_BACK_TO_FIRST_SCREEN:
                if self.debug == True:
                    Log.print("stair::ONBOARDING_DONE_BACK_TO_FIRST_SCREEN")
                obj = self.get_obj("text:" + self.device_name, True)
                if obj or self.count >= 3:
                    if self.debug == True:
                        Log.print(f"obj={obj}")
                    self.vc.device.press("BACK")
                    QTest.qWait(3000)
                    if self.debug == True:
                        Log.print("press BACK")
                    return True
                else:
                    if self.debug == True:
                        Log.print(
                            f"stair::ONBOARDING_DONE_BACK_TO_FIRST_SCREEN {self.device_name} not found")
                    self.count += 1
            elif obj:
                if self.debug == True:
                    Log.print(f"stair::{stair}, obj={obj}")
                obj.touch()
                QTest.qWait(1000)
                stair += 1
            elif not obj:
                if stair == ONBOARDING_MATTER_DEVICE_NAME_CHANGE:
                    if self.debug == True:
                        Log.print("waiting download plugin in SmartThings...")
                    self.view_dump(5)
                else:
                    if self.debug == True:
                        Log.print(f"not found stair::{stair}'s obj")
                    self.view_dump()
            if True not in self.is_request.values():
                return False
            # screenshot when error occurs
            err = self.get_obj(str(ERROR_CHECK_LAYOUT))
            if err:
                if err.getText() in [self.get_smartthings_view_id(ERROR_OCCUR_KOR),
                                     self.get_smartthings_view_id(ERROR_OCCUR_ENG)]:
                    if self.debug == True:
                        Log.print(err)
                    self.screenshot()
                    err2 = self.get_obj(
                        str(ONBOARDING_MATTER_DEVICE_NAME_CHANGE_DONE))
                    if err2:
                        err2.touch()
                    QTest.qWait(1000)
                    self.vc.device.press("BACK")
                    if self.debug == True:
                        Log.print("press BACK")
                    return False

            # screenshot when too much delay occurred during onboarding and return error
            now_time = time.time()
            if now_time - start_time > ONBOARDING_TIMEOUT:
                Log.print(
                    f"Too much time {ONBOARDING_TIMEOUT}s goes on for onboarding... it is failed!")
                self.vc.device.press("BACK")
                while self.running:
                    ti = self.get_obj(str(ERROR_CHECK_LAYOUT), True)
                    if ti:
                        self.screenshot()
                        if self.debug == True:
                            Log.print(ti)
                        ti.touch()
                        break
                QTest.qWait(1000)
                self.vc.device.press("BACK")
                QTest.qWait(1000)
                if self.debug == True:
                    Log.print("press BACK")
                return False

    ## Disconnect device ##
    def disconnect_device(self, device_num):
        if device_num in self.is_request:
            del self.is_request[device_num]
            # self.step = 0

    ## Remove request ##
    def request_remove(self, comport, device_num, device_id):
        if self.step != AutoDeviceState.IDLE:
            Log.print(f'working on something else  step : {self.is_request}')
            return
        if True in self.is_request.values():
            Log.print(f'working on something else is_request : {self.is_request}')
            return
        if not device_num in self.is_request:
            return
        self.is_request[device_num] = True
        self.device_num = device_num
        self.comport = comport
        self.device_id = device_id
        self.step = AutoDeviceState.REMOVING

    ## Check remove status of device ##
    def auto_remove_device(self):
        self.device_name = f"{CommandUtil.get_device_type_by_device_id(self.device_id)}-{self.device_num}"
        if self.remove_device():
            Log.print("removing success!")
            self.update_onboarding_state.emit(
                STOnboardingResult.REMOVING_SUCCESS, self.comport, self.device_num)
            self.vc.sleep(1)
        else:
            Log.print("removing failed!")
            self.update_onboarding_state.emit(
                STOnboardingResult.REMOVING_FAILURE, self.comport, self.device_num)
            self.vc.sleep(1)
        if self.device_num in self.is_request:
            del self.is_request[self.device_num]

    ## Remove device ##
    def remove_device(self):
        Log.print(f"{self.device_name} will be removed ...")
        start_time = time.time()
        stair = REMOVE_START
        while self.running:
            if stair == REMOVE_START:
                obj = self.get_obj("text:" + self.device_name, True)
                if obj:
                    if self.debug == True:
                        Log.print(obj)
                    (x, y) = obj.getCenter()
                    self.device.drag((x, y), (x, y), 2000, 1)
                    stair = stair + 1
                else:
                    Log.print(f"can't find {self.device_name}")
                    if time.time() - start_time > REMOVING_TIMEOUT:
                        Log.print(f"can't not find {self.device_name} anymore")
                        return False
                    continue
            elif stair >= REMOVE_BUTTON and stair <= REMOVE_DONE:
                self.view_dump()
                if stair == REMOVE_BUTTON:
                    obj = self.get_obj("text:" + str(REMOVE_BUTTON_KOR)
                                       ) or self.get_obj("text:" + str(REMOVE_BUTTON_ENG))
                else:
                    obj = self.get_obj(str(stair))
                if obj:
                    if self.debug == True:
                        Log.print(obj)
                    obj.touch()
                    stair = stair + 1
                else:
                    if stair == REMOVE_BUTTON:
                        Log.print(f"can't not find edit button")
                    elif stair == REMOVE_DONE:
                        Log.print(f"can't find remove device button")
                    continue
            else:
                Log.print("exit removing device")
                return True

    ## Take screen shot ##
    def screenshot(self):
        screenshot_path = Utils.get_screenshot_path()
        if not os.path.isdir(screenshot_path):
            os.mkdir(screenshot_path)
        self.view_dump()
        self.device.takeSnapshot(reconnect=True).save(
            f"{screenshot_path}error_{self.device_name}_{time.strftime('%Y_%m_%d-%H_%M_%S')}.png", "PNG")
        Log.print("error screenshot done")

    ## Get object ##
    def get_obj(self, key, request_dump=False):
        if not self.vc:
            return None
        if request_dump:
            self.view_dump()
        if key.startswith("text:"):
            text = key[len("text:"):]
            if text.isdecimal():
                return self.vc.findViewWithText(self.get_smartthings_view_id(int(text)))
            else:
                return self.vc.findViewWithText(text)
        else:
            return self.vc.findViewById(self.get_smartthings_view_id(int(key)))

    ## View dump ##
    def view_dump(self, delay=1):
        try:
            self.vc.dump(window=-1, sleep=delay)
        except:
            pass

    ## Get smartthings view id ##
    def get_smartthings_view_id(self, key):
        type = {
            ONBOARDING_ADD_BUTTON: "com.samsung.android.oneconnect:id/add_menu_button",
            ONBOARDING_ADDITIONAL_ADD_BUTTON: "com.samsung.android.oneconnect:id/title",
            ONBOARDING_MANUAL_PAIRING_CODE_BOTTON: "com.samsung.android.oneconnect:id/enter_setup_code_button",
            ONBOARDING_MANUAL_PAIRING_CODE_TEXTBOX: "com.samsung.android.oneconnect:id/add_device_item_serial_edit_text",
            ONBOARDING_MANUAL_PAIRING_CODE_INPUT_DONE: "com.samsung.android.oneconnect:id/menu_done",
            ONBOARDING_CONTINUE_BUTTON: "com.samsung.android.oneconnect:id/onboarding_item_main_button",
            ONBOARDING_NO_MATTER_CERT_DEVICE_SKIP_BUTTON: "android:id/button1",
            ONBOARDING_MATTER_DEVICE_NAME_CHANGE: "com.samsung.android.oneconnect:id/onboarding_success_card_detail_view_editor",
            ONBOARDING_MATTER_DEVICE_NAME_CHANGE_DONE: "com.samsung.android.oneconnect:id/onboarding_item_positive_navigation_text",
            ONBOARDING_DONE_BACK_TO_FIRST_SCREEN: "android.widget.Button",\
            # REMOVE_BUTTON:"id/no_id/5",\
            REMOVE_BUTTON_ENG: "Remove",\
            REMOVE_DONE: "android:id/button1",\
            REMOVE_BUTTON_KOR: "삭제",\
            ERROR_CHECK_LAYOUT: "com.samsung.android.oneconnect:id/onboarding_step_description_layout",\
            ERROR_OCCUR_KOR: "오류가 있어요",\
            ERROR_OCCUR_ENG: "Something went wrong",\
            ADD_DEVICE_KOR: "기기 추가",\
            ADD_DEVICE_ENG: "Add device"
        }.get(key, key)
        return type

    ## Phone removed ##
    def removed_phone(self):
        del self.device
        del self.vc
        self.device = None
        self.vc = None

    ## Stop Onboarding ##
    def stop(self):
        if not self.running:
            return
        self.removed_phone()
        self.running = False
        self.update_onboarding_state.emit(
            STOnboardingResult.REMOVED_PHONE, self.comport, self.device_num)
        self.quit()
        self.wait(1000)


from typing import Optional, Tuple

from cortex_xdr_client.api.authentication import Authentication
from cortex_xdr_client.api.base_api import BaseAPI
from cortex_xdr_client.api.models.action_status import GetActionStatus
from cortex_xdr_client.api.models.filters import new_request_data

class ActionsAPI(BaseAPI):
    def __init__(self, auth: Authentication, fqdn: str, timeout: Tuple[int, int]) -> None:
        super(ActionsAPI, self).__init__(auth, fqdn, "actions", timeout)

    # https://docs.paloaltonetworks.com/cortex/cortex-xdr/cortex-xdr-api/cortex-xdr-apis/response-actions/get-action-status.html
    def get_action_status(self,
                          group_action_id: int
                          ) -> Optional[GetActionStatus]:
        """
        Retrieve the status of the requested actions according to the action ID.

        :param group_action_id: String the represents the Action ID of the selected request.
        :return: Returns a GetActionStatus object if successful.
        """
        request_data = new_request_data(other={'group_action_id': group_action_id})

        response = self._call(call_name="get_action_status",
                              json_value=request_data)
        return GetActionStatus.parse_obj(response.json())

    # https://docs-cortex.paloaltonetworks.com/r/Cortex-XDR/Cortex-XDR-API-Reference/File-Retrieval-Details
    def get_file_retrieval_details(self,
                                   group_action_id: int
                                   ) -> Optional[GetActionStatus]:
        """
        Retrieve the status of the requested file retrieval action.

        :param group_action_id: String the represents the Action ID of the selected request.
        :return: Returns a GetActionStatus object if successful.
        """
        request_data = new_request_data(other={'group_action_id': group_action_id})

        response = self._call(call_name="file_retrieval_details",
                              json_value=request_data)
        return GetActionStatus.parse_obj(response.json())


#testing regularization
import re

CONTRACTIONS_NEG = re.compile(r"cannot\b|\w+n't\b|shant|wont", re.I) #add cant? technically a separate word
CONTRACTIONS_FUT = re.compile(r"\b(i'll|he'll|she'll|you'll|youll|we'll)\b", re.I) #ill, hell, shell, well
# assuming "'d" is modal "should/would" for now; "had" also possible but not coded here
CONTRACTIONS_MOD = re.compile(r"\b(i'd|you'd|youd|he'd|she'd|we'd)\b", re.I) #id, hed, shed, wed
CONTRACTIONS_COPULA = re.compile(r"\b(i'm|im|you're|youre|we're|they're|theyre|he's|hes|shes|she's|it's)\b", re.I) #were, its
CONTRACTIONS_HAVE = re.compile(r"\w+'ve\b", re.I)
GOTTA = re.compile(r'\bgotta\b', re.I)
GONNA = re.compile(r'\bgonna\b', re.I)
HAFTA = re.compile(r'\bhafta\b', re.I)
WANNA = re.compile(r'\bwanna\b', re.I)

class Regularizer():
    '''Casual text regularization, for common contractions in English
    '''

    def __init__(self):
        pass

    def infinitives(self, text):
        '''Separate infinitive contractions.
        Returns text string.
        ::param text:: tweet
        ::type text:: str
        '''

        if re.findall(GOTTA, text):
            text = re.sub(GOTTA, 'got to', text)
        if re.findall(GONNA, text):
            text = re.sub(GONNA, 'going to', text)
        if re.findall(HAFTA, text):
            text = re.sub(HAFTA, 'have to', text)
        if re.findall(WANNA, text):
            text = re.sub(WANNA, 'want to', text)

        return text

    def copula_contracts(self, text):
        '''Un-contract copulas. Returns text string.
        ::param text:: tweet
        ::type text:: str
        '''
        cop_matches = re.findall(CONTRACTIONS_COPULA, text)
        if len(cop_matches) >= 1:
            for match in cop_matches:
                if match.lower() in ["i'm", "im"]:
                    replace_with = "I am"
                elif match.lower() in ["you're", "youre"]:
                    replace_with = "you are"
                elif match.lower() in ["they're", "theyre"]:
                    replace_with = "they are"
                elif match.lower() == "we're":
                    replace_with = "we are"
                elif match.lower() in ["hes", "shes"]:
                    replace_with = match.split("s")[0] + ' is'
                else:
                    replace_with = match.split("'")[0] + ' is'
                text = re.sub(match, replace_with, text)

        return text

    def neg_contracts(self, text):
        '''Un-contract negatives. Returns text string.
        ::param text:: tweet
        ::type text:: str
        '''
        neg_matches = re.findall(CONTRACTIONS_NEG, text)
        if len(neg_matches) >= 1:
            # Get substrings, and replace with verb + not
            for match in neg_matches:
                if match.lower() in ["won't", "wont"]:
                    replace_with = "will not"
                elif match.lower() in ['cannot', "can't"]:
                    replace_with = 'can not'
                elif match.lower() in ["shan't", "shant"]:
                    replace_with = 'shall not'
                else:
                    splitting_neg = re.compile(r"n't", re.I)
                    replace_with = re.split(splitting_neg, match)[0] + " not"
                text = re.sub(match, replace_with, text)
        return text

    def fut_contracts(self, text):
        '''Un-contract futures. Returns text string.
        ::param text:: tweet
        ::type text:: str
        '''
        fut_matches = re.findall(CONTRACTIONS_FUT, text)
        if len(fut_matches) >= 1:
            # Get substrings and replace with pro + will
            for match in fut_matches:
                if match.lower() == "youll":
                    replace_with = match.split("ll")[0] + ' will'
                else:
                    replace_with = match.split("'")[0] + ' will'
                text = re.sub(match, replace_with, text)
        return text

    def mod_contracts(self, text):
        '''Un-contract modals. Returns text string.
        ::param text:: tweet
        ::type text:: str
        '''
        mod_matches = re.findall(CONTRACTIONS_MOD, text)
        if len(mod_matches) >= 1:
            # Get substrings and replace with pro + would
            for match in mod_matches:
                if match.lower() == "youd":
                    replace_with = match.split("d")[0] + ' would'
                else:
                    replace_with = match.split("'")[0] + ' would'
                text = re.sub(match, replace_with, text)

        return text

    def have_contracts(self, text):
        '''Un-contract futures. Returns text string.
        ::param text:: tweet
        ::type text:: str
        '''
        have_matches = re.findall(CONTRACTIONS_HAVE, text)
        if len(have_matches) >= 1:
            # Get substrings and replace with pro + have
            for match in have_matches:
                replace_with = match.split("'")[0] + ' have'
                text = re.sub(match, replace_with, text)
        return text

    def regularize(self, text):
        '''Simple regularization to de-contract negatives,
        futures, modals, copulas, and pluperfect.
        Returns text string
        ::param text:: tweet text
        ::type text:: str
        '''
        text = self.infinitives(text)
        text = self.neg_contracts(text)
        text = self.fut_contracts(text)
        text = self.mod_contracts(text)
        text = self.copula_contracts(text)
        text = self.have_contracts(text)

        return text


import django_tables2 as tables
from .models import Courses

class CourseTable(tables.Table):
    class Meta:
        model = Courses
        fields = ("subject", "crse", "crstitle", "hoursperwkinclclass", "challenge")
        attrs = {'id': 'courseTable'}
        row_attrs = {
        	'draggable':True, 'ondragstart':'drag(event, this)'
        }

class RegisteredTable(tables.Table):
	class Meta:
			model = Courses
			fields = ("subject", "crse", "crstitle", "hoursperwkinclclass", "challenge")


#(*) 참고한 풀이
def solution(number, k):
    st = []
    for i, n in enumerate(number):
        while len(st) > 0 and st[-1] < n and k > 0:
            st.pop()
            k -= 1
        if k == 0:
            st += list(number[i:]) # k == 0이면 나머지 숫자를 모두 더함
            break
        st.append(n)
    st = st[:-k] if k > 0 else st # k>0이면 스택 뒤의 k개 숫자를 제거
    answer = ''.join(st)
    return answer

print(solution("4177252841", 4))

# 시간 초과
'''
def solution(number, k):
    answer = ''
    index = -1
    for i in range(len(number)-k):
        maxN = 0
        for j in range(index+1, k+i+1):
            if maxN < int(number[j]):
                index = j
                maxN = int(number[j])
        answer += str(maxN)
    return answer
'''

# 예제는 맞았으나 채점은 1개를 제외하고 모두 틀림
'''
def solution(number, k):
    cnt, idx = 0, 0
    while (cnt < k and len(number) > 1):
        print(cnt, idx, number)
        if number[idx] < number[idx+1]:
            number = number[:idx]+number[idx+1:]
            cnt += 1
        else:
            idx += 1
        if idx == len(number)-1:
            idx = 0

    return number

print(solution("4177252841", 4))
'''


data = ''
with open('test.txt', 'r') as f:
    data = f.read()

data = data.strip()

groups = data.split('\n\n')

for i in range(len(groups)):
    groups[i] = groups[i].split('\n')

sums = []

for group in groups:
    group = [int(x) for x in group]
    inner_sum = sum(group)
    sums.append(inner_sum)

max = max(sums)
print(max)

sums.sort(reverse = True)
top3 = sums[:3]
print(sum(top3))


from keras.models import load_model
from tensorflow.keras.datasets import cifar10
from tensorflow.keras import utils
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D
from tensorflow.keras.layers import Dense, Dropout, Flatten
import util3 as u

(x_train, y_train), (x_test, y_test) = cifar10.load_data()

x_train_norm = x_train.astype('float32')/255
x_test_norm = x_test.astype('float32')/255

y_train_onehot = utils.to_categorical(y_train, 10)
y_test_onehot = utils.to_categorical(y_test, 10)

cnn = Sequential()

cnn.add(Conv2D(filters=32,
               kernel_size=[3,3],
               activation='relu',
               padding='same',
               input_shape=[32,32,3]))

cnn.add(Dropout(0.25))
cnn.add(MaxPooling2D(pool_size=[2,2]))

cnn.add(Conv2D(filters=64,
               kernel_size=[3,3],
               padding='same',
               activation='relu'))
cnn.add(Dropout(0.25))
cnn.add(MaxPooling2D(pool_size=[2,2]))

cnn.add(Flatten())
cnn.add(Dropout(0.25))

cnn.add(Dense(1024, activation='relu'))
cnn.add(Dropout(0.25))

cnn.add(Dense(10, activation='softmax'))

cnn.compile(loss='categorical_crossentropy',
            optimizer='adam',
            metrics='acc')

old_cnn = load_model(r'C:\Users\d19fd\Documents\tf.Keras\model\cifar10model.h5')

test_loss, test_val = cnn.evaluate(x_test_norm, y_test_onehot)

print('測試資料損失值 :', test_loss)
print('測試資料準確率 :', test_val)


class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        max_length=0
        m_length=0
        tempstring = []
        string_length = len(s)
        for i in range(string_length):
            if s[i] in tempstring:
                if m_length>max_length:
                    max_length=m_length
                # print(max_length,s[i])
                while tempstring[0]!=s[i]:
                    tempstring.pop(0)
                    m_length=m_length-1
                tempstring.pop(0)
                tempstring.append(s[i])
                # print("重构后:",tempstring,m_length)
                continue

            m_length=m_length+1
            tempstring.append(s[i])
            # print(tempstring,m_length)
        # print(max_length)
        if m_length>max_length:

            max_length = m_length
        return max_length

if __name__=='__main__':
    sl=Solution()

    s="abcabcaa"
    print(sl.lengthOfLongestSubstring(s))


import numpy as np
import cv2 as cv

img = cv.imread('imagens/catiorrinho.jpg')
cv.imshow('original', img)
cv.waitKey(0)

"""**b - Abrir uma imagem e exibir na tela a imagem invertida horizontalmente**"""

horizontal_img = np.fliplr(img)
cv.imshow('flip-horizontal', horizontal_img)
cv.waitKey(0)
cv.destroyAllWindows()


from collections import deque
import threading

import errors
import modes
import console
import mi_interface as mi
from config import settings
from command_completer import CommandCompleter
from util import format_error, format_warning, format_info, repr_str_dict

session_manager = None
selected_sessions = None
sessions_history = None

history_length = int(settings['sessions']['history_length'])

def init_debugging_mode(mgr, msgs):
    global selected_sessions
    global session_manager
    global sessions_history

    session_manager = mgr
    sessions_history = {}

    oldest_session = mgr.get_oldest()
    if oldest_session:
        selected_sessions = [oldest_session.tag]

    for tag in session_manager.list_session_tags():
        sessions_history[tag] = deque(maxlen = history_length)
        sessions_history[tag].append(msgs[tag])

    return modes.debugging, None

def _ls_out():
    ls_out = []
    for s_i in session_manager.list_sessions():
        if not s_i.tag in selected_sessions:
            ls_head = s_i.tag
        else:
            ls_head = '(*) {}'.format(s_i.tag)
        ls_out.append('%6s) %s:%d' % (
            ls_head,
            s_i.hostname,
            s_i.meta,
        ))
    return '\n'.join(ls_out)

def list_sessions(args):
    '''Lists all active sessions.'''
    # Verify command syntax
    if len(args) != 0:
        raise errors.BadArgsError(
            'ls', 'This command does not accept arguments'
        )

    pretty_session_list = _ls_out()
    if not pretty_session_list:
        return modes.debugging, 'ls: Empty. No sessions are alive.'
    return modes.debugging, 'Sessions:\n' + pretty_session_list

def select_session_complete(args):
    '''readline library tab completion for session selection in debugging
    mode'''
    if not args:
        return ['all', 'none'] + session_manager.list_session_tags()

    # If 'all' or 'none' then no further arguments are meaningful
    if 'all' in args or 'none' in args:
        return []

    if 'all'.startswith(args[0]):
        return ['all']

    if 'none'.startswith(args[0]):
        return ['none']

    return [
        tag for tag in session_manager.list_session_tags() if not tag in args
    ]

def select_session(args):
    '''Mark the provided sessions as selected'''
    # Verify command syntax
    if not args:
        raise errors.BadArgsError(
            'select', 'select all | none | <session id>[ <session id>[ ...]]'
        )

    if args:
        if args[0] == 'all':
            global selected_sessions
            selected_sessions = sorted(session_manager.list_session_tags())

            return modes.debugging, 'Selected session(s) #{0}\n{1}'.format(
                ', '.join(selected_sessions), _ls_out()
            )
        elif args[0] == 'none':
            global selected_sessions
            selected_sessions = []

            return modes.debugging, 'No sessions selected'.format(
                ', '.join(selected_sessions), _ls_out()
            )

    non_existing_sessions = [
        id for id in args if not session_manager.exists(id)
    ]
    if non_existing_sessions:
        raise errors.BadArgsError(
            'select', 'Session(s) {0} do not exist.'.
            format(', '.join(non_existing_sessions))
        )

    global selected_sessions
    selected_sessions = args
    return modes.debugging, 'Selected session(s) #{0}\n{1}'.format(
        ', '.join(selected_sessions), _ls_out()
    )

def _kill_all():
    for s_i in session_manager.list_sessions():
        if s_i.is_alive():
            s_i.query('-gdb-exit')
    session_manager.kill_all()

    global session_manager
    global sessions_history
    session_manager = None
    sessions_history = None

def end_sessions(args):
    # Verify command syntax
    if len(args) != 0:
        raise errors.BadArgsError(
            'ls', 'This command does not accept arguments'
        )

    _kill_all()
    return modes.offline, None

def quit(args):
    '''Exit scimitar'''
    # Verify command syntax
    if len(args) != 0:
        raise errors.BadArgsError(
            'ls', 'This command does not accept arguments'
        )

    _kill_all()
    return modes.quit, None

def _ensure_sessions_selected(cmd):
    '''Verifies that there are sessions selected at this moment.'''
    if not selected_sessions:
        raise errors.CommandFailedError(
            cmd,
            'No session(s) selected. Debugging mode failed to start. (Maybe init_debugging_mode() was not called?)'
        )

def _ensure_valid_sessions_selected(cmd):
    '''Verifies if all selected sessions are still alive'''
    non_existing_sessions = [
        id for id in selected_sessions if not session_manager.exists(id)
    ]
    if non_existing_sessions:
        raise errors.BadArgsError(
            cmd, 'Cannot proceed. Dead session(s): {0}.'.
            format(', '.format(non_existing_sessions))
        )

def message_history(args):
    '''Prints the selected sessions' history records at index args[0]'''
    _ensure_sessions_selected('history')

    index = -1
    if len(args) == 1:
        try:
            index = -int(args[0])
        except ValueError:
            raise errors.BadArgsError(
                'history', 'history[ <index>]'
            )

    if index > history_length:
        raise errors.BadArgsError(
            'history', 'Selected record does not exist in the history'
        )

    results = []
    for tag in selected_sessions:
        # Output header
        results.append('~~~ Scimitar - Session: {} ~~~'.format(tag))
        try:
            ind_rec, cout, tout, lout = sessions_history[tag][index]
            if ind_rec:
                # Check the type of indicator
                if ind_rec[0] == mi.indicator_error:
                    results.append(format_error(ind_rec[1]))
                elif ind_rec[0] == mi.indicator_exit:
                    session_manager.remove(tag)
                    sessions_history.remove(tag)
                    results.append(format_error('Session {} died.', tag))
                else:
                    results.append(cout)
            else:
                results.append(''.join([cout, tout, lout]))
        except IndexError:
            results.append(format_error('Scimitar: Record does not exist'))
    return modes.debugging, '\n'.join(results)

def gdb_exec(cmd):
    '''Runs the provided user command cmd on all selected sessions.'''

    class RemoteCommandExecutingThread(threading.Thread):
        '''This thread type is responsible for running commands on terminal'''

        def __init__(self, term, cmd):
            super(RemoteCommandExecutingThread, self).__init__()
            self.term = term
            self.cmd = cmd
            self.error = None
            self.result = None

        def run(self):
            '''Start the execution'''
            try:
                self._run()
            except Exception as e:
                self.error = e

        def _run(self):
            # Send the command
            gdb_response = self.term.query(self.cmd)
            # In case GDB dies
            if gdb_response in (r'^exit', r'^kill'):
                raise console.SessionDiedError
            else:
                self.result = mi.parse(gdb_response)

        def report(self):
            if self.error:
                raise self.error
            return self.result

    def _sanitize_gdb_command(cmd):
        '''Explicitly tell GDB that this is not an MI command following. Tries to
        differentiate between control signals and commands.'''
        if cmd and not repr_str_dict.has_key(cmd[0]):
            return ['-interpreter-exec', 'console'] + cmd
        return cmd

    def _parallel_exec_async(cmd, tag, target_sessions):
        '''Start running the provided cmd per each target session in separate
        thread '''
        tasks = {}
        for tag in target_sessions:
            # Get the session
            cs = session_manager.get(tag)
            exctr = RemoteCommandExecutingThread(cs, ' '.join(cmd))
            exctr.start()
            tasks[tag] = exctr
        return tasks

    def _collect_exec_results(tasks):
        '''Wait until threads finish and then collect the results.'''
        # If sessions died during execution collect them
        session_casualties = []
        # Results
        results = []

        # Go through the results
        for tag, task in tasks.iteritems():
            task.join()
            try:
                mi_response = task.report()
                # Add it to message history stash
                sessions_history[tag].append(mi_response)
                # Output header
                results.append('~~~ Scimitar - Session: {} ~~~'.format(tag))
                ind_rec, cout, tout, lout = mi_response
                # Check the type of indicator
                # Error
                if ind_rec[0] == mi.indicator_error:
                    results.append(format_error(ind_rec[1]))
                # Exit
                elif ind_rec[0] == mi.indicator_exit:
                    session_manager.remove(tag)
                    sessions_history.remove(tag)
                    results.append(format_error('Session {} died.', tag))
                # Connected, Success, etc
                else:
                    results.append(cout)
            # When the session is dead
            except console.SessionDiedError:
                # It is not a session we can work with in future
                session_manager.remove(tag)
                sessions_history.remove(tag)
                selected_sessions.remove(tag)
                # Add this session to casualty list
                session_casualties += [tag]
        return results, session_casualties

    #
    # gdb_exec starts here
    #

    # Ensure there are selected sessions
    _ensure_sessions_selected('gdb:cmd(?)')
    # Make sure selected sessions are valid
    _ensure_valid_sessions_selected('gdb:cmd(?)')

    # GDB launch command
    cmd = _sanitize_gdb_command(cmd)

    # Threads that run the command
    tasks = _parallel_exec_async(cmd, tag, selected_sessions)

    # Wait for all commands to finish
    session_casualties, results = _collect_exec_results(tasks)

    # In case we had dead sessions the command has essentially failed.
    if session_casualties:
        results.append(
            format_error(
                'Session(s) {} died.', ', '.join(session_casualties)
            )
        )
    return modes.debugging, '\n'.join(results)

def debug(args):
    import pdb
    pdb.set_trace()
    return modes.debugging, None

commands = {
    'ls': (list_sessions, None),
    'select': (select_session, select_session_complete),
    'debug': (debug, None), # HACK: For debugging only
    'history': (message_history, None),
    'end': (end_sessions, None),
    'quit': (quit, None),
}

def process(cmd, args):
    if cmd in commands:
        return commands[cmd][0](args)
    else:
        return gdb_exec([cmd] + (args or []))
    raise errors.CommandImplementationIncompleteError

class DebugSessionCommandCompleter(CommandCompleter):

    def _complete_command(self):
        return commands.keys()

    def _complete_command_arguments(self, cmd, args):
        if commands.has_key(cmd) and commands[cmd][1]:
            return commands[cmd][1](args)

# vim: :ai:sw=4:ts=4:sts=4:et:ft=python:fo=corqj2:sm:tw=79:


import networkx as nx
import numpy as np

from mo.graph.graph import Node
from mo.ops.op import Op

class Gather(Op):
    op = 'Gather'

    def __init__(self, graph: nx.MultiDiGraph, attrs: dict):
        mandatory_props = {
            'type': __class__.op,
            'op': __class__.op,
            'axis': 0,
            'infer': __class__.infer
        }
        super().__init__(graph, mandatory_props, attrs)

    def supported_attrs(self):
        return [
            'axis',
        ]

    @staticmethod
    def infer(node: Node):
        assert len(node.in_nodes()) == 2 or len(node.in_nodes()) == 3

        # There may be three inputs in TensorFlow. The third input is axis
        if len(node.in_nodes()) == 3:
            if node.in_node(2).value is None:
                log.error("Gather is supported only with constant axis value")
                return
            node.axis = node.in_node(2).value.item()
            node.graph.remove_edge(node.in_node(2).id, node.id)

        axis = node.axis
        data = node.in_node(0)
        indices = node.in_node(1)

        # both inputs are constant
        if data.value is not None and indices.value is not None:
            node.out_node(0).value = np.take(data.value, indices.value, axis)
            node.out_node(0).shape = np.array(node.out_node(0).value.shape, dtype=np.int64)
            return

        shape = np.concatenate((data.shape[:axis], indices.shape))
        if axis < len(data.shape) - 1:
            shape = np.concatenate((shape, data.shape[axis+1:]))

        node.out_node(0).shape = np.array(shape, dtype=np.int64)


from sympy import *

# price_increment = 1e-8
# initial_price = 1e-7

initial_price = Symbol('P_0')
price_increment = Symbol('Delta_p')
supply = Symbol('S')
eth = Symbol('R')

price_supply = initial_price + price_increment*supply
# price_supply = sqrt(supply)

total_eth = integrate(price_supply, (supply, 0, supply))

pprint(total_eth)

supply_eth = solve(eth - total_eth, supply)[0]

pprint(supply_eth)
# supply_fun = lambdify(eth, supply_eth)

# supply_eth = (sqrt(initial_price**2+2*price_increment*eth) - initial_price)/price_increment

price_eth = price_supply.subs(supply, supply_eth)

pprint(price_eth)
print()

pprint(diff(price_eth, eth))

print()

initial_deriv = simplify(diff(price_eth, eth).subs(eth, 0))
pprint(initial_deriv)

interval = Symbol('D')

bound1 = supply_eth.subs(eth, interval)
bound2 = supply_eth.subs(eth, 2*interval)

eth1 = integrate(price_supply, (supply, 0, bound1))
eth2 = integrate(price_supply, (supply, bound2-bound1, bound2))

return_ = simplify(eth2/eth1)

pprint(return_)
print(return_)
pprint(limit(return_, interval, 'oo'))
# pprint(limit(return_, interval, 'oo').evalf())

print()
pprint(limit(return_, interval, '0'))
print()

# import ipdb; ipdb.set_trace()

# pprint(simplify(return_.subs(interval, 1)))

# price_increment = 1e-8
# initial_price = 1e-7

return_ = return_.subs([
    # (interval, 100),
    (initial_price, 1e-7),
    (price_increment, 1e-8),
    # (initial_price, 0.0001),
    # (price_increment, 1e-12),
])

return_fun = lambdify(interval, return_)

# import ipdb; ipdb.set_trace()
pprint(return_fun(1))

# import matplotlib.pyplot as plt
# import numpy as np

# X = np.linspace(0, 100000000, 10000)
# plt.plot(X, [return_fun(x) for x in X])
# plt.show()

# import ipdb; ipdb.set_trace()


import os
import re
import time
import Adafruit_SSD1306
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

class StatusDisplay:
    def __init__(self, bb8):
        #LCD.__init__(self, 0x20)
        self.display = Adafruit_SSD1306.SSD1306_128_32(rst=16)
        self.display.begin()
        self.image = Image.new('1', (self.display.width, self.display.height))
        self.draw = ImageDraw.Draw(self.image)
        self.font = ImageFont.load_default()

        self.BB8 = bb8
        self.showIP = True
        self.lastUpdateTime = 0

    def Update(self):
        t = time.time()
        if t > self.lastUpdateTime + 2:
            #self.draw.rectangle((0, 0, self.display.width, self.display.height), outline=0, fill=0)
            ip = ("IP: " + self.BB8.Network.IP) if self.BB8.Network.IP else "No Network"
            ssid = ("SSID: " + self.BB8.Network.SSID) if self.BB8.Network.SSID else "No Network"
            #if self.lastIP != ip:
            self.draw.rectangle((0, 0, self.display.width, self.display.height), outline=0, fill=0)
            self.draw.text((0, 0), ip if self.showIP else ssid, font=self.font, fill=255)
            self.display.image(self.image)
            self.display.display()
            self.showIP = not self.showIP
            #cpu = "CPU: " + os.popen("top -bn1 | tail -n +8 | awk '{ SUM += $(NF-3) } END { printf \"%.0f%%\", SUM }'").read()
            #mem = "Mem: " + os.popen("free -m | awk 'NR==2{printf \"%s/%s MB %.0f%%\", $3,$2,$3*100/$2 }'").read()
            #disk = "Disk: " + os.popen("df -h | awk '$NF==\"/\"{printf \"%.2g/%d GB %s\", $3,$2,$5}'").read()
            #self.draw.text((0, -1), ip, font=self.font, fill=255)
            #self.draw.text((0, 7), cpu, font=self.font, fill=255)
            #self.draw.text((0, 15), mem, font=self.font, fill=255)
            #self.draw.text((0, 23), disk, font=self.font, fill=255)
            #self.display.image(self.image)
            #self.display.display()
            self.lastUpdateTime = t

    def Exit(self):
        self.display.clear()
        self.display.display()

    def format(self, number):
        if number >= 100:
            return str(int(round(number)))
        elif number >= 10:
            return "%.1f" % number
        else:
            return "%.2f" % number