'''
Author   : Pranav Gaikwad
Unity Id : 200203543
'''

import sys
import argparse

from sncaeshelper import AesHelper

def parse_snc_args():
    """
    parses command line arguments
    """
    # custom usage message
    usage_msg = 'snc.py [-h] [-l] --key KEY server port'

    # parses CLI arguments
    argparser = argparse.ArgumentParser(usage=usage_msg)
    # positional arguments
    # Refer https://docs.python.org/2/library/argparse.html#nargs
    argparser.add_argument("connection", nargs='*',
                           help="Connection string in format [server] [port]")
    # other args
    argparser.add_argument(
        "-l", help="listen mode / start as client",
        action="store_true", default=False)
    argparser.add_argument("--key", help="encryption key", required=True)

    args = argparser.parse_args()

    # 'connection' argument is a list of all
    # arguments remained after parsing --key & -l
    # it could be server & port values; or just a
    # port value when '-l' is set
    connection_string_list = args.connection

    # checks if '-l' argument is set.
    # if yes, program will run in 'listen' mode
    listen = args.l

    host = ''
    port = ''
    key = args.key

    if len(key) < AesHelper.LENGTH_IDEAL_KEY:
        sys.stderr.write('Key should be at least %s characters long\n' %
                         str(AesHelper.LENGTH_IDEAL_KEY))
        sys.exit(1)

    # if 'listen' mode is set, connection_string_list only has PORT
    # in it. If not, connection_string_list needs to be parsed
    # as SERVER & port. this is due to limitation of 'argparser'
    # module which does not support conditional positional variables
    if listen:
        try:
            port = int(connection_string_list[0])
        except IndexError:
            sys.stderr.write('Please specify a port\n')
            sys.exit(1)
    else:
        try:
            host = connection_string_list[0]
            port = int(connection_string_list[1])
        except IndexError:
            sys.stderr.write(
                'Please specify connection string in [server] [port] format\n')
            sys.exit(1)
        except ValueError:
            sys.stderr.write('Incorrect host or port\n')
            sys.exit(1)

    return host, port, listen, key


import time
from typing import Optional
from CSP.Problem import Problem
from CSP.Variable import Variable

class Solver:

    def __init__(self, problem: Problem, use_mrv=False, use_lcv=False, use_forward_check=False):
        self.problem = problem
        self.use_lcv = use_lcv
        self.use_mrv = use_mrv
        self.use_forward_check = use_forward_check

    def is_finished(self) -> bool:
        return all([x.is_satisfied() for x in self.problem.constraints]) and len(
            self.problem.get_unassigned_variables()) == 0

    def solve(self):
        self.problem.calculate_neighbors()
        start = time.time()
        for var in self.problem.variables:
            if not self.forward_check(var):
                print("Problem Unsolvable")
                return
        result = self.backtracking()
        end = time.time()
        time_elapsed = (end - start) * 1000
        if result:
            print(f'Solved after {time_elapsed} ms')
        else:
            print(f'Failed to solve after {time_elapsed} ms')

    def backtracking(self):
        if self.is_finished():
            return True
        var = self.select_unassigned_variable()
        if var is None:
            return False
        for value in self.order_domain_values(var):
            var.value = value
            if self.use_forward_check:
                self.forward_check(var)
            if self.is_consistent(var):
                if self.backtracking():
                    return True
            var.value = None
        return False

    def forward_check(self, var):
        for neighbor in var.neighbors:
            if not neighbor.has_value:
                for value in neighbor.domain:
                    neighbor.value = value
                    consistent = self.is_consistent(neighbor)
                    neighbor.value = None
                    if not consistent:
                        neighbor.domain.remove(value)
                if not neighbor.domain:
                    return False
        return True

    def select_unassigned_variable(self) -> Optional[Variable]:
        if self.use_mrv:
            return self.mrv()
        unassigned_variables = self.problem.get_unassigned_variables()
        return unassigned_variables[0] if unassigned_variables else None

    def order_domain_values(self, var: Variable):
        if self.use_lcv:
            return self.lcv(var)
        return var.domain

    def mrv(self) -> Optional[Variable]:
        unassigned_variables = self.problem.get_unassigned_variables()
        if not unassigned_variables:
            return None
        return min(unassigned_variables, key=lambda var: len(var.domain))

    def is_consistent(self, var: Variable):
        for neighbor in var.neighbors:
            if neighbor.has_value and neighbor.value == var.value:
                return False
        return True

    def lcv(self, var: Variable):
        value_count = {}
        for value in var.domain:
            count = 0
            for neighbor in var.neighbors:
                if not neighbor.has_value and value in neighbor.domain:
                    count += 1
            value_count[value] = count
        sorted_values = sorted(value_count, key=value_count.get)
        return sorted_values


import random

class Board:
    """
    Creates a board instance for playing the battleship game.
    Contains methods for displaying the board, placing ships, creating
    random coordinates and guessing where ships are.
    """

    def __init__(self, name):
        self.name = name
        self.board = [
            [" ", "A", "B", "C", "D", "E"],
            ["1", "~", "~", "~", "~", "~"],
            ["2", "~", "~", "~", "~", "~"],
            ["3", "~", "~", "~", "~", "~"],
            ["4", "~", "~", "~", "~", "~"],
            ["5", "~", "~", "~", "~", "~"],
        ]
        self.ship_count = 5
        self.turn_count = 0
        self.win = 0
        self.num_of_getting_hit = 0
        self.coordinates_list = [
            (col, row) for col in range(1, 6) for row in range(1, 6)
        ]

    def column_number(self, col):
        """
        Converts a letter from a to e to a number based on the
        letter's index in the first nested list inside the board list
        """
        return self.board[0].index(col.upper())

    def display_board(self):
        """
        Prints the board and the name of its player to the terminal.
        """
        print(f"\n   {self.name}'s board:\n")
        for row in self.board:
            joint_row = "   ".join(row)
            print(f"{joint_row}\n")

    def place_ships(self, col, row):
        """
        Places ships (represented by "@") at the
        coordinates specified by the player
        """
        if type(col) is str:
            col_num = self.column_number(col)
        else:
            col_num = col
        self.board[int(row)][col_num] = "@"

    def create_five_random_coordinates(self):
        """
        Creates 5 random coordinates without
        duplicates and returns them in a nested list.
        """
        col_list = ["A", "B", "C", "D", "E"]
        row_list = [1, 2, 3, 4, 5]
        coordinate_list = []
        x = 0
        while x < 5:
            col = random.choice(col_list)
            row = random.choice(row_list)
            col_num = self.column_number(col)
            rand_coordinates = [row, col_num]
            if rand_coordinates in coordinate_list:
                pass
            else:
                coordinate_list.append(rand_coordinates)
                x += 1
        return coordinate_list

    def guess_computer_ships(self, col, row, coor_list):
        """
        Lets the player guess the computer's ship coordinates.
        """
        col_num = self.column_number(col)
        coords = [int(row), col_num]
        if coords in coor_list:
            self.board[int(row)][col_num] = "X"
            coor_list.remove(coords)
            self.ship_count -= 1
            self.num_of_getting_hit += 1
            if self.ship_count > 1:
                print(
                    f"\n---You shot {col.upper()} {row}, it's a hit! We "
                    f"need to sink {self.ship_count} more ships to "
                    f"destroy the enemy's fleet---"
                )
            elif self.ship_count == 1:
                print(
                    f"\n---You shot {col.upper()} {row}, it's a hit! "
                    "We only need to sink one more ship to destroy the "
                    "enemy's fleet!---"
                )
        else:
            print(f"\n---You shot {col.upper()} {row}, it's a miss...---")
            self.board[int(row)][col_num] = "O"

    def guess_player_ships(self, player_name):
        """
        Pulls a random coordinate from the coordinate_list
        instance variable, then removes that coordinate
        from the coordinate_list and changes the
        corresponding character on the board based on
        whether that character is an @ or not.
        """
        i = len(self.coordinates_list)
        rand_index = random.randrange(i)
        rand_coordinate = self.coordinates_list[rand_index]

        col, row = rand_coordinate
        coordinate = self.board[row][col]
        self.coordinates_list.remove(rand_coordinate)
        if coordinate == "@":
            self.board[row][col] = "X"
            self.ship_count -= 1
            self.num_of_getting_hit += 1
            if self.ship_count > 1:
                print(
                    f"\n---{player_name}! The enemy has sunken our ship at "
                    f"{self.board[0][col].upper()} {row}!\n"
                    f"We still have {self.ship_count} ships in our fleet.---"
                )
            elif self.ship_count == 1:
                print(
                    f"\n---{player_name}! The enemy has sunken our ship at "
                    f"{self.board[0][col].upper()} {row}!\n"
                    f"We only have {self.ship_count} ship left...---"
                )
            else:
                print(
                    f"\n---{player_name}! The enemy has sunken our last ship "
                    f"at {self.board[0][col].upper()} {row}!\n"
                    "We are defeated!---"
                )
        else:
            print(
                "\n---The enemy shot "
                f"{self.board[0][col].upper()} {row}. It's a miss!---"
            )
            self.board[row][col] = "O"


#Write a Python program to display the current date and time.

from datetime import datetime

now = datetime.now()

print("now =", now)
# dd/mm/YY H:M:S
date_time_format = now.strftime("%d/%m/%Y %H:%M:%S")
print("date and time =", date_time_format)


#! usr/bin/python
#coding=utf-8

# importing the basic library
from __future__ import print_function
from utils import *
ctx = check_ctx()

# importing MxNet >= 1.0
import mxnet as mx
from mxnet import ndarray as nd
from mxnet import autograd, gluon

import random

mx.random.seed(1)
random.seed(1)

def test_ctx():
    try:
        ctx = mx.gpu()
        _ = nd.zeros((1,), ctx=ctx)
    except:
        ctx = mx.cpu()
    print('CPU or GPU? : ', ctx)

def lr_decay(lr, epoch, lr_decay):
    # 学习率自我衰减。
    if epoch > 4:
#         lr *= 0.1
        lr /= (1+lr_decay * epoch)
    return lr

# Mini-batch stochastic gradient descent.
def sgd(params, lr, batch_size):
    for param in params:
        param[:] = param - lr * param.grad / batch_size
    return params

# Adam.
def adam(params, vs, sqrs, lr, batch_size, t):
    beta1 = 0.9
    beta2 = 0.999
    eps_stable = 1e-8
#     print(params)
    for param, v, sqr in zip(params, vs, sqrs):
#         print(param)
        g = params[param].grad / batch_size

        v[:] = beta1 * v + (1. - beta1) * g
        sqr[:] = beta2 * sqr + (1. - beta2) * nd.square(g)

        v_bias_corr = v / (1. - beta1 ** t)
        sqr_bias_corr = sqr / (1. - beta2 ** t)

        div = lr * v_bias_corr / (nd.sqrt(sqr_bias_corr) + eps_stable)
        params[param][:] = params[param] - div

    return params, vs, sqrs

if __name__ == '__main__':
    print('CPU or GPU? : ', ctx)


#!/bin/python
import time
import boto3
import csv
import numpy as np
from pms3003 import PMSensor
import RPi.GPIO as GPIO
import dht11

# set up project path for csv generation
path = '/project/path/'

# set sensor environment - indoor/outdoor (0/1)
environment = 1

# set up gpio serial port
# /dev/ttyAMA0 -> Bluetooth (or GPIO when Bluetooth module turned off)
# /dev/ttyS0 -> GPIO serial port (also referenced as '/dev/serial0')
device = '/dev/serial0'

# set up dynamodb table name
dynamodb_table = 'pms3003'

# get dht11 data
# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()

# read dht11 data using pin 4
instance = dht11.DHT11(pin = 4)		#verify if pin is correct

# measure hum and temp (n-1)-times
n = 10
data_dht = []

# loop over
for i in range(1,int(n/2)):
        while True:
                result = instance.read()
                if result.is_valid():
                        data_dht = np.append([data_dht], [result.temperature, result.humidity])
                        break
        time.sleep(2)

# call a PMSensor class
pm = PMSensor(device, environment)

# get PM1, PM2.5, PM10 values
data = pm.read_pm()

# reject outliers
data = data[np.all(np.abs((data - np.mean(data, axis=0))) <= 2 * np.std(data, axis=0), axis=1)]
data = data[np.array(data[:,2], dtype=float)/np.array(data[:,1], dtype=float) < 2]
data = data[np.array(data[:,2], dtype=float) > np.array(data[:,1], dtype=float)]

# get the pm average as an int
pm1, pm25, pm10 = np.mean(data, axis=0, dtype=int)

# continue measuring hum and temp
for i in range(1,int(n/2)):
        while True:
                result = instance.read()
                if result.is_valid():
                        data_dht = np.append([data_dht], [result.temperature, result.humidity])
                        break
        time.sleep(2)

# GPIO cleanup
GPIO.cleanup()

# reshape and reject outliers
data_dht = data_dht.reshape((n-2,2))
data_dht = data_dht[np.all(np.abs((data_dht - np.mean(data_dht, axis=0))) <= 2 * np.std(data_dht, axis=0), axis=1)]

# get the dht average as an int
temp, hum = np.mean(data_dht, axis=0, dtype=int)

# get current timestamp
pm_date = (time.strftime('%Y-%m-%d ') + time.strftime('%H:%M:%S'))

# write to csv
with open(path + 'pm-archive.csv','a+') as f:
 writer = csv.writer(f)
 writer.writerow([pm_date,pm1,pm25,pm10,temp,hum])

# write to dynamodb table
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(dynamodb_table)

try:
        # insert the data
        table.put_item(
                Item={
                'device' : 'pms3003',
                'dt' : pm_date,
                'pm1' : str(pm1),
                'pm25' : str(pm25),
                'pm10' : str(pm10),
                'temp' : str(temp),
                'hum' : str(hum)
                }
        )

except Exception:
        # write to csv in case of error
        with open(path + 'pm-not-loaded.csv','a+') as fn:
         writer = csv.writer(fn)
         writer.writerow([pm_date,pm1,pm25,pm10,temp,hum])

	# SNS notification about an unsuccessful load
        #sns = boto3.resource('sns')
        #topic = sns.Topic('arn::pastehere::')
        #response = topic.publish(
        #       Message='Problem loading data on: ' + pm_date,
        #       Subject='PMS3003 Unsuccessful Data Load',
        #       MessageStructure='string'
        #)


import sys
from os import path
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox

errorIcon = path.join(path.dirname(__file__), "error.png")

class UI_MainWindow(object):

    def errorBox(self):
        msg = QMessageBox()
        msg.setWindowTitle("Error")
        msg.setText("Lost connection")
        msg.setWindowIcon(QtGui.QIcon(errorIcon))
        msg.setStandardButtons(QMessageBox.Ok)
        x = msg.exec_()

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(660, 780)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(0, 0, 661, 781))
        self.label.setStyleSheet("background-color:rgba(255,255,255,255);")
        self.label.setText("")
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(0, 0, 661, 781))
        self.label_2.setStyleSheet("background-color:rgba(186, 191, 148, 180);")
        self.label_2.setText("")
        self.label_2.setObjectName("label_2")

################################################## Phía trên là khung và màu nền ####################################################

########################################################### Date Input ##############################################################

        self.dateEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.dateEdit.setGeometry(QtCore.QRect(70, 60, 220, 40))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.dateEdit.setFont(font)
        self.dateEdit.setStyleSheet("background-color: rgba(0,0,0,0);\n"
"border:none;\n"
"border-bottom:2px solid rgba(46,82,101,200);\n"
"color: rgba(0,0,0,240);\n"
"padding-bottom: 7px;")
        self.dateEdit.setText("")
        self.dateEdit.setCursorMoveStyle(QtCore.Qt.VisualMoveStyle)
        self.dateEdit.setObjectName("dateEdit")

####################################################### Text (Không cần quan tâm) ###############################################

##################################################### Message Input ###########################################################

        self.message = QtWidgets.QLineEdit(self.centralwidget)
        self.message.setGeometry(QtCore.QRect(70, 130, 220, 40))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.message.setFont(font)
        self.message.setStyleSheet("background-color: rgba(0,0,0,0);\n"
"border:none;\n"
"border-bottom:2px solid rgba(46,82,101,200);\n"
"color: rgba(0,0,0,240);\n"
"padding-bottom: 7px;")
        self.message.setText("")
        self.message.setCursorMoveStyle(QtCore.Qt.VisualMoveStyle)
        self.message.setObjectName("message")

######################################################### Bank Input #########################################################

        self.bank = QtWidgets.QLineEdit(self.centralwidget)
        self.bank.setGeometry(QtCore.QRect(370, 60, 220, 40))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.bank.setFont(font)
        self.bank.setStyleSheet("background-color: rgba(0,0,0,0);\n"
"border:none;\n"
"border-bottom:2px solid rgba(46,82,101,200);\n"
"color: rgba(0,0,0,240);\n"
"padding-bottom: 7px;")
        self.bank.setText("")
        self.bank.setObjectName("bank")

######################################################### Button Send ########################################################

        self.send = QtWidgets.QPushButton(self.centralwidget)
        self.send.setGeometry(QtCore.QRect(220, 230, 190, 40))
        font = QtGui.QFont()
        font.setPointSize(11)
        font.setBold(True)
        font.setWeight(75)
        self.send.setFont(font)
        self.send.setStyleSheet("QPushButton#send{\n"
"    background-color: qlineargradient(spread:pad, x1:0, y1:0.505682, x2:1, y2:0.477, stop:0 rgba(11, 131, 120, 219), stop:1 rgba(85, 98, 112, 226));\n"
"    color:rgba(255,255,255,210);\n"
"    border-radius:5px;\n"
"}\n"
"\n"
"QPushButton#send:hover{\n"
"    background-color: qlineargradient(spread:pad, x1:0, y1:0.505682, x2:1, y2:0.477, stop:0 rgba(150, 123, 111, 219), stop:1 rgba(85, 81, 84, 226));\n"
"}\n"
"\n"
"QPushButton#send:pressed{\n"
"    padding-left:5px;\n"
"    padding-top:5px;\n"
"    background-color:rgba(150,123,111,255);\n"
"}")
        self.send.setObjectName("send")

####################################################### Button Disconnect ###################################################

        self.disconnect = QtWidgets.QPushButton(self.centralwidget)
        self.disconnect.setGeometry(QtCore.QRect(220, 300, 190, 40))
        font = QtGui.QFont()
        font.setPointSize(11)
        font.setBold(True)
        font.setWeight(75)
        self.disconnect.setFont(font)
        self.disconnect.setStyleSheet("QPushButton#disconnect{\n"
"    background-color: qlineargradient(spread:pad, x1:0, y1:0.505682, x2:1, y2:0.477, stop:0 rgba(11, 131, 120, 219), stop:1 rgba(85, 98, 112, 226));\n"
"    color:rgba(255,255,255,210);\n"
"    border-radius: 5px;\n"
"}\n"
"\n"
"QPushButton#disconnect:hover{\n"
"    background-color: qlineargradient(spread:pad, x1:0, y1:0.505682, x2:1, y2:0.477, stop:0 rgba(150, 123, 111, 219), stop:1 rgba(85, 81, 84, 226));\n"
"}\n"
"\n"
"QPushButton#disconnect:pressed{\n"
"    padding-left:5px;\n"
"    padding-top:5px;\n"
"    background-color:rgba(150,123,111,255);\n"
"}\n"
"\n"
"\n"
"")
        self.disconnect.setObjectName("disconnect")

####################################################### Phần OutPut cho Client ##############################################

        self.listView = QtWidgets.QTextEdit(self.centralwidget)
        self.listView.setGeometry(QtCore.QRect(10, 380, 640, 350))
        self.listView.setObjectName("listView")

######################################################## Currency Input #######################################################

        self.currency = QtWidgets.QLineEdit(self.centralwidget)
        self.currency.setGeometry(QtCore.QRect(370, 130, 220, 40))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.currency.setFont(font)
        self.currency.setStyleSheet("background-color: rgba(0,0,0,0);\n"
"border:none;\n"
"border-bottom:2px solid rgba(46,82,101,200);\n"
"color: rgba(0,0,0,240);\n"
"padding-bottom: 7px;")
        self.currency.setText("")
        self.currency.setObjectName("currency")

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

        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Client"))
        MainWindow.setWindowIcon(QtGui.QIcon('client.png'))
        self.message.setPlaceholderText(_translate("MainWindow", "Messenger"))
        self.dateEdit.setPlaceholderText(_translate("MainWindow", "Date"))
        self.bank.setPlaceholderText(_translate("MainWindow", "Bank"))
        self.send.setText(_translate("MainWindow", "Send"))
        self.disconnect.setText(_translate("MainWindow", "Disconnect"))
        self.currency.setPlaceholderText(_translate("MainWindow", "Currency"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = UI_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())


'''
write to a file
Take the code from the How To Decode A Website exercise (if you didn’t do it or just want to play with some different code, use the code from the solution), and instead of printing the results to a screen, write the results to a txt file. In your code, just make up a name for the file you are saving to.

Extras:
Ask the user to specify the name of the output file that will be saved.
'''

def main():
    str_filename = input("please input a filename: ")
    with open(str_filename, 'w') as open_file:
        open_file.write('A string to write')

if __name__ == '__main__':
    main()


from sys import argv
import re

### TODO{
## v2.0.0  -> v3.0.0: Implement line tags
# -[v2.1.0]- adjust get_asm parsing to deal with tabs and line
#		   - fix "bug" where '\n' doesn't get removed in get_asm()
# -[v2.2.0]- find and collect line addresses at parse
#		   - _asm_, _tags_ = get_asm(file): return asm, tags
#		   - must check if tags are called more than once -> err
# -[v2.3.0]- insert addresses when assembling
# -[v2.4.0]- type/subop sugar, eg: psuad -> padd.su, psssu -> psub.ss
## v3.0.0  -> v4.0.0: Sugar Sugar ;)
# -[v3.1.0]- Assembly cache to save re computing
# -[v3.2.0]- Figure out how to operate on a file while it's being read
# -[v3.?.?]- Variables(spooky), only after t16-emulator hits v1.0.0
### }

def get_asm(file):
	asm = {}
	f = open(file, 'r')
	for k, v in enumerate(f):
		hot_cmd = re.split(' ', v, 1)
		if len(v.split()) >= 2:
			asm[k] = (hot_cmd[0], re.split(' \n| ;', hot_cmd[1])[0])
	f.close()
	return asm #asm[i-line] -> (op, 'oper str')

def get_rc(_asm_):
	rc = {}
	op_set = {v[0] for v in _asm_.values()}
	with open('_t16_format_', 'r') as f:
		for ln in f:
			hot_ln = ln.split()
			if len(hot_ln) > 1:
				if hot_ln[0] in op_set:
					rc[hot_ln[0]] = hot_ln[1].replace('-', '')
	return rc #rc[op] -> fmt

def parse(entry): # entry = ('op,er,an,ds', ('fmt', {}))
	fmt = entry[1][0]
	hot_fmt = re.findall('M|N|C|B|A', fmt)
	if len(hot_fmt) > 0: # one or more operand to be processed
		try: # if '-v' passed into command line args
			_debug_[v](entry)
		except:
			pass
		opr_dic = entry[1][1]
		entry_opr = entry[0].rsplit(', ', 1)
		hot_opr = entry_opr[-1]
		blen = len(re.findall(f"{hot_fmt[-1]}", fmt))
		try: # extract addresses or immediates
			hot_val = int(re.sub('[a-zA-Z|\n]', '', hot_opr)) # <-- gets calculated regardless of exception
			hot_val>>hot_val # -ve shifts generate a ValueError
			opr_dic[hot_fmt[-1]] = f"{hot_val:0{int(blen)}b}"
		except ValueError: # -ve values get sign extended  ## -ve values are rare as only immediates use them
			opr_dic[hot_fmt[-1]] = f"{((1<<blen)-1)-(~hot_val):0{int(blen)}b}"
		except:
			try: # string supplied as operand is searched in _t16_misc to find it's binary value
				_t16_misc = {
					'k': 0,					# peeK mask
					'p': 1,					# poP mask
					'$': 'NOT IMPLEMENTED',	# Variable indicator - if I go that far
				}
				hot_val = re.sub('[ |\n]', '', hot_opr)
				opr_dic[hot_fmt[-1]] = str(_t16_misc[hot_val])
			except Exception: #learn how to give more + accurate error messages
				print(f"Unknown Error:: Check assembly file for errors.\n\tHINT: Err in parse({entry})")
				exit()
		fmt = fmt.replace(hot_fmt[-1], '', (blen-1)).replace(hot_fmt[-1], opr_dic[hot_fmt[-1]])
		return parse((entry_opr[0], (fmt, opr_dic)))
	else: # entry = ('op,er,an,ds', ('fmt', {}))
		try: # if '-v' passed into command line args
			_debug_[v](entry)
		except:
			pass
		return entry[1][0]

def gen_output(data, fmt):
	dec = int(str(data), 2)
	bits = len(str(data))
	fmt_dict = {
		'b': f"{dec:0{bits}b}",
		'x': f"{dec:0{bits>>2}X}",
		'bx': f"{dec:0{bits}b} {dec:0{bits>>2}X}",
		'xb': f"{dec:0{bits}b} {dec:0{bits>>2}X}",
	}
	try:
		return fmt_dict[fmt]
	except:
		print('UnknownError::')
		exit()

def main():
	global _argv_, _debug_, v
	version = '[v2.0.1]'
	_debug_ = {'v' : print}
	_help_ =  f"\nT16 assembler{version}\n  -h\tHelp\n  -v\tVerbose output/debug\n  -b\tBinary output[Default]\n  -x\tHexadecimal output\nExample: -vxb == verbose hex + bin ouput",
	# ---- argv checks and collection ---- #
	arg_len = len(argv)
	if (argv[1][0] == '-') & (arg_len == 4):
		if 'h' in argv[1]: # --help
			print(_help_)
			exit()
		if 'v' in argv[1]: # --verbose
			v = 'v'
			_argv_ = argv[1].replace(v, '').replace('-', '')
		else:
			_argv_ = argv[1].replace('-', '')
		_asm_ = get_asm(argv[2]) # asm[i-line] -> (op, 'oper str')
	elif arg_len == 3: # default: --binary
		_argv_ = 'b'
		_asm_ = get_asm(argv[1]) # asm[i-line] -> (op, 'oper str')
	else:
		print(f"Unknown Error:: .\n\tHINT:")
		exit()

	# ---- parse and write _bytecode_ to file ---- #
	_rc_ = get_rc(_asm_) #rc[op] -> 'fmt'
	try: # if '-v' passed into command line args
		_debug_[v](f"Argv:\n{argv}\nAssembly:\n{_asm_}\nReference Cache:\n{_rc_}")
	except:
		pass
	_t16_ = {}
	_bytecode_ = open(argv[-1], 'w')
	for l in _asm_.keys(): # main loop
		try: # parse(('oper str', ('fmt', {}))) <- empty dict
			tmp = {}
			asm_ln = _asm_[l]
			_t16_[l] = gen_output(parse((asm_ln[1], (_rc_[asm_ln[0]], tmp))), _argv_)
			_bytecode_.write(f"{_t16_[l]}\n")
		except KeyError:
			print(f"KeyError:: Line {l}, in <{argv[-2]}>:\n\tHINT: no instruction '{_asm_[l][0]}' found in T16's isa.")
			_bytecode_.close()
			exit()
		except:
			print(f"Unknown Error:: Check <{argv[-2]}> and '_t16_format_' for errors.")
			_bytecode_.close()
			exit()
	_bytecode_.close()
	try: # if '-v' passed into command line args
		_debug_[v](_t16_) # Didn't want to make the main loop any longer so printing _t16_ all at once'
	except:
		pass
	return print('done')

if __name__ == "__main__":
	main()


from itertools import permutations

class Intcode():
	def __init__(self, program, noun=None, verb=None):
		self.program = [int(i) for i in program]

		if noun:
			self.program[1] = noun
		if verb:
			self.program[2] = verb

		self.i = 0
		self._output = None

	def parameter_mode(self, mode, param):
		if mode == '0':
			return self.program[param]
		elif mode == '1':
			return param
		else:
			raise Exception('Invalid mode.')

	def get_params(self, param_mode, n_params):
		params = [None for n in range(n_params)]
		params[0] = self.parameter_mode(param_mode[0], self.program[self.i + 1])
		params[1] = self.parameter_mode(param_mode[1], self.program[self.i + 2])
		if n_params == 3:
			params[2] = self.program[self.i + 3]
		return params

	def run(self, _input):
		while self.i <= len(self.program):
			instruction = self.program[self.i]
			opcode = instruction % 100
			param_mode = str(instruction // 100)
			param_mode = param_mode[::-1] + '0' * (3 - len(param_mode))
			ix_change = False

			if opcode == 1:
				params = self.get_params(param_mode, 3)
				self.program[params[2]] = params[0] + params[1]
			elif opcode == 2:
				params = self.get_params(param_mode, 3)
				self.program[params[2]] = params[0] * params[1]
			elif opcode == 3:
				params = [self.program[self.i + 1]]
				current_input = _input[0]
				_input.pop(0)
				self.program[params[0]] = current_input
			elif opcode == 4:
				params = [self.parameter_mode(param_mode[0], self.program[self.i + 1])]
				self._output = params[0]
				self.i += 1 + len(params) # still need to increment!
				return self
			elif opcode == 5:
				params = self.get_params(param_mode, 2)
				if params[0] != 0:
					self.i = params[1]
					ix_change = True
			elif opcode == 6:
				params = self.get_params(param_mode, 2)
				if params[0] == 0:
					self.i = params[1]
					ix_change = True
			elif opcode == 7:
				params = self.get_params(param_mode, 3)
				self.program[params[2]] = 1 if params[0] < params[1] else 0
			elif opcode == 8:
				params = self.get_params(param_mode, 3)
				self.program[params[2]] = 1 if params[0] == params[1] else 0
			elif opcode == 99:
				self._output = self.program[0]
				return self
			else:
				raise Exception('Unknown opcode.')

			if not ix_change:
				self.i += 1 + len(params)

def amplifier_controller(_input):
	signals = []
	perm = list(permutations([0, 1, 2, 3, 4]))
	for thruster in perm:
		a = Intcode(_input).run([thruster[0], 0])
		b = Intcode(_input).run([thruster[1], a._output])
		c = Intcode(_input).run([thruster[2], b._output])
		d = Intcode(_input).run([thruster[3], c._output])
		e = Intcode(_input).run([thruster[4], d._output])
		signals.append(e._output)

	return signals, perm

def feedback_loop(_input):
	signals = []
	perm = list(permutations([5, 6, 7, 8, 9]))
	for thruster in perm:
		a = Intcode(_input).run([thruster[0], 0])
		b = Intcode(_input).run([thruster[1], a._output])
		c = Intcode(_input).run([thruster[2], b._output])
		d = Intcode(_input).run([thruster[3], c._output])
		e = Intcode(_input).run([thruster[4], d._output])

		while a.program[a.i] != 99:
			a = a.run([e._output])
			b = b.run([a._output])
			c = c.run([b._output])
			d = d.run([c._output])
			e = e.run([d._output])
			e_val = e._output

		signals.append(e_val)

	return signals, perm

def run(_input, part):
	if part == 1:
		signals, perm = amplifier_controller(_input)
	elif part == 2:
		signals, perm = feedback_loop(_input)
	else:
		raise Exception('Only 2 parts to this problem.')

	best_signal = max(signals)  # 4215746
	optimal_thruster = perm[signals.index(best_signal)]
	print(f'PART {part}: highest signal: {best_signal}, best thruster combination: {"".join([str(s) for s in optimal_thruster])}')

if __name__ == '__main__':
	_input = open("2019/aoc7.txt").read().split(',')
	run(_input, part=1)  # 844468
	run(_input, part=2)  # 4215746


import time
import mpi4py.MPI as MPI

import maia
import maia.pytree        as PT
import maia.utils.logging as mlog
from   maia.factory  import dist_from_part
from   maia.transfer import utils                as TEU
from   maia.utils    import np_utils, layouts, py_utils
from   .extraction_utils   import local_pl_offset, LOC_TO_DIM, get_partial_container_stride_and_order
from   .point_cloud_utils  import create_sub_numbering

import numpy as np

import Pypdm.Pypdm as PDM

DIMM_TO_DIMF = { 0: {'Vertex':'Vertex'},
               # 1: {'Vertex': None,    'EdgeCenter':None, 'FaceCenter':None, 'CellCenter':None},
                 2: {'Vertex':'Vertex', 'EdgeCenter':'EdgeCenter', 'FaceCenter':'CellCenter'},
                 3: {'Vertex':'Vertex', 'EdgeCenter':'EdgeCenter', 'FaceCenter':'FaceCenter', 'CellCenter':'CellCenter'}}

class Extractor:
  def __init__( self,
                part_tree, point_list, location, comm,
                equilibrate=True,
                graph_part_tool="hilbert"):

    self.part_tree     = part_tree
    self.exch_tool_box = list()
    self.comm          = comm

    # Get zones by domains
    part_tree_per_dom = dist_from_part.get_parts_per_blocks(part_tree, comm).values()
    # Check : monodomain
    assert len(part_tree_per_dom) == 1

    # ExtractPart dimension
    self.dim    = LOC_TO_DIM[location]
    assert self.dim in [0,2,3], "[MAIA] Error : dimensions 0 and 1 not yet implemented"
    #CGNS does not support 0D, so keep input dim in this case (which is 3 since 2d is not managed)
    cell_dim = 3 if location == 'Vertex' else self.dim

    # ExtractPart CGNSTree
    extracted_tree = PT.new_CGNSTree()
    extracted_base = PT.new_CGNSBase('Base', cell_dim=cell_dim, phy_dim=3, parent=extracted_tree)

    assert graph_part_tool in ["hilbert","parmetis","ptscotch"]
    assert not( (self.dim==0) and graph_part_tool in ['parmetis', 'ptscotch']),\
           '[MAIA] Vertex extraction not available with parmetis or ptscotch partitioning. Please check your script.'

    # Compute extract part of each domain
    for i_domain, part_zones in enumerate(part_tree_per_dom):
      extracted_zone, etb = extract_part_one_domain(part_zones, point_list[i_domain], self.dim, comm,
                                                    equilibrate=equilibrate,
                                                    graph_part_tool=graph_part_tool)
      self.exch_tool_box.append(etb)
      if PT.Zone.n_vtx(extracted_zone)!=0:
        PT.add_child(extracted_base, extracted_zone)
    self.extracted_tree = extracted_tree

  def exchange_fields(self, fs_container):
    # Get zones by domains (only one domain for now)
    part_tree_per_dom = dist_from_part.get_parts_per_blocks(self.part_tree, self.comm).values()

    # Get zone from extractpart
    extracted_zones = PT.get_all_Zone_t(self.extracted_tree)
    assert len(extracted_zones) <= 1
    extracted_zone = extracted_zones[0] if len(extracted_zones)!=0 else None

    for container_name in fs_container:
      # Loop over domains
      for i_domain, part_zones in enumerate(part_tree_per_dom):
        exchange_field_one_domain(part_zones, extracted_zone, self.dim, self.exch_tool_box[i_domain], \
            container_name, self.comm)

  def get_extract_part_tree(self) :
    return self.extracted_tree

def exchange_field_one_domain(part_zones, part_zone_ep, mesh_dim, exch_tool_box, container_name, comm) :

  loc_correspondance = {'Vertex'    : 'Vertex',
                        'FaceCenter': 'Cell',
                        'CellCenter': 'Cell'}

  # > Retrieve fields name + GridLocation + PointList if container
  #   is not know by every partition
  mask_zone = ['MaskedZone', None, [], 'Zone_t']
  dist_from_part.discover_nodes_from_matching(mask_zone, part_zones, container_name, comm, \
      child_list=['GridLocation', 'BCRegionName', 'GridConnectivityRegionName'])

  fields_query = lambda n: PT.get_label(n) in ['DataArray_t', 'IndexArray_t']
  dist_from_part.discover_nodes_from_matching(mask_zone, part_zones, [container_name, fields_query], comm)
  mask_container = PT.get_child_from_name(mask_zone, container_name)
  if mask_container is None:
    raise ValueError("[maia-extract_part] asked container for exchange is not in tree")

  # > Manage BC and GC ZSR
  ref_zsr_node    = mask_container
  bc_descriptor_n = PT.get_child_from_name(mask_container, 'BCRegionName')
  gc_descriptor_n = PT.get_child_from_name(mask_container, 'GridConnectivityRegionName')
  assert not (bc_descriptor_n and gc_descriptor_n)
  if bc_descriptor_n is not None:
    bc_name      = PT.get_value(bc_descriptor_n)
    dist_from_part.discover_nodes_from_matching(mask_zone, part_zones, ['ZoneBC_t', bc_name], comm, child_list=['PointList', 'GridLocation_t'])
    ref_zsr_node = PT.get_child_from_predicates(mask_zone, f'ZoneBC_t/{bc_name}')
  elif gc_descriptor_n is not None:
    gc_name      = PT.get_value(gc_descriptor_n)
    dist_from_part.discover_nodes_from_matching(mask_zone, part_zones, ['ZoneGridConnectivity_t', gc_name], comm, child_list=['PointList', 'GridLocation_t'])
    ref_zsr_node = PT.get_child_from_predicates(mask_zone, f'ZoneGridConnectivity_t/{gc_name})')

  gridLocation = PT.Subset.GridLocation(ref_zsr_node)
  partial_field = PT.get_child_from_name(ref_zsr_node, 'PointList') is not None
  assert gridLocation in ['Vertex', 'FaceCenter', 'CellCenter']

  # > FlowSolution node def by zone
  if part_zone_ep is not None :
    if PT.get_label(mask_container) == 'FlowSolution_t':
      FS_ep = PT.new_FlowSolution(container_name, loc=DIMM_TO_DIMF[mesh_dim][gridLocation], parent=part_zone_ep)
    elif PT.get_label(mask_container) == 'ZoneSubRegion_t':
      FS_ep = PT.new_ZoneSubRegion(container_name, loc=DIMM_TO_DIMF[mesh_dim][gridLocation], parent=part_zone_ep)
    else:
      raise TypeError

  # > Get PTP and parentElement for the good location
  ptp        = exch_tool_box['part_to_part'][gridLocation]

  # LN_TO_GN
  _gridLocation    = {"Vertex" : "Vertex", "FaceCenter" : "Element", "CellCenter" : "Cell"}

  if part_zone_ep is not None:
    elt_n            = part_zone_ep if gridLocation!='FaceCenter' else PT.Zone.NGonNode(part_zone_ep)
    if elt_n is None :return
    part1_elt_gnum_n = PT.maia.getGlobalNumbering(elt_n, _gridLocation[gridLocation])
    part1_ln_to_gn   = [PT.get_value(part1_elt_gnum_n)]

  # Get reordering informations if point_list
  # https://stackoverflow.com/questions/8251541/numpy-for-every-element-in-one-array-find-the-index-in-another-array
  if partial_field:
    pl_gnum1, stride = get_partial_container_stride_and_order(part_zones, container_name, gridLocation, ptp, comm)

  # > Field exchange
  for fld_node in PT.get_children_from_label(mask_container, 'DataArray_t'):
    fld_name = PT.get_name(fld_node)
    fld_path = f"{container_name}/{fld_name}"

    if partial_field:
      # Get field and organize it according to the gnum1_come_from arrays order
      fld_data = list()
      for i_part, part_zone in enumerate(part_zones) :
        fld_n = PT.get_node_from_path(part_zone,fld_path)
        fld_data_tmp = PT.get_value(fld_n) if fld_n is not None else np.empty(0, dtype=np.float64)
        fld_data.append(fld_data_tmp[pl_gnum1[i_part]])
      p2p_type = PDM._PDM_PART_TO_PART_DATA_DEF_ORDER_GNUM1_COME_FROM

    else :
      fld_data = [PT.get_node_from_path(part_zone,fld_path)[1] for part_zone in part_zones]
      stride   = 1
      p2p_type = PDM._PDM_PART_TO_PART_DATA_DEF_ORDER_PART2

    # Reverse iexch
    req_id = ptp.reverse_iexch(PDM._PDM_MPI_COMM_KIND_P2P,
                               p2p_type,
                               fld_data,
                               part2_stride=stride)
    part1_stride, part1_data = ptp.reverse_wait(req_id)

    # Interpolation and placement
    if part_zone_ep is not None:
      i_part = 0
      PT.new_DataArray(fld_name, part1_data[i_part], parent=FS_ep)

  # Build PL with the last exchange stride
  if partial_field:
    if len(part1_data)!=0 and part1_data[0].size!=0:
      new_point_list = np.where(part1_stride[0]==1)[0] if part1_data[0].size!=0 else np.empty(0, dtype=np.int32)
      point_list = new_point_list + local_pl_offset(part_zone_ep, LOC_TO_DIM[gridLocation])+1
      new_pl_node = PT.new_PointList(name='PointList', value=point_list.reshape((1,-1), order='F'), parent=FS_ep)
      partial_part1_lngn = [part1_ln_to_gn[0][new_point_list]]
    else:
      partial_part1_lngn = []

    # Update global numbering in FS
    partial_gnum = create_sub_numbering(partial_part1_lngn, comm)
    if part_zone_ep is not None and len(partial_gnum)!=0:
      PT.maia.newGlobalNumbering({'Index' : partial_gnum[0]}, parent=FS_ep)

def extract_part_one_domain(part_zones, point_list, dim, comm,
                            equilibrate=True,
                            graph_part_tool="hilbert"):
  """
  TODO : AJOUTER LE CHOIX PARTIONNEMENT
  """
  n_part_in  = len(part_zones)
  n_part_out = 1 if equilibrate else n_part_in

  pdm_ep = PDM.ExtractPart(dim, # face/cells
                           n_part_in,
                           n_part_out,
                           equilibrate,
                           eval(f"PDM._PDM_SPLIT_DUAL_WITH_{graph_part_tool.upper()}"),
                           True,
                           comm)

  # Loop over domain zone : preparing extract part
  for i_part, part_zone in enumerate(part_zones):
    # Get NGon + NFac
    cx, cy, cz = PT.Zone.coordinates(part_zone)
    vtx_coords = np_utils.interweave_arrays([cx,cy,cz])

    ngon  = PT.Zone.NGonNode(part_zone)
    nface = PT.Zone.NFaceNode(part_zone)

    cell_face_idx = PT.get_child_from_name(nface, "ElementStartOffset" )[1]
    cell_face     = PT.get_child_from_name(nface, "ElementConnectivity")[1]
    face_vtx_idx  = PT.get_child_from_name(ngon,  "ElementStartOffset" )[1]
    face_vtx      = PT.get_child_from_name(ngon,  "ElementConnectivity")[1]

    vtx_ln_to_gn, face_ln_to_gn, cell_ln_to_gn = TEU.get_entities_numbering(part_zone)

    n_cell = cell_ln_to_gn.shape[0]
    n_face = face_ln_to_gn.shape[0]
    n_edge = 0
    n_vtx  = vtx_ln_to_gn .shape[0]

    pdm_ep.part_set(i_part,
                    n_cell, n_face, n_edge, n_vtx,
                    cell_face_idx, cell_face    ,
                    None, None, None,
                    face_vtx_idx , face_vtx     ,
                    cell_ln_to_gn, face_ln_to_gn,
                    None,
                    vtx_ln_to_gn , vtx_coords)

    pdm_ep.selected_lnum_set(i_part, point_list[i_part] - local_pl_offset(part_zone, dim) - 1)

  pdm_ep.compute()

  # > Reconstruction du maillage de l'extract part
  n_extract_cell = pdm_ep.n_entity_get(0, PDM._PDM_MESH_ENTITY_CELL  )
  n_extract_face = pdm_ep.n_entity_get(0, PDM._PDM_MESH_ENTITY_FACE  )
  n_extract_edge = pdm_ep.n_entity_get(0, PDM._PDM_MESH_ENTITY_EDGE  )
  n_extract_vtx  = pdm_ep.n_entity_get(0, PDM._PDM_MESH_ENTITY_VERTEX)

  size_by_dim = {0: [[n_extract_vtx, 0             , 0]], # not yet implemented
                 1:   None                              , # not yet implemented
                 2: [[n_extract_vtx, n_extract_face, 0]],
                 3: [[n_extract_vtx, n_extract_cell, 0]] }

  # > ExtractPart zone construction
  extracted_zone = PT.new_Zone(PT.maia.conv.add_part_suffix('Zone', comm.Get_rank(), 0),
                               size=size_by_dim[dim],
                               type='Unstructured')

  ep_vtx_ln_to_gn  = pdm_ep.ln_to_gn_get(0,PDM._PDM_MESH_ENTITY_VERTEX)
  PT.maia.newGlobalNumbering({"Vertex" : ep_vtx_ln_to_gn}, parent=extracted_zone)

  # > Grid coordinates
  cx, cy, cz = layouts.interlaced_to_tuple_coords(pdm_ep.vtx_coord_get(0))
  extract_grid_coord = PT.new_GridCoordinates(parent=extracted_zone)
  PT.new_DataArray('CoordinateX', cx, parent=extract_grid_coord)
  PT.new_DataArray('CoordinateY', cy, parent=extract_grid_coord)
  PT.new_DataArray('CoordinateZ', cz, parent=extract_grid_coord)

  if dim == 0:
    PT.maia.newGlobalNumbering({'Cell' : np.empty(0, dtype=ep_vtx_ln_to_gn.dtype)}, parent=extracted_zone)

  # > NGON
  if dim >= 2:
    ep_face_vtx_idx, ep_face_vtx  = pdm_ep.connectivity_get(0, PDM._PDM_CONNECTIVITY_TYPE_FACE_VTX)
    ngon_n = PT.new_NGonElements( 'NGonElements',
                                  erange  = [1, n_extract_face],
                                  ec      = ep_face_vtx,
                                  eso     = ep_face_vtx_idx,
                                  parent  = extracted_zone)

    ep_face_ln_to_gn = pdm_ep.ln_to_gn_get(0, PDM._PDM_MESH_ENTITY_FACE)
    PT.maia.newGlobalNumbering({'Element' : ep_face_ln_to_gn}, parent=ngon_n)
    if dim == 2:
      PT.maia.newGlobalNumbering({'Cell' : ep_face_ln_to_gn}, parent=extracted_zone)

  # > NFACES
  if dim == 3:
    ep_cell_face_idx, ep_cell_face = pdm_ep.connectivity_get(0, PDM._PDM_CONNECTIVITY_TYPE_CELL_FACE)
    nface_n = PT.new_NFaceElements('NFaceElements',
                                    erange  = [n_extract_face+1, n_extract_face+n_extract_cell],
                                    ec      = ep_cell_face,
                                    eso     = ep_cell_face_idx,
                                    parent  = extracted_zone)

    ep_cell_ln_to_gn = pdm_ep.ln_to_gn_get(0, PDM._PDM_MESH_ENTITY_CELL)
    PT.maia.newGlobalNumbering({'Element' : ep_cell_ln_to_gn}, parent=nface_n)
    PT.maia.newGlobalNumbering({'Cell' : ep_cell_ln_to_gn}, parent=extracted_zone)

    maia.algo.nface_to_pe(extracted_zone, comm)

  # - Get PTP by vertex and cell
  ptp = dict()
  if equilibrate:
    ptp['Vertex']       = pdm_ep.part_to_part_get(PDM._PDM_MESH_ENTITY_VERTEX)
    if dim >= 2: # NGON
      ptp['FaceCenter'] = pdm_ep.part_to_part_get(PDM._PDM_MESH_ENTITY_FACE)
    if dim == 3: # NFACE
      ptp['CellCenter'] = pdm_ep.part_to_part_get(PDM._PDM_MESH_ENTITY_CELL)

  # - Get parent elt
  parent_elt = dict()
  parent_elt['Vertex']       = pdm_ep.parent_ln_to_gn_get(0,PDM._PDM_MESH_ENTITY_VERTEX)
  if dim >= 2: # NGON
    parent_elt['FaceCenter'] = pdm_ep.parent_ln_to_gn_get(0,PDM._PDM_MESH_ENTITY_FACE)
  if dim == 3: # NFACE
    parent_elt['CellCenter'] = pdm_ep.parent_ln_to_gn_get(0,PDM._PDM_MESH_ENTITY_CELL)

  exch_tool_box = {'part_to_part' : ptp, 'parent_elt' : parent_elt}

  return extracted_zone, exch_tool_box

def extract_part_from_zsr(part_tree, zsr_name, comm,
                          # transfer_fields=True
                          containers_name=[], **options):
  """Extract the submesh defined by the provided ZoneSubRegion from the input volumic
  partitioned tree.

  Dimension of the output mesh is set up accordingly to the GridLocation of the ZoneSubRegion.
  Submesh is returned as an independant partitioned CGNSTree and includes the relevant connectivities.

  In addition, containers specified in ``containers_name`` list are transfered to the extracted tree.
  Containers to be transfered can be either of label FlowSolution_t or ZoneSubRegion_t.

  Args:
    part_tree       (CGNSTree)    : Partitioned tree from which extraction is computed. Only U-NGon
      connectivities are managed.
    zsr_name        (str)         : Name of the ZoneSubRegion_t node
    comm            (MPIComm)     : MPI communicator
    containers_name (list of str) : List of the names of the fields containers to transfer
                                    on the output extracted tree.
    **options: Options related to the extraction.
  Returns:
    extracted_tree (CGNSTree)  : Extracted submesh (partitioned)

  Extraction can be controled by the optional kwargs:

    - ``graph_part_tool`` (str) -- Partitioning tool used to balance the extracted zones.
      Admissible values are ``hilbert, parmetis, ptscotch``. Note that
      vertex-located extractions require hilbert partitioning. Defaults to ``hilbert``.

  Important:
    - Input tree must be unstructured and have a ngon connectivity.
    - Partitions must come from a single initial domain on input tree.

  See also:
    :func:`create_extractor_from_zsr` takes the same parameters, excepted ``containers_name``,
    and returns an Extractor object which can be used to exchange containers more than once through its
    ``Extractor.exchange_fields(container_name)`` method.

  Example:
    .. literalinclude:: snippets/test_algo.py
      :start-after: #extract_from_zsr@start
      :end-before:  #extract_from_zsr@end
      :dedent: 2
  """

  start = time.time()
  extractor = create_extractor_from_zsr(part_tree, zsr_name, comm, **options)

  if containers_name:
    extractor.exchange_fields(containers_name)
  end = time.time()

  extracted_tree = extractor.get_extract_part_tree()

  # Print some light stats
  elts_kind = ['vtx', 'edges', 'faces', 'cells'][extractor.dim]
  if extractor.dim == 0:
    n_cell = sum([PT.Zone.n_vtx(zone) for zone in PT.iter_all_Zone_t(extracted_tree)])
  else:
    n_cell = sum([PT.Zone.n_cell(zone) for zone in PT.iter_all_Zone_t(extracted_tree)])
  n_cell_all = comm.allreduce(n_cell, MPI.SUM)
  mlog.info(f"Extraction from ZoneSubRegion \"{zsr_name}\" completed ({end-start:.2f} s) -- "
            f"Extracted tree has locally {mlog.size_to_str(n_cell)} {elts_kind} "
            f"(Σ={mlog.size_to_str(n_cell_all)})")

  return extracted_tree

def create_extractor_from_zsr(part_tree, zsr_path, comm, **options):
  """Same as extract_part_from_zsr, but return the extractor object."""
  # Get zones by domains

  graph_part_tool = options.get("graph_part_tool", "hilbert")

  part_tree_per_dom = dist_from_part.get_parts_per_blocks(part_tree, comm)

  # Get point_list for each partitioned zone and group it by domain
  point_list = list()
  location = ''
  for domain, part_zones in part_tree_per_dom.items():
    point_list_domain = list()
    for part_zone in part_zones:
      zsr_node     = PT.get_node_from_path(part_zone, zsr_path)
      if zsr_node is not None:
        #Follow BC or GC link
        related_node = PT.getSubregionExtent(zsr_node, part_zone)
        zsr_node     = PT.get_node_from_path(part_zone, related_node)
        point_list_domain.append(PT.get_child_from_name(zsr_node, "PointList")[1][0])
        location = PT.Subset.GridLocation(zsr_node)
      else: # ZSR does not exists on this partition
        point_list_domain.append(np.empty(0, np.int32))
    point_list.append(point_list_domain)

  # Get location if proc has no zsr
  location = comm.allreduce(location, op=MPI.MAX)

  return Extractor(part_tree, point_list, location, comm,
                   graph_part_tool=graph_part_tool)

def extract_part_from_bc_name(part_tree, bc_name, comm,
                              transfer_dataset=True,
                              containers_name=[],
                              **options):
  """Extract the submesh defined by the provided BC name from the input volumic
  partitioned tree.

  Behaviour and arguments of this function are similar to those of :func:`extract_part_from_zsr`
  (``zsr_name`` becomes ``bc_name``). Optional ``transfer_dataset`` argument allows to
  transfer BCDataSet from BC to the extracted mesh (default to ``True``).

  Example:
    .. literalinclude:: snippets/test_algo.py
      :start-after: #extract_from_bc_name@start
      :end-before:  #extract_from_bc_name@end
      :dedent: 2
  """

  # Local copy of the part_tree to add ZSR
  l_containers_name = containers_name
  local_part_tree   = PT.shallow_copy(part_tree)
  part_tree_per_dom = dist_from_part.get_parts_per_blocks(local_part_tree, comm)

  # Adding ZSR to tree
  there_is_bcdataset = False
  for domain, part_zones in part_tree_per_dom.items():
    for part_zone in part_zones:
      bc_n = PT.get_node_from_name_and_label(part_zone, bc_name, 'BC_t')
      if bc_n is not None:
        zsr_bc_n  = PT.new_ZoneSubRegion(name=bc_name, bc_name=bc_name, parent=part_zone)
        if transfer_dataset:
          assert PT.get_child_from_predicates(bc_n, 'BCDataSet_t/IndexArray_t') is None,\
                 'BCDataSet_t with PointList aren\'t managed'
          ds_arrays = PT.get_children_from_predicates(bc_n, 'BCDataSet_t/BCData_t/DataArray_t')
          for ds_array in ds_arrays:
            PT.new_DataArray(name=PT.get_name(ds_array), value=PT.get_value(ds_array), parent=zsr_bc_n)
          if len(ds_arrays) != 0:
            there_is_bcdataset = True
            # PL and Location is needed for data exchange, but this should be done in ZSR func
            for name in ['PointList', 'GridLocation']:
              PT.add_child(zsr_bc_n, PT.get_child_from_name(bc_n, name))

  if transfer_dataset and comm.allreduce(there_is_bcdataset, MPI.LOR):
    l_containers_name = containers_name + [bc_name] # not to change the initial containers_name list

  return extract_part_from_zsr(local_part_tree, bc_name, comm, l_containers_name, **options)


import datetime
import json

# The data sent for each action (turning on, fan speed, heating temp etc) all use the same format with the only change being the data in the data key.
# We create a Parent class with this template and all the child classes have their own implementation of it with the added data + the value that will be passed in.

class Commands:
    def __init__(self):
        self.publish_template = {
            'data' : {
            },
            'mode-reason' : 'LAPP',
            'time' : '',
            'msg' : 'STATE-SET'
        }
    def get_time(self):
        date = datetime.datetime.utcnow()
        return date.strftime('%y-%m-%d') + 'T' + date.strftime('%H:%M:%S') + 'Z'

    def publish(self):
        print(self.publish_template)
        self.publish_template['time'] = self.get_time()
        return json.dumps(self.publish_template, indent=2)

    #On, Off or AUTO.
    #Data fmod.
    #FAN = ON | OFF = OFF | AUTO = AUTO.
    # Auto mode automatically maintains air quality and temperature.
    def set_state(self,value):
        publish_data = self.publish_template.copy()
        publish_data['data']['fmod'] = value.upper()
        publish_data['time'] = self.get_time()
        return json.dumps(publish_data,indent=2)

    #Heating or cooling.
    #Data hmod.
    #HEAT = Heating | OFF = Cooling.
    def set_mode(self, value):
        publish_data = self.publish_template.copy()
        publish_data['data']['hmod'] = value.upper()
        publish_data['time'] = self.get_time()
        return json.dumps(publish_data,indent=2)

    #Fan speed.
    #Data fnsp.
    #4 digits 0 to 10. Must have 4 digits. We can use rjust(4,'0') to pad the data with zero's. 1 = 0001 | 10 = 0010.
    def set_speed(self, value):
        publish_data = self.publish_template.copy()
        publish_data['data']['fnsp'] = value.rjust(4,'0')
        publish_data['time'] = self.get_time()
        return json.dumps(publish_data,indent=2)

    #Heating Temperature.
    #Data hmax.
    #The fan itself displays as Celsius. However, we need to send the data as Kelvin. The formula  for that is (c + 273.15). We also need to round it.
    #This is because Kelvin scale does not use the degree symbol. Kelvin is an absolute scale based on absolute 0 while Celsius is based on the properties of water. It then is multiplied by 10.
    def set_temp(self, value):
        publish_data = self.publish_template.copy()
        publish_data['data']['hmax'] = round((int(value) + 273.15) * 10)
        publish_data['time'] = self.get_time()
        return json.dumps(publish_data,indent=2)

    #Timer
    #Data sltm
    #4 digits required. Data is sent in minutes.
    def set_timer(self, value):
        publish_data = self.publish_template.copy()
        publish_data['data']['sltm'] = value.rjust(4,'0')
        publish_data['time'] = self.get_time()
        return json.dumps(publish_data,indent=2)

    #Oscillation.
    #Data oson.
    #ON = ON | OFF = OFF.
    def set_osci(self, value):
        publish_data = self.publish_template.copy()
        publish_data['data']['oson'] = value
        publish_data['time'] = self.get_time()
        return json.dumps(publish_data,indent=2)

    #Night Mode
    #Data nmod
    #ON = ON | OFF = OFF.
    def set_nmod(self, value):
        publish_data = self.publish_template.copy()
        publish_data['data']['nmod'] = value
        publish_data['time'] = self.get_time()
        return json.dumps(publish_data,indent=2)

    #Diffused Mode
    #Data ffoc
    # OFF = diffused mode on | ON = diffused mode off
    def set_diffused(self, value):
        publish_data = self.publish_template.copy()
        publish_data['data']['ffoc'] = value
        publish_data['time'] = self.get_time()
        return json.dumps(publish_data,indent=2)

    def get_current_state(self):
        publish_data = {
            'mode-reason' : 'LAPP',
            'time' : '',
            'msg' : 'REQUEST-CURRENT-STATE'
        }
        publish_data['time'] = self.get_time()
        return json.dumps(publish_data,indent=2)

    def get_env_state(self):
        publish_data = {
            'mode-reason' : 'LAPP',
            'time' : '',
            'msg' : 'REQUEST-ENVIRONMENTAL-CURRENT-SENSOR-DATA'
        }
        publish_data['time'] = self.get_time()
        return json.dumps(publish_data,indent=2)

    def get_help(self, value):
        command_info = {
            'state' : 'Turns the fan ON, OFF or sets it to AUTO mode. Values: FAN = ON | OFF = OFF | AUTO = AUTO.',
            'mode' : 'Turns on Heating or Cooling. Values: HEAT = Heating | OFF = Cooling.',
            'speed' : 'Changes the Fan Speed. Values: 0 to 10.',
            'temp' : 'Sets the Heating temperature. Value in Celsius.',
            'timer' : 'Sets the Timer to turn off. Value in minutes.',
            'osci' : 'Turns the Oscillation ON or OFF. Values ON | OFF.',
            'night' : 'Turns Night Mode ON or OFF. Values ON | OFF.',
            'diffused' : 'Turns Diffused Mode ON or OFF. Values:  OFF = diffused mode on | ON = difused mode off.'
        }
        if value in command_info.keys():
            print(command_info[value])
        else:
            print("Unknown command")


import json
import nltk
from scipy import sparse
from nltk.tokenize import word_tokenize
from pymystem3 import Mystem
from nltk.corpus import stopwords
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer

# nltk.download('stopwords')
sw = stopwords.words('russian')
m = Mystem()

def make_corpus(path):
    with open(path, 'r') as f:
        corpus = list(f)[:50000]
    answers = []
    for doc in corpus:
        doc = json.loads(doc)
        ans = sorted(doc['answers'], key=lambda x: x['author_rating']['value'])
        if len(ans) > 0:
            answers.append(ans[-1]['text'])
    return answers

def preprocess_text(text):
    words = [w.lower() for w in word_tokenize(text) if w.isalpha()]
    words = [w for w in words if w not in sw]
    text = m.lemmatize(' '.join(words))
    return ''.join(text)[:-1]

def index_mtx(docs):
    texts = [preprocess_text(d) for d in docs]
    count_vectorizer = CountVectorizer()
    tf_vectorizer = TfidfVectorizer(use_idf=False, norm='l2')
    tfidf_vectorizer = TfidfVectorizer(use_idf=True, norm='l2')
    x_count_vec = count_vectorizer.fit_transform(texts)
    x_tf_vec = tf_vectorizer.fit_transform(texts)
    x_tfidf_vec = tfidf_vectorizer.fit_transform(texts)
    idf = tfidf_vectorizer.idf_
    tf = x_tf_vec
    k = 2
    b = 0.75
    len_d = x_count_vec.sum(axis=1)
    avdl = len_d.mean()
    B_1 = (k * (1 - b + b * len_d/avdl))
    values = []
    rows = []
    cols = []
    for i, rc in enumerate(zip(*tf.nonzero())):
        val_a = tf.data[i] * idf[rc[1]] * (k+1)
        val_b = tf.data[i] + float(B_1[rc[0]])
        values.append(val_a/val_b)
        rows.append(rc[0])
        cols.append(rc[1])
    mtx = sparse.csr_matrix((values, (rows, cols)))
    return mtx, count_vectorizer

def ind_query(qr, vct):
    return vct.transform([qr])

def calc_distance(ind_qr, ind_mtx):
    return np.dot(ind_mtx, ind_qr.T).toarray()

def main():
    answers = make_corpus('data.jsonl')
    # у меня не хватает памяти для хранения answers в арэе, поэтому каждому элементу соответствует айди (чтобы мотом можно было реализовать сортировку через маску)
    ans_ids = np.arange(0, len(answers)*3, 3)
    ind_mtx, vct = index_mtx(answers)
    qr = input('Введите запрос или нажмите на Enter, если больше не хотите спрашивать: ')
    results = []
    while qr != '':
        qr = preprocess_text(qr)
        ind_q = ind_query(qr, vct)
        sort_ind = calc_distance(ind_q, ind_mtx).argsort(axis=0)[-1::-1]
        res = ans_ids[sort_ind.ravel()]
        results.append(res)
        print('Топ 5:\n', '\n'.join([answers[i//3] for i in res[:5]]))
        qr = input('Введите запрос или нажмите на Enter, если больше не хотите спрашивать: ')
    return results

if __name__ == '__main__':
   results = main()


#!/usr/bin/python2
# -*- coding: utf-8 -*-
import xlrd
import sys
import os
import re
reload(sys)
sys.setdefaultencoding('utf8')

#region FIELDS
ROOT_DIR = os.getcwd()
LUAOUT_DIR = os.path.join(ROOT_DIR,"Test")
EXCEL_DIR = os.path.join(ROOT_DIR,"xlsx_origin")
FILETYPE = ".xlsx"
LUAFILETYPE = ".lua"
TBASE = {"int":True, "string":True, "float":True}
TBASESWITCH = {
    "int": lambda ds,f,v: save_int_value(ds,f,v),
    "float": lambda ds,f,v: save_float_value(ds,f,v),
    "string": lambda ds,f,v: save_string_vale(ds,f,v),
}
TBASESAPPENDWITCH = {
    "int": lambda ds,f,v: append_int_value(ds,f,v),
    "float": lambda ds,f,v: append_float_value(ds,f,v),
    "string": lambda ds,f,v: append_string_vale(ds,f,v),
}
#endregion

#out lua path
lua_path = "LuaOutPath"
#region COMMON

def value_is_none(value):
    return value == ''

def get_int_value(v):
    return 0 if value_is_none(v) else int(v)

def get_float_value(v):
    return 0.0 if value_is_none(v) else float(v)

def get_string_value(v):
    return '' if value_is_none(v) else str(v)

TBASESGETWITCH = {
    "int": get_int_value,
    "float": get_float_value,
    "string": get_string_value,
}
def save_int_value(ds,f,v):
    ds[f] = get_int_value(v)

def save_float_value(ds,f,v):
    ds[f] = get_float_value(v)

def save_string_vale(ds,f,v):
    ds[f] = get_string_value(v)

def append_int_value(ds,f,v):
    ds.append(get_int_value(v))

def append_float_value(ds,f,v):
    ds.append(get_float_value(v))

def append_string_vale(ds,f,v):
    ds.append(get_string_value(v))

def save_list_vale(ds,f,v,tp):
    data = []
    ds[f] = data
    #处理只填了一个值
    if type(v) == int or type(v) == float:
        TBASESAPPENDWITCH[tp](data,0,v)
    else:
        sl = v.split(';')
        for i, v in enumerate(sl):
            TBASESAPPENDWITCH[tp](data,i,v)

def save_dictionary_vale(ds,f,v,tp1,tp2,dm):
    data = {}
    ds[f] = data
    sdi = v.split(';')
    for i, di in enumerate(sdi):
        if not value_is_none(di):
            skv = di.split(',')
            if len(skv) != 2:raise Exception("Error Dictionary ")
            dkey = TBASESGETWITCH[tp1](skv[0])
            TBASESWITCH[tp2](data,dkey,skv[1])
#endregion

#region FUNCTIONS
def check_types(record,types):
    col_idx = 0
    for value in record:
        if col_idx > 0:
            if not value: raise Exception("第 %d 列没填类型"%(col_idx))
            if col_idx == 1 and value != 'int': raise Exception("first type isnot int")
            elif value in TBASE:
                types.append(str(value.strip()))
            elif value.find('List') != -1:
                tb = re.findall(re.compile(r"<(.*?)>",re.S),value)
                if tb[0] in TBASE:
                    types.append(str(value.strip()))
                else:
                    raise Exception("暂不支持该类型List:%s"%(str(value)))
            elif value.find('Dictionary') != -1:
                tb = re.findall(re.compile(r"<(.*?),(.*?)>",re.S),value)
                for tp in tb[0]:
                    if not tp in TBASE:
                        raise Exception("暂不支持该类型Dictionary:%s"%(str(value)))
                types.append(str(value.strip()))
            else:
                raise Exception("暂不支持该类型:%s"%(str(value)))
        col_idx += 1

def check_fields(record,types,fields):
    col_idx = 0
    for value in record:
        if col_idx > 0:
            if value_is_none(value): raise Exception("第 %d 列字段名为空"%(col_idx))
            if col_idx == 1 and value != 'Id': raise Exception("first Key not Id")
            if value in fields:
                raise Exception("重复的字段名:%s"%(str(value.strip())))
            fields.append(str(value.strip()))
        col_idx += 1

def make_data(record,types,fields,datas):
    data = {}
    if record[1] == '': return
    datas[int(record[1])] = data
    for i, tp in enumerate(types):
        if not tp: continue
        if tp in TBASE:
            TBASESWITCH[tp](data,fields[i],record[i + 1])
        elif tp.find('List') != -1:
            tb = re.findall(re.compile(r"<(.*?)>",re.S),tp)
            save_list_vale(data,fields[i],record[i + 1],tb[0])
        elif tp.find('Dictionary') != -1:
            tb = re.findall(re.compile(r"<(.*?),(.*?)>",re.S),tp)
            save_dictionary_vale(data,fields[i],record[i + 1],tb[0][0],tb[0][1],datas)
        else:
            raise Exception("暂不支持该类型:%s"%(tp))

def make_defalue_value(datas,defalut_values,fields):
    value_refs = {}
    for id,data in datas.items():
        for key,value in data.items():
            if not key in value_refs:
                value_refs[key] = {}
            value2str = str(value)
            if not value2str in value_refs[key]:
                value_refs[key][value2str] = {}
                value_refs[key][value2str]['cnt'] = 1
                value_refs[key][value2str]['value'] = value
            else:
                value_refs[key][value2str]['cnt'] += 1
    for key,vl in value_refs.items():
        if not key in defalut_values:
            defalut_values[key] = {}
            defalut_values[key]['cnt'] = 0
        for _,vi in vl.items():
            curr_cnt = defalut_values[key]['cnt']
            if curr_cnt < vi['cnt']:
                defalut_values[key]['value'] = vi['value']
                defalut_values[key]['cnt'] = vi['cnt']

def handle_one_file(dirname, filename):
    basename = filename.replace(FILETYPE,"")
    rpath = os.path.join(dirname,filename)

    print("process>>>>>>>>>    " + basename)
    excel = xlrd.open_workbook(rpath)
    tables = excel.sheets()

    if len(tables) == 0:
        raise Exception("file is empty" + basename)

    for table in tables:
        rows = table.nrows
        if rows < 4:
            raise Exception(basename + "    content error")
        types,fields = [],[]
        datas,defalut_values = {},{}
        #跳过服务器表
        if table.cell(0, 2).value == "server":
            print("break server cfg >",filename)
            return
        for row_idx in range(rows):
            record = table.row_values(row_idx)
            if row_idx == 1:
                check_types(record,types)
            if row_idx == 2:
                check_fields(record,types,fields)
            if row_idx >3:
                make_data(record,types,fields,datas)
        make_defalue_value(datas,defalut_values,fields)
        #TODO 只读第一个table
        break

    gen_lua_file(basename,datas,fields,defalut_values)

def gen_lua_file(baseName,datas,fields,default_value):
    if not os.path.isdir(LUAOUT_DIR):
        os.makedirs(LUAOUT_DIR)

    outfilepath = os.path.join(LUAOUT_DIR,baseName + LUAFILETYPE)
    outfp = open(outfilepath, "w")
    outfp.write('local keys = {')
    for idx,keyn in enumerate(fields):
        outfp.write('%s = %d,'%(keyn,idx + 1))
    outfp.write('}\n')
    outfp.write('local d = \"__default_value__\"\n')
    outfp.write('local data = { \n')
    for key,value in datas.items():
        outfp.write('\t[%d] = {'%(key))
        for idx,keyn in enumerate(fields):
            dlv = value[keyn]
            if dlv == default_value[keyn]['value']:
                outfp.write('d,')
            else:
                if type(dlv) == int:
                    outfp.write('%d,'%(dlv))
                elif type(dlv) == float:
                    outfp.write('%f,'%(dlv))
                elif type(dlv) == str:
                    outfp.write('\"%s\",'%(dlv))
                elif type(dlv) == list:
                    outfp.write('{')
                    for idx,lv in enumerate(dlv):
                        if type(lv) == str:
                            outfp.write('\"%s\",'%(str(lv)))
                        else:
                            outfp.write('%s,'%(str(lv)))
                    outfp.write('},')
                elif type(dlv) == dict:
                    outfp.write('{')
                    for dk,dv in dlv.items():
                        if type(dv) == str:
                            outfp.write('[\"%s\"] = '%(dk) + "\"" + str(dv) + '\",')
                        else:
                            outfp.write('[\"%s\"] = '%(dk) + str(dv) + ',')
                    outfp.write('},')
        outfp.write('},\n')

    outfp.write('}\n')
    outfp.write('local default_value = {\n')
    for k,v in default_value.items():
        outfp.write('\t%s = '%(k))
        dv = v['value']
        if type(dv) == int:
            outfp.write('%d,\n'%(dv))
        elif type(dv) == float:
            outfp.write('%f,\n'%(dv))
        elif type(dv) == str:
            outfp.write('\"%s\",\n'%(dv))
        elif type(dv) == list:
            outfp.write('{')
            for idx,lv in enumerate(dv):
                if type(lv) == str:
                    outfp.write('\"%s\",'%(str(lv)))
                else:
                    outfp.write('%s,'%(str(lv)))
            outfp.write('},\n')
        elif type(dv) == dict:
            outfp.write('{')
            for dk,dv in dv.items():
                if type(dv) == str:
                    outfp.write('[\"%s\"] = '%(dk) + "\"" + str(dv) + '\",')
                else:
                    outfp.write('[\"%s\"] = '%(dk) + str(dv) + ',')
            outfp.write('},\n')
    outfp.write('}\n')

    outfp.write('local mt = {}\n')
    outfp.write('mt.__index = function(t,k)\n')
    outfp.write('\t local key = keys[k]\n')
    outfp.write('\t local value = rawget(t,key)\n')
    outfp.write('\tif value == d then return default_value[k] end\n')
    outfp.write('\treturn value')
    outfp.write('\nend')

    outfp.write('\nmt.__newindex = function(t,k)')
    outfp.write('\t error( \' do not edit config \') end')

    outfp.write('\nmt.metatable = false')

    outfp.write('\nfor _,v in pairs(data) do')
    outfp.write('\n\tsetmetatable(v,mt)')
    outfp.write('\nend')

    outfp.write('\nreturn data')

    outfp.close()

#endregion

def main():
    for parent, dirnames, filenames in os.walk(EXCEL_DIR):
        for filename in filenames:
            if filename.endswith(FILETYPE):
                handle_one_file(parent, filename)
    print("tolua datatable done")
    # handle_one_file(EXCEL_DIR, "itemsBuy.xlsx")

if __name__ == '__main__':
    main()


import socket
import threading
import queue
import json
import os

IP = ''
PORT_CHAT = 50007
PORT_FILE = 50008
PORT_IMG = 50009
que = queue.Queue()  # 用于存放客户端发送的信息的队列
user_list = []  # 用于存放在线用户的信息  [conn, user, addr]
lock = threading.Lock()  # 创建锁, 防止多个线程写入数据的顺序打乱
# 获取服务端图片缓存文件夹的绝对路径
p = os.getcwd().split('\\')
for i in range(len(p)):
    if p[i] == 'myproject':
        break
server_cache = ('\\'.join(p[:i+1])) + '\\imgcache_server'
# 如果文件夹不存在则创建一个
if not os.path.exists(server_cache):
    os.mkdir(server_cache)
# print(server_cache)

################################################################################################################################
class Chat_Server(threading.Thread):
    global user_list, lock, que

    def __init__(self, ip, port):
        threading.Thread.__init__(self)
        self.ADDR = (ip, port)
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def run(self):
        self.s.bind(self.ADDR)
        self.s.listen(5)
        print('聊天服务器运行中...')
        q = threading.Thread(target=self.send_message)
        q.start()
        while True:
            conn, addr = self.s.accept()
            t = threading.Thread(target=self.chat_connect, args=(conn, addr))
            t.start()
        self.s.close()

    # 将接收到的信息存入que
    def enter_que(self, addr, data):
        lock.acquire()
        try:
            que.put((addr, data))
        finally:
            lock.release()

    # 将离线用户移出user_list
    def del_user(self, conn, addr):
        for i in range(len(user_list)):
            if user_list[i][0] == conn:
                user_list.pop(i)
                # 显示当前在线用户
                online_user_list = [user_list[i][1] for i in range(len(user_list))]
                self.enter_que(addr, online_user_list)
                print('剩余在线用户：', online_user_list)
                break

    # 用于接收所有客户端发送信息的函数
    def chat_connect(self, conn, addr):
        print('*****聊天服务器已连接: ', addr)
        # 连接后将用户信息添加到user_list
        user = conn.recv(1024).decode()  # 接收用户名
        if user == 'no':
            user = addr[0] + ':' + str(addr[1])
        else:
            # 防止重名
            user = user + '[' + str(addr[1]) + ']'
        user_list.append((conn, user, addr))
        # print(user_list)
        online_user_list = [user_list[i][1] for i in range(len(user_list))]
        self.enter_que(addr, online_user_list)
        try:
            while True:
                data = conn.recv(1024)
                data = data.decode()
                self.enter_que(addr, data)  # 保存信息到队列
            conn.close()
        except:
            print('*****聊天服务器断开连接: ', addr)
            self.del_user(conn, addr)  # 将断开用户移出users
            conn.close()

    # 将队列que中的消息发送给所有连接到的用户
    def send_message(self):
        while True:
            if not que.empty():
                data = ''
                message = que.get()  # 取出队列第一个元素
                # print('-------------', message)
                # 如果是字符串，说明是消息
                if isinstance(message[1], str):
                    for i in range(len(user_list)):
                        for j in range(len(user_list)):
                            if message[0] == user_list[j][2]:
                                data = message[1]
                                # print(message[1])
                                break
                        user_list[i][0].send(data.encode())
                # print(data)
                data = data.split('$&')[0]
                # print(data)
                # 如果是列表，说明是用户列表
                if isinstance(message[1], list):
                    data = json.dumps(message[1])
                    for i in range(len(user_list)):
                        user_list[i][0].send(data.encode())

 ################################################################################################################################
class File_Server(threading.Thread):
    def __init__(self, ip, port):
        threading.Thread.__init__(self)
        self.ADDR = (ip, port)
        self.upload = './filerecv'
        if not os.path.exists(self.upload):
            os.mkdir(self.upload)
        os.chdir(self.upload)  # 将filerecv作为文件上传默认路径
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def run(self):
        self.s.bind(self.ADDR)
        self.s.listen(5)
        print('文件服务器运行中...')
        while True:
            conn, addr = self.s.accept()
            t = threading.Thread(target=self.file_connect, args=(conn, addr))
            t.start()
        self.s.close()

    # 传输当前目录列表
    def send_current_dirlist(self, conn):
        current_dir = os.listdir(os.getcwd())
        current_dir = json.dumps(current_dir)
        conn.sendall(current_dir.encode())

    # 客户端上传文件
    def upload_file(self, path, conn):
        file_path = './' + path
        with open(file_path, 'wb') as f:
            while True:
                line = conn.recv(1024)
                if 'EOF'.encode() in line:
                    f.write(line[:-3])
                    break
                f.write(line)
            # 发送同步消息
            conn.send('ok'.encode())
            print('文件上传完成', file_path)

    # 客户端下载文件
    def download_file(self, path, conn):
        file_path = './' + path
        with open(file_path, 'rb') as f:
            lines = f.read()
            conn.sendall(lines)
        conn.send('EOF'.encode())
        # 接收同步消息
        y = conn.recv(1024).decode()
        if y == 'ok':
            print('文件下载完成', file_path)

    # 切换目录
    def cd(self, item, conn):
        # 如果是新连接或者下载上传文件后的发送则不切换,只发送当前工作目录
        if item != 'same':
            f = './' + item
            os.chdir(f)
        path_list = os.getcwd().split('\\')  # 当前工作目录
        # print('===============', path_list)
        for i in range(len(path_list)):
            if path_list[i] == 'filerecv':
                break
        path = ''
        for j in range(i, len(path_list)):
            path = path + path_list[j] + ' '
        path = '\\'.join(path.split())
        # print('+++++++++', path)
        # 如果切换目录超出范围则退回切换根目录
        if not 'filerecv' in path_list:
            f = './filerecv'
            os.chdir(f)
            path = 'filerecv'
        conn.send(path.encode())

    def file_connect(self, conn, addr):
        print('*****文件服务器已连接: ', addr)
        while True:
            # 获取客户端请求
            request = conn.recv(1024).decode()
            # 打印客户端请求
            print('客户端请求：', ' '.join(request.split('!@')))
            # if request == 'quit':
            #     print('*****文件服务器断开连接: ', addr)
            #     break
            # 获取客户端传来的操作命令
            command = request.split('!@')[0]
            # 获取客户端传来的目标路径
            path = request.split('!@')[1]
            if command == 'quit':
                print('*****文件服务器断开连接: ', addr)
                break
            elif command == 'upload':
                self.upload_file(path, conn)
            elif command == 'download':
                self.download_file(path, conn)
            elif command == 'show':
                self.send_current_dirlist(conn)
            elif command == 'cd':
                self.cd(path, conn)
        conn.close()

################################################################################################################################
class Img_Server(threading.Thread):
    global server_cache
    def __init__(self, ip, port):
        threading.Thread.__init__(self)
        self.ADDR = (ip, port)
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def run(self):
        self.s.bind(self.ADDR)
        self.s.listen(5)
        print('图片服务器运行中...')
        while True:
            conn, addr = self.s.accept()
            t = threading.Thread(target=self.img_connect, args=(conn, addr))
            t.start()
        self.s.close()

    def upload_img(self, name, conn):
        img_path = server_cache + '\\' + name
        self.server_img = []
        for _, _, namelist in os.walk(server_cache):
            for n in namelist:
                self.server_img.append(n)
        # print(self.server_img)
        if name not in self.server_img:
            self.server_img.append(name)
            conn.send('permit'.encode())
            with open(img_path, 'wb') as f:
                while True:
                    line = conn.recv(1024)
                    if 'EOF'.encode() in line:
                        f.write(line[:-3])
                        break
                    f.write(line)
            # 发送同步消息
            conn.send('ok'.encode())
            print('图片上传完成', img_path)
        else:
            conn.send('deny'.encode())
            print('图片已存在')

    def download_img(self, name, conn):
        img_path = server_cache + '\\' + name
        with open(img_path, 'rb') as f:
            lines = f.read()
            conn.sendall(lines)
        conn.send('EOF'.encode())
        # 接收同步消息
        x = conn.recv(1024).decode()
        if x == 'ok':
            print('图片下载完成', img_path)

    def img_connect(self, conn, addr):
        print('*****图片服务器已连接: ', addr)
        while True:
            # 接收客户端传来的请求
            request = conn.recv(1024).decode()
            # 打印客户端请求
            print('客户端请求：', ' '.join(request.split('!@')))
            # 获取客户端传来的操作命令
            command = request.split('!@')[0]
            # 获取客户端传来的图片名
            name = request.split('!@')[1]
            # 将图片上传至服务器缓存文件夹
            if command == 'upload':
                self.upload_img(name, conn)
            # 下载图片到客户端缓存文件夹
            elif command == 'download':
                self.download_img(name, conn)
        conn.close()

################################################################################################################################
if __name__ == '__main__':
    chat_server = Chat_Server(IP, PORT_CHAT)
    chat_server.start()
    file_server = File_Server(IP, PORT_FILE)
    file_server.start()
    img_server = Img_Server(IP, PORT_IMG)
    img_server.start()


from django.db import models
from DjangoUeditor.models import UEditorField

# Create your models here.
class Tag(models.Model):    # 分类模型类
    name = models.CharField(max_length=50,
                            verbose_name='分类名称',
                            unique=True)
    add_time = models.DateTimeField(auto_now_add=True,
                                    verbose_name='添加时间')

    def __str__(self):  # 避免admin后台显示object
        return self.name

    class Meta:
        db_table = 't_tag'
        ordering = ['-add_time']
        verbose_name = '文章分类'
        verbose_name_plural = verbose_name  # 去掉复数s

# class Chapter(models.Model):
#     chapter = models.CharField(max_length=)

class Art(models.Model):    # 文章模型类
    title = models.CharField(max_length=100,
                             verbose_name='标题')
    author = models.CharField(max_length=50,
                              verbose_name='作者')
    state = models.IntegerField(choices=((0, '连载中'), (1, '已完本')),
                                verbose_name='状态', default=0)
    summary = models.CharField(max_length=500,
                               verbose_name='简介')
    # content 可以定义字段,也可以用文章章节类
    # content = models.TextField(verbose_name='正文')

    content = UEditorField(verbose_name='内容',
                           width=640, height=480,
                           imagePath='art/u_images/',
                           filePath='art/u_files/',
                           toolbars='full',
                           blank=True,
                           null=True)
    publish_date = models.DateTimeField(auto_now_add=True,
                                        verbose_name='发布时间')
    last_refresh_date = models.DateTimeField(auto_now_add=True,
                                             verbose_name='更新时间')
    tag = models.ForeignKey(Tag, verbose_name='分类',
                            on_delete=models.SET_NULL,
                            null=True)
    cover = models.ImageField(verbose_name='封面',
                              upload_to='art/images',
                              null=True,
                              blank=True)  # 相对于MEDIA_ROOT

    @property
    def stateName(self):
        return '已完本' if self.state else '连载中'

    def __str__(self):
        return self.title

    class Meta:
        db_table = 't_art'
        verbose_name = '文章'
        verbose_name_plural = verbose_name


"""
Store some constants related to "Emeeting"
"""

# maximum length constraints
COMMON_MAX_LENGTH = 256
AGENDA_MAX_LENGTH = 9216
PHONE_MAX_LENGTH = 32
EMAIL_MAX_LENGTH = 128

MNFT_ALL = 'all'
MNFT_MINE = 'mine'
MNFT_INVITED = 'invited'
MEETING_LISTS = [MNFT_ALL, MNFT_MINE, MNFT_INVITED]
MEETING_LIST_CHOICES = [(v, v) for v in MEETING_LISTS]


from ij import *
from ij import IJ, ImagePlus, Macro
from ij.gui import Roi, PointRoi, GenericDialog, Overlay, HistogramWindow
from ij.plugin import Duplicator, Straightener, Selection
from ij.plugin.frame import RoiManager
from ij.io import FileSaver
from ij.process import ImageStatistics
import csv

def masking_macro(image_plus, dialog_value):
    IJ.run("Enhance Contrast...", "saturated=0.3 normalize")
    IJ.run(image_plus, "Find Edges", "slice")
    IJ.run(image_plus, "Auto Threshold", "method=Minimum white")
    Macro.setOptions("BlackBackground")
    for i in range(0,dialog_value):
        IJ.run(image_plus, "Dilate", "slice")
    IJ.run("Analyze Particles...", "size=5000-Infinity show=Masks add in_situ")
    IJ.run("Create Selection")

def run_script():

    imgplus = IJ.getImage()  # Gets entire ImageStack of loaded images, packaged in an ImagePlus object
    transform = imgplus.duplicate()
    print(type(imgplus))
    current = IJ.getProcessor()  # Gets current image shown in ACTIVE window (ImageProcessor)

    print(imgplus)  # Outputs image details to console

    orig_selection = imgplus.getOverlay()  # Object containing line selections
    transform.setOverlay(orig_selection)
    line_selection = transform.getOverlay().iterator()

    number_worms = 1  # Counter for number of worms selected

    working_img = current.duplicate()

    # Dialog box to select masking sensitivity (number of times to run DILATE)
    dialog = GenericDialog("Choose Masking Sensitivity")
    dialog.addSlider("Sensitivity", 1, 10, 3)
    dialog.hideCancelButton()
    dialog.showDialog()
    value = dialog.getSliders().get(0).getValue()  # Get dialog slider selection

    imp = ImagePlus("Masking Result", working_img)  # Creates an ImagePlus object for current image displayed in window
    imp.show()

    roiman = RoiManager()  # Creates instance of RoiManager

    masking_macro(imp, value)  # Runs masking & dilate specified number of times

    transform.show()
    transform_stack = transform.getStack()
    num_slices = transform_stack.getSize()
    for slice in range(1, num_slices+1):
        current_processor = transform_stack.getProcessor(slice)
        current_processor.setColor(0)
        current_processor.fillOutside(roiman.getRoi(roiman.getCount() -1))

    roiman.reset()  # Clears ROI manager after background is removed

    roiman.setOverlay(transform.getOverlay())  # Sets worm selection as Overlay
    print(roiman.getCount())  # Prints number of worms selected for verification

    for line in line_selection:  # Iterates through worms selected (in order of selection)
        line_width = line.getStrokeWidth()  # Line width as selected in segmented line settings
        print(line)
        print("current roi " + transform.getOverlay().get(number_worms -1).toString())
        roiman.select(number_worms -1)
        print(transform.getTitle())
        command = "title=" + transform.getTitle() + " line=" + str(int(line_width)) + " process"
        IJ.run("Straighten...", command)  # Runs ImageJ built in "Straighten" tool on selection

        polygon = line.getPolygon()  # Prints coordinates of selected worms to console
        x_points = polygon.xpoints
        y_points = polygon.ypoints
        print("worm" + str(number_worms))
        for i in range(0, len(x_points)):
            print(x_points[i], y_points[i])  # Prints coordinates of each point on polyline
        number_worms += 1  # Increments worm number bc iterator can only be FIFO

    IJ.run("Surface Plot...", "polygon=100 shade draw_axis smooth stack")  # Runs "Surface Plot" with default options

if __name__ in ['__builtin__', '__main__']:
    run_script()


import requests, json
from tkinter import *
from datetime import datetime
from pygame import mixer

def internet_on():
    try:
        requests.get('http://216.58.192.142', timeout=5)
        return True
    except requests.ConnectionError:
        return False

#import winsound
#winsound.PlaySound("SystemExit", winsound.SND_ALIAS)

def select_place(user, coach, coaches):
    print(coach)
    key = ""
    for value in coach['value']['places']:
        key = value
        break
    places = {0: {
        'ord': 0,
        'charline': "А",
        'wagon_num': coaches["coaches"][0]["num"],
        'wagon_class': coaches["coaches"][0]["coach_class"],
        'wagon_type': coaches["coaches"][0]["type"],
        'firstname': user.f_name,
        'lastname': user.l_name,
        'child': "",
        'stud': "",
        'bedding': 0,
        'place_num': coach['value']['places'][key][0]
    }}
    coach = {
        'from': user.st_from_id,
        'to': user.st_till_id,
        'train': user.my_train['num'],
        'date': user.dep_date.strftime('%Y-%m-%d'),
        'round_trip': 0,
        'places': places
    }
    r = requests.post('http://booking.uz.gov.ua/cart/add/', data=coach)
    print(r.status_code)
    print(r.text)
    print(requests.utils.dict_from_cookiejar(r.cookies))

def find_coach(user, coaches):
    data = {
        'station_id_from': user.st_from_id,
        'station_id_till': user.st_till_id,
        'train': user.my_train['num'],
        'coach_num': coaches['coaches'][0]['num'],
        'coach_class': coaches['coaches'][0]["coach_class"],
        'coach_type_id': coaches['coaches'][0]["coach_type_id"],
        'date_dep': user.my_train['from']['date'],
        'scheme_id': 0
    }
    r = requests.post('http://booking.uz.gov.ua/purchase/coach/', data=data)
    print(r.status_code)
    select_place(user, json.loads(r.text), coaches)

def find_coaches(user):
    data = {
        'station_id_from' : user.st_from_id,
        'station_id_till' : user.st_till_id,
        'train' : user.my_train['num'],
        'coach_type' : user.place_type,
        'model': user.my_train['model'],
        'date_dep': user.my_train['from']['date'],
        'round_trip': 0,
        'another_ec': 0
    }
    r = requests.post('http://booking.uz.gov.ua/purchase/coaches/', data=data)
    print(r.status_code)
    find_coach(user, json.loads(r.text))

def compare_place_type(all_trains_val, search_place, user):
    if search_place:
        for element in all_trains_val:
            for types in element['types']:
                if types['id'] == search_place and element['num'] == '063О':
                    print(types)
                    user.my_train = element
                    return True
    else:
        print(all_trains_val)
        return True
    return False

def find_place(user, all_trains):
    print("Шукаю " + user.place_type + " Осання перевірка - " + datetime.now().strftime("%H:%M:%S"))
    print(all_trains)
    if isinstance(all_trains['value'], str):
        print(all_trains['value'])
        return True
    else:
        if compare_place_type(all_trains['value'], user.place_type, user):
            mixer.init()
            mixer.music.load('vopli_vidopljasova_-_strivaj__parovoze_bonus_(zvukoff.ru).mp3')
            mixer.music.play()
            if user.f_name and user.l_name:
                find_coaches(user)
            return False
        else:
            return True

def get_all_places(user):
    print("=============Шукаю вльні місця============")
    data = {
        'station_id_from': user.st_from_id,
        'station_id_till': user.st_till_id,
        'station_from': user.st_from,
        'station_till': user.st_till,
        'date_dep': user.dep_date.strftime('%d.%m.%Y'),
        'time_dep': user.dep_date.strftime('%H:%M'),
        'time_dep_till': '',
        'another_ec': '',
        'search': ''
    }
    r = requests.post('http://booking.uz.gov.ua/purchase/search/', data=data)
    print(r.status_code)
    return find_place(user, json.loads(r.text))

def get_station_id(name):
    r = requests.get('http://booking.uz.gov.ua/purchase/station/', params={'term': name})
    print(r.status_code)
    print(r.text)
    obj = json.loads(r.text)
    print(obj[0]['value'])
    return obj[0]['value']

def try_find_ticket(my_fild):
    if my_fild.simple_not_empty() == False:
        print("Заповніть пусті рядки")
        return False
    else:
        user = Pasenger(my_fild.station_from.get(), my_fild.station_till.get(), my_fild.dep_date.get(),
                        my_fild.place_type.get())
        user.f_name = my_fild.first_name.get()
        user.l_name = my_fild.last_name.get()
        if get_all_places(user):
            root.after(int(60000 * float(my_fild.r_time.get())), try_find_ticket, my_fild)

class EntryFild:
    def __init__(self):
        self.label = Label(root, text="New Label", font="Arial 48", bg="green")
        self.label.place(relx=0.5, rely=0.5, anchor="center")
        self.r_time = Entry(root, width="5")
        self.r_time.insert(END, 2)
        self.r_time.pack()
        self.station_from = Entry(root, width="40")
        self.station_from.insert(END, "Тернопіль")
        self.station_from.pack()
        self.station_till = Entry(root, width="40")
        self.station_till.insert(END, "Київ")
        self.station_till.pack()
        self.dep_date = Entry(root, width="15")
        self.dep_date.insert(END, datetime.now().strftime("%d.%m.%Y %H:%M"))
        self.dep_date.pack()
        self.place_type = Entry(root, width="5")
        self.place_type.insert(END, "П")
        self.place_type.pack()
        self.first_name = Entry(root, width="40")
        self.first_name.pack()
        self.last_name = Entry(root, width="40")
        self.last_name.pack()
    def simple_not_empty(self):
        if self.station_from.get() and self.station_till.get() and self.dep_date.get():
            return True
        else:
            return False

class FindButton:
    def __init__(self):
        self.but = Button(root)
        self.but['text'] = "Шукати"
        self.but.pack()
        self.but.bind("<Button-1>", self.action_find)
        self.but.bind('<Return>', self.action_find)
    def action_find(self, event):
        try_find_ticket(my_fild)

class Pasenger :
    def __init__(self, st_from, st_till, dep_date, place_type):
        self.st_from_id = get_station_id(st_from)
        self.st_from = st_from
        self.st_till_id = get_station_id(st_till)
        self.st_till = st_till
        self.dep_date = datetime.strptime(dep_date, '%d.%m.%Y %H:%M')
        self.place_type = place_type
        self.f_name = ""
        self.l_name = ""
        self.my_train = {}

s = requests.Session()

root = Tk()
my_fild = EntryFild()
if internet_on():
    my_button = FindButton()
else:
    print('"Інернет си скінчив))"')
root.mainloop()


import numpy as np
import tensorflow as tf
from tensorflow import keras
import cv2

# Paso 1: Preprocesar las imágenes
# Supongamos que tienes un conjunto de datos etiquetado, donde las imágenes y las etiquetas están en dos listas separadas.
# Aquí, cargamos una imagen de ejemplo y la procesamos para que tenga un tamaño fijo y se normalice.

image = cv2.imread(r"C:\Users\Raderly\Documents\TrabajoTerminal\Algoritmos\espora.jpg")  # Reemplaza 'espora.jpg' con la ruta de tu imagen
# Display the image

image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)  # Convertir la imagen a escala de grises

image = cv2.resize(image, (128, 128))  # Redimensionar la imagen a un tamaño fijo (ajusta según tus necesidades)
image = image / 255.0  # Normalizar los valores de píxeles al rango [0, 1]
image = np.expand_dims(image, axis=0)  # Agregar una dimensión para crear un lote (batch)

# Paso 2: Definir el modelo de la red neuronal
model = keras.Sequential([
    keras.layers.Flatten(input_shape=(128, 128)),  # Aplanar la imagen
    keras.layers.Dense(128, activation='relu'),  # Capa oculta con activación ReLU
    keras.layers.Dense(2, activation='softmax')  # Capa de salida con dos neuronas (por ejemplo, "espora" y "no espora")
])

# Paso 3: Compilar el modelo
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# Paso 4: Entrenar el modelo (suponiendo que tengas un conjunto de datos etiquetado)
# X_train contiene tus imágenes de entrenamiento y y_train las etiquetas correspondientes.
# Ajusta estos datos según tu conjunto de datos real.
X_train = image # Ejemplo con una sola imagen de entrenamiento
y_train = np.array([1])  # Suponiendo que 0 representa "espora" y 1 representa "no espora"
#print(X_train.shape)
#print(y_train.shape)

model.fit(X_train, y_train, epochs=10)  # Ajusta el número de épocas según sea necesario

# Paso 5: Hacer predicciones en nuevas imágenes
# Aquí cargamos una nueva imagen (new_image) y hacemos una predicción.
new_image = cv2.imread(r"C:\Users\Raderly\Documents\TrabajoTerminal\Algoritmos\nueva_espora.jpg")  # Reemplaza 'nueva_espora.jpg' con la ruta de tu nueva imagen
new_image = cv2.cvtColor(new_image, cv2.COLOR_BGR2GRAY)
new_image = cv2.resize(new_image, (128, 128))
new_image = new_image / 255.0
new_image = np.expand_dims(new_image, axis=0)

predictions = model.predict(new_image)
predicted_class = np.argmax(predictions)
print(predicted_class)
# La variable 'predicted_class' contendrá la etiqueta predicha (0 para "espora" o 1 para "no espora").


#!/usr/bin/env python

def main() -> None:
    """Entry point for the CLI"""
    from .config import config

    config.update_config("cli")
    from .node_deployer import app

    app()

def debug() -> None:
    """Entry point for the debug CLI"""
    from .config import config

    config.update_config("debug")
    from .node_deployer import app

    # Below, we set the default value of the debug flag
    # for the base function of each command to True
    def unwrap(f):  # Not a closure, just here to avoid polluting the namespace
        if hasattr(f, "__wrapped__"):
            return unwrap(f.__wrapped__)
        else:
            return f

    for c in app.registered_commands:
        f = unwrap(c.callback)
        defaults = list(f.__defaults__)
        defaults[-1] = True
        f.__defaults__ = tuple(defaults)

    app()

if __name__ == "__main__":
    main()


un, deux, trois, quatre, cinq = input().split()
nombres = [un, deux, trois, quatre, cinq] # memb: STR

values_nombres = [int(n) for n in nombres]
in_order = sorted(values_nombres)

stage = nombres
while stage != list(map(str, in_order)):
    for i in range(4):
        if int(stage[i]) > int(stage[i+1]):
            stage[i], stage[i+1] = stage[i+1], stage[i]
            print(*nombres)