#include <chrono>
#include <cstdlib>
#include <ctime>
#include <format>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>

#include <evolab/evolab.hpp>
#include <nlohmann/json.hpp>

using namespace evolab;

// Default values for random TSP instance fallback
namespace {
constexpr int DEFAULT_RANDOM_CITIES = 100;
constexpr double DEFAULT_MAX_COORD = 1000.0;
} // namespace

/// Command-line arguments structure
/// Wraps both the configuration and runtime options
struct CLIConfig {
    std::string instance_file;
    std::string config_file;
    std::string algorithm = "basic";
    std::size_t population = 256;
    std::size_t generations = 1000;
    double crossover_prob = 0.9;
    double mutation_prob = 0.1;
    std::uint64_t seed = 1;
    bool verbose = false;
    std::string output_file;
    bool json_output = false;
    std::string json_file;

    // Runtime warnings for JSON output transparency
    mutable std::vector<std::string> warnings;

    // Track which values were explicitly set via command line
    bool has_population_override = false;
    bool has_generations_override = false;
    bool has_crossover_override = false;
    bool has_mutation_override = false;
    bool has_seed_override = false;

    // Convert CLI overrides to configuration overrides
    config::ConfigOverrides to_overrides() const {
        config::ConfigOverrides overrides;
        // Only set overrides if explicitly provided via command line
        if (has_population_override) {
            overrides.population_size = population;
        }
        if (has_generations_override) {
            overrides.max_generations = generations;
        }
        if (has_crossover_override) {
            overrides.crossover_probability = crossover_prob;
        }
        if (has_mutation_override) {
            overrides.mutation_probability = mutation_prob;
        }
        if (has_seed_override) {
            overrides.seed = seed;
        }
        return overrides;
    }
};

/// Get git commit hash (from CMake build)
std::string get_git_hash() {
#ifdef GIT_HASH
    return GIT_HASH;
#else
    return "unknown";
#endif
}

/// Get hostname (from CMake build)
std::string get_hostname() {
#ifdef BUILD_HOSTNAME
    return BUILD_HOSTNAME;
#else
    return "unknown";
#endif
}

/// Get build configuration info
std::string get_build_config() {
#ifdef NDEBUG
    std::string mode = "Release";
#else
    std::string mode = "Debug";
#endif

#ifdef __clang__
    std::string compiler =
        "Clang " + std::to_string(__clang_major__) + "." + std::to_string(__clang_minor__);
#elif defined(__GNUC__)
    std::string compiler = "GCC " + std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__);
#elif defined(_MSC_VER)
    std::string compiler = "MSVC " + std::to_string(_MSC_VER);
#else
    std::string compiler = "Unknown";
#endif

    return mode + " (" + compiler + ")";
}

/// Print usage information
void print_usage(const char* program_name) {
    std::cout << "Usage: " << program_name << " [OPTIONS]\n\n"
              << "Options:\n"
              << "  -h, --help              Show this help message\n"
              << "  --config FILE           Load configuration from TOML file\n"
              << "  -i, --instance FILE     TSP instance file (random if not specified)\n"
              << "  -a, --algorithm ALGO    Algorithm: basic, advanced, config (default: basic)\n"
              << "  -p, --population SIZE   Population size (default: 256)\n"
              << "  -g, --generations NUM   Max generations (default: 1000)\n"
              << "  -c, --crossover PROB    Crossover probability (default: 0.9)\n"
              << "  -m, --mutation PROB     Mutation probability (default: 0.1)\n"
              << "  -s, --seed SEED         Random seed (default: 1)\n"
              << "  -v, --verbose           Verbose output\n"
              << "  -o, --output FILE       Output file for best tour\n"
              << "  --json                  Enable JSON output format\n"
              << "  --json-file FILE        Write JSON results to file\n"
              << "\nExamples:\n"
              << "  " << program_name << " --config config/basic.toml --instance data/pr76.tsp\n"
              << "  " << program_name << " --algorithm advanced --population 512\n"
              << "  " << program_name << " --verbose --output solution.tour\n"
              << "  " << program_name << " --json --json-file results.json\n";
}

/// Parse command line arguments
CLIConfig parse_args(int argc, char** argv) {
    CLIConfig config;

    for (int i = 1; i < argc; ++i) {
        std::string arg = argv[i];

        if (arg == "-h" || arg == "--help") {
            print_usage(argv[0]);
            std::exit(0);
        } else if (arg == "--config" && i + 1 < argc) {
            config.config_file = argv[++i];
        } else if ((arg == "-i" || arg == "--instance") && i + 1 < argc) {
            config.instance_file = a


// Copyright 2014 BitPay Inc.
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <string.h>
#include <vector>
#include <stdio.h>
#include "univalue.h"
#include "univalue_utffilter.h"

/*
 * According to stackexchange, the original json test suite wanted
 * to limit depth to 22.  Widely-deployed PHP bails at depth 512,
 * so we will follow PHP's lead, which should be more than sufficient
 * (further stackexchange comments indicate depth > 32 rarely occurs).
 */
static const size_t MAX_JSON_DEPTH = 512;

static bool json_isdigit(int ch)
{
    return ((ch >= '0') && (ch <= '9'));
}

// convert hexadecimal string to unsigned integer
static const char *hatoui(const char *first, const char *last,
                          unsigned int& out)
{
    unsigned int result = 0;
    for (; first != last; ++first)
    {
        int digit;
        if (json_isdigit(*first))
            digit = *first - '0';

        else if (*first >= 'a' && *first <= 'f')
            digit = *first - 'a' + 10;

        else if (*first >= 'A' && *first <= 'F')
            digit = *first - 'A' + 10;

        else
            break;

        result = 16 * result + digit;
    }
    out = result;

    return first;
}

enum jtokentype getJsonToken(std::string& tokenVal, unsigned int& consumed,
                            const char *raw, const char *end)
{
    tokenVal.clear();
    consumed = 0;

    const char *rawStart = raw;

    while (raw < end && (json_isspace(*raw)))          // skip whitespace
        raw++;

    if (raw >= end)
        return JTOK_NONE;

    switch (*raw) {

    case '{':
        raw++;
        consumed = (raw - rawStart);
        return JTOK_OBJ_OPEN;
    case '}':
        raw++;
        consumed = (raw - rawStart);
        return JTOK_OBJ_CLOSE;
    case '[':
        raw++;
        consumed = (raw - rawStart);
        return JTOK_ARR_OPEN;
    case ']':
        raw++;
        consumed = (raw - rawStart);
        return JTOK_ARR_CLOSE;

    case ':':
        raw++;
        consumed = (raw - rawStart);
        return JTOK_COLON;
    case ',':
        raw++;
        consumed = (raw - rawStart);
        return JTOK_COMMA;

    case 'n':
    case 't':
    case 'f':
        if (!strncmp(raw, "null", 4)) {
            raw += 4;
            consumed = (raw - rawStart);
            return JTOK_KW_NULL;
        } else if (!strncmp(raw, "true", 4)) {
            raw += 4;
            consumed = (raw - rawStart);
            return JTOK_KW_TRUE;
        } else if (!strncmp(raw, "false", 5)) {
            raw += 5;
            consumed = (raw - rawStart);
            return JTOK_KW_FALSE;
        } else
            return JTOK_ERR;

    case '-':
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9': {
        // part 1: int
        std::string numStr;

        const char *first = raw;

        const char *firstDigit = first;
        if (!json_isdigit(*firstDigit))
            firstDigit++;
        if ((*firstDigit == '0') && json_isdigit(firstDigit[1]))
            return JTOK_ERR;

        numStr += *raw;                       // copy first char
        raw++;

        if ((*first == '-') && (raw < end) && (!json_isdigit(*raw)))
            return JTOK_ERR;

        while (raw < end && json_isdigit(*raw)) {  // copy digits
            numStr += *raw;
            raw++;
        }

        // part 2: frac
        if (raw < end && *raw == '.') {
            numStr += *raw;                   // copy .
            raw++;

            if (raw >= end || !json_isdigit(*raw))
                return JTOK_ERR;
            while (raw < end && json_isdigit(*raw)) { // copy digits
                numStr += *raw;
                raw++;
            }
        }

        // part 3: exp
        if (raw < end && (*raw == 'e' || *raw == 'E')) {
            numStr += *raw;                   // copy E
            raw++;

            if (raw < end && (*raw == '-' || *raw == '+')) { // copy +/-
                numStr += *raw;
                raw++;
            }

            if (raw >= end || !json_isdigit(*raw))
                return JTOK_ERR;
            while (raw < end && json_isdigit(*raw)) { // copy digits
                numStr += *raw;
                raw++;
            }
        }

        tokenVal = numStr;
        consumed = (raw - rawStart);
        return JTOK_NUMBER;
        }

    case '"': {
        raw++;                                // skip "

        std::string valStr;
        JSONUTF8StringFilter writer(valStr);

        while (true) {
            if (raw >= end || (unsigned char)*raw < 0x20)
                return JTOK_ERR;

            else if (*raw == '\\') {
                raw++;                        // skip backslash

                if (raw >= end)
                    return JTOK_ERR;

                switch (*raw) {
                case '"'


#include <numeric>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <random>
#include <queue>

void clearScreen() {
    printf("\033[2J\033[1;1H");
}

void openCell(int r, int c, const std::vector<std::vector<int>>& field,
              std::vector<std::vector<int>>& UI, int n, int m) {
    if (UI[r][c] == 1) return;

    std::queue<std::pair<int,int>> q;
    q.push({r, c});

    while (!q.empty()) {
        auto [x, y] = q.front(); q.pop();
        if (UI[x][y] == 1) continue;
        UI[x][y] = 1;

        if (field[x][y] == 0) {
            for (int dx = -1; dx <= 1; ++dx) {
                for (int dy = -1; dy <= 1; ++dy) {
                    if (dx == 0 && dy == 0) continue;
                    int nx = x + dx, ny = y + dy;
                    if (nx >= 0 && nx < n && ny >= 0 && ny < m && UI[nx][ny] == 0) {
                        q.push({nx, ny});
                    }
                }
            }
        }
    }
}

bool checkWin(const std::vector<std::vector<int>>& field,
              const std::vector<std::vector<int>>& UI, int n, int m, int mine) {
    int opened = 0;
    for (int r = 0; r < n; ++r)
        for (int c = 0; c < m; ++c)
            if (UI[r][c] == 1) ++opened;

    return opened == n * m - mine;
}

void generateMines(std::vector<int>& ground, std::vector<std::vector<int>>& field, int n, int m, int totalMines){
    std::iota(ground.begin(), ground.end(), 0);

    std::random_device rd;
    std::mt19937 g(rd());
    std::shuffle(ground.begin(), ground.end(), g);
    for (int i = 0; i < totalMines; ++i) {
        int r = ground[i] / m;
        int c = ground[i] % m;
        field[r][c] = -1;
    }

    for (int r = 0; r < n; ++r) {
        for (int c = 0; c < m; ++c) {
            if (field[r][c] == -1) {
                for (int dr = -1; dr <= 1; ++dr)
                    for (int dc = -1; dc <= 1; ++dc) {
                        int nr = r + dr, nc = c + dc;
                        if (nr < 0 || nr >= n || nc < 0 || nc >= m) continue;
                        if (field[nr][nc] == -1) continue;
                        field[nr][nc]++;
                    }
            }
        }
    }
}

int main() {
    int n, m, minePercent;
    printf("size(n m) & min percentage(example: 10 10 10): ");
    scanf("%d %d %d", &n, &m, &minePercent);

    if(n <= 0 || m <= 0 || minePercent <= 0 || minePercent > 100) {
        printf("bad size or min percentage");
        return 1;
    }

    int totalMines = n * m * minePercent / 100;

    std::vector<int> ground(n*m);
    std::vector<std::vector<int>> field(n, std::vector<int>(m, 0));

    generateMines(ground, field, n, m, totalMines);

    std::vector<std::vector<int>> UI(n, std::vector<int>(m, 0));
    bool boom = false;

    while (!boom) {
        clearScreen();
        printf("   ");
        for (int c = 0; c < m; ++c)
            printf("%3d ", c);
        printf("\n");

        for (int r = 0; r < n; ++r) {
            printf("%2d ", r);
            for (int c = 0; c < m; ++c) {
                if (UI[r][c] == 1) {
                    if (field[r][c] == 0) {
                            printf("[0] ");
                        continue;
                    }
                    printf("[\033[32m%d\033[0m] ", field[r][c]);
                } else {
                    printf("[\033[34mX\033[0m] ");
                }
            }
            printf("\n");
        }

        int x, y;
        printf("Coordinate(example: 2 1): ");
        scanf("%d %d", &x, &y);

        if (x < 0 || x >= n || y < 0 || y >= m) continue;

        if (field[x][y] == -1) {
            boom = true;
        } else {
            openCell(x, y, field, UI, n, m);
            if (checkWin(field, UI, n, m, totalMines)) break;
        }
    }

    clearScreen();
    printf("   ");
    for (int c = 0; c < m; ++c)
        printf("%3d ", c);
    printf("\n");

    for (int r = 0; r < n; ++r) {
        printf("%2d ", r);
        for (int c = 0; c < m; ++c) {
            if (field[r][c] == -1) printf("[\033[31m*\033[0m] ");
            else printf("[\033[32m%d\033[0m] ", field[r][c]);
        }
        printf("\n");
    }

    if (boom) printf("You lose.\n");
    else printf("You win!\n");
    system("pause");
    return 0;
}


#include "serial_Transmit_worker.h"

// 构造函数
SerialTransmitWorker::SerialTransmitWorker(QSerialPort *sharedSerial,QObject *parent)
    : QThread(parent), serial(sharedSerial)
{
}

// 析构函数
SerialTransmitWorker::~SerialTransmitWorker()
{
    quit();
    wait();
    //terminate();//强制关闭线程
}

// 线程运行函数，负责接收数据
void SerialTransmitWorker::run()
{
    exec(); // 进入事件循环
}

//更新控制参数
void SerialTransmitWorker::updateTransValues(int8_t WorkMode,int8_t tx, int8_t ty, int8_t tz, int8_t tphi, int8_t ttheta, int8_t tpsi, float depth, float yaw)
{
    QMutexLocker locker(&mutex);// 更新控制参数（确保线程安全）
    currentWorkMode = WorkMode;
    taw_x = tx;
    taw_y = ty;
    taw_z = tz;
    taw_phi = tphi;
    taw_theta = ttheta;
    taw_psi = tpsi;
    Depth_d = depth;
    Yaw_d = yaw;
}

void SerialTransmitWorker::updateTransValues2(int8_t WorkMode, float p1, float p2, float p3, float p4, float p5, float p6)
{
    QMutexLocker locker(&mutex);// 更新控制参数（确保线程安全）
    currentWorkMode = WorkMode;
    pos1 = p1;
    pos2 = p2;
    pos3 = p3;
    pos4 = p4;
    pos5 = p5;
    pos6 = p6;

    //qDebug()<<pos1<<pos2<<pos3<<pos4<<pos5<<pos6;
}

//发送数据，使用协议封装
void SerialTransmitWorker::sendSerialData()
{
    QMutexLocker locker(&mutex); // 加锁，保证线程安全
    if (!serial || !serial->isOpen()) return;

    QByteArray packet;

    switch(currentWorkMode)
    {
    case 1:
    case 2:
    case 3:
    case 4:
        //currentWorkMode=0x01;
        packet.append(0xFE); // 包头
        packet.append(currentWorkMode);
        packet.append(taw_x);
        packet.append(taw_y);
        packet.append(taw_z);
        packet.append(taw_phi);
        packet.append(taw_theta);
        packet.append(taw_psi);

        appendFloat(packet,Depth_d);//使用函数占4位
        appendFloat(packet,Yaw_d);
        packet.append(0xFF); // 包尾
        break;
    case 5://全自主模式
        currentWorkMode=0x05;
        packet.append(0xFE); // 包头
        packet.append(currentWorkMode);

        appendFloat(packet,pos1);
        appendFloat(packet,pos2);
        appendFloat(packet,pos3);
        appendFloat(packet,pos4);
        appendFloat(packet,pos5);
        appendFloat(packet,pos6);//使用函数占4位

        packet.append(0xFF); // 包尾
        break;
    default:
        break;
    }
    serial->write(packet); // 发送数据
    QString hexData = packet.toHex(' ').toUpper();  // 字节间用空格分隔
    QString timestamp = QDateTime::currentDateTime().toString("[hh:mm:ss.zzz] ");
    TransmitView = timestamp + hexData;
    emit transmitViewUpdated(TransmitView);  // 发送发送预览更新信号
    //qDebug()<<TransmitView;
}

void SerialTransmitWorker::appendFloat(QByteArray &packet, float value)//使得float变量在Array中占4个字节
{
    char bytes[4];
    memcpy(bytes, &value, sizeof(float)); // 拷贝4字节内存
    packet.append(bytes[0]);  // 按系统字节序追加
    packet.append(bytes[1]);
    packet.append(bytes[2]);
    packet.append(bytes[3]);
}


#include <iostream>
#include <cmath>
#include <iomanip>
#include <fstream>
#include <map>
#include <vector>
using namespace std;
const double exact_value = -0.0705436323534222;
const double second_derivative_f = 1.27;
const int p = 2;
int f_call_count = 0;

double f(double x) {
    f_call_count++;
    return sin(2 * x) / (1 + x);
}

double trapezoid(int N, double a, double b) {
    double h = (b - a) / N;
    double sum = 0.5 * (f(a) + f(b));
    for (int i = 1; i < N; ++i) {
        sum += f(a + i * h);
    }
    return h * sum;
}

double rectangle(int N, double a, double b) {
    double h = (b - a) / N;
    double sum = 0.0;
    for (int i = 1; i <= N; ++i) {
        double xi = a + i * h;
        sum += f(xi - h / 2.0);
    }
    return h * sum;
}

int runge(double epsilon, double& result, double& error, double a, double b, int& total_f_calls) {
    int N = 10;
    double h = (b - a) / N;
    double Q_N = 0.5 * (f(a) + f(b));
    for (int k = 1; k < N; ++k) {
        Q_N += f(a + k * h);
    }
    Q_N *= h;

    while (true) {
        double sum_new = 0.0;
        for (int k = 1; k <= N; ++k) {
            sum_new += f(a + (2 * k - 1) * h / 2.0);
        }

        double Q_2N = 0.5 * Q_N + h / 2.0 * sum_new;

        double R = fabs(Q_2N - Q_N) / (pow(2, p) - 1);
        //double R = (Q_2N - Q_N) * pow((h / 2), 2) / (pow((h), 2) - pow((h / 2), 2));

        if (R <= epsilon) {
            result = Q_2N;
            error = fabs(result - exact_value);
            total_f_calls = f_call_count;
            return 2 * N;
        }

        Q_N = Q_2N;
        h = h / 2.0;
        N *= 2;
    }
}

double amount_N_f_trapezoid(double error, double a, double b) {
    double n_f = ceil(sqrt(pow((b - a),3)/ 12 * second_derivative_f * pow(error, -1)));
    return n_f +1;
}

double amount_N_f_rectangle(double error, double a, double b) {
    double n_f = ceil(sqrt(pow((b - a), 3) / 24 * second_derivative_f * pow(error, -1)));
    return n_f;
}

int main() {
    double a = 1.0, b = 10.0;

    cout << fixed << setprecision(16);
    ofstream trapezoidal_file("trapezoidal_results.txt");
    ofstream rectangle_file("rectangle_results.txt");
    ofstream runge_file("runge.txt");

    trapezoidal_file << "N, Error" << endl;
    rectangle_file << "N, Error" << endl;
    runge_file << "N, Error" << endl;

    for (int k = 1; k <= 10; ++k) {
        int N = pow(10, k);

        cout <<"N_f trapezoid: " << amount_N_f_trapezoid(pow(10, -7), a, b) << endl;
        cout << "N_f rectangle: " << amount_N_f_rectangle(pow(10, -7), a, b) << endl;
        f_call_count = 0;
        double approx_trapezoid = trapezoid(N, a, b);
        double error_trapezoid = fabs(exact_value - approx_trapezoid);
        trapezoidal_file << f_call_count << ", " << error_trapezoid << endl;
        cout << "N tr = " << f_call_count << endl;
        cout << "  Trapezoid: " << approx_trapezoid << ", error = " << error_trapezoid << endl;
        f_call_count = 0;
        double approx_rectangle = rectangle(N, a, b);
        double error_rectangle = fabs(exact_value - approx_rectangle);
        rectangle_file << f_call_count << ", " << error_rectangle << endl;

        double epsilon = pow(10, -k);
        double result_runge, error_runge;
        int n_f;
        int N_runge = runge(epsilon, result_runge, error_runge, a, b, n_f);
        runge_file << n_f << ", " << error_runge << endl;
        cout << n_f << endl;
        cout << "N re = " << f_call_count << endl;
        cout << "  Trapezoid: " << approx_trapezoid << ", error = " << error_trapezoid << endl;
        cout << "  Rectangle: " << approx_rectangle << ", error = " << error_rectangle << endl;
        cout << "---------------------------------------------------------------" << endl;
    }

    trapezoidal_file.close();
    rectangle_file.close();
    return 0;
}


#include "Shader.hpp"
#include <Util/MessageBox.hpp>
#include <glm/gtc/type_ptr.hpp>

GLShader::GLShader() : id(0)
{
}

GLShader::~GLShader()
{
    if (id) glDeleteProgram(id);
}

bool GLShader::compile(const char* vertexCode, const char* fragmentCode)
{
    /* Compile shaders */
    GLint success;
    GLchar infoLog[512];

    /* Compile vertex shader */
    GLuint vertexShader;
    vertexShader = glCreateShader(GL_VERTEX_SHADER);

    glShaderSource(vertexShader, 1, &vertexCode, NULL);
    glCompileShader(vertexShader);
    glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
    if (!success)
    {
        glGetShaderInfoLog(vertexShader, 512, nullptr, infoLog);
        std::string errorLog(infoLog);
        errorLog = "Failed to compile vertex shader: " + errorLog;
        MSG_ERROR("Shader compilation error", errorLog.c_str());
        return false;
    }

    /* Compile fragment shader */
    GLuint fragmentShader;
    fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);

    glShaderSource(fragmentShader, 1, &fragmentCode, NULL);
    glCompileShader(fragmentShader);
    glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
    if (!success)
    {
        glGetShaderInfoLog(fragmentShader, 512, nullptr, infoLog);
        std::string errorLog(infoLog);
        errorLog = "Failed to compile fragment shader: " + errorLog;
        MSG_ERROR("Shader compilation error", errorLog.c_str());
        return false;
    }

    /* Link shaders into a program */
    GLuint shaderProgram;
    shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glLinkProgram(shaderProgram);
    glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
    if (!success) {
        glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
        std::string errorLog(infoLog);
        errorLog = "Failed to link shader program: " + errorLog;
        MSG_ERROR("Shader compilation error", errorLog.c_str());
        return false;
    }

    // delete compiled shaders
    glDeleteShader(vertexShader);
    glDeleteShader(fragmentShader);

    id = shaderProgram;
    return true;
}

void GLShader::use()
{
    glUseProgram(id);
}

void GLShader::uniformMatrix4fv(std::string name, glm::mat4 matrix)
{
    GLuint location = glGetUniformLocation(id, name.c_str());
    glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(matrix));
}


#include <arpa/inet.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

#define BROADCAST_IP "192.168.4.255"
#define LIFX_PORT 56700

#pragma pack(push, 1)
typedef struct {
  uint16_t size;
  uint16_t protocol : 12;
  uint16_t addressable : 1;
  uint16_t tagged : 1;
  uint16_t origin : 2;
  uint32_t source;

  uint8_t target[8];
  uint8_t reserved[6];
  uint8_t res_required : 1;
  uint8_t ack_required : 1;
  uint8_t : 6;
  uint8_t sequence;

  uint64_t at_time;
  uint16_t type;
  uint16_t reserved2;
} lifx_header_t;

typedef struct {
  lifx_header_t header;
  uint16_t level;
  uint32_t duration;
} lifx_set_power_t;

typedef struct {
  lifx_header_t header;
  uint8_t reserved;
  uint16_t hue;
  uint16_t saturation;
  uint16_t brightness;
  uint16_t kelvin;
  uint32_t duration;
} lifx_set_color_t;

typedef struct {
  lifx_header_t header;
  uint8_t reserved6;
  uint8_t transient;
  uint16_t hue;
  uint16_t saturation;
  uint16_t brightness;
  uint16_t kelvin;
  uint32_t period;
  float cycles;
  int16_t skew_ratio;
  uint8_t waveform;
} lifx_set_waveform_t;

#pragma pack(pop)

int lifx_socket = 0;
struct sockaddr_in lifx_addr;

void send_lifx_pkt(void *pkt, int size) {
  sendto(lifx_socket, pkt, size, 0, (struct sockaddr *)&lifx_addr,
         sizeof(lifx_addr));
}

void send_lifx_set_color(uint16_t hue, uint16_t saturation,
                         uint16_t brightness) {
  lifx_set_color_t pkt;
  memset(&pkt, 0, sizeof(pkt));

  pkt.header.size = sizeof(pkt);
  pkt.header.protocol = 1024;
  pkt.header.addressable = 1;
  pkt.header.tagged = 0;
  pkt.header.origin = 0;
  pkt.header.source = 0x12345678;
  memset(pkt.header.target, 0, sizeof(pkt.header.target)); // use MAC if known
  pkt.header.sequence = 1;
  pkt.header.type = 102;

  pkt.reserved = 0;
  pkt.hue = hue;
  pkt.saturation = saturation;
  pkt.brightness = brightness;
  pkt.kelvin = 3500;
  pkt.duration = 500;

  send_lifx_pkt(&pkt, sizeof(pkt));
}

void send_lifx_set_waveform(uint16_t hue, uint16_t saturation,
                            uint16_t brightness) {
  lifx_set_waveform_t pkt;
  memset(&pkt, 0, sizeof(pkt));

  pkt.header.size = sizeof(pkt);
  pkt.header.protocol = 1024;
  pkt.header.addressable = 1;
  pkt.header.tagged = 0;
  pkt.header.origin = 0;
  pkt.header.source = 0x12345678;
  memset(pkt.header.target, 0, sizeof(pkt.header.target));
  pkt.header.res_required = 0;
  pkt.header.ack_required = 0;
  pkt.header.sequence = 1;
  pkt.header.at_time = 0;
  pkt.header.type = 103;

  pkt.reserved6 = 0;
  pkt.transient = 1;
  pkt.hue = hue;
  pkt.saturation = saturation;
  pkt.brightness = brightness;
  pkt.kelvin = 4000;
  pkt.period = 5000;
  pkt.cycles = 65535.0f;
  pkt.skew_ratio = 0;
  pkt.waveform = 1;

  send_lifx_pkt(&pkt, sizeof(pkt));
}

void send_lifx_set_power(int on) {
  lifx_set_power_t pkt;
  memset(&pkt, 0, sizeof(pkt));

  pkt.header.size = sizeof(pkt);
  pkt.header.protocol = 1024;
  pkt.header.addressable = 1;
  pkt.header.tagged = 0;
  pkt.header.origin = 0;
  pkt.header.source = 0x12345678;
  memset(pkt.header.target, 0, sizeof(pkt.header.target));
  pkt.header.res_required = 0;
  pkt.header.ack_required = 0;
  pkt.header.sequence = 1;
  pkt.header.at_time = 0;
  pkt.header.type = 21;
  pkt.level = on ? 65535 : 0;
  pkt.duration = 5000;

  send_lifx_pkt(&pkt, sizeof(pkt));
}

void reflect_lifx() {
  lifx_addr.sin_family = AF_INET;
  lifx_addr.sin_port = htons(LIFX_PORT);
  lifx_socket = socket(AF_INET, SOCK_DGRAM, 0);
  if (lifx_socket < 0) {
    return;
  }

  int broadcast = 1;
  if (setsockopt(lifx_socket, SOL_SOCKET, SO_BROADCAST, &broadcast,
                 sizeof(broadcast)) < 0) {
    return;
  }

  inet_pton(AF_INET, BROADCAST_IP, &lifx_addr.sin_addr);
}


#include "internal/MarketDataFeedHandler.h"
#include <iostream>
#include <stdexcept>

MarketDataFeedHandler::MarketDataFeedHandler()
    : curl_(nullptr)
    , baseUrl_("https://api.elections.kalshi.com/trade-api/v2/markets/")
    , timeout_(30)
    , userAgent_("Kalshi-Orderbook-Client/1.0")
    , initialized_(false) {
}

MarketDataFeedHandler::~MarketDataFeedHandler() {
    cleanup();
}

bool MarketDataFeedHandler::initialize() {
    if (initialized_) {
        return true;
    }

    CURLcode globalResult = curl_global_init(CURL_GLOBAL_DEFAULT);
    if (globalResult != CURLE_OK) {
        lastError_ = "Failed to initialize curl globally: " + std::string(curl_easy_strerror(globalResult));
        return false;
    }

    curl_ = curl_easy_init();
    if (!curl_) {
        lastError_ = "Failed to initialize curl handle";
        curl_global_cleanup();
        return false;
    }

    curl_easy_setopt(curl_, CURLOPT_TIMEOUT, timeout_);
    curl_easy_setopt(curl_, CURLOPT_FOLLOWLOCATION, 1L);
    curl_easy_setopt(curl_, CURLOPT_USERAGENT, userAgent_.c_str());
    curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYPEER, 1L);
    curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYHOST, 2L);

    initialized_ = true;
    lastError_.clear();
    return true;
}

void MarketDataFeedHandler::cleanup() {
    if (curl_) {
        curl_easy_cleanup(curl_);
        curl_ = nullptr;
    }

    if (initialized_) {
        curl_global_cleanup();
        initialized_ = false;
    }
}

json MarketDataFeedHandler::fetchOrderbookData(const std::string& ticker) {
    if (!initialized_ && !initialize()) {
        throw std::runtime_error("Failed to initialize MarketDataFeedHandler: " + lastError_);
    }

    std::string url = buildOrderbookUrl(ticker);
    APIResponse response;

    if (!performHttpRequest(url, response)) {
        throw std::runtime_error("HTTP request failed: " + lastError_);
    }

    if (response.responseCode != 200) {
        throw std::runtime_error("HTTP request failed with code: " + std::to_string(response.responseCode));
    }

    try {
        return json::parse(response.data);
    } catch (const json::parse_error& e) {
        throw std::runtime_error("Failed to parse JSON response: " + std::string(e.what()));
    }
}

bool MarketDataFeedHandler::populateOrderbook(Orderbook& orderbook, const std::string& ticker) {
    try {
        json marketData = fetchOrderbookData(ticker);

        if (!marketData.contains("orderbook")) {
            lastError_ = "Invalid response: missing orderbook data";
            return false;
        }

        json orderbookData = marketData["orderbook"];
        OrderId currentOrderId = 1;

        return parseAndAddOrders(orderbookData, orderbook, currentOrderId);

    } catch (const std::exception& e) {
        lastError_ = std::string(e.what());
        return false;
    }
}

bool MarketDataFeedHandler::getOrderbookLevelInfos(const std::string& ticker, OrderbookLevelInfos& levelInfos) {
    try {
        json marketData = fetchOrderbookData(ticker);

        if (!marketData.contains("orderbook")) {
            lastError_ = "Invalid response: missing orderbook data";
            return false;
        }

        json orderbookData = marketData["orderbook"];
        LevelInfos bids, asks;

        if (parseIntoLevelInfos(orderbookData, bids, asks)) {
            levelInfos = OrderbookLevelInfos(bids, asks);
            return true;
        }

        return false;

    } catch (const std::exception& e) {
        lastError_ = std::string(e.what());
        return false;
    }
}

void MarketDataFeedHandler::setApiEndpoint(const std::string& endpoint) {
    baseUrl_ = endpoint;
}

void MarketDataFeedHandler::setTimeout(long timeoutSeconds) {
    timeout_ = timeoutSeconds;
    if (curl_) {
        curl_easy_setopt(curl_, CURLOPT_TIMEOUT, timeout_);
    }
}

void MarketDataFeedHandler::setUserAgent(const std::string& userAgent) {
    userAgent_ = userAgent;
    if (curl_) {
        curl_easy_setopt(curl_, CURLOPT_USERAGENT, userAgent_.c_str());
    }
}

std::string MarketDataFeedHandler::getLastError() const {
    return lastError_;
}

bool MarketDataFeedHandler::hasError() const {
    return !lastError_.empty();
}

size_t MarketDataFeedHandler::writeCallback(void* contents, size_t size, size_t nmemb, APIResponse* response) {
    size_t totalSize = size * nmemb;
    if (response) {
        response->data.append(static_cast<char*>(contents), totalSize);
    }
    return totalSize;
}

bool MarketDataFeedHandler::performHttpRequest(const std::string& url, APIResponse& response) {
    if (!curl_) {
        lastError_ = "Curl handle not initialized";
        return false;
    }

    response.data.clear();
    response.responseCode = 0;

    curl_easy_setopt(curl_, CURLOPT_URL, url.c_str());
    curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, writeCallback);
    curl_easy_setopt(curl_, CURLOPT_WRITEDATA, &response);

    CURLcode resul


#include <bits/stdc++.h>

using namespace std;
vector<int> findRedundantDirectedConnection(vector<vector<int>>& edges) {
     vector<int> Unio;
    reverse(edges.begin(),edges.end());
    Unio.push_back(edges[edges.size()-1][0]);
    Unio.push_back(edges[edges.size()-1][1]);
    edges.pop_back();
    int size = edges.size() - 1;
    while (true)
    {
        int size1= edges.size()-1;
        int i,j;
        i = edges[size][0];
        j = edges[size][1];
        bool checker = false;
        if (i == edges[0][0] && j == edges[0][1])
        {
           checker = true;
        }
        if (find(Unio.begin(),Unio.end(),j)== Unio.end())
        {
            Unio.push_back(j);
            if (size > 0)
            {
                size--;
                edges.erase(edges.begin() + size);
            }else
            {
                edges.erase(edges.begin());
            }
        }
     if (checker == true)
     {
        break;
     }
        int size2=edges.size()-1;
     if (size1 == size2)
     {
         size--;
     }
    }
    return edges[0];
}
int main()
{
    return 0;
}


#include <Arduino.h>
#include <WiFi.h>

TaskHandle_t connectToWiFi_handle = NULL;

const char *ssid = "RAX3000M"; // Should be 2.4GHz WiFi
const char *password = "********";
const int timeoutMs = 10000; // Connection timeout in milliseconds

void connectToWiFiTask(void *params)
{
  for (;;)
  {
    WiFi.begin(ssid, password);
    Serial.printf("Connecting to WiFi: %s\n", ssid);

    unsigned long startAttemptTime = millis();
    while (WiFi.status() != WL_CONNECTED && millis() - startAttemptTime < timeoutMs)
    {
      neopixelWrite(RGB_BUILTIN, RGB_BRIGHTNESS, 0, 0);
      vTaskDelay(100 / portTICK_PERIOD_MS);
      neopixelWrite(RGB_BUILTIN, 0, 0, 0);
      vTaskDelay(100 / portTICK_PERIOD_MS);
    }

    if (WiFi.status() == WL_CONNECTED)
    {
      neopixelWrite(RGB_BUILTIN, 0, RGB_BRIGHTNESS, 0);
      Serial.println("Connected!");
      Serial.println(WiFi.localIP());

      // Keep checking the connection status
      while (WiFi.status() == WL_CONNECTED)
      {
        vTaskDelay(1000 / portTICK_PERIOD_MS);
      }
    }
    else
    {
      Serial.println("WiFi connection failed, attempting to reconnect...");
    }
  }
}
void setup()
{
  Serial.begin(9600);
  Serial.println();

  WiFi.mode(WIFI_STA); // Set WiFi to station mode

  xTaskCreate(connectToWiFiTask, "Connect to WiFi", 4096, NULL, 1, &connectToWiFi_handle);
}

void loop()
{
}


#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;

// Function to solve Two Sum
vector<int> twoSum(vector<int>& nums, int target) {
    unordered_map<int, int> seen; // stores value -> index
    for (int i = 0; i < nums.size(); i++) {
        int complement = target - nums[i];
        if (seen.find(complement) != seen.end()) {
            return {seen[complement], i};
        }
        seen[nums[i]] = i;
    }
    return {}; // problem guarantees one solution
}

int main() {
    // Example 1
    vector<int> nums1 = {2, 7, 11, 15};
    int target1 = 9;
    vector<int> ans1 = twoSum(nums1, target1);
    cout << "[" << ans1[0] << ", " << ans1[1] << "]" << endl;

    // Example 2
    vector<int> nums2 = {3, 2, 4};
    int target2 = 6;
    vector<int> ans2 = twoSum(nums2, target2);
    cout << "[" << ans2[0] << ", " << ans2[1] << "]" << endl;

    // Example 3
    vector<int> nums3 = {3, 3};
    int target3 = 6;
    vector<int> ans3 = twoSum(nums3, target3);
    cout << "[" << ans3[0] << ", " << ans3[1] << "]" << endl;

    return 0;
}


#include<iostream>
#include<string>
#include<vector>
using namespace std;

class Point {
private:
   string pname;
   int x, y;
public:
   Point(string pname = NULL, int x = 0, int y = 0) {
      this->pname = pname;
      this->x = x;
      this->y = y;
   }

   void setName(string str) {
      this->pname = str;
   }

   void setX(int x) {
      this->x = x;
   }

   void setY(int y) {
      this->y = y;
   }

   string getName() {
      return pname;
   }

   int getX() {
      return x;
   }

   int getY() {
      return y;
   }
};

int main() {
   int N;
   cout << "Number of points: ";
   cin >> N;
   vector<Point> v;
   for (int i{ 0 }; i < N; i++) {
      cin.ignore(100, '\n');
      string str;
      int x, y;
      cout << "Name of a point: ";
      getline(cin, str);
      cout << "Position of a point: ";
      cin >> x >> y;
      Point p = Point(str, x, y);
      p.setName(str);
      p.setX(x);
      p.setY(y);
      v.push_back(p);
      cout << p.getName() << " (" << p.getX() << ", " << p.getY() << ")\n\n";
   }
   cout << fixed;
   cout.precision(1);
   int finalX = 0, finalY = 0;
   for (int i{ 0 }; i < N; i++) {
      finalX += v[i].getX();
      finalY += v[i].getY();
   }
   cout << "Center of " << N << " points: (" << (double)finalX / N << ", " << (double)finalY / N << ")";
}


// fastmelee_gui.cpp
// C++17, FastMelee GUI для L4D2 з фоном і вибором методу вводу

#include <windows.h>
#include <thread>
#include <atomic>
#include <string>
#include <chrono>
#include <gdiplus.h>
#pragma comment(lib, "gdiplus.lib")

using namespace Gdiplus;

std::atomic<bool> running(false);
std::atomic<int> slot_mode(1); // 1, 4, 5
std::atomic<int> delay_before_mouse1(450);
std::atomic<int> mouse1_duration(500);
std::atomic<int> delay_before_melee(60);

enum InputMethod { SENDINPUT, KEYBD_EVENT, POSTMESSAGE };
std::atomic<InputMethod> input_method(SENDINPUT);

HWND hSlotCombo, hDelay1Edit, hDurationEdit, hDelay2Edit, hMethodCombo;
HBITMAP hBackground = nullptr;

// Відправка клавіші з вибраним методом
void send_key(WORD vk, WORD sc) {
    switch (input_method.load()) {
    case SENDINPUT: {
        INPUT input[2] = {};
        input[0].type = INPUT_KEYBOARD;
        input[0].ki.wVk = 0;
        input[0].ki.wScan = sc;
        input[0].ki.dwFlags = KEYEVENTF_SCANCODE;
        input[1] = input[0];
        input[1].ki.dwFlags |= KEYEVENTF_KEYUP;
        SendInput(2, input, sizeof(INPUT));
        break;
    }
    case KEYBD_EVENT:
        keybd_event(static_cast<BYTE>(vk), 0, 0, 0);
        std::this_thread::sleep_for(std::chrono::milliseconds(30));
        keybd_event(static_cast<BYTE>(vk), 0, KEYEVENTF_KEYUP, 0);
        break;
    case POSTMESSAGE:
        HWND fg = GetForegroundWindow();
        PostMessage(fg, WM_KEYDOWN, static_cast<WPARAM>(vk), 0);
        std::this_thread::sleep_for(std::chrono::milliseconds(30));
        PostMessage(fg, WM_KEYUP, static_cast<WPARAM>(vk), 0);
        break;
    }
    std::this_thread::sleep_for(std::chrono::milliseconds(30));
}

// Клік Mouse1
void send_mouse1() {
    INPUT input[2] = {};
    input[0].type = INPUT_MOUSE;
    input[0].mi.dwFlags = MOUSEEVENTF_LEFTDOWN;
    input[1].type = INPUT_MOUSE;
    input[1].mi.dwFlags = MOUSEEVENTF_LEFTUP;
    SendInput(2, input, sizeof(INPUT));
    std::this_thread::sleep_for(std::chrono::milliseconds(mouse1_duration.load()));
}

// Основний цикл
void fastmelee_loop() {
    while (running) {
        send_key('2', 0x03); // Slot 2
        std::this_thread::sleep_for(std::chrono::milliseconds(delay_before_mouse1.load()));
        send_mouse1();
        std::this_thread::sleep_for(std::chrono::milliseconds(delay_before_melee.load()));
        switch (slot_mode.load()) {
        case 1: send_key('1', 0x02); break;
        case 4: send_key('4', 0x05); break;
        case 5: send_key('5', 0x06); break;
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(60));
    }
}

// Потік для Mouse5
DWORD WINAPI hotkey_thread(LPVOID) {
    bool prev_mouse5 = false;
    while (true) {
        SHORT mouse5 = GetAsyncKeyState(VK_XBUTTON2);
        bool pressed = (mouse5 & 0x8000);
        if (pressed && !prev_mouse5) {
            running = true;
            std::thread(fastmelee_loop).detach();
        }
        if (!pressed && prev_mouse5) {
            running = false;
        }
        prev_mouse5 = pressed;
        std::this_thread::sleep_for(std::chrono::milliseconds(20));
    }
    return 0;
}

// Зчитування GUI
void read_gui_values() {
    wchar_t buf[16];
    GetWindowTextW(hDelay1Edit, buf, 16);
    delay_before_mouse1 = _wtoi(buf);
    GetWindowTextW(hDurationEdit, buf, 16);
    mouse1_duration = _wtoi(buf);
    GetWindowTextW(hDelay2Edit, buf, 16);
    delay_before_melee = _wtoi(buf);
    int sel = SendMessage(hSlotCombo, CB_GETCURSEL, 0, 0);
    slot_mode = (sel == 0) ? 1 : (sel == 1) ? 4 : 5;
    int method = SendMessage(hMethodCombo, CB_GETCURSEL, 0, 0);
    input_method = (method == 0) ? SENDINPUT : (method == 1) ? KEYBD_EVENT : POSTMESSAGE;
}

// Малювання фону
void draw_background(HWND hwnd, HDC hdc) {
    if (!hBackground) return;
    HDC memDC = CreateCompatibleDC(hdc);
    SelectObject(memDC, hBackground);
    BITMAP bmp;
    GetObject(hBackground, sizeof(BITMAP), &bmp);
    RECT rc;
    GetClientRect(hwnd, &rc);
    StretchBlt(hdc, 0, 0, rc.right, rc.bottom, memDC, 0, 0, bmp.bmWidth, bmp.bmHeight, SRCCOPY);
    DeleteDC(memDC);
}

// Завантаження JPEG
HBITMAP LoadJPEG(const wchar_t* path) {
    GdiplusStartupInput gdiplusStartupInput;
    ULONG_PTR gdiplusToken;
    GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, nullptr);
    Bitmap* bmp = Bitmap::FromFile(path, FALSE);
    HBITMAP hBmp;
    bmp->GetHBITMAP(Color::White, &hBmp);
    delete bmp;
    GdiplusShutdown(gdiplusToken);
    return hBmp;
}

// Callback
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
    switch (uMsg) {
    case WM_PAINT: {
        PAINTSTRUCT ps;
        HDC hdc = BeginPaint(hwnd, &ps);
        draw_background(hwnd, hdc);
        EndPaint(hwnd, &ps);
        return 0;
    }
    case WM_COMMAND:
        read_gui_values();
        return 0;


#include <windows.h>
#include <math.h>

//#define _LIGHT_CPP_
#include "graph.h"
#include "d3d.h"
#include "drawd3d.h"
//#include "light.h"

extern SDeviceList _dL;
extern IDirect3DDevice2       *_d3dDevice;

//extern "C" SGRPolygon _gr_polygon;

#define I65536 (0.00001525878906)

#define COPY_FLOAT(a,b) *((int*)&(a)) = *((int*)&(b))
#define SET_FLOAT_ZERO(a) *((int*)&(a)) = 0
#define FLOAT_NEG(a,b) *((int*)&(a)) = (*((int*)&(b)) ^ 0x80000000)
#define FLOAT_CHANGE_SIGN(f) (*((int*)&(f)) ^= 0x80000000)

#define ARROW_MAX_SECTORS 128

#define POINTER_R0 0.15
#define POINTER_R1 0.6

extern "C" void GRLUDrawArrow(int *points, int numPoint, float r0, float r1,
                              unsigned long color)
{ int i,j;
  float sumLen = 0, len = 0;
  float arrowT[ARROW_MAX_SECTORS][4];  //dx,dy,len,1/len
  float w,dx,dy;
  float xl0,yl0,xr0,yr0;
  float xl1,yl1,xr1,yr1;
  float xl2,yl2,xr2,yr2;
  float xl3,yl3,xr3,yr3;

  GRSetZPrecision(0);
  //GRZBufferEnable(0);

  _gr_polygon.dwFullType = GR_POLY_FLAT;
  _gr_polygon.dwAddType = 0;
  _gr_polygon.nVertices = 4;
  _gr_polygon.dwColor.color = color;
  _gr_polygon.nLights = 0;

  for(i = 0,j = 0;i < (numPoint - 1)*2;i += 2,j++) {
     arrowT[j][0] = points[i+2]-points[i+0];
     arrowT[j][1] = points[i+3]-points[i+1];
     arrowT[j][2] = sqrt(arrowT[j][0]*arrowT[j][0] + arrowT[j][1]*arrowT[j][1]);

     points[i+0] -= _gr_nScreenOriginX;
     points[i+1] -= _gr_nScreenOriginY;

     arrowT[j][3] = 1.0 / arrowT[j][2];

     sumLen += arrowT[j][2];
  }

  points[i+0] -= _gr_nScreenOriginX;
  points[i+1] -= _gr_nScreenOriginY;

  sumLen = (r1-r0) / sumLen;

  //start
  w   = (sumLen*len + r0) * arrowT[0][3];
  len += arrowT[0][2];
  dx  = arrowT[0][1] * w;
  dy  = arrowT[0][0] * w;
  xl0 = points[0] + dx;
  yl0 = points[1] - dy;
  xr0 = points[0] - dx;
  yr0 = points[1] + dy;
  //end
  w   = (sumLen*len + r0) * arrowT[0][3];
  dx  = arrowT[0][1] * w;
  dy  = arrowT[0][0] * w;
  xl1 = points[2] + dx;
  yl1 = points[3] - dy;
  xr1 = points[2] - dx;
  yr1 = points[3] + dy;

  //draw Arrow
  for(i = 1,j = 2;i < numPoint - 1;i++,j += 2) {
     w = (sumLen*len + r0) * arrowT[i][3];
     len += arrowT[i][2];
     dx  = arrowT[i][1] * w;
     dy  = arrowT[i][0] * w;
     xl2 = points[j+0] + dx;
     yl2 = points[j+1] - dy;
     xr2 = points[j+0] - dx;
     yr2 = points[j+1] + dy;

     w = (sumLen*len + r0) * arrowT[i][3];
     dx  = arrowT[i][1] * w;
     dy  = arrowT[i][0] * w;
     xl3 = points[j+2] + dx;
     yl3 = points[j+3] - dy;
     xr3 = points[j+2] - dx;
     yr3 = points[j+3] + dy;

     _gr_vertices[0].any.x = (int)xl0;
     _gr_vertices[0].any.y = (int)yl0;
     _gr_vertices[0].any.iz = 6550;

     _gr_vertices[1].any.x = (int)xr0;
     _gr_vertices[1].any.y = (int)yr0;
     _gr_vertices[1].any.iz = 6550;

     //solve left
     //x(yl1-yl0)+y(xl0-xl1)=xl0yl1-xl1yl0
     //x(yl3-yl2)+y(xl2-xl3)=xl2yl3-xl3yl2
     w = (yl1-yl0)*(xl2-xl3) - (yl3-yl2)*(xl0-xl1);
     if (w == 0.) {
        xl0 = xl1;
        yl0 = yl1;
     }
     else {
        w = 1. / w;
        dx = (xl0*yl1-xl1*yl0)*(xl2-xl3) - (xl2*yl3-xl3*yl2)*(xl0-xl1);
        dy = (yl1-yl0)*(xl2*yl3-xl3*yl2) - (yl3-yl2)*(xl0*yl1-xl1*yl0);

        xl0 = dx*w;
        yl0 = dy*w;
     }

     //solve right
     //x(yr1-yr0)+y(xr0-xr1)=xr0yr1-xr1yr0
     //x(yr3-yr2)+y(xr2-xr3)=xr2yr3-xr3yr2
     w = (yr1-yr0)*(xr2-xr3) - (yr3-yr2)*(xr0-xr1);
     if (w == 0.) {
        xr0 = xr1;
        yr0 = yr1;
     }
     else {
        w = 1. / w;
        dx = (xr0*yr1-xr1*yr0)*(xr2-xr3) - (xr2*yr3-xr3*yr2)*(xr0-xr1);
        dy = (yr1-yr0)*(xr2*yr3-xr3*yr2) - (yr3-yr2)*(xr0*yr1-xr1*yr0);

        xr0 = dx*w;
        yr0 = dy*w;
     }

     _gr_vertices[2].any.x = (int)xr0;
     _gr_vertices[2].any.y = (int)yr0;
     _gr_vertices[2].any.iz = 6550;

     _gr_vertices[3].any.x = (int)xl0;
     _gr_vertices[3].any.y = (int)yl0;
     _gr_vertices[3].any.iz = 6550;

     GRDrawPolygonPCCW();

     xl1 = xl3;
     yl1 = yl3;
     xr1 = xr3;
     yr1 = yr3;
  }

  _gr_vertices[0].any.x = (int)xl0;
  _gr_vertices[0].any.y = (int)yl0;
  _gr_vertices[0].any.iz = 6550;

  _gr_vertices[1].any.x = (int)xr0;
  _gr_vertices[1].any.y = (int)yr0;
  _gr_vertices[1].any.iz = 6550;

  _gr_vertices[2].any.x = (int)xr1;
  _gr_vertices[2].any.y = (int)yr1;
  _gr_vertices[2].any.iz = 6550;

  _gr_vertices[3].any.x = (int)xl1;
  _gr_vertices[3].any.y = (int)yl1;
  _gr_vertices[3].any.iz = 6550;

  GRDrawPolygonPCCW();

  //draw pointer
  i--;
  xl0 = points[j+0] - arrowT[i][0]*POINTER_R0;
  yl0 = points[j+1] - arrowT[i][1]*POINTER_R0;

  _gr_polygon.nVertices = 3;

  _gr_vertices[0].any.x = (int)points[j+0];
  _gr_vertices[0].any.y = (int)points[j+1];
  _gr_vertices[0].any.iz = 6550;

  dx = arrowT[i][0]*POINTER_R0*POINTER_R1;
  dy = arrowT[i


//
// Created by Lakshya Mittal on 17-12-2021.
// Modified by Pranav Harresh on 25-07-2025.
//

#include "RubiksCube.h"

class RubiksCube3dArray : public RubiksCube {
private:

    void rotateFace(int ind) {
        char temp_arr[3][3] = {};
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                temp_arr[i][j] = cube[ind][i][j];
            }
        }
        for (int i = 0; i < 3; i++) cube[ind][0][i] = temp_arr[2 - i][0];
        for (int i = 0; i < 3; i++) cube[ind][i][2] = temp_arr[0][i];
        for (int i = 0; i < 3; i++) cube[ind][2][2 - i] = temp_arr[i][2];
        for (int i = 0; i < 3; i++) cube[ind][2 - i][0] = temp_arr[2][2 - i];
    }

public:
    char cube[6][3][3]{};

    RubiksCube3dArray() {
        for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 3; j++) {
                for (int k = 0; k < 3; k++)
                    cube[i][j][k] = getColorLetter(COLOR(i));
            }
        }
    }

    COLOR getColor(FACE face, unsigned row, unsigned col) const override {
        char color = cube[int(face)][row][col];
        switch (color) {
            case 'B':
                return COLOR::BLUE;
            case 'R':
                return COLOR::RED;
            case 'G':
                return COLOR::GREEN;
            case 'O':
                return COLOR::ORANGE;
            case 'Y':
                return COLOR::YELLOW;
            default:
                return COLOR::WHITE;
        }
    }

    void setColor(FACE face, int row, int col, COLOR color) override {
        cube[int(face)][row][col] = getColorLetter(color);
    }

    bool isSolved() const override {
        for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 3; j++) {
                for (int k = 0; k < 3; k++) {
                    if (this->cube[i][j][k] == getColorLetter(COLOR(i))) continue;
                    return false;
                }
            }
        }
        return true;
    }

    RubiksCube &u() override {
        this->rotateFace(0);

        char temp_arr[3] = {};
        for (int i = 0; i < 3; i++) temp_arr[i] = cube[4][0][2 - i];
        for (int i = 0; i < 3; i++) cube[4][0][2 - i] = cube[1][0][2 - i];
        for (int i = 0; i < 3; i++) cube[1][0][2 - i] = cube[2][0][2 - i];
        for (int i = 0; i < 3; i++) cube[2][0][2 - i] = cube[3][0][2 - i];
        for (int i = 0; i < 3; i++) cube[3][0][2 - i] = temp_arr[i];

        return *this;
    }

    RubiksCube &uPrime() override {
        this->u();
        this->u();
        this->u();

        return *this;
    }

    RubiksCube &u2() override {
        this->u();
        this->u();

        return *this;
    }

    RubiksCube &l() override {
        this->rotateFace(1);

        char temp_arr[3] = {};
        for (int i = 0; i < 3; i++) temp_arr[i] = cube[0][i][0];
        for (int i = 0; i < 3; i++) cube[0][i][0] = cube[4][2 - i][2];
        for (int i = 0; i < 3; i++) cube[4][2 - i][2] = cube[5][i][0];
        for (int i = 0; i < 3; i++) cube[5][i][0] = cube[2][i][0];
        for (int i = 0; i < 3; i++) cube[2][i][0] = temp_arr[i];

        return *this;
    }

    RubiksCube &lPrime() override {
        this->l();
        this->l();
        this->l();

        return *this;
    }

    RubiksCube &l2() override {
        this->l();
        this->l();

        return *this;
    }

    RubiksCube &f() override {
        this->rotateFace(2);

        char temp_arr[3] = {};
        for (int i = 0; i < 3; i++) temp_arr[i] = cube[0][2][i];
        for (int i = 0; i < 3; i++) cube[0][2][i] = cube[1][2 - i][2];
        for (int i = 0; i < 3; i++) cube[1][2 - i][2] = cube[5][0][2 - i];
        for (int i = 0; i < 3; i++) cube[5][0][2 - i] = cube[3][i][0];
        for (int i = 0; i < 3; i++) cube[3][i][0] = temp_arr[i];

        return *this;
    }

    RubiksCube &fPrime() override {
        this->f();
        this->f();
        this->f();

        return *this;
    }

    RubiksCube &f2() override {
        this->f();
        this->f();

        return *this;
    }

    RubiksCube &r() override {
        this->rotateFace(3);

        char temp_arr[3] = {};
        for (int i = 0; i < 3; i++) temp_arr[i] = cube[0][2 - i][2];
        for (int i = 0; i < 3; i++) cube[0][2 - i][2] = cube[2][2 - i][2];
        for (int i = 0; i < 3; i++) cube[2][2 - i][2] = cube[5][2 - i][2];
        for (int i = 0; i < 3; i++) cube[5][2 - i][2] = cube[4][i][0];
        for (int i = 0; i < 3; i++) cube[4][i][0] = temp_arr[i];

        return *this;
    }

    RubiksCube &rPrime() override {
        this->r();
        this->r();
        this->r();

        return *this;
    }

    RubiksCube &r2() override {
        this->r();
        this->r();

        return *this;
    }

    RubiksCube &b() override {
        this->rotateFace(4);

        char temp_arr[3] = {};
        for (int i = 0; i < 3; i++) temp_arr[i] = cube[0][0][2 - i];
        for (int i = 0; i < 3; i++) cube[0][0][2 - i] = cube[3][2 - i][2];


#include<bits/stdc++.h>

using namespace std;

const int N=66;
int n;
int a[N],sum,maxlen;
int len;
int cnt;
int used[N];
bool found;

void dfs(int u,int cur,int start){
    if(found)return;
    if(u>cnt){
        cout<<len<<endl;
        found=true;
        return;
    }
    if(cur==len){
        dfs(u+1,0,1);
        return;
    }

    for(int i=start;i<=n;i++){
        if(used[i])continue;
        if(a[i]+cur>len)continue;

        used[i]=1;
        dfs(u,a[i]+cur,i+1);
        used[i]=0;

        if(found)return;

        if(cur==0)return;
        if(cur+a[i]==len)return;
        while(i<n&&a[i]==a[i+1])i++;

    }

}

int main(){

    while(cin>>n,n){
        memset(used,0,sizeof used);
        sum=0;
        maxlen=0;
        found=false;

        for(int i=1;i<=n;i++){
            cin>>a[i];
            sum+=a[i];
            maxlen=max(maxlen,a[i]);
        }

        sort(a+1,a+n+1);
        reverse(a+1,a+n+1);

        for (int i = maxlen; i <= sum; i++) {
            if (sum % i == 0) {
                len=i;
                cnt=sum/len;
                dfs(1,0,1);

                memset(used, 0, sizeof used);
            }
        }

    }
    return 0;
}


#include <iostream>
#include <string>
#include <vector>
#include <immintrin.h>
#include <cstring>
#include <cstdint>
#include <cpuid.h>

bool check_cpu_support() {
    unsigned int eax, ebx, ecx, edx;

    // Check if CPUID is supported
    if (!__get_cpuid(1, &eax, &ebx, &ecx, &edx)) {
        return false;
    }

    // Check for both SSE4.2 and required alignment support
    bool has_sse42 = (ecx & bit_SSE4_2) != 0;
    bool has_alignment = (ecx & bit_SSSE3) != 0;

    return has_sse42 && has_alignment;
}

using namespace std;

// SIMD data structure

struct AlignedPasswords {
    alignas(16) uint8_t current[16];
    alignas(16) uint8_t target[16];
};

// SIMD comparison function

// Modify comparePasswords_SIMD to handle alignment more safely
bool comparePasswords_SIMD(const string& attempt, const string& target) {
    AlignedPasswords aligned;

    try {
        // Zero out buffers
        memset(aligned.current, 0, 16);
        memset(aligned.target, 0, 16);

        // Safe copy with bounds checking
        size_t attempt_len = min(size_t(16), attempt.length());
        size_t target_len = min(size_t(16), target.length());

        if (attempt_len != target_len) return false;

        memcpy(aligned.current, attempt.c_str(), attempt_len);
        memcpy(aligned.target, target.c_str(), target_len);

        // Use unaligned loads to be safer
        __m128i current_simd = _mm_loadu_si128((__m128i*)aligned.current);
        __m128i target_simd = _mm_loadu_si128((__m128i*)aligned.target);

        __m128i result = _mm_cmpeq_epi8(current_simd, target_simd);
        return _mm_movemask_epi8(result) == 0xFFFF;

    } catch (...) {
        // Fall back to regular comparison if SIMD fails
        return false;
    }
}

bool increment(vector<int>& indices, int base) {
    for (int i = indices.size() - 1; i >= 0; --i) {
        if (indices[i] + 1 < base) {
            indices[i]++;
            return true;
        } else {
            indices[i] = 0;
        }
    }
    return false;
}

int crack() {
    string characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    string target;
    bool use_simd = check_cpu_support();

    cout << "Enter the password to crack (any length): ";
    cin >> target;

    if (target.empty()) {
        cerr << "Error: Password cannot be empty\n";
        return 1;
    }

    int base = characters.size();
    int length = target.size();
    vector<int> indices(length, 0);
    long long attempts = 0;

    // Print SIMD status
    cout << "SIMD support: " << (use_simd ? "enabled" : "disabled") << "\n";

    while (true) {
        // Convert indices to string
        string attempt;
        attempt.reserve(length);
        for (int idx : indices) {
            attempt += characters[idx];
        }

        attempts++;

        // Use SIMD comparison only if supported and password length <= 16
        if (use_simd && length <= 16) {
            if (comparePasswords_SIMD(attempt, target)) {
                cout << "Password found: " << attempt << " in " << attempts << " attempts\n";
                break;
            }
        } else {
            if (attempt == target) {
                cout << "Password found: " << attempt << " in " << attempts << " attempts\n";
                break;
            }
        }

        if (!increment(indices, base)) {
            cout << "Password not found after trying all combinations.\n";
            break;
        }

        // Optional: Print progress every million attempts
        if (attempts % 1000000 == 0) {
            cout << "Attempts: " << attempts << "\r" << flush;
        }
    }

    return 0;
}

int main() {
    return crack();
}


#include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <windows.h>

#include "flutter_window.h"
#include "utils.h"

int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
                      _In_ wchar_t *command_line, _In_ int show_command) {
  // Attach to console when present (e.g., 'flutter run') or create a
  // new console when running with a debugger.
  if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
    CreateAndAttachConsole();
  }

  // Initialize COM, so that it is available for use in the library and/or
  // plugins.
  ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);

  flutter::DartProject project(L"data");

  std::vector<std::string> command_line_arguments =
      GetCommandLineArguments();

  project.set_dart_entrypoint_arguments(std::move(command_line_arguments));

  FlutterWindow window(project);
  Win32Window::Point origin(10, 10);
  Win32Window::Size size(1280, 720);
  if (!window.Create(L"flutter_app", origin, size)) {
    return EXIT_FAILURE;
  }
  window.SetQuitOnClose(true);

  ::MSG msg;
  while (::GetMessage(&msg, nullptr, 0, 0)) {
    ::TranslateMessage(&msg);
    ::DispatchMessage(&msg);
  }

  ::CoUninitialize();
  return EXIT_SUCCESS;
}


#include <pybind11/pybind11.h>
#include "minicpmo_iface.hpp"

PYBIND11_MODULE(_C, m) {
    m.doc() = "pybind11 for minicpmo-cpp";

    m.def("get_minicpmo_default_llm_params", &get_minicpmo_default_llm_params, "default llm params for MiniCPM-omni");

    py::class_<minicpmo>(m, "minicpmo")
        .def(py::init<minicpmo_params>())
        .def("streaming_prefill", &minicpmo::streaming_prefill)
        .def("eval_system_prompt", &minicpmo::eval_system_prompt, py::arg("lang") = "en")
        .def("streaming_generate", &minicpmo::streaming_generate, py::arg("prompt"))
        .def("chat_generate", &minicpmo::chat_generate, py::arg("prompt"), py::arg("stream") = true)
        .def("apm_kv_clear", &minicpmo::apm_kv_clear)
        .def("apm_streaming_mode", &minicpmo::apm_streaming_mode, py::arg("stream") = false)
        .def("reset", &minicpmo::reset);

    py::class_<minicpmo_params>(m, "minicpmo_params")
        .def(py::init<>())
        .def_readwrite("vpm_path", &minicpmo_params::vpm_path)
        .def_readwrite("apm_path", &minicpmo_params::apm_path)
        .def_readwrite("llm_path", &minicpmo_params::llm_path)
        .def_readwrite("ttc_model_path", &minicpmo_params::ttc_model_path)
        .def_readwrite("cts_model_path", &minicpmo_params::cts_model_path)
        .def_readwrite("common_params", &minicpmo_params::llm_params);

    py::class_<common_params>(m, "common_params")
        .def(py::init<>())
        .def_readwrite("n_batch", &common_params::n_batch)
        .def_readwrite("n_predict", &common_params::n_predict)
        .def_readwrite("n_ctx", &common_params::n_ctx)
        .def_readwrite("flash_attn", &common_params::flash_attn)
        .def_readwrite("n_keep", &common_params::n_keep);
}


#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <cstdlib>
#include <filesystem>

const char* RESULTS_LOG = "target/results.log";

struct Row {
    std::string name;
    std::string secs;
    std::string base;
    std::string mb;
    std::string joules;
};

struct FinalRow {
    std::string name;
    std::string secs;
    std::string mb;
    std::string joules;
};

std::vector<std::string> split(const std::string& str, char delimiter) {
    std::vector<std::string> tokens;
    std::string token;
    std::istringstream tokenStream(str);
    while (std::getline(tokenStream, token, delimiter)) {
        tokens.push_back(token);
    }
    return tokens;
}

std::string trim(const std::string& str) {
    size_t first = str.find_first_not_of(' ');
    if (std::string::npos == first) {
        return str;
    }
    size_t last = str.find_last_not_of(' ');
    return str.substr(first, (last - first + 1));
}

double median(std::vector<double> array) {
    if (array.empty()) return 0.0;

    std::sort(array.begin(), array.end());
    size_t len = array.size();
    return (array[(len - 1) / 2] + array[len / 2]) / 2.0;
}

std::string sd(const std::vector<double>& list, double scale = 1.0, int precision = 2) {
    std::vector<double> values = list;
    double list_median = median(values);

    std::vector<double> deviations;
    for (double x : list) {
        deviations.push_back(std::abs(x - list_median));
    }

    double mad = median(deviations);

    std::ostringstream oss;
    oss << std::fixed << std::setprecision(precision)
        << (list_median / scale) << "<sub>±"
        << std::setfill('0') << std::setw(precision + 3) << std::setprecision(precision)
        << (mad / scale) << "</sub>";
    return oss.str();
}

std::string pad(int n, const std::string& str, char padchar = ' ') {
    std::string trimmed = trim(str);
    if (trimmed.length() >= static_cast<size_t>(n)) return trimmed;
    return std::string(n - trimmed.length(), padchar) + trimmed;
}

int main(int argc, char* argv[]) {
    int ATTEMPTS = 10;
    const char* attempts_env = std::getenv("ATTEMPTS");
    if (attempts_env) {
        ATTEMPTS = std::stoi(attempts_env);
    }

    if (argc > 1) {
        std::filesystem::remove(RESULTS_LOG);

        for (int n = 0; n < ATTEMPTS; n++) {
            std::cout << "--- Iteration " << (n + 1) << std::endl;

            std::string command;
            for (int i = 1; i < argc; i++) {
                if (i > 1) command += " ";
                command += argv[i];
            }

            setenv("QUIET", "1", 1);
            int result = system(command.c_str());
            if (result != 0) {
                return 1;
            }
        }
    }

    std::map<std::string, std::string> name_repl = {
        {"ruby", "Ruby"},
        {"jruby", "Ruby/jruby"},
        {"gccgo", "Go/gccgo"},
        {"gc", "Go"},
        {"CPython", "Python"},
        {"PyPy", "Python/pypy"},
        {"Digital Mars D", "D/dmd"},
        {"GNU D", "D/gdc"},
        {"LDC", "D/ldc2"}
    };

    std::vector<Row> lines;
    std::ifstream file(RESULTS_LOG);
    if (!file.is_open()) {
        std::cerr << "Error: Cannot open " << RESULTS_LOG << std::endl;
        return 1;
    }

    std::string line;
    while (std::getline(file, line)) {
        std::vector<std::string> values = split(line, '\t');
        if (values.size() >= 5) {
            Row row;
            std::string name = values[0];
            row.name = name_repl.count(name) ? name_repl[name] : name;
            row.secs = values[1];
            row.base = values[2];
            row.mb = values[3];
            row.joules = trim(values[4]);
            lines.push_back(row);
        }
    }
    file.close();

    std::vector<std::string> keys;
    for (const auto& row : lines) {
        if (std::find(keys.begin(), keys.end(), row.name) == keys.end()) {
            keys.push_back(row.name);
        }
    }

    std::vector<FinalRow> results;
    for (const std::string& k : keys) {
        std::vector<Row> rows;
        for (const auto& line : lines) {
            if (line.name == k) {
                rows.push_back(line);
            }
        }

        if (static_cast<int>(rows.size()) != ATTEMPTS) {
            std::cerr << "Integrity check failed (" << k << ")" << std::endl;
            return 1;
        }

        std::vector<double> secs_vals, base_vals, mb_vals, joules_vals;
        for (const auto& row : rows) {
            secs_vals.push_back(std::stod(row.secs));
            base_vals.push_back(std::stod(row.base));
            mb_vals.push_back(std::stod(row.mb) - std::stod(row.base));
            joules_vals.push_back(std::stod(row.joules));
        }

        std::string secs = sd(secs_vals, 1e9, 3);
        std::string base = sd(base_


#include<iostream>
using namespace std;
#define MAX_ORDER 50//limit the maximum order number

void showMenu()
{
	cout << "*******************************" << endl;
	cout << "*****Welcome to CodePizza!*****" << endl;
	cout << "*******************************" << endl;
	cout << "***** 1. Place an order *******" << endl;
	cout << "***** 2. View order queue *****" << endl;
	cout << "***** 3. Bake next order ******" << endl;
	cout << "***** 4. Check the total revenue" << endl;
	cout << "***** 0. Quit *****************" << endl;
	cout << "*******************************" << endl;
	cout << "please input a number(1,2,3,or 0)" << endl;
	cout << "*******************************" << endl;

}

//one single pizza(categore)
struct Pizza
{
	string m_Size;
	string m_Crust;
	string m_Toppings;
	int m_SinglePrice;
};

//the different orders will contain one or more than one pizzas
//struct Order
//{
//	int m_PizzaCount;
//	int m_SingleOrderPrice;
//};

//store many orders
struct OrderQueue
{
	int orderCount;//how many orders currently,  after each addition the orderCount will add 1;
	int totalRevenue;//the total revenue
	Pizza pizzaArray[MAX_ORDER];
};

void calculatePrice(OrderQueue* queue)
{
	if (queue->orderCount == 0)
	{
		cout << "the queue is empty!" << endl;
	}
	else
	{
		//the price for size
		int price1 = 0;
		if (queue->pizzaArray[queue->orderCount - 1].m_Size == "Small")
		{
			price1 = 8;
		}
		else if (queue->pizzaArray[queue->orderCount - 1].m_Size == "Medium")
		{
			price1 = 10;
		}
		else
		{
			price1 = 12;
		}

		//the price for crust
		int price2 = 0;
		if (queue->pizzaArray[queue->orderCount - 1].m_Crust == "Deep_Dish")
		{
			price2 = 2;
		}
		else
		{
			price2 = 0;
		}

		//the price for toppings
		int price3 = 1;
		int price = price1 + price2 + price3;
		int ultimatePrice = price * 1.1;
		queue->pizzaArray[queue->orderCount - 1].m_SinglePrice = ultimatePrice;
	}
}

//place order function
void placeOrder(OrderQueue* queue)
{

	cout << "size opt(please input Small, Medium, Large)" << endl;
	string size;
	cin >> size;
	queue->pizzaArray[queue->orderCount].m_Size = size;

	cout << "crust opt(please input Thin, Regular, Deep_Dish)" << endl;
	string crust;
	cin >> crust;
	queue->pizzaArray[queue->orderCount].m_Crust = crust;

	cout << "toppings opt(please input list/array of strings or integers, pepperoni, cheese, pineapple)" << endl;
	string toppings;
	cin >> toppings;
	queue->pizzaArray[queue->orderCount].m_Toppings = toppings;

	queue->orderCount++;//ÏÈ¼ÓÒ»
	calculatePrice(queue);//ÔÙ¼ÆËã¼Û¸ñ
	cout <<"the price is : "<< queue->pizzaArray[queue->orderCount-1].m_SinglePrice << endl;

	system("pause");
	system("cls");

}

//View order function
void printOrder(OrderQueue* queue)
{
	if (queue->orderCount == 0)
	{
		cout << "the order-queue is empty! " << endl;
	}
	else
	{
		for (int i=0;i<queue->orderCount;i++)
		{

			cout << "this is order :" << i+1 << endl;
			cout << "the size is :" << queue->pizzaArray[i].m_Size << endl;
			cout << "the crust is :" << queue->pizzaArray[i].m_Crust << endl;
			cout << "the toppings is :" << queue->pizzaArray[i].m_Toppings << endl;
			cout << "the price is : " << queue->pizzaArray[i].m_SinglePrice << endl;
			cout << "==============================" << endl;

		}
	}
	system("pause");
	system("cls");
}

//bake function
void bake(OrderQueue* queue)
{
	if (queue->orderCount == 0)
	{
		cout << "the queue is empty!" << endl;
	}
	else
	{
		//show the info of the first pizza in the queue
		cout << "the currently baking pizza is: " << endl;
		cout << "size : " << queue->pizzaArray[0].m_Size << endl;
		cout << "crust : " << queue->pizzaArray[0].m_Crust << endl;
		cout << "toppings : " << queue->pizzaArray[0].m_Toppings << endl;
		cout << "=======================" << endl;
		cout << "please enjoy your pizza!" << endl;

		//remove the first one in the queue
		//all the orders in the line will move forward
		for (int i=0;i<queue->orderCount-1;i++)
		{
			queue->pizzaArray[i] = queue->pizzaArray[i+1];
		}

		//after the circle, the orderCount will be minused one
		queue->orderCount --;
	}
	system("pause");
	system("cls");
}

//check the revenue
void checkRevenue(OrderQueue* queue)
{
	int totalRevenue = 0;
	for (int i=0;i<queue->orderCount;i++)
	{
		totalRevenue += queue->pizzaArray[i].m_SinglePrice;
	}
	cout << "the total revenue is : " << totalRevenue << endl;
}

int main()
{
	OrderQueue queue;//creat an order book to store the orders
	queue.orderCount = 0;
	while (true)
	{
		showMenu();
		int opt;
		cin >> opt;
			switch (opt)
			{
			case 1:
				//placeOrder();
				placeOrder(&queue);
				break;
			case 2:
				//viewOrderQueue();
				calculatePrice(&queue);
				printOrder(&queue);
				break;
			case 3:
				//bakeNextOrder();
				bake(&queue);
				break;
			case


#include<iostream>
#include<vector>
#include<cmath>
#include<string>
#include<sstream>
#include<ctime>

#include "hash_funcs.h"
#include "fileattr_map.h"
#include "filename_map.h"
#include "version_map.h"
#include "File_class.h"
#include "TreeNode.h"
#include "FileMaxHeap.h"

using namespace std;

bool containsNonNumeral(const std::string& str) {
    return str.find_first_not_of("0123456789") != std::string::npos;
}

class File_system
{

//support for calling files by name
//functions to build the maxheap(instantiate a maxheap for this class)
//keeping track of the modification time and calling a function to update the trees with each command interpreted.
// file_map recent;
// file_map frequent;
public:
filename_map file_names;
FileMaxHeap recent_heap;
FileMaxHeap biggest_heap;
void create(string filename, time_t timestamp)
{
    if(file_names.lookup(filename)!=nullptr)
    {
        cout<<"ERROR: filename already exists\n";
        return;
    }
    else
    {
        File* newfile = new File;
        newfile->root->created_timestamp=timestamp;
        newfile->root->snapshot_timestamp=timestamp;

        file_names.insert(filename,newfile);

        biggest_heap.addFile(filename,newfile->total_versions);
        biggest_heap.store_indices();

        recent_heap.addFile(filename,timestamp);
        recent_heap.store_indices();
    }

}
void read(string filename)
{
    File* current =file_names.lookup(filename);
    if(current==nullptr)
    {
        cout<<"ERROR: filename doesn't exist\n";
        return;
    }
    else
    {
        current->READ();
    }
}
void insert(string filename, string content, time_t timestamp)
{
    File* current =file_names.lookup(filename);
    if(current==nullptr)
    {
        cout<<"ERROR: filename doesn't exist\n";
        return;
    }
    else
    {
        current->INSERT(content,timestamp);

        //update the recency heap
        int idx=recent_heap.file_index.lookup(filename);
        recent_heap.heap_data[idx].first=timestamp; //will only increase, hence heapifyUp
        recent_heap.heapifyUp(idx);
        recent_heap.store_indices();

        //update the size heap
        int idx2=biggest_heap.file_index.lookup(filename);
        biggest_heap.heap_data[idx2].first=current->total_versions;
        biggest_heap.heapifyUp(idx2);
        biggest_heap.store_indices();
    }
}
void update(string filename, string content, time_t timestamp)
{
    File* current =file_names.lookup(filename);
    if(current==nullptr)
    {
        cout<<"ERROR: filename doesn't exist\n";
        return;
    }
    else
    {
        current->UPDATE(content,timestamp);
        //update the recency heap
        int idx=recent_heap.file_index.lookup(filename);
        recent_heap.heap_data[idx].first=timestamp; //will only increase, hence heapifyUp
        recent_heap.heapifyUp(idx);
        recent_heap.store_indices();

        //update the size heap
        int idx2=biggest_heap.file_index.lookup(filename);
        biggest_heap.heap_data[idx2].first=current->total_versions;
        biggest_heap.heapifyUp(idx2);
        biggest_heap.store_indices();
    }
}
void snapshot(string filename, string message, time_t timestamp)
{
    File* current =file_names.lookup(filename);
    if(current==nullptr)
    {
        cout<<"ERROR: filename doesn't exist\n";
        return;
    }
    else
    {
        current->SNAPSHOT(message,timestamp);
        int idx=recent_heap.file_index.lookup(filename);
        recent_heap.heap_data[idx].first=timestamp;
        recent_heap.heapifyUp(idx);
        recent_heap.store_indices();
    }
}
void rollback(string filename, int verid)
{
    File* current=file_names.lookup(filename);
    if(current==nullptr)
    {
        cout<<"ERROR: filename doesn't exist\n";
        return;
    }
    else
    {
        current->ROLLBACKf(verid);
    }
}

void rollback(string filename)
{
    File* current =file_names.lookup(filename);
    if(current==nullptr)
    {
        cout<<"ERROR: filename doesn't exist\n";
        return;
    }
    else
    {
        current->ROLLBACKf();
    }
}
void history(string filename)
{
    File* current =file_names.lookup(filename);
    if(current==nullptr)
    {
        cout<<"ERROR: filename doesn't exist\n";
        return;
    }
    else
    {
        current->HISTORY();
    }
}
};

//main file instantiates the file system and parses the input string to do stuff

int main()
{
    File_system system1;//file system has constructor for the files heap
    string line;
    time_t timestamp;
    cout<<"Welcome!\n";
    while(getline(cin,line))
    {
        stringstream parser(line);
        string op;
        parser>>op;

        if (op=="EXIT")
        {
            cout<<"Exiting program\n"<<"Bye bye";
            break;
        }
        else


//
// The MIT License (MIT)
//
// Copyright (c) 2022 Livox. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//

#include "parse_cfg_file.h"

#include <iostream>
#include <cstdio>
#include <arpa/inet.h>

namespace livox_ros {

ParseCfgFile::ParseCfgFile(const std::string& path) : path_(path) {}

bool ParseCfgFile::ParseSummaryInfo(LidarSummaryInfo& lidar_summary_info) {
  FILE* raw_file = std::fopen(path_.c_str(), "rb");
  if (!raw_file) {
    std::cout << "parse summary info failed, can not open file: " << path_ << std::endl;
    return false;
  }

  char read_buffer[kMaxBufferSize];
  rapidjson::FileReadStream config_file(raw_file, read_buffer, sizeof(read_buffer));
  rapidjson::Document doc;
  do {
    if (doc.ParseStream(config_file).HasParseError()) {
      break;
    }
    if (!doc.HasMember("lidar_summary_info") || !doc["lidar_summary_info"].IsObject()) {
      break;
    }
    const rapidjson::Value &object = doc["lidar_summary_info"];
    if (!object.HasMember("lidar_type") || !object["lidar_type"].IsUint()) {
      break;
    }
    lidar_summary_info.lidar_type = static_cast<uint8_t>(object["lidar_type"].GetUint());
    std::fclose(raw_file);
    return true;
  } while (false);

  std::cout << "parse lidar type failed." << std::endl;
  std::fclose(raw_file);
  return false;
}

} // namespace livox_ros


//numplay-memory-game
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <vector>

#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif

using namespace std;

void clearScreen() {
#ifdef _WIN32
    system("cls");
#else
    system("clear");
#endif
}

void wait(int seconds) {
#ifdef _WIN32
    Sleep(seconds * 1000);
#else
    sleep(seconds);
#endif
}

string generateRandomString(int length, int difficulty) {
    string digits = "0123456789";
    string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    string special = "!@#$%^&*()-_=+<>?";

    string pool = digits;
    if (difficulty >= 2) pool += letters;
    if (difficulty >= 3) pool += special;

    string result = "";
    for (int i = 0; i < length; i++) {
        result += pool[rand() % pool.size()];
    }
    return result;
}

struct Player {
    string name;
    int score = 0;
    int attempts = 0;
    int correct = 0;
    int remainingChances = 3;
};

int main() {
    srand(time(0));

    cout << "===================================" << endl;
    cout << "   Welcome to NUMPLAY - A Memory Game" << endl;
    cout << "===================================" << endl;

    char mode;
    cout << "Play in Single (S) or Group (G) mode? ";
    cin >> mode;
    cin.ignore();

    vector<Player> players;
    if (mode == 'S' || mode == 's') {
        string name;
        cout << "Enter your name: ";
        getline(cin, name);
        players.push_back({name});
    } else if (mode == 'G' || mode == 'g') {
        int numPlayers;
        cout << "Enter number of players: ";
        cin >> numPlayers;
        cin.ignore();
        for (int i = 0; i < numPlayers; i++) {
            string pname;
            cout << "Enter name of player " << (i + 1) << ": ";
            getline(cin, pname);
            players.push_back({pname});
        }
    } else {
        cout << "Invalid choice. Exiting..." << endl;
        return 0;
    }

    int level = 1, difficulty = 1;
    bool playAgain = true;

    while (playAgain) {
        for (auto &p : players) {
            p.score = 0;
            p.attempts = 0;
            p.correct = 0;
            p.remainingChances = 3;
        }

        bool gameActive = true;
        while (gameActive) {
            gameActive = false; // will become true if at least one player has chances left

            for (auto &p : players) {
                if (p.remainingChances <= 0) continue; // skip if player is out

                gameActive = true;

                int length = (level / 3) + 3;
                if (level > 5) difficulty = 2;
                if (level > 10) difficulty = 3;

                string sequence = generateRandomString(length, difficulty);

                clearScreen();
                cout << "Player: " << p.name << endl;
                cout << "Memorize this sequence: " << sequence << endl;
                wait(3);

                clearScreen();
                string userInput;
                cout << p.name << ", enter the sequence: ";
                cin >> userInput;

                p.attempts++;

                if (userInput == sequence) {
                    cout << "Correct!" << endl;
                    p.score += 10;
                    p.correct++;
                } else {
                    p.remainingChances--;
                    if (p.remainingChances > 0) {
                        cout << "Wrong! You have " << p.remainingChances
                             << " chance(s) left.\nTry again next turn." << endl;
                    } else {
                        cout << "Wrong! You have no chances left.\n" << endl;
                    }
                }
                wait(2);
            }
            level++;
        }

        // Show final individual and group results
        clearScreen();
        cout << "\n===== Final Results =====\n";
        int groupScore = 0;
        for (auto &p : players) {
            double acc = (p.attempts > 0) ? (p.correct * 100.0 / p.attempts) : 0;
            cout << p.name << " → Score: " << p.score << " | Accuracy: " << acc << "%\n";
            if (p.score < 50)
                cout << "Keep practicing, " << p.name << "!\n";
            else if (p.score < 120)
                cout << "Impressive memory, " << p.name << "!\n";
            else
                cout << "Outstanding memory, " << p.name << "!\n";

            groupScore += p.score;
        }
        cout << "\nGroup Score: " << groupScore << endl;

        char choice;
        cout << "\nDo you want to play again? (Y/N): ";
        cin >> choice;
        if (choice == 'N' || choice == 'n')
            playAgain = false;
    }

    cout << "\nThanks for playing NUMPLAY!" << endl;
    return 0;
}


#include "ringct.h"
#include <iostream>

RingCT::RingCT() : ring_size(DEFAULT_RING_SIZE) {
  // Constructor
}

RingCT::~RingCT() {
  // Destructor
}

void RingCT::initialize() {
  std::cout << "Initializing RingCT privacy protocol..." << std::endl;
  std::cout << "Ring size: " << ring_size << " (16 decoys + 1 real)"
            << std::endl;
  std::cout << "Using Pedersen commitments for amount encryption" << std::endl;
}

bool RingCT::createTransaction(
    const std::vector<std::string> &real_outputs,
    const std::vector<std::vector<std::string>> &decoy_sets, uint64_t amount,
    const std::string &recipient) {
  // Validate inputs
  if (real_outputs.empty() || decoy_sets.size() != real_outputs.size()) {
    return false;
  }

  // Each decoy set should have ring_size-1 elements
  for (const auto &decoy_set : decoy_sets) {
    if (decoy_set.size() != ring_size - 1) {
      std::cout << "Invalid decoy set size. Expected: " << (ring_size - 1)
                << ", Got: " << decoy_set.size() << std::endl;
      return false;
    }
  }

  std::cout << "Creating RingCT transaction:" << std::endl;
  std::cout << "- Amount: " << amount << " atomic units" << std::endl;
  std::cout << "- Recipient: " << recipient << std::endl;
  std::cout << "- Ring size: " << ring_size << std::endl;

  // In practice, this would:
  // 1. Create Pedersen commitments for amounts
  // 2. Generate ring signatures
  // 3. Mix real outputs with decoys
  // 4. Encrypt transaction data

  return true;
}

bool RingCT::verifyTransaction(const std::string &tx_data) {
  // Simplified verification - in practice this would check:
  // 1. Valid ring signatures
  // 2. Proper Pedersen commitments
  // 3. Correct mixing of real and decoy outputs

  std::cout << "Verifying RingCT transaction..." << std::endl;
  return !tx_data.empty(); // Simplified check
}

uint32_t RingCT::getRingSize() { return ring_size; }


// EXPERIMENT-13
// MAITRAIYEE VASHISTHA
// 24070123057
// ENTC A3

#include <iostream>
using namespace std;

class add {
public:
add(int a, int b) {
        cout << "The sum of the numbers using add(int a, int b) is: " << a + b << endl;
    }
add(int c, int d, int e) {
        cout << "The sum of the numbers using add(int c, int d, int e) is: " << c + d + e << endl;
    }
add(float f, float g) {
        cout << "The sum of the numbers using add(float f, float g) is: " << f + g << endl;
    }
};

int main() {
    int a, b, c, d, e;
    float f, g;

    cout << "Enter the value for a: ";
    cin >> a;
    cout << "Enter the value for b: ";
    cin >> b;

    add obj1(a, b);
    cout<<endl;

    cout << "Enter the value for c: ";
    cin >> c;
    cout << "Enter the value for d: ";
    cin >> d;
    cout << "Enter the value for e: ";
    cin >> e;

    add obj2(c, d, e);
    cout<<endl;

    cout << "Enter the value for f: ";
    cin >> f;
    cout << "Enter the value for g: ";
    cin >> g;

    add obj3(f, g);

    return 0;
}

/*Output :

Enter the value for a: 1
Enter the value for b: 2
The sum of the numbers using add(int a, int b) is: 3

Enter the value for c: 3
Enter the value for d: 4
Enter the value for e: 5
The sum of the numbers using add(int c, int d, int e) is: 12

Enter the value for f: 5.2
Enter the value for g: 6.5
The sum of the numbers using add(float f, float g) is: 11.7

*/


// MIT License
//
// Copyright (c) 2022 Ignacio Vizzo, Tiziano Guadagnino, Benedikt Mersch, Cyrill Stachniss.
// Modified by Daehan Lee, Hyungtae Lim, and Soohee Han, 2024
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <Eigen/Core>
#include <memory>
#include <sophus/se3.hpp>
#include <utility>
#include <vector>
#include <yaml-cpp/yaml.h>

// GenZ-ICP-ROS
#include "OdometryServer.hpp"
#include "Utils.hpp"

// GenZ-ICP
#include "genz_icp/pipeline/GenZICP.hpp"

// ROS 2 headers
#include <tf2_ros/static_transform_broadcaster.h>
#include <tf2_ros/transform_broadcaster.h>

#include <geometry_msgs/msg/pose_stamped.hpp>
#include <geometry_msgs/msg/transform_stamped.hpp>
#include <nav_msgs/msg/odometry.hpp>
#include <nav_msgs/msg/path.hpp>
#include <rclcpp/qos.hpp>
#include <rclcpp/rclcpp.hpp>
#include <sensor_msgs/msg/point_cloud2.hpp>
#include <std_msgs/msg/string.hpp>
#include "ament_index_cpp/get_package_share_directory.hpp"
#include "rcpputils/filesystem_helper.hpp"

namespace genz_icp_ros {

using utils::EigenToPointCloud2;
using utils::GetTimestamps;
using utils::PointCloud2ToEigen;

OdometryServer::OdometryServer(const rclcpp::NodeOptions &options)
    : rclcpp::Node("odometry_node", options) {
    // clang-format off
    base_frame_ = declare_parameter<std::string>("base_frame", base_frame_);
    odom_frame_ = declare_parameter<std::string>("odom_frame", odom_frame_);
    publish_odom_tf_ = declare_parameter<bool>("publish_odom_tf", publish_odom_tf_);
    publish_debug_clouds_ = declare_parameter<bool>("visualize", publish_debug_clouds_);
    declare_parameter<double>("max_range", config_.max_range);
    declare_parameter<double>("min_range", config_.min_range);
    declare_parameter<bool>("deskew", config_.deskew);
    declare_parameter<double>("voxel_size", config_.max_range / 100.0);
    declare_parameter<double>("map_cleanup_radius", config_.map_cleanup_radius);
    declare_parameter<double>("planarity_threshold", config_.planarity_threshold);
    declare_parameter<int>("max_points_per_voxel", config_.max_points_per_voxel);
    declare_parameter<int>("desired_num_voxelized_points", config_.desired_num_voxelized_points);
    declare_parameter<int>("max_num_iterations", config_.max_num_iterations);
    declare_parameter<double>("convergence_criterion", config_.convergence_criterion);
    declare_parameter<double>("initial_threshold", config_.initial_threshold);
    declare_parameter<double>("min_motion_th", config_.min_motion_th);
    declare_parameter<std::string>("config_file", "");

    // Load the configuration file
    std::string config_file = get_parameter("config_file").as_string();
    if (!config_file.empty()) {
        rcpputils::fs::path path(config_file);
        if (!path.is_absolute()) {
            path = rcpputils::fs::path(ament_index_cpp::get_package_share_directory("genz_icp")) / "config" / path;
        }
        YAML::Node yaml = YAML::LoadFile(path.string());

        std::vector<rclcpp::Parameter> overrides;
        for (const auto &param : yaml) {
            const auto &name = param.first.as<std::string>();
            const auto &value = param.second;

            if (value.IsScalar()) {
                // Get the declared type of the parameter
                rcl_interfaces::msg::ParameterDescriptor descriptor;
                descriptor = this->describe_parameter(name);

                using ParamType = rcl_interfaces::msg::ParameterType;
                switch (descriptor.type) {
                    case ParamType::PARAMETER_DOUBLE:
                        overrides.emplace_back(name, value.as<double>());
                        break;
                    case ParamType::PARAMETER_INTEGER:
                        overrides.emplace_back(name, value.as<int>());
                        break;
                    case ParamType::PARAMETER_BOOL:
                        overrides.emplace_back(name, value.as<bool>());
                        break;


#include "NodeLibraryModel.h"

#include <QDebug>

NodeLibraryModel::NodeLibraryModel( QObject *parent )
  : QAbstractListModel( parent )
{
}

int NodeLibraryModel::rowCount( const QModelIndex &parent ) const
{
  Q_UNUSED( parent );
  return m_nodes.count();
}

QVariant NodeLibraryModel::data( const QModelIndex &index, int role ) const
{
  if ( !index.isValid() || index.row() >= m_nodes.size() )
    return QVariant();

  const NodeItem &item = m_nodes.at( index.row() );

  switch ( role )
  {
    case TypeRole:
      return item.type;
    case NameRole:
      return item.name;
    case DescriptionRole:
      return item.description;
    case IconRole:
      return item.icon;
    case ColorRole:
      return item.color;
    case AttributesRole:
      return item.attributes;
    case ValuesRole:
      return item.values;
    default:
      return QVariant();
  }
}

QHash<int, QByteArray> NodeLibraryModel::roleNames() const
{
  QHash<int, QByteArray> roles;
  roles[TypeRole] = "type";
  roles[NameRole] = "name";
  roles[DescriptionRole] = "description";
  roles[IconRole] = "icon";
  roles[ColorRole] = "color";
  roles[AttributesRole] = "attributes";
  roles[ValuesRole] = "values";
  return roles;
}

bool NodeLibraryModel::loadFromJson( const QString &path )
{
  QFile file( path );
  if ( !file.open( QIODevice::ReadOnly ) )
  {
    qWarning() << "Cannot open JSON file:" << path;
    return false;
  }

  QByteArray data = file.readAll();
  QJsonDocument doc = QJsonDocument::fromJson( data );
  if ( !doc.isArray() )
    return false;

  QJsonArray arr = doc.array();
  beginResetModel();
  m_nodes.clear();
  for ( int i = 0; i < arr.size(); ++i )
  {
    QJsonValue v = arr.at( i );
    if ( !v.isObject() )
      continue;
    QJsonObject obj = v.toObject();
    NodeItem item;
    item.type = obj["type"].toString();
    item.name = obj["name"].toString();
    item.description = obj["description"].toString();
    item.icon = obj["icon"].toString();
    item.color = obj["color"].toString();

    item.attributes.clear();
    if ( obj.contains( "attributes" ) && obj["attributes"].isArray() )
    {
      QJsonArray attrArr = obj["attributes"].toArray();
      for ( int j = 0; j < attrArr.size(); ++j )
      {
        QJsonValue attrVal = attrArr.at( j );
        if ( attrVal.isObject() )
        {
          item.attributes.append( attrVal.toObject().toVariantMap() );
        }
      }
    }

    if ( obj.contains( "values" ) && obj["values"].isObject() )
    {
      item.values = obj["values"].toObject().toVariantMap();
    }
    else
    {
      item.values.clear();
    }

    m_nodes.append( item );
  }

  endResetModel();
  return true;
}

QVariantMap NodeLibraryModel::nodeByName( const QString &name ) const
{
  for ( const NodeItem &item : m_nodes )
  {
    if ( item.name == name )
    {
      QVariantMap map;
      map["type"] = item.type;
      map["name"] = item.name;
      map["description"] = item.description;
      map["icon"] = item.icon;
      map["color"] = item.color;
      map["attributes"] = item.attributes;
      map["values"] = QVariant::fromValue( item.values );
      return map;
    }
  }
  return {};
}

void NodeLibraryProxyModel::setFilterText( const QString &text )
{
  if ( m_filterText != text )
  {
    m_filterText = text;
    invalidateFilter();
    emit filterTextChanged();
  }
}

bool NodeLibraryProxyModel::filterAcceptsRow( int source_row, const QModelIndex &source_parent ) const
{
  if ( m_filterText.isEmpty() )
    return true;

  QModelIndex index = sourceModel()->index( source_row, 0, source_parent );
  QString name = index.data( Qt::DisplayRole ).toString();
  QString description = index.data( NodeLibraryModel::DescriptionRole ).toString();

  return name.contains( m_filterText, Qt::CaseInsensitive ) || description.contains( m_filterText, Qt::CaseInsensitive );
}


#include <esp_wifi.h>
#include <esp_now.h>
#include <EEPROM.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <ArduinoJson.h>
#include <PZEM004Tv30.h>

#define EEPROM_SIZE 100
#define ADDR_COORDINATOR_MAC 0
#define ADDR_STATUS 24
#define ADDR_DEVICE 40
#define ADDR_WIFI_CHANNEL 80
#define ADDR_FRECUENCY 90

#define BLUE_LED_PIN 21
#define CONFIG_PIN 23
#define RX_PIN 16
#define TX_PIN 17

#define NUM_BLINKS 5
#define AUTOPAIRING_HALTEN_TIME 3000
#define CHANNEL_SCAN_TIMEOUT 3000
#define NO_CONFIGURATION_HALTEN 8000

uint8_t Broadcast_MAC[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
uint8_t Coordinator_MAC[6];
uint8_t WiFi_Channel = 1;
uint8_t Current_Scan_Channel = 1;
String Device = "";
bool Is_Configured;
unsigned long Last_Sensor_Reading = 0;
unsigned long Last_Channel_Scan;
int Sensor_Reading_Interval = 5; // In seconds
AsyncWebServer Web_Server(80);
HardwareSerial Serial_Port(2);
PZEM004Tv30 Pzem(Serial_Port, RX_PIN, TX_PIN);

enum Message_Type : uint8_t { PAIRING = 0, DATA = 1, CHANNEL_CHANGE = 2, FRECUENCY = 3 };
struct Pairing_Struct { uint8_t Message_Type; uint8_t ID;  uint8_t WiFi_Channel; char Device[40]; };
struct Message_Struct{ uint8_t Message_Type; float Voltage; float Current; float Power; char Device[40]; };

void ChannelChange();

void BlinkLed(int Num_Times, int Led_Pin){
    for(int i = 0; i < Num_Times; i++){
        digitalWrite(Led_Pin, HIGH);
        delay(250);
        digitalWrite(Led_Pin, LOW);
        delay(250);
    }
}

void AddFriend(const uint8_t * MAC, bool Save_MAC){ // Function to add a new friend, to communicate with him
    if(Save_MAC){
        for(int j = 0; j < 6; j++){
            EEPROM.write(j + ADDR_COORDINATOR_MAC, MAC[j]);
            EEPROM.commit();
        }
    }

    esp_now_peer_info_t Friend;
    memset(&Friend, 0, sizeof(Friend));
    memcpy(Friend.peer_addr, MAC, 6);
    Friend.channel = WiFi_Channel;
    Friend.encrypt = false;
    esp_now_add_peer(&Friend);
}

void MessageReceived(const uint8_t *MAC, const uint8_t *Data_On_the_Way, int Length){
    Pairing_Struct Pairing_Data;
    memset(&Pairing_Data, 0, sizeof(Pairing_Data));
    memcpy(&Pairing_Data, Data_On_the_Way, sizeof(Pairing_Data));
    switch(Pairing_Data.Message_Type){
        case PAIRING:
            if(Pairing_Data.ID == 0){ // If the id isn't 0, it doesn't come from the coordinator
                Is_Configured = true;
                BlinkLed(NUM_BLINKS, BLUE_LED_PIN);
                WiFi_Channel = Current_Scan_Channel;
                Current_Scan_Channel = 14; // I don't have to search for more channels anymore, I make the loop end
                memcpy(Coordinator_MAC, MAC, 6);
            }
            break;
        case CHANNEL_CHANGE:
            if((Pairing_Data.ID == 0) && (Pairing_Data.WiFi_Channel != WiFi_Channel)){
                WiFi_Channel = Pairing_Data.WiFi_Channel;
                ChannelChange();
            }
            break;
        case FRECUENCY:
            if(Pairing_Data.ID == 0){
                if (String(Pairing_Data.Device) == Device) {
                    Sensor_Reading_Interval = Pairing_Data.WiFi_Channel; // Using WiFi_Channel to store the reading interval
                    EEPROM.writeInt(ADDR_FRECUENCY, Sensor_Reading_Interval);
                    EEPROM.commit();
                }
            }
            break;
    }
}

void ChannelChange(){
    esp_now_deinit();
    delay(500);
    ESP_ERROR_CHECK(esp_wifi_set_channel(WiFi_Channel,  WIFI_SECOND_CHAN_NONE));
    if(esp_now_init() != ESP_OK)
        ESP.restart();
    esp_now_register_recv_cb(MessageReceived);
    AddFriend(Coordinator_MAC, false);
    EEPROM.write(ADDR_WIFI_CHANNEL, WiFi_Channel);
    EEPROM.commit();
}

void ReadEEPROM(){
    for(int i = 0; i < 6; i++)
        Coordinator_MAC[i] = EEPROM.read(i + ADDR_COORDINATOR_MAC );
    AddFriend(Coordinator_MAC, false); // I add the coordinator as a friend so that I can communicate with him

    Device = EEPROM.readString(ADDR_DEVICE);
    WiFi_Channel = EEPROM.read(ADDR_WIFI_CHANNEL);
    Sensor_Reading_Interval = EEPROM.readInt(ADDR_FRECUENCY);

    if((WiFi_Channel < 1) || (WiFi_Channel > 13)) // Validate WiFi channel
        WiFi_Channel = 1; // Default channel
}

bool CompareMACs(){ // Function to compare the Broadcast MAC with the Coordinator MAC
    return (memcmp(Broadcast_MAC, Coordinator_MAC, 6) == 0);
}

void ScanChannelsForPairing(){
    unsigned long Current_Time = 0;
    Last_Channel_Scan = 0;
    Is_Configured = false;

    Pairing_Struct Pairing_Data;
    Pairing_Data.Message_Type = PAIRING;
    Pairing_Data.ID = 1;
    esp_now_del_peer(Broadcast_MAC);

    while((Current_Scan_Channel <= 13)){
        Current_Time = millis();
        if(Current_Time - Last_Channel_Scan >= CHANNEL_SCAN_TIMEOUT){
            esp_now_deinit(); // I de-initialise ESP-NOW to change channel
            delay(500);
            esp_err_t channel_result = esp_wifi_set_channel(Current_Scan_Channel, WIFI