#include <thread> // needed for sleep
#include <print>
#include <exception>

#include "cosched.hpp"

using namespace cosched;

class Context {
  public:
    int  cnt = 0;
};

Task<Context> grandchild900(Context& )
{
  std::println("grandchild900 started; sleep");
  co_await AwaitSleep{MilliSeconds(900)};
  std::println("grandchild900 woke up; return");
  co_return;
}

Task<Context> grandchild800(Context&)
{
  std::println("grandchild800 started; sleep");
  co_await AwaitSleep{MilliSeconds(800)};
  std::println("grandchild800 woke up; return");
  co_return;
}

Task<Context> grandchild700(Context&)
{
  std::println("grandchild700 started; sleep");
  co_await AwaitSleep{MilliSeconds(700)};
  std::println("grandchild700 woke up; return");
  throw std::logic_error("test");
  co_return;
}
Task<Context> grandchild600(Context&)
{
  std::println("grandchild600 started; sleep");
  co_await AwaitSleep{MilliSeconds(600)};
  std::println("grandchild600 woke up; return");
  co_return;
}
Task<Context> grandchild500(Context&)
{
  std::println("grandchild500 started; sleep");
  co_await AwaitSleep{MilliSeconds(500)};
  std::println("grandchild500 woke up; return");
  co_return;
}
Task<Context> grandchild400(Context&)
{
  std::println("grandchild400 started; sleep");
  co_await AwaitSleep{MilliSeconds(400)};
  std::println("grandchild400 woke up; return");
  co_return;
}
Task<Context> grandchild300(Context&)
{
  std::println("grandchild300 started; sleep");
  co_await AwaitSleep{MilliSeconds(300)};
  std::println("grandchild300 woke up; return");
  co_return;
}
Task<Context> grandchild200(Context&)
{
  std::println("grandchild200 started; sleep");
  co_await AwaitSleep{MilliSeconds(200)};
  std::println("grandchild200 woke up; return");
  co_return;
}

Task<Context> grandchild100(Context&)
{
  std::println("grandchild100 started; sleep");
  co_await AwaitSleep{MilliSeconds(100)};
  std::println("grandchild100 woke up; return");
  co_return;
}

Task<Context> grandchild0(Context&)
{
  std::println("grandchild0 started; sleep");
  co_await AwaitSleep{MilliSeconds(0)};
  std::println("grandchild0 woke up; return");
  co_return;
}

Task<Context> grandchild(Context&)
{
  std::println("grandchild started; sleep");
  co_await AwaitSleep{MilliSeconds(300)};
  std::println("grandchild woke up; return");
  co_await AwaitSpawn{grandchild900, NULL};
  co_await AwaitSpawn{grandchild0, NULL};
  co_await AwaitSpawn{grandchild800, NULL};
  co_await AwaitSpawn{grandchild100, NULL};
  co_await AwaitSpawn{grandchild700, NULL};
  co_await AwaitSpawn{grandchild200, NULL};
  co_await AwaitSpawn{grandchild600, NULL};
  co_await AwaitSpawn{grandchild300, NULL};
  co_await AwaitSpawn{grandchild500, NULL};

  co_return;
}

Task<Context> child1(Context&)
{
  std::println("child1 started; sleep");
  co_await AwaitSleep{MilliSeconds(100)};
  std::println("child1 woke up; return");
  co_return;
}

Task<Context> child2(Context&)
{
  std::println("child2 started; sleep");
  co_await AwaitSleep{MilliSeconds(10)};
  std::println("child2 woke up; spawn grandchild");
  co_await AwaitSpawn{grandchild, NULL};
  co_return;
}

Task<Context> comain(Context&)
{
  std::println("main start");

  TaskId child1id, child2id;
  std::println("main started; spawn child1");
  co_await AwaitSpawn{child1, &child1id};
  std::println("main child1 spawned; spawn child2");
  co_await AwaitSpawn{child2, &child2id};
  std::println("main child2 spawned; sleep");
  co_await AwaitSleep{MilliSeconds(20)};
  std::println("main woke up; spawn child2");
  co_await AwaitSpawn{child2, &child2id};
  std::println("main spawned child2; join child1");
  co_await AwaitJoin{child1id};
  std::println("main joined child1; join child2");
  co_await AwaitJoin{child2id};
  std::println("main joined child2; return");
}

int main()
{
  {
    Context ctx;
  Scheduler<Context> sched(comain, ctx);
  for  (int i = 0; !sched.done(); i++) {
    //std::println("poll {}", i);
    try {
      sched.Poll();
    } catch (std::logic_error e) {
      std::println("exception cauth {}", e.what());
    }
    std::this_thread::sleep_for(std::chrono::milliseconds(1));
  }
  }

}


#include <iostream>
#include <windows.h>
#include <string>
#include <thread>
#include <iomanip>

using namespace std;

bool isKeyPresset(int vKey) {
    return GetAsyncKeyState(vKey) < 0;
}

COLORREF GetPixelColorFromCenterWithOffset(int xOffset, int yOffset, HDC hdc)
{
    int screenWidth = GetSystemMetrics(SM_CXSCREEN);
    int screenHeight = GetSystemMetrics(SM_CYSCREEN);

    int centerX = screenWidth / 2 + xOffset;
    int centerY = screenHeight / 2 + yOffset;

    HDC hdcMem = CreateCompatibleDC(hdc);
    if (!hdcMem) {
        return RGB(0, 0, 0);
    }

    HBITMAP hBitMap = CreateCompatibleBitmap(hdc, 1, 1);
    if (!hBitMap) {
        DeleteDC(hdcMem);
        return RGB(0, 0, 0);
    }

    SelectObject(hdcMem, hBitMap);
    BitBlt(hdcMem, 0, 0, 1, 1, hdc, centerX, centerY, SRCCOPY);

    COLORREF color = GetPixel(hdc, centerX, centerY);

    DeleteDC(hdcMem);
    DeleteObject(hBitMap);

    return color;
}

void SchemaMouseEvent(int ms) {
    INPUT input;
    input.type = INPUT_MOUSE;
    input.mi.time = 0;

    this_thread::sleep_for(chrono::milliseconds(ms));

    input.mi.dwFlags = MOUSEEVENTF_LEFTDOWN;
    SendInput(1, &input, sizeof(input));

    this_thread::sleep_for(chrono::milliseconds(1));

    input.mi.dwFlags = MOUSEEVENTF_LEFTUP;
    SendInput(1, &input, sizeof(input));
}

int main()
{
    setlocale(LC_ALL, "");

    int threshold = 20;
    int ms = 20;
    int bindkey = VK_XBUTTON1;

    while (true) {

        if (isKeyPresset(bindkey)) {
            HDC hdc = GetDC(NULL);
            if (hdc == NULL) {
                return 1;
            }

            COLORREF color1 = GetPixelColorFromCenterWithOffset(2, 2, hdc);
            this_thread::sleep_for(chrono::milliseconds(11));
            COLORREF color2 = GetPixelColorFromCenterWithOffset(2, 2, hdc);

            BYTE r1 = GetRValue(color1);
            BYTE g1 = GetGValue(color1);
            BYTE b1 = GetBValue(color1);

            BYTE r2 = GetRValue(color2);
            BYTE g2 = GetGValue(color2);
            BYTE b2 = GetBValue(color2);

            if (abs(r1 - r2) > threshold || abs(g1 - g2) > threshold || abs(b1 - b2) > threshold) {
                cout << "Fire" << endl;
                SchemaMouseEvent(ms);
            }

            ReleaseDC(NULL, hdc);
        }
    }

    return 0;
}


#include "histogram/Histogram.hpp"
#include "histogram/SVGExporter.hpp"
#include <iostream>
#include <random>
#include <vector>
#include <tuple>

int main() {
    std::cout << "=== 波峰检测可视化示例 ===\n\n";

    // 创建直方图，范围[0, 20]，40个bin
    histogram::Histogram hist(0.0f, 20.0f, 40);

    // 生成多峰值数据（三个正态分布的混合）
    std::mt19937 gen(12345); // 固定种子以便重现结果

    // 第一个峰值：均值=4，标准差=0.8
    std::normal_distribution<float> dist1(4.0f, 0.8f);
    for (int i = 0; i < 400; ++i) {
        hist.addData(dist1(gen));
    }

    // 第二个峰值：均值=10，标准差=1.2
    std::normal_distribution<float> dist2(10.0f, 1.2f);
    for (int i = 0; i < 600; ++i) {
        hist.addData(dist2(gen));
    }

    // 第三个峰值：均值=16，标准差=0.9
    std::normal_distribution<float> dist3(16.0f, 0.9f);
    for (int i = 0; i < 500; ++i) {
        hist.addData(dist3(gen));
    }

    std::cout << "添加了 " << hist.getTotalCount() << " 个数据点\n";
    std::cout << "bin数量: " << hist.getResolution() << "\n";
    std::cout << "bin宽度: " << hist.getBinWidth() << "\n\n";

    // 检测波峰
    std::cout << "检测波峰 (最小突出度阈值: 10%):\n";
    auto peaksInfo = hist.getPeaksInfo(0.1f);

    if (peaksInfo.empty()) {
        std::cout << "未检测到波峰\n";
    } else {
        std::cout << "检测到 " << peaksInfo.size() << " 个波峰:\n";
        for (const auto& peak : peaksInfo) {
            size_t index = std::get<0>(peak);
            size_t count = std::get<1>(peak);
            auto range = std::get<2>(peak);
            float center = (range.first + range.second) / 2.0f;

            std::cout << "  - 索引: " << index
                      << ", 计数值: " << count
                      << ", 范围: [" << range.first << ", " << range.second << "]"
                      << ", 中心值: " << center << "\n";
        }
    }

    // 导出带波峰标记的SVG
    try {
        histogram::SVGExporter::exportHistogramWithPeaks(hist, peaksInfo,
                                                       "peak_visualization.svg",
                                                       800, 600,
                                                       "Histogram with Detected Peaks");
        std::cout << "\nSVG图像已导出: peak_visualization.svg\n";

        // 同时导出普通直方图用于对比
        histogram::SVGExporter::exportHistogram(hist, "normal_histogram.svg",
                                              800, 600, "Normal Histogram");
        std::cout << "普通直方图已导出: normal_histogram.svg\n";

    } catch (const std::exception& e) {
        std::cerr << "导出SVG时出错: " << e.what() << "\n";
        return 1;
    }

    std::cout << "\n=== 可视化完成 ===\n";
    std::cout << "请查看生成的SVG文件来观察波峰检测结果。\n";

    return 0;
}


// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// Copyright (C) 2021-2025 by Agustin L. Alvarez. All rights reserved.
//
// This work is licensed under the terms of the MIT license.
//
// For a copy, see <https://opensource.org/licenses/MIT>.
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// [  HEADER  ]
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

#include "ImGuiRenderer.hpp"
#include <Zyphryon.Math/Matrix4x4.hpp>
#include <Zyphryon.Content/Service.hpp>

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// [   CODE   ]
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

namespace Plugin
{
    // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
    // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

    void ImGuiRenderer::Initialize(Ref<Service::Host> Host)
    {
        ConstTracker<Content::Service> Content = Host.GetService<Content::Service>();
        mPipeline = Content->Load<Graphic::Pipeline>("Engine://Pipeline/UI.effect");
        mGraphics = Host.GetService<Graphic::Service>();

        BakeDefaultFonts();
        CreateTextureFontAtlas(Host);
    }

    // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
    // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

    void ImGuiRenderer::CreateTextureFontAtlas(Ref<Service::Host> Host)
    {
        Ptr<UInt8> Pixels;
        SInt32     Width;
        SInt32     Height;
        ImGui::GetIO().Fonts->GetTexDataAsRGBA32(&Pixels, &Width, &Height);

        Tracker<Graphic::Texture> Texture = Tracker<Graphic::Texture>::Create("ImGUI_FontAtlas");
        Blob Data(Pixels, Width * Height * 4, Blob::kEmptyDeleter);

        Texture->Load(Graphic::TextureFormat::RGBA8UIntNorm, Width, Height, 1, Move(Data));
        Texture->Create(Host);

        ImGui::GetIO().Fonts->SetTexID(Texture->GetID());
    }

    // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
    // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

    void ImGuiRenderer::Submit(ConstRef<ImDrawData> Commands)
    {
        // Abort drawing if the pipeline has not finished loading or compiling.
        if (!mPipeline->HasCompleted())
        {
            return;
        }

        auto [VtxPtr, VtxStream] = mGraphics->Allocate<ImDrawVert>(Graphic::Usage::Vertex, Commands.TotalVtxCount);
        auto [IdxPtr, IdxStream] = mGraphics->Allocate<ImDrawIdx>(Graphic::Usage::Index, Commands.TotalIdxCount);

        const Matrix4x4 Projection = Matrix4x4::CreateOrthographic(
                Commands.DisplayPos.x,
                Commands.DisplayPos.x + Commands.DisplaySize.x,
                Commands.DisplayPos.y + Commands.DisplaySize.y,
                Commands.DisplayPos.y,
                -1.0f,
                +1.0f);
        const auto Uniforms = mGraphics->Allocate(Graphic::Usage::Uniform, ConstSpan(&Projection, 1));

        UInt32 VtxOffset = 0;
        UInt32 IdxOffset = 0;

        for (ConstPtr<ImDrawList> CommandList : Commands.CmdLists)
        {
            std::memcpy(VtxPtr, CommandList->VtxBuffer.Data, CommandList->VtxBuffer.Size * sizeof(ImDrawVert));
            std::memcpy(IdxPtr, CommandList->IdxBuffer.Data, CommandList->IdxBuffer.Size * sizeof(ImDrawIdx));
            VtxPtr += CommandList->VtxBuffer.Size;
            IdxPtr += CommandList->IdxBuffer.Size;

            for (ConstRef<ImDrawCmd> Command : CommandList->CmdBuffer)
            {
                if (Command.UserCallback)
                {
                    Command.UserCallback(CommandList, &Command);
                }
                else
                {
                    // Apply scissor/clipping rectangle
                    const Graphic::Scissor Scissor(
                        Command.ClipRect.x - Commands.DisplayPos.x,
                        Command.ClipRect.y - Commands.DisplayPos.y,
                        Command.ClipRect.z - Commands.DisplayPos.x - Command.ClipRect.x,
                        Command.ClipRect.w - Commands.DisplayPos.y - Command.ClipRect.y);
                    if (Scissor.Width == 0 || Scissor.Height == 0)
                    {
                        continue;
                    }

                    mEncoder.SetScissor(Sc


#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
    vector<vector<int>> criticalConnections(int n, vector<vector<int>>& connections) {
        // Grafo (não direcionado)
        vector<vector<int>> g(n);
        g.reserve(n);
        for (auto &e : connections) {
            int a = e[0], b = e[1];
            g[a].push_back(b);
            g[b].push_back(a);
        }

        vector<int> disc(n, -1);   // tempo de descoberta (dfs time) de cada nó
        vector<int> low(n, 0);     // menor tempo alcançável a partir do nó (incluindo back-edges)
        vector<vector<int>> bridges;
        bridges.reserve(connections.size());

        int time = 0;

        function<void(int,int)> dfs = [&](int u, int parent) {
            disc[u] = low[u] = time++;
            for (int v : g[u]) {
                if (v == parent) continue;              // ignora aresta para o pai
                if (disc[v] == -1) {                    // árvore de DFS
                    dfs(v, u);
                    low[u] = min(low[u], low[v]);
                    // Se o menor alcançável de v é maior que o discovery de u,
                    // não há back-edge fechando ciclo acima de u -> (u,v) é ponte
                    if (low[v] > disc[u]) {
                        bridges.push_back({u, v});
                    }
                } else {
                    // back-edge
                    low[u] = min(low[u], disc[v]);
                }
            }
        };

        // O grafo pode não ser estritamente conexo em instâncias gerais;
        // o enunciado diz que é alcançável, mas varremos por segurança.
        for (int i = 0; i < n; ++i) {
            if (disc[i] == -1) dfs(i, -1);
        }

        return bridges;
    }
};


#include "bnn-library.h"
#include "dnn_config.hpp"

void top_level_0(ap_uint<INPUT_MEM_WIDTH> *conv_layer_0_input_mem,
	ap_uint<OUTPUT_MEM_WIDTH> *conv_layer_10_output_mem)
{

#pragma HLS INTERFACE s_axilite port=return bundle=control

	unsigned const conv_layer_0_reads_per_input_mem = CONV_LAYER_0_IFM_BITS_ALIGNED * CONV_LAYER_0_IFM_CH * CONV_LAYER_0_IFM_DIM * CONV_LAYER_0_IFM_DIM  / INPUT_MEM_WIDTH;
#pragma HLS INTERFACE m_axi offset=slave port=conv_layer_0_input_mem bundle=conv_layer_0_input_mem depth=conv_layer_0_reads_per_input_mem * Reps
#pragma HLS INTERFACE s_axilite port=conv_layer_0_input_mem bundle=control
	unsigned const conv_layer_10_writes_per_output_mem = CONV_LAYER_10_OFM_BITS_ALIGNED * CONV_LAYER_10_OFM_CH * CONV_LAYER_10_OFM_DIM * CONV_LAYER_10_OFM_DIM  / OUTPUT_MEM_WIDTH;
	unsigned const conv_layer_10_writes_per_output_stream = CONV_LAYER_10_OUTPUT_ACCESSES;
#pragma HLS INTERFACE m_axi offset=slave port=conv_layer_10_output_mem bundle=conv_layer_10_output_mem depth=conv_layer_10_writes_per_output_mem * Reps
#pragma HLS INTERFACE s_axilite port=conv_layer_10_output_mem bundle=control

#pragma HLS DATAFLOW
auto const default_compute_resource = ap_resource_dflt();
#include "dnn_params_0.hpp"

	hls::stream<ap_uint<INPUT_MEM_WIDTH>> conv_layer_0_m2s;
#pragma HLS STREAM variable=conv_layer_0_m2s depth=128
	hls::stream<ap_uint<CONV_LAYER_0_INPUT_STREAM_WIDTH>> conv_layer_0_input_stream;
#pragma HLS STREAM variable=conv_layer_0_input_stream depth=128
	hls::stream<ap_uint<CONV_LAYER_1_INPUT_STREAM_WIDTH>> conv_layer_0_conv_layer_1_stream;
#pragma HLS STREAM variable=conv_layer_0_conv_layer_1_stream depth=128
	hls::stream<ap_uint<CONV_LAYER_1_OUTPUT_STREAM_WIDTH>> conv_layer_1_sdwc_0_stream;
#pragma HLS STREAM variable=conv_layer_1_sdwc_0_stream depth=128
	hls::stream<ap_uint<SPLIT_0_INPUT_STREAM_WIDTH>> sdwc_0_split_0_stream;
#pragma HLS STREAM variable=sdwc_0_split_0_stream depth=128
	hls::stream<ap_uint<MAXPOOL_0_INPUT_STREAM_WIDTH>> split_0_maxpool_0_stream;
#pragma HLS STREAM variable=split_0_maxpool_0_stream depth=128
	hls::stream<ap_uint<MAXPOOL_0_OUTPUT_STREAM_WIDTH>> maxpool_0_sdwc_1_stream;
#pragma HLS STREAM variable=maxpool_0_sdwc_1_stream depth=128
	hls::stream<ap_uint<CONV_LAYER_2_INPUT_STREAM_WIDTH>> sdwc_1_conv_layer_2_stream;
#pragma HLS STREAM variable=sdwc_1_conv_layer_2_stream depth=128
	hls::stream<ap_uint<CONV_LAYER_2_OUTPUT_STREAM_WIDTH>> conv_layer_2_sdwc_2_stream;
#pragma HLS STREAM variable=conv_layer_2_sdwc_2_stream depth=128
	hls::stream<ap_uint<CONV_LAYER_3_INPUT_STREAM_WIDTH>> sdwc_2_conv_layer_3_stream;
#pragma HLS STREAM variable=sdwc_2_conv_layer_3_stream depth=128
	hls::stream<ap_uint<CONV_LAYER_3_OUTPUT_STREAM_WIDTH>> conv_layer_3_sdwc_3_stream;
#pragma HLS STREAM variable=conv_layer_3_sdwc_3_stream depth=128
	hls::stream<ap_uint<SPLIT_1_INPUT_STREAM_WIDTH>> sdwc_3_split_1_stream;
#pragma HLS STREAM variable=sdwc_3_split_1_stream depth=128
	hls::stream<ap_uint<MAXPOOL_1_INPUT_STREAM_WIDTH>> split_1_maxpool_1_stream;
#pragma HLS STREAM variable=split_1_maxpool_1_stream depth=128
	hls::stream<ap_uint<MAXPOOL_1_OUTPUT_STREAM_WIDTH>> maxpool_1_sdwc_4_stream;
#pragma HLS STREAM variable=maxpool_1_sdwc_4_stream depth=128
	hls::stream<ap_uint<CONV_LAYER_4_INPUT_STREAM_WIDTH>> sdwc_4_conv_layer_4_stream;
#pragma HLS STREAM variable=sdwc_4_conv_layer_4_stream depth=128
	hls::stream<ap_uint<CONV_LAYER_4_OUTPUT_STREAM_WIDTH>> conv_layer_4_sdwc_5_stream;
#pragma HLS STREAM variable=conv_layer_4_sdwc_5_stream depth=128
	hls::stream<ap_uint<CONV_LAYER_5_INPUT_STREAM_WIDTH>> sdwc_5_conv_layer_5_stream;
#pragma HLS STREAM variable=sdwc_5_conv_layer_5_stream depth=128
	hls::stream<ap_uint<CONV_LAYER_5_OUTPUT_STREAM_WIDTH>> conv_layer_5_sdwc_6_stream;
#pragma HLS STREAM variable=conv_layer_5_sdwc_6_stream depth=128
	hls::stream<ap_uint<CONVTRANSPOSE_0_INPUT_STREAM_WIDTH>> sdwc_6_convtranspose_0_stream;
#pragma HLS STREAM variable=sdwc_6_convtranspose_0_stream depth=128
	hls::stream<ap_uint<CONVTRANSPOSE_0_OUTPUT_STREAM_WIDTH>> convtranspose_0_sdwc_7_stream;
#pragma HLS STREAM variable=convtranspose_0_sdwc_7_stream depth=128
	hls::stream<ap_uint<CONCAT_0_INPUT_STREAM_WIDTH>> split_1_concat_0_stream;
#pragma HLS STREAM variable=split_1_concat_0_stream depth=118092
	hls::stream<ap_uint<CONCAT_0_INPUT_STREAM_WIDTH>> sdwc_7_concat_0_stream;
#pragma HLS STREAM variable=sdwc_7_concat_0_stream depth=128
	hls::stream<ap_uint<CONCAT_0_OUTPUT_STREAM_WIDTH>> concat_0_sdwc_8_stream;
#pragma HLS STREAM variable=concat_0_sdwc_8_stream depth=128
	hls::stream<ap_uint<CONV_LAYER_6_INPUT_STREAM_WIDTH>> sdwc_8_conv_layer_6_stream;
#pragma HLS STREAM variable=sdwc_8_conv_layer_6_stream depth=128
	hls::stream<ap_uint<CONV_LAYER_7_INPUT_STREAM_WIDTH>> conv_layer_6_conv_layer_7_stream;
#pragma HLS STREAM variable=conv_layer_6_conv_layer_7_stream depth=128
	hls::stream<ap_uint<CONV_LAYER_7_OUTPUT_STREAM_WIDTH>> conv_layer_7_sdwc_9_stream;
#pragma HLS STREAM variable=conv_layer_7_sdwc_9_stream depth=128
	h


#include "maxExport.h"
#include "3dsmaxport.h"

#include "decomp.h"
#include "modstack.h"

HINSTANCE hInstance;

static BOOL showPrompts;
static BOOL exportSelected;

using namespace std;
using namespace MaxSDK::Util;

namespace Globals {
	static MeshExporter	meshExporter;
	static ofstream	outputFile;
	Interface* interfacePtr;
}

#define MAX_EXP_CLASS_ID Class_ID(0x95348e0b, 0x5a26458c)
#define SYMMETRY_MOD_CLASS_ID Class_ID(763260982, 199498355)

BOOL WINAPI DllMain(HINSTANCE hinstDLL, ULONG fdwReason, LPVOID lpvReserved) {
   if (fdwReason == DLL_PROCESS_ATTACH) {
      MaxSDK::Util::UseLanguagePackLocale();
      hInstance = hinstDLL;
      DisableThreadLibraryCalls(hInstance);
   }

	return (TRUE);
}

__declspec( dllexport ) const TCHAR* LibDescription() {
	return GetString(IDS_LIBDESCRIPTION);
}

/// MUST CHANGE THIS NUMBER WHEN ADD NEW CLASS
__declspec( dllexport ) int LibNumberClasses() {
	return 1;
}

__declspec( dllexport ) ClassDesc* LibClassDesc(int i) {
	switch(i) {
	case 0: return GetMaxExportDesc();
	default: return 0;
	}
}

__declspec( dllexport ) ULONG LibVersion() {
	return VERSION_3DSMAX;
}

// Let the plug-in register itself for deferred loading
__declspec( dllexport ) ULONG CanAutoDefer() {
	return 1;
}

class MaxExpClassDesc: public ClassDesc {
public:
	int				IsPublic() { return 1; }
	void*			Create(BOOL loading = FALSE) { return new MaxExport; }
	const TCHAR*	ClassName() { return GetString(IDS_MAX_EXPORT); }
	const TCHAR*	NonLocalizedClassName() { return _T("MaxExport"); }
	SClass_ID		SuperClassID() { return SCENE_EXPORT_CLASS_ID; }
	Class_ID		ClassID() { return MAX_EXP_CLASS_ID; }
	const TCHAR*	Category() { return GetString(IDS_CATEGORY); }
};

static MaxExpClassDesc maxExportDesc;

ClassDesc* GetMaxExportDesc() {
	return &maxExportDesc;
}

TCHAR *GetString(int id) {
	static TCHAR buf[256];

	if (hInstance)
		return LoadString(hInstance, id, buf, _countof(buf)) ? buf : NULL;

	return NULL;
}

MaxExport::MaxExport() {
}

MaxExport::~MaxExport() {
}

int MaxExport::ExtCount() {
	return 1;
}

const TCHAR * MaxExport::Ext(int n) {
	switch(n) {
	case 0:
		// This cause a static string buffer overwrite
		// return GetString(IDS_EXTENSION1);
		return _T("RZ");
	}
	return _T("");
}

const TCHAR * MaxExport::LongDesc() {
	return GetString(IDS_LONGDESC);
}

const TCHAR * MaxExport::ShortDesc() {
	return GetString(IDS_SHORTDESC);
}

const TCHAR * MaxExport::AuthorName() {
	return _T("Ryze Graphics");
}

const TCHAR * MaxExport::CopyrightMessage() {
	return GetString(IDS_COPYRIGHT);
}

const TCHAR * MaxExport::OtherMessage1() {
	return _T("");
}

const TCHAR * MaxExport::OtherMessage2() {
	return _T("");
}

unsigned int MaxExport::Version() {
	return 200;
}

static INT_PTR CALLBACK AboutBoxDlgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
	switch (msg) {
	case WM_INITDIALOG:
		CenterWindow(hWnd, GetParent(hWnd));
		break;
	case WM_COMMAND:
		switch (LOWORD(wParam)) {
		case IDOK:
			EndDialog(hWnd, 1);
			break;
		}
		break;
		default:
			return FALSE;
	}
	return TRUE;
}

void MaxExport::ShowAbout(HWND hWnd) {
	DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, AboutBoxDlgProc, 0);
}

static INT_PTR CALLBACK ExportDlgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
	return TRUE;
}

// Dummy function for progress bar
DWORD WINAPI fn(LPVOID arg) {
	return(0);
}

namespace {
	FILE* OpenWriteFileWithBom(const TCHAR* filename, UINT codepage) {
		unsigned int encoding = TextFile::Writer::WRITE_BOM | codepage;

		// for a360 support - allows binary diff syncing
		MaxSDK::Util::Path storageNamePath(filename);
		storageNamePath.SaveBaseFile();

		switch (encoding & MSDE_CP_MASK) {
			case CP_UTF8:
				return  _tfopen(filename, _T("wt, ccs=UTF-8"));
				break;

			case MSDE_CP_UTF16:
				if (encoding & TextFile::Writer::FLIPPED) {
					return _tfopen(filename, _T("wt, ccs=UTF-16BE"));
				}
				else {
					return _tfopen(filename, _T("wt, ccs=UNICODE"));
				}
				break;
			default:
				return _tfopen(filename, _T("wt"));
		}
	}
}

// This is the real entrypoint to the exporter.
// After the user has selected the filename (and he's prompted for overwrite etc.) this method is called.
int MaxExport::DoExport(const TCHAR *name,ExpInterface *ei, Interface *ip, BOOL suppressPrompts, DWORD options) {
	Globals::outputFile.open(name, ios::out | ios::binary);

	Globals::interfacePtr = ip;

	int currHeader = ID_VERSION;
	Globals::outputFile.write((char*)&currHeader, 2);

	// Go Through all scene nodes
	ei->theScene->EnumTree(&Globals::meshExporter);

	Globals::outputFile.close();

	// Return TRUE If the file is exported properly
	return TRUE;
}

BOOL MaxExport::SupportsOptions(int ext, DWORD options) {
	assert(ext == 0);	// We only support one extension
	retu


#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <map>
#include <set>
#include <stdexcept>

using namespace std;

long double convertToDecimal(const string &val, int base) {
    long double result = 0;
    for (char c : val) {
        int digit;
        if (isdigit(c)) digit = c - '0';
        else digit = tolower(c) - 'a' + 10;
        if (digit >= base) {
            cerr << "Invalid digit for base " << base << ": " << c << "\n";
            exit(1);
        }
        result = result * base + digit;
    }
    return result;
}

vector<long double> lagrangeInterpolation(const vector<long double>& x, const vector<long double>& y) {
    int n = x.size();
    vector<long double> coef(n, 0.0);

    for (int i = 0; i < n; i++) {
        vector<long double> basis = {1.0};
        long double denom = 1.0;

        for (int j = 0; j < n; j++) {
            if (i == j) continue;
            vector<long double> next(basis.size() + 1, 0.0);
            for (int k = 0; k < basis.size(); k++) {
                next[k] -= basis[k] * x[j];
                next[k+1] += basis[k];
            }
            basis = next;
            denom *= (x[i] - x[j]);
        }

        for (int k = 0; k < basis.size(); k++)
            coef[k] += y[i] * basis[k] / denom;
    }

    return coef;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    string input, json;
    while (getline(cin, input)) json += input;
    if (json.empty()) {
        cerr << "Empty input\n";
        return 1;
    }

    // Remove spaces
    json.erase(remove(json.begin(), json.end(), ' '), json.end());

    // Extract n and k
    size_t pos = json.find("\"n\":");
    if (pos == string::npos) { cerr << "Missing n\n"; return 1; }
    int n = stoi(json.substr(pos + 4, json.find(',', pos) - (pos + 4)));

    pos = json.find("\"k\":");
    if (pos == string::npos) { cerr << "Missing k\n"; return 1; }
    int k = stoi(json.substr(pos + 4, json.find('}', pos) - (pos + 4)));

    // Collect roots
    vector<long double> X, Y;
    for (int i = 1; i <= n; i++) {
        string key = "\"" + to_string(i) + "\":";
        pos = json.find(key);
        if (pos == string::npos) continue;

        size_t bpos = json.find("\"base\":\"", pos);
        if (bpos == string::npos) continue;
        bpos += 8;
        size_t bend = json.find("\"", bpos + 1);
        int base = stoi(json.substr(bpos + 1, bend - (bpos + 1)));
        if (base < 2 || base > 16) {
            cerr << "Unsupported base: " << base << "\n";
            return 1;
        }

        size_t vpos = json.find("\"value\":\"", pos);
        if (vpos == string::npos) continue;
        vpos += 9;
        size_t vend = json.find("\"", vpos + 1);
        string value = json.substr(vpos + 1, vend - (vpos + 1));

        long double val = convertToDecimal(value, base);
        X.push_back(i);
        Y.push_back(val);
    }

    if (X.size() < k) {
        cerr << "Not enough roots to reconstruct polynomial\n";
        return 1;
    }

    // Use first k roots
    vector<long double> coef = lagrangeInterpolation(
        vector<long double>(X.begin(), X.begin() + k),
        vector<long double>(Y.begin(), Y.begin() + k)
    );

    // Output decimal roots
    cout << "Converted Roots:\n";
    for (auto v : Y) cout << fixed << setprecision(0) << v << " ";
    cout << "\n\n";

    // Output coefficients
    cout << "Polynomial Coefficients (from constant term to degree m):\n";
    for (auto c : coef) cout << fixed << setprecision(2) << c << " ";
    cout << "\n";

    return 0;
}


#include<windows.h>
#include<iostream>
using namespace std;

int main() {
	/*SetConsoleCP(1251);
	SetConsoleOutputCP(1251);
	cout << "Ââåäèòå ñâî¸ èìÿ: ";
	string name;
	cin >> name;
	int age;
	cout << "Ââåäèòå ñâîé âîçðàñò: ";
	cin >> age;
	cout << "Ïðèâåò," << name << "÷åðåç 10 ëåò òåáå áóäåò " << age + 10;
	*/

	/*double a;
	double b;
	double c;
	double d;
	double f;
	cin >> a>>b>>c>>d>>f;
	cout << (a + b + c + d + f)/5;
	return 0;
	*/

	/*void startMenu();
	void name_and_age();
	void average_aritmetic();
	int main() {
		startMenu();
	}
	void name_and_age() {
		çàäà÷à 1;
	}
	void startMenu() {
		bool flag = true;
		while (flag) {
			cout << "1-çàäà÷à1" << endl;
			cout << "2-çàäà÷à2" << endl;
			cout << "0-âûõîä" << endl;
		}
			int item;
			cin >> item;
			switch (item) {
			case1: name_and_age();
				break;
			case0: flag = false;
				break;
			}

	}*/

	/*int main() {
		char symb;
		cout << "Enter symbol= ";
		cin >> symb;
		cout << (int)symb;

		int code;
		cin >> code;
		cout << (char)code;
	}*/
}


/* * *********************************************************************
 \file main.cpp

 \brief Ce programme trouve la probabilité de gagner une mini loto.

 \author   Tiré du livre "starting out with C++" de Tony Gaddis
 \date     juillet 2016
 \modif    Marie-Flavie Auclair-Fortier, octobre 2020
 \version  2.0
 ********************************************************************** * */

#include <iostream>
#include <iomanip>
#include "modules.h"

using namespace std;

int main()
{

    // Declaration des fonctions
    void entrerInfosTirage(int&, int&);

    int nbChiffresTotaux;           // Le nombre total de chiffres
    int nbChiffresAChoisir;         // Le nombre de chiffre à choisir
    long int nbCombinaisons;        // Le nombre de combinaisons possibles

    cout << "Ce programme vous donne la probabilite de gagner la \"loto UdeS\". \n";
    entrerInfosTirage(nbChiffresTotaux, nbChiffresAChoisir);
    nbCombinaisons = calculeNbCombinaisons(nbChiffresTotaux, nbChiffresAChoisir);

    cout << fixed << showpoint << setprecision(4);
    cout << "\nVotre chance de gagner la lotterie est de "<< "une chance sur " << nbCombinaisons << ".\n";
    cout << "Ce qui equivaut a une probabilite de " << (1.0 / nbCombinaisons)    << "\n";

    return 0;
}

/* *****************************************************************

 \brief Ce module permet de demander et d'entrer les informations du tirage au clavier

 \param[out] s_nbChiffres : nb total de chiffres dans l'ensemble
 \param[out] s_nbChiffresAChoisir : nb de chiffres a choisir dans cet ensemble
 \post le nb total de chiffres devrait etre entre 1 et 12
 \post le nb a choisir devrait etre entre 1 et le nb total de chiffre

 ***************************************************************** */

void entrerInfosTirage(int &s_nbChiffres, int &s_nbChiffresAChoisir)
{

    while (s_nbChiffres < 1 || s_nbChiffres > 12) {
        cout << endl << "Parmi combien de chiffres (1 à 12) devez-vous choisir? ";
        cin >> s_nbChiffres;
    }

    while (s_nbChiffresAChoisir < 1 || s_nbChiffresAChoisir > s_nbChiffres) {
        cout << "Combien de chiffre devez-vous choisir? ";
        cin >> s_nbChiffresAChoisir;
    }
}


#ifdef NDEBUG
#undef NDEBUG
#endif

#include "llama.h"

#include "../src/llama-grammar.h"

#include <cassert>
#include <stdexcept>

int main()
{
    llama_grammar_parser parsed_grammar;

    std::vector<std::pair<std::string, uint32_t>> expected = {
        {"expr", 2},
        {"expr_6", 6},
        {"expr_7", 7},
        {"ident", 8},
        {"ident_10", 10},
        {"num", 9},
        {"num_11", 11},
        {"root", 0},
        {"root_1", 1},
        {"root_5", 5},
        {"term", 4},
        {"ws", 3},
        {"ws_12", 12},
    };

    std::vector<std::vector<llama_grammar_element>> expected_rules = {
        {{LLAMA_GRETYPE_RULE_REF, 5}, {LLAMA_GRETYPE_END, 0}},
        {
            {LLAMA_GRETYPE_RULE_REF, 2},
            {LLAMA_GRETYPE_CHAR, 61},
            {LLAMA_GRETYPE_RULE_REF, 3},
            {LLAMA_GRETYPE_RULE_REF, 4},
            {LLAMA_GRETYPE_CHAR, 10},
            {LLAMA_GRETYPE_END, 0},
        },
        {{LLAMA_GRETYPE_RULE_REF, 4}, {LLAMA_GRETYPE_RULE_REF, 7}, {LLAMA_GRETYPE_END, 0}},
        {{LLAMA_GRETYPE_RULE_REF, 12}, {LLAMA_GRETYPE_END, 0}},
        {
            {LLAMA_GRETYPE_RULE_REF, 8},
            {LLAMA_GRETYPE_ALT, 0},
            {LLAMA_GRETYPE_RULE_REF, 9},
            {LLAMA_GRETYPE_ALT, 0},
            {LLAMA_GRETYPE_CHAR, 40},
            {LLAMA_GRETYPE_RULE_REF, 3},
            {LLAMA_GRETYPE_RULE_REF, 2},
            {LLAMA_GRETYPE_CHAR, 41},
            {LLAMA_GRETYPE_RULE_REF, 3},
            {LLAMA_GRETYPE_END, 0},
        },
        {{LLAMA_GRETYPE_RULE_REF, 1}, {LLAMA_GRETYPE_RULE_REF, 5}, {LLAMA_GRETYPE_ALT, 0}, {LLAMA_GRETYPE_RULE_REF, 1}, {LLAMA_GRETYPE_END, 0}},
        {
            {LLAMA_GRETYPE_CHAR, 45},
            {LLAMA_GRETYPE_CHAR_ALT, 43},
            {LLAMA_GRETYPE_CHAR_ALT, 42},
            {LLAMA_GRETYPE_CHAR_ALT, 47},
            {LLAMA_GRETYPE_RULE_REF, 4},
            {LLAMA_GRETYPE_END, 0},
        },
        {{LLAMA_GRETYPE_RULE_REF, 6}, {LLAMA_GRETYPE_RULE_REF, 7}, {LLAMA_GRETYPE_ALT, 0}, {LLAMA_GRETYPE_END, 0}},
        {
            {LLAMA_GRETYPE_CHAR, 97},
            {LLAMA_GRETYPE_CHAR_RNG_UPPER, 122},
            {LLAMA_GRETYPE_RULE_REF, 10},
            {LLAMA_GRETYPE_RULE_REF, 3},
            {LLAMA_GRETYPE_END, 0},
        },
        {{LLAMA_GRETYPE_RULE_REF, 11}, {LLAMA_GRETYPE_RULE_REF, 3}, {LLAMA_GRETYPE_END, 0}},
        {
            {LLAMA_GRETYPE_CHAR, 97},
            {LLAMA_GRETYPE_CHAR_RNG_UPPER, 122},
            {LLAMA_GRETYPE_CHAR_ALT, 48},
            {LLAMA_GRETYPE_CHAR_RNG_UPPER, 57},
            {LLAMA_GRETYPE_CHAR_ALT, 95},
            {LLAMA_GRETYPE_RULE_REF, 10},
            {LLAMA_GRETYPE_ALT, 0},
            {LLAMA_GRETYPE_END, 0},
        },
        {
            {LLAMA_GRETYPE_CHAR, 48},
            {LLAMA_GRETYPE_CHAR_RNG_UPPER, 57},
            {LLAMA_GRETYPE_RULE_REF, 11},
            {LLAMA_GRETYPE_ALT, 0},
            {LLAMA_GRETYPE_CHAR, 48},
            {LLAMA_GRETYPE_CHAR_RNG_UPPER, 57},
            {LLAMA_GRETYPE_END, 0},
        },
        {
            {LLAMA_GRETYPE_CHAR, 32},
            {LLAMA_GRETYPE_CHAR_ALT, 9},
            {LLAMA_GRETYPE_CHAR_ALT, 10},
            {LLAMA_GRETYPE_RULE_REF, 12},
            {LLAMA_GRETYPE_ALT, 0},
            {LLAMA_GRETYPE_END, 0},
        },
    };

    for (auto pair : expected)
    {
        parsed_grammar.symbol_ids[pair.first] = pair.second;
    }

    for (auto rule : expected_rules)
    {
        parsed_grammar.rules.emplace_back();
        for (auto element : rule)
        {
            parsed_grammar.rules.back().push_back(element);
        }
    }

    std::vector<const llama_grammar_element *> grammar_rules(parsed_grammar.c_rules());

    llama_grammar * grammar = llama_grammar_init_impl(nullptr, grammar_rules.data(), grammar_rules.size(), parsed_grammar.symbol_ids.at("root"));
    if (grammar == nullptr) {
        throw std::runtime_error("Failed to initialize llama_grammar");
    }

    std::vector<std::vector<llama_grammar_element>> expected_stacks = {
        {
            {LLAMA_GRETYPE_RULE_REF, 5},
            {LLAMA_GRETYPE_CHAR, 61},
            {LLAMA_GRETYPE_RULE_REF, 7},
            {LLAMA_GRETYPE_CHAR, 97},
        },
        {
            {LLAMA_GRETYPE_RULE_REF, 5},
            {LLAMA_GRETYPE_CHAR, 61},
            {LLAMA_GRETYPE_RULE_REF, 7},
            {LLAMA_GRETYPE_RULE_REF, 3},
            {LLAMA_GRETYPE_CHAR, 48},
        },
        {
            {LLAMA_GRETYPE_RULE_REF, 5},
            {LLAMA_GRETYPE_CHAR, 61},
            {LLAMA_GRETYPE_RULE_REF, 7},
            {LLAMA_GRETYPE_RULE_REF, 3},
            {LLAMA_GRETYPE_CHAR, 48},
        },
        {
            {LLAMA_GRETYPE_RULE_REF, 5},
            {LLAMA_GRETYPE_CHAR, 61},
            {LLAMA_GRETYPE_RULE_REF, 7},
            {LLAMA_GRETYPE_CHAR, 40},
        },
        {
            {LLAMA_GRETYPE_CHAR, 61},
            {LLAMA_GRETYPE_RULE_REF, 7},
            {LLAMA_GRETYPE_CHAR, 97},
        },
        {
            {LLAMA_GRETYPE_CHAR, 61},
            {LL


#include <Arduino.h>

/* ************************************************************************
 * AeroHalo Fan PWM step test (Timer1 @ 25 kHz)
 * D9 = OC1A (PB1): fan PWM
 * D5 = LED blink
 * Duty steps: 0, 64, 128, 192, 255
 * ************************************************************************/

#define FAN_PWM_PIN     9    // D9 = PB1 / OC1A
#define LED_BLINK_PIN   5    // D5

// Set to true if your fan expects active-low PWM (Intel 4-wire spec)
static const bool PWM_INVERTED = true;

// 25 kHz using Fast PWM, TOP = ICR1 = 639 (F_CPU = 16 MHz, prescaler = 1)
static const uint16_t PWM_TOP = 639;

#define DUTY_STEPS_N 5
static const uint8_t duty_steps[DUTY_STEPS_N] = { 0, 64, 128, 192, 255 };

// Initialize Timer1 for 25 kHz on OC1A (D9)
static void timer1_init_25k_oc1a(bool inverted) {
  // Set D9 (PB1/OC1A) as output
  DDRB |= _BV(DDB1);

  // Fast PWM, mode 14: WGM13:0 = 1110 (TOP = ICR1)
  TCCR1A = 0;
  TCCR1B = 0;
  // Compare output: OC1A enabled, inverting or non-inverting
  if (inverted) {
    // Inverting: COM1A1=1, COM1A0=1  (low-time proportional to OCR1A)
    TCCR1A |= _BV(COM1A1) | _BV(COM1A0);
  } else {
    // Non-inverting: COM1A1=1, COM1A0=0 (high-time proportional to OCR1A)
    TCCR1A |= _BV(COM1A1);
  }
  // WGM bits
  TCCR1A |= _BV(WGM11);
  TCCR1B |= _BV(WGM13) | _BV(WGM12);

  // No prescale (clk/1)
  TCCR1B |= _BV(CS10);

  // Set TOP for 25 kHz
  ICR1 = PWM_TOP;

  // Start with 0% duty
  OCR1A = 0;
}

// Set duty using 0..255 scale (like analogWrite), mapped to 0..PWM_TOP
static void set_pwm_0_255(uint8_t duty) {
  // Map 0..255 -> 0..PWM_TOP
  uint16_t ticks = (uint32_t)duty * (PWM_TOP + 1) / 255u;
  if (ticks > PWM_TOP) ticks = PWM_TOP;
  OCR1A = ticks;
}

void setup() {
  pinMode(LED_BLINK_PIN, OUTPUT);
  digitalWrite(LED_BLINK_PIN, LOW);

  Serial.begin(115200);
  delay(200);
  Serial.println(F("\n--- FAN PWM static-step test on D9 (Timer1 @ 25 kHz) ---"));
  Serial.println(F("Steps: 0, 64, 128, 192, 255"));
  Serial.println(F("Multimeter should read average voltage ≈ 5.0 * duty/255 V"));

  timer1_init_25k_oc1a(PWM_INVERTED);
}

void loop() {
  for (uint8_t i = 0; i < DUTY_STEPS_N; ++i) {
    set_pwm_0_255(duty_steps[i]);

    // Blink LED briefly
    digitalWrite(LED_BLINK_PIN, HIGH);
    delay(10);
    digitalWrite(LED_BLINK_PIN, LOW);

    // Print status
    float duty_percent = (100.0 * duty_steps[i]) / 255.0;
    float v_avg = 5.0 * duty_steps[i] / 255.0;
    Serial.print(F("Step "));
    Serial.print(i + 1);
    Serial.print(F(": duty_raw="));
    Serial.print(duty_steps[i]);
    Serial.print(F(" ("));
    Serial.print(duty_percent, 1);
    Serial.print(F("% of scale), Timer1 OCR1A="));
    Serial.print(OCR1A);
    Serial.print(F("/"));
    Serial.print(PWM_TOP);
    Serial.print(F("), "));
    Serial.print(F("Vavg= "));
    Serial.print(v_avg, 2);
    Serial.println(F(" V"));

    delay(4900); // ~5 s
  }
}


//*********************************************************
// AboutCommand.cpp
//
// Copyright (C) 2007-2021 Skeletal Studios
// All rights reserved.
//
//*********************************************************

//*********************************************************
#include "AboutCommand.h"
#include "ErrorReporting.h"
//*********************************************************

//*********************************************************
// Constants
//*********************************************************
const char* AboutCommand::nameFlag = "-n";
const char* AboutCommand::nameLongFlag = "-name";
const char* AboutCommand::versionFlag = "-v";
const char* AboutCommand::versionLongFlag = "-version";
const char* AboutCommand::copyrightFlag = "-c";
const char* AboutCommand::copyrightLongFlag = "-copyright";

const char* AboutCommand::name = "tradigitools";
const char* AboutCommand::version = "1.5";

const char* AboutCommand::copyright = "Copyright 2007-2021 Skeletal Studios";

//*********************************************************
// Name: AboutCommand
// Desc: Constructor
//*********************************************************
AboutCommand::AboutCommand()
{

}

//*********************************************************
// Name: ~AboutCommand
// Desc: Destructor
//*********************************************************
AboutCommand::~AboutCommand()
{

}

//*********************************************************
// Name: doIt
// Desc: All of the one-time setup and initialization
//       code for the set key command.  doIt is called
//       by Maya when any command is executed in MEL.
//*********************************************************
MStatus AboutCommand::doIt( const MArgList &args )
{
    parseCommandFlags( args );

    return MS::kSuccess;
}

//*********************************************************
// Name: newSyntax
// Desc: Method for registering the command flags
//       with Maya
//*********************************************************
MSyntax AboutCommand::newSyntax()
{
    // Use MSyntax for a more robust solution to the
    // parsing the command flags
    MSyntax syntax;

    syntax.addFlag( nameFlag, nameLongFlag, MSyntax::kNoArg );
    syntax.addFlag( versionFlag, versionLongFlag, MSyntax::kNoArg );
    syntax.addFlag( copyrightFlag, copyrightLongFlag, MSyntax::kNoArg );

    return syntax;
}

//*********************************************************
// Name: parseCommandFlags
// Desc: Parse the command flags and stores the values
//       in the appropriate variables
//*********************************************************
MStatus AboutCommand::parseCommandFlags( const MArgList &args )
{
    MArgDatabase argData( syntax(), args );

    // No flags set returns the name
    if( argData.isFlagSet( versionFlag ))
        setResult( version );
    else if( argData.isFlagSet( copyrightFlag ))
        setResult( copyright );
    else
        setResult( name );

    return MS::kSuccess;
}


#include "il2cpp-config.h"
#include "il2cpp-api.h"
#include "il2cpp-class-internals.h"
#include "il2cpp-object-internals.h"
#include "il2cpp-tabledefs.h"
#include "icalls/mscorlib/System.Runtime.Remoting.Messaging/MonoMethodMessage.h"
#include "gc/WriteBarrier.h"
#include "os/Atomic.h"
#include "vm/Array.h"
#include "vm/Exception.h"
#include "vm/Method.h"
#include "vm/String.h"
#include "utils/dynamic_array.h"

namespace il2cpp
{
namespace icalls
{
namespace mscorlib
{
namespace System
{
namespace Runtime
{
namespace Remoting
{
namespace Messaging
{
    void MonoMethodMessage::InitMessage(Il2CppMethodMessage *this_obj, Il2CppReflectionMethod *method, Il2CppArray *out_args)
    {
        static Il2CppClass *object_array_klass;
        static Il2CppClass *byte_array_klass;
        static Il2CppClass *string_array_klass;
        Il2CppString *name;
        Il2CppArray *arr;
        int i, j;
        unsigned char arg_type;

        if (!object_array_klass)
        {
            Il2CppClass *klass;

            klass = il2cpp_array_class_get(il2cpp_defaults.byte_class, 1);
            IL2CPP_ASSERT(klass);
            byte_array_klass = klass;

            klass = il2cpp_array_class_get(il2cpp_defaults.string_class, 1);
            IL2CPP_ASSERT(klass);
            string_array_klass = klass;

            klass = il2cpp_array_class_get(il2cpp_defaults.object_class, 1);
            IL2CPP_ASSERT(klass);

            il2cpp::os::Atomic::ExchangePointer(&object_array_klass, klass);
        }

        IL2CPP_OBJECT_SETREF(this_obj, method, method);

        arr = il2cpp_array_new_specific(object_array_klass, method->method->parameters_count);

        IL2CPP_OBJECT_SETREF(this_obj, args, arr);

        arr = il2cpp_array_new_specific(byte_array_klass, method->method->parameters_count);

        IL2CPP_OBJECT_SETREF(this_obj, arg_types, arr);

        this_obj->async_result = NULL;
        this_obj->call_type = Il2Cpp_CallType_Sync;

        il2cpp::utils::dynamic_array<const char*> names(method->method->parameters_count);

        for (int i = 0; i < method->method->parameters_count; ++i)
            names[i] = vm::Method::GetParamName(method->method, i);

        arr = il2cpp_array_new_specific(string_array_klass, method->method->parameters_count);

        IL2CPP_OBJECT_SETREF(this_obj, names, arr);

        for (i = 0; i < method->method->parameters_count; i++)
        {
            name = il2cpp::vm::String::New(names[i]);
            il2cpp_array_setref(this_obj->names, i, name);
        }

        for (i = 0, j = 0; i < method->method->parameters_count; i++)
        {
            if (method->method->parameters[i]->byref)
            {
                if (out_args)
                {
                    Il2CppObject* arg = (Il2CppObject*)il2cpp_array_get(out_args, void*, j);
                    il2cpp_array_setref(this_obj->args, i, arg);
                    j++;
                }

                arg_type = 2;
                if (!(method->method->parameters[i]->attrs & PARAM_ATTRIBUTE_OUT))
                    arg_type |= 1;
            }
            else
            {
                arg_type = 1;
                if (method->method->parameters[i]->attrs & PARAM_ATTRIBUTE_OUT)
                    arg_type |= 4;
            }

            il2cpp_array_set(this_obj->arg_types, unsigned char, i, arg_type);
        }
    }
} /* namespace Messaging */
} /* namespace Remoting */
} /* namespace Runtime */
} /* namespace System */
} /* namespace mscorlib */
} /* namespace icalls */
} /* namespace il2cpp */


// Created by IT-JIM
// VIDEO1 : Send video to appsink, display with cv::imshow()

#include <iostream>
#include <string>
#include <thread>

#include <gst/gst.h>
#include <gst/app/gstappsink.h>
#include <fstream>

#include "encode_z16.h"
#include "encodeRGBtoI420.h"

#include <opencv2/opencv.hpp>

//======================================================================================================================
/// A simple assertion function + macro
inline void myAssert(bool b, const std::string& s = "MYASSERT ERROR !") {
    if (!b)
        throw std::runtime_error(s);
}

#define MY_ASSERT(x) myAssert(x, "MYASSERT ERROR :" #x)

//======================================================================================================================
/// Check GStreamer error, exit on error
inline void checkErr(GError* err) {
    if (err) {
        std::cerr << "checkErr : " << err->message << std::endl;
        exit(0);
    }
}

//======================================================================================================================
/// Our global data, serious gstreamer apps should always have this !
struct GoblinData {
    GstElement* pipeline = nullptr;
    GstElement* sinkVideo = nullptr;
};

//======================================================================================================================
/// Process a single bus message, log messages, exit on error, return false on eof
static bool busProcessMsg(GstElement* pipeline, GstMessage* msg, const std::string& prefix) {
    using namespace std;

    GstMessageType mType = GST_MESSAGE_TYPE(msg);
    cout << "[" << prefix << "] : mType = " << mType << " ";
    switch (mType) {
    case (GST_MESSAGE_ERROR):
        // Parse error and exit program, hard exit
        GError* err;
        gchar* dbg;
        gst_message_parse_error(msg, &err, &dbg);
        cout << "ERR = " << err->message << " FROM " << GST_OBJECT_NAME(msg->src) << endl;
        cout << "DBG = " << dbg << endl;
        g_clear_error(&err);
        g_free(dbg);
        exit(1);
    case (GST_MESSAGE_EOS):
        // Soft exit on EOS
        cout << " EOS !" << endl;
        return false;
    case (GST_MESSAGE_STATE_CHANGED):
        // Parse state change, print extra info for pipeline only
        cout << "State changed !" << endl;
        if (GST_MESSAGE_SRC(msg) == GST_OBJECT(pipeline)) {
            GstState sOld, sNew, sPenging;
            gst_message_parse_state_changed(msg, &sOld, &sNew, &sPenging);
            cout << "Pipeline changed from " << gst_element_state_get_name(sOld) << " to " <<
                gst_element_state_get_name(sNew) << endl;
        }
        break;
    case (GST_MESSAGE_STEP_START):
        cout << "STEP START !" << endl;
        break;
    case (GST_MESSAGE_STREAM_STATUS):
        cout << "STREAM STATUS !" << endl;
        break;
    case (GST_MESSAGE_ELEMENT):
        cout << "MESSAGE ELEMENT !" << endl;
        break;

    default:
        cout << endl;
    }
    return true;
}

//======================================================================================================================
/// Run the message loop for one bus
void codeThreadBus(GstElement* pipeline, GoblinData& data, const std::string& prefix) {
    using namespace std;
    GstBus* bus = gst_element_get_bus(pipeline);

    int res;
    while (true) {
        GstMessage* msg = gst_bus_timed_pop(bus, GST_CLOCK_TIME_NONE);
        MY_ASSERT(msg);
        res = busProcessMsg(pipeline, msg, prefix);
        gst_message_unref(msg);
        if (!res)
            break;
    }
    gst_object_unref(bus);
    cout << "BUS THREAD FINISHED : " << prefix << endl;
}

//======================================================================================================================
/// Appsink process thread
void codeThreadProcessV(GoblinData& data) {
    using namespace std;
    initialize_delta_table();
    initialize_z16_tables();

    int imW = 1280;
    int imH = 720;
    uint8_t* color_rgba = new uint8_t[imH * imW * 4 * 2]; // attention si concatene pas oublier le fois 2
    uint8_t* color_yuv = new uint8_t[imH * imW * 3/2];
    uint8_t* depth_yuv = new uint8_t[imH * imW * 3/2];
    uint16_t* depth_z16 = new uint16_t[imH * imW];

    std::string filename_z16 = "z16_video1_received.raw";
    std::string filename_ARGB = "ARGB_video1_received.raw";

    // === Writting RAW files ===
    std::ofstream ofs_Z16(filename_z16, std::ios::binary);
    std::ofstream ofs_ARGB(filename_ARGB, std::ios::binary);

    for (;;) {
        // Exit on EOS
        if (gst_app_sink_is_eos(GST_APP_SINK(data.sinkVideo))) {
            cout << "EOS !" << endl;
            break;
        }

        // Pull the sample (synchronous, wait)
        GstSample* sample = gst_app_sink_pull_sample(GST_APP_SINK(data.sinkVideo));
        if (sample == nullptr) {
            cout << "NO sample !" << endl;
            break;
        }

        GstBuffer* buffer = gst_sample_get_buffer(sample);


#include "ramfs.hpp"
#include <unordered_map>
#include <functional>
#include <ranges>

string join(vector<string> arr, const string& sep = " ")
{
    string joined;
    for (int i = 0; i < arr.size() - 1; i ++)
    {
        joined += arr[i] + sep;
    }
    joined += arr[arr.size() - 1];

    return joined;
}
int main()
{
    // cmds - cd, ls, touch, rm, mkdir, rmdir, exit
    RamFS ramFS;
    string fsCmd;
    string ramFSAscii = R"(
 _  .-')     ('-.     _   .-')                .-')
( \( -O )   ( OO ).-.( '.( OO )_             ( OO ).
 ,------.   / . --. / ,--.   ,--.)  ,------.(_)---\_)
 |   /`. '  | \-.  \  |   `.'   |('-| _.---'/    _ |
 |  /  | |.-'-'  |  | |         |(OO|(_\    \  :` `.
 |  |_.' | \| |_.'  | |  |'.'|  |/  |  '--.  '..`''.)
 |  .  '.'  |  .-.  | |  |   |  |\_)|  .--' .-._)   \
 |  |\  \   |  | |  | |  |   |  |  \|  |_)  \       /
 `--' '--'  `--' `--' `--'   `--'   `--'     `-----'
    )";

    string helpMsg = R"(
    +-------------------+----------------------------------+
    | Command           | Usage                            |
    +-------------------+----------------------------------+
    | make directory    | mkdir <dir-name>                 |
    | delete directory  | rmdir <dir-name>                 |
    | make file         | touch <file-name>                |
    | delete file / dir | rm <file-name> / <dir-name>      |
    | navigate to dir   | cd <dir-name>                    |
    | list contents     | ls <dir-name>                    |
    | write to file     | write <file-name> <contents>     |
    | read file         | read <file-name>                 |
    +-------------------+----------------------------------+

    Notes:
    - Current directory is represented by `.`
    - Parent directory is represented by `..`
    )";
    unordered_map<string, function< void(const string&, const string&) > > commands =
    {
        {"cd", [&](const string& path, const string&){ramFS.cd(path.empty() ? "." : path);} },
        {"ls", [&](const string& path, const string&){ramFS.ls(path.empty() ? "." : path);} },
        {"touch", [&](const string& path, const string&){ramFS.mknod(path);} },
        {"rm", [&](const string& path, const string&){ramFS.rmnod(path);} },
        {"mkdir", [&](const string& path, const string&){ramFS.mkdir(path);} },
        {"rmdir", [&](const string& path, const string&){ramFS.rmdir(path);} },
        {"write", [&](const string& path, const string& content){ramFS.write(path, content);} },
        {"read", [&](const string& path, const string& content){ramFS.read(path);} },
        {"help", [&](const string& path, const string&){cout << helpMsg << endl;} },
        {"exit", [&](const string& path, const string&){cout << "Catchya Later:)" << endl; exit(0);} }
    };

    cout << ramFSAscii << endl << endl;
    while (true)
    {
        cout << "--(RamFS)--[" << ramFS.getCurrentDir() << "]--# ";
        getline(cin, fsCmd);
        if (fsCmd.empty()) continue;

        auto fsCmds = ramFS.split(fsCmd, ' ');
        string cmd = fsCmds[0];
        string path;
        string fileContent;
        if (fsCmds.size() >= 2)
        {
            path = fsCmds[1];
        }
        if (fsCmds.size() >= 3)
        {
            vector<string> fileContentArr(fsCmds.begin() + 2, fsCmds.end());
            fileContent = join(fileContentArr);
        }
        auto it = commands.find(cmd);
        if (it != commands.end())
        {
            it->second(path, fileContent);
        }
        else
        {
            cout << "Unknown command" << endl;
        }
    }

    return 0;
}


// ChenGangQiang All rights Reserved.

#include "ShooterAnimInstance.h"
#include "ShooterCharacter.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "Kismet/KismetMathLibrary.h"

void UShooterAnimInstance::NativeInitializeAnimation()
{
	ShooterCharacter = Cast<AShooterCharacter>(TryGetPawnOwner());
}

void UShooterAnimInstance::UpdateAnimationProperties(float DeltaTime)
{
	if (ShooterCharacter == nullptr)
	{
		ShooterCharacter = Cast<AShooterCharacter>(TryGetPawnOwner());
	}

	if (ShooterCharacter)
	{
		// 从速度（矢量）中获取角色的横向速度 Get the lateral speed of the character from velocity
		FVector Velocity { ShooterCharacter->GetVelocity() };
		Velocity.Z = 0;
		Speed = Velocity.Size();

		// 是否在空中 Is the character in the air?
		bIsInAir = ShooterCharacter->GetCharacterMovement()->IsFalling();

		// 是否加速 Is the character accelerating?
		if (ShooterCharacter->GetCharacterMovement()->GetCurrentAcceleration().Size() > 0.f)
		{
			bIsAccelerating = true;
		}
		else
		{
			bIsAccelerating = false;
		}

		// 角色朝向与移动方向的夹角 The angle between the character's
		FRotator AimRotation = ShooterCharacter->GetBaseAimRotation();
		FRotator MovementRotation = UKismetMathLibrary::MakeRotFromX(ShooterCharacter->GetVelocity());
		MovementOffsetYaw = UKismetMathLibrary::NormalizedDeltaRotator(MovementRotation, AimRotation).Yaw;

		if (ShooterCharacter->GetVelocity().Size() > 0.f)
		{
			LastMovementOffsetYaw = MovementOffsetYaw;
		}

	}
}


/*
 [auto_generated]
 libs/numeric/odeint/test/same_size.cpp

 [begin_description]
 tba.
 [end_description]

 Copyright 2009-2012 Karsten Ahnert
 Copyright 2009-2012 Mario Mulansky

 Distributed under the Boost Software License, Version 1.0.
 (See accompanying file LICENSE_1_0.txt or
 copy at http://www.boost.org/LICENSE_1_0.txt)
 */

#include <boost/config.hpp>
#ifdef BOOST_MSVC
    #pragma warning(disable:4996)
#endif

#define BOOST_TEST_MODULE odeint_dummy

#include <boost/test/unit_test.hpp>

#include <boost/numeric/odeint/util/same_size.hpp>

using namespace boost::unit_test;
using namespace boost::numeric::odeint;

BOOST_AUTO_TEST_SUITE( same_size_test )

BOOST_AUTO_TEST_CASE( test_vector_true )
{
    std::vector< double > v1( 10 ) , v2( 10 );
    BOOST_CHECK_EQUAL( true , same_size( v1 , v2 ) );
}

BOOST_AUTO_TEST_CASE( test_vector_false )
{
    std::vector< double > v1( 10 ) , v2( 20 );
    BOOST_CHECK_EQUAL( false , same_size( v1 , v2 ) );
}

BOOST_AUTO_TEST_CASE( test_fusion_true )
{
    boost::fusion::vector< double , std::vector< double > > v1 , v2;
    boost::fusion::at_c< 1 >( v1 ).resize( 10 );
    boost::fusion::at_c< 1 >( v2 ).resize( 10 );
    BOOST_CHECK_EQUAL( true , same_size( v1 , v2 ) );
}

BOOST_AUTO_TEST_CASE( test_fusion_false )
{
    boost::fusion::vector< double , std::vector< double > > v1 , v2;
    boost::fusion::at_c< 1 >( v1 ).resize( 10 );
    boost::fusion::at_c< 1 >( v2 ).resize( 20 );
    BOOST_CHECK_EQUAL( false , same_size( v1 , v2 ) );
}

BOOST_AUTO_TEST_SUITE_END()


// File: circuit.cpp
// Author: Dylan George
// Date Modified: 1st September 2025
// Description: Implementation file for circuit-related classes and functions.

#include "circuits.hpp"

// cSubCircuit constructor initializes the subcircuit with the given number of inputs and outputs.
cSubCircuit::cSubCircuit(int aNumInputs, int aNumOutputs)
    : cLogicGate( aNumInputs, aNumOutputs) {
}
//---
// cHalfAdder constructor sets up a half adder with 2 inputs and 2 outputs.
cHalfAdder::cHalfAdder() : cSubCircuit(/*inputs*/2, /*outputs*/2) {
    ComputeOutput(); // Compute initial output values
}
// Calls ComputeOutput to set initial output values.
//---
void cHalfAdder::ComputeOutput() {
    // Compute the outputs for the half adder:
    // - AND gate computes carry output
    // - XOR gate computes sum output
    mAND.DriveInput(INPUT_A, mInputs[INPUT_A]); // Set first input of AND gate
    mAND.DriveInput(INPUT_B, mInputs[INPUT_B]); // Set second input of AND gate
    mAND.ComputeOutput(); // Calculate AND gate output

    mXOR.DriveInput(INPUT_A, mInputs[INPUT_A]); // Set first input of XOR gate
    mXOR.DriveInput(INPUT_B, mInputs[INPUT_B]); // Set second input of XOR gate
    mXOR.ComputeOutput(); // Calculate XOR gate output

    mOutputValues[SUM_OUTPUT] = mXOR.GetOutputState(OUTPUT); // Store XOR output as SUM
    mOutputValues[CARRY_OUTPUT] = mAND.GetOutputState(OUTPUT); // Store AND output as CARRY
}
//---
void cHalfAdder::TestOutputs() {
    // Print the truth table for the half adder
    std::cout << "\nTest Output for Half Adder" << std::endl;
    std::cout << "A B | Sum Cout" << std::endl;
    std::cout << "----------------" << std::endl;
    for (int i = 0; i < 4; i++) {
        int A = (i >> 1) & 1;
        int B = i & 1;
        DriveInput(INPUT_A, A ? cLogic::LOGIC_HIGH : cLogic::LOGIC_LOW);
        DriveInput(INPUT_B, B ? cLogic::LOGIC_HIGH : cLogic::LOGIC_LOW);
        ComputeOutput();
        int Sum = GetOutputState(SUM_OUTPUT);
        int Cout = GetOutputState(CARRY_OUTPUT);
        std::cout << A << " " << B << " |  " << Sum << "    " << Cout << std::endl;
    }
}

//---cFullAdder Implementation------------------------------------------------
cFullAdder::cFullAdder() : cSubCircuit(/*inputs*/3, /*outputs*/2) {
    ComputeOutput();
}
// cFullAdder constructor sets up a full adder with 3 inputs and 2 outputs.
// Calls ComputeOutput to set initial output values.
//---
void cFullAdder::ComputeOutput() {
    // Compute the outputs for the full adder:
    // - First half adder adds A and B
    // - Second half adder adds sum from first half adder and carry-in
    // - OR gate combines carry outputs
    mHalfAdder1.DriveInput(INPUT_A, mInputs[INPUT_A]);
    mHalfAdder1.DriveInput(INPUT_B, mInputs[INPUT_B]);
    mHalfAdder1.ComputeOutput();

    mHalfAdder2.DriveInput(INPUT_A, mHalfAdder1.GetOutputState(SUM_OUTPUT));
    mHalfAdder2.DriveInput(INPUT_B, mInputs[INPUT_CARRY]);
    mHalfAdder2.ComputeOutput();

    mOutputValues[SUM_OUTPUT] = mHalfAdder2.GetOutputState(SUM_OUTPUT);

    mOR.DriveInput(INPUT_A, mHalfAdder2.GetOutputState(CARRY_OUTPUT));
    mOR.DriveInput(INPUT_B, mHalfAdder1.GetOutputState(CARRY_OUTPUT) );
    mOR.ComputeOutput();

    mOutputValues[CARRY_OUTPUT] = mOR.GetOutputState(OUTPUT);
}
//---
void cFullAdder::TestOutputs() {
    // Print the truth table for the full adder
    std::cout << "\nTest Output for Full Adder " << std::endl;
    std::cout << "A B Cin | Sum Cout" << std::endl;
    std::cout << "------------------" << std::endl;

    // Loop through all input combinations (0 to 7)
    for (int i = 0; i < 8; i++) {
        // Extract bits for A, B, Cin
        int A   = (i >> 2) & 1;  // MSB
        int B   = (i >> 1) & 1;  // Middle bit
        int Cin =  i       & 1;  // LSB

        // Drive inputs
        DriveInput(INPUT_A, A ? cLogic::LOGIC_HIGH : cLogic::LOGIC_LOW);
        DriveInput(INPUT_B, B ? cLogic::LOGIC_HIGH : cLogic::LOGIC_LOW);
        DriveInput(INPUT_CARRY, Cin ? cLogic::LOGIC_HIGH : cLogic::LOGIC_LOW);

        // Compute output if needed
        ComputeOutput();

        // Read outputs
        int Sum  = GetOutputState(SUM_OUTPUT);
        int Cout = GetOutputState(CARRY_OUTPUT);

        // Print in ordered table
        std::cout << A << " " << B << "  " << Cin
                  << "   |  " << Sum << "    " << Cout << std::endl;
    }
}

//---cThreeBitAdder Implementation------------------------------------------------
// Constructor for ThreeBitAdder, sets up a 6-input, 4-output subcircuit
cThreeBitAdder::cThreeBitAdder() : cSubCircuit(/*inputs*/6, /*outputs*/4) {
    ComputeOutput();
}
// cThreeBitAdder constructor sets up a 3-bit adder with 6 inputs and 4 outputs.
// Calls ComputeOutput to set initial output values.
//---
void cThreeBitAdder::ComputeOutput() {
    // Compute the outputs for the 3-bit adder:
    // - Stage 0: LSB uses Half Adder on A0, B0
    mHalfAdder.DriveInput(INPUT_A, mInputs[A0]);
    mHalfAdder.DriveInput(INPUT_B,


// Circular queue using arr?

#include<iostream>

using namespace std;

template <typename t>
class Queue
{
    int size;
    int front;
    int rear;
    t *q;

    public:

    Queue()
    {
        cout<<"Enter the size of the queue : ";
        cin>>size;
        size++;
        q = new t[size];

        front = rear = 0;
    }

    bool isempty()
    {
        return front == rear;
    }

    bool isfull()
    {
        return (rear+1)%size == front;
    }

    void push(t x)
    {
        //cout<<"front = "<<front<<" , rear = "<<rear<<"\n";
        if(isfull())
        {
            cout<<"Queue is FULL cannot insert "<<x<<"\n";
            return;
        }

        rear = (rear+1) % size;
        q[rear] = x;
        cout<<x<<" successfully inserted\n";
    }

    void pop()
    {
        if(isempty())
        {
            cout<<"Queue is Empty\n";
            return;
        }

        front = (front+1)%size;
        cout<<q[front]<<" is popped \n";
        return;
    }

    void display()
    {
        if(isempty())
        {
            cout<<"Empty queue to display\n";
            return;
        }

        for(int i=(front+1)%size; i != (rear+1)%size ;)
        {
            cout<<q[i]<<"<-";
            i = (i+1)%size;
        }
        cout<<"\n";
    }
};

int main()
{
    cout<<"Integer Queue\n";
    Queue <int> q1;
    q1.push(10);
    q1.push(20);
    q1.display();
    q1.push(30);
    q1.display();
    q1.pop();
    q1.display();
    q1.pop();
    q1.display();
    q1.pop();

    cout<<"=========================\n";
    cout<<"\nDouble Queue\n";
    Queue <double> q2;
    q2.push(1.0);
    q2.push(2.20);
    q2.display();
    q2.push(3.3);
    q2.display();
    q2.pop();
    q2.display();
    q2.pop();
    q2.display();
    q2.pop();
}


// inotifywatcher.cpp
#include "inotifywatcher.h"
#include <sys/inotify.h>
#include <unistd.h>
#include <QDebug>

InotifyWatcher::InotifyWatcher(const QString &path, QObject *parent)
    : QObject(parent)
{
    fd = inotify_init1(IN_NONBLOCK);
    if (fd < 0) {
        perror("inotify_init1");
        return;
    }

    addWatch(path);

    notifier = new QSocketNotifier(fd, QSocketNotifier::Read, this);
    connect(notifier, &QSocketNotifier::activated, this, &InotifyWatcher::processEvents);
}

InotifyWatcher::~InotifyWatcher() {
    if (notifier) delete notifier;
    if (fd >= 0) close(fd);
}

void InotifyWatcher::addWatch(const QString &path) {
    int wd = inotify_add_watch(fd, path.toUtf8().constData(),
                               IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO);
    if (wd < 0) {
        perror("inotify_add_watch");
    } else {
        watchDescriptors[wd] = path;
    }
}

void InotifyWatcher::processEvents() {
    char buf[4096]
        __attribute__ ((aligned(__alignof__(struct inotify_event))));
    ssize_t len;

    while ((len = read(fd, buf, sizeof buf)) > 0) {
        for (char *ptr = buf; ptr < buf + len; ) {
            struct inotify_event *event = (struct inotify_event *) ptr;
            QString base = watchDescriptors[event->wd];
            QString full = base + "/" + QString::fromUtf8(event->name);

            if (event->mask & (IN_CREATE | IN_MOVED_TO)) emit fileCreated(full);
            if (event->mask & (IN_DELETE | IN_MOVED_FROM)) emit fileDeleted(full);

            ptr += sizeof(struct inotify_event) + event->len;
        }
    }
}


// Copyright Epic Games, Inc. All Rights Reserved.

#include "SideScrollingCharacter.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "Components/CapsuleComponent.h"
#include "Camera/CameraComponent.h"
#include "Components/InputComponent.h"
#include "InputActionValue.h"
#include "EnhancedInputComponent.h"
#include "InputAction.h"
#include "Engine/World.h"
#include "SideScrollingInteractable.h"
#include "Kismet/KismetMathLibrary.h"
#include "TimerManager.h"

ASideScrollingCharacter::ASideScrollingCharacter()
{
	PrimaryActorTick.bCanEverTick = true;

	// create the camera component
	Camera = CreateDefaultSubobject<UCameraComponent>(TEXT("Camera"));
	Camera->SetupAttachment(RootComponent);

	Camera->SetRelativeLocationAndRotation(FVector(0.0f, 300.0f, 0.0f), FRotator(0.0f, -90.0f, 0.0f));

	// configure the collision capsule
	GetCapsuleComponent()->SetCapsuleSize(35.0f, 90.0f);

	// configure the Pawn properties
	bUseControllerRotationYaw = false;

	// configure the character movement component
	GetCharacterMovement()->GravityScale = 1.75f;
	GetCharacterMovement()->MaxAcceleration = 1500.0f;
	GetCharacterMovement()->BrakingFrictionFactor = 1.0f;
	GetCharacterMovement()->bUseSeparateBrakingFriction = true;
	GetCharacterMovement()->Mass = 500.0f;

	GetCharacterMovement()->SetWalkableFloorAngle(75.0f);
	GetCharacterMovement()->MaxWalkSpeed = 500.0f;
	GetCharacterMovement()->MinAnalogWalkSpeed = 20.0f;
	GetCharacterMovement()->BrakingDecelerationWalking = 2000.0f;
	GetCharacterMovement()->bIgnoreBaseRotation = true;

	GetCharacterMovement()->PerchRadiusThreshold = 15.0f;
	GetCharacterMovement()->LedgeCheckThreshold = 6.0f;

	GetCharacterMovement()->JumpZVelocity = 750.0f;
	GetCharacterMovement()->AirControl = 1.0f;

	GetCharacterMovement()->RotationRate = FRotator(0.0f, 750.0f, 0.0f);
	GetCharacterMovement()->bOrientRotationToMovement = true;

	GetCharacterMovement()->SetPlaneConstraintNormal(FVector(0.0f, 1.0f, 0.0f));
	GetCharacterMovement()->bConstrainToPlane = true;

	// enable double jump and coyote time
	JumpMaxCount = 3;
}

void ASideScrollingCharacter::EndPlay(EEndPlayReason::Type EndPlayReason)
{
	Super::EndPlay(EndPlayReason);

	// clear the wall jump timer
	GetWorld()->GetTimerManager().ClearTimer(WallJumpTimer);
}

void ASideScrollingCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent)
{
	Super::SetupPlayerInputComponent(PlayerInputComponent);

	// Set up action bindings
	if (UEnhancedInputComponent* EnhancedInputComponent = Cast<UEnhancedInputComponent>(PlayerInputComponent))
	{
		// Jumping
		EnhancedInputComponent->BindAction(JumpAction, ETriggerEvent::Started, this, &ASideScrollingCharacter::DoJumpStart);
		EnhancedInputComponent->BindAction(JumpAction, ETriggerEvent::Completed, this, &ASideScrollingCharacter::DoJumpEnd);

		// Interacting
		EnhancedInputComponent->BindAction(InteractAction, ETriggerEvent::Triggered, this, &ASideScrollingCharacter::DoInteract);

		// Moving
		EnhancedInputComponent->BindAction(MoveAction, ETriggerEvent::Triggered, this, &ASideScrollingCharacter::Move);

		// Dropping from platform
		EnhancedInputComponent->BindAction(DropAction, ETriggerEvent::Triggered, this, &ASideScrollingCharacter::Drop);
		EnhancedInputComponent->BindAction(DropAction, ETriggerEvent::Completed, this, &ASideScrollingCharacter::DropReleased);

	}
}

void ASideScrollingCharacter::NotifyHit(class UPrimitiveComponent* MyComp, AActor* Other, class UPrimitiveComponent* OtherComp, bool bSelfMoved, FVector HitLocation, FVector HitNormal, FVector NormalImpulse, const FHitResult& Hit)
{
	Super::NotifyHit(MyComp, Other, OtherComp, bSelfMoved, HitLocation, HitNormal, NormalImpulse, Hit);

	// only apply push impulse if we're falling
	if (!GetCharacterMovement()->IsFalling())
	{
		return;
	}

	// ensure the colliding component is valid
	if (OtherComp)
	{
		// ensure the component is movable and simulating physics
		if (OtherComp->Mobility == EComponentMobility::Movable && OtherComp->IsSimulatingPhysics())
		{
			const FVector PushDir = FVector(ActionValueY > 0.0f ? 1.0f : -1.0f, 0.0f, 0.0f);

			// push the component away
			OtherComp->AddImpulse(PushDir * JumpPushImpulse, NAME_None, true);
		}
	}
}

void ASideScrollingCharacter::Landed(const FHitResult& Hit)
{
	// reset the double jump
	bHasDoubleJumped = false;
}

void ASideScrollingCharacter::OnMovementModeChanged(EMovementMode PrevMovementMode, uint8 PreviousCustomMode /*= 0*/)
{
	Super::OnMovementModeChanged(PrevMovementMode, PreviousCustomMode);

	// are we falling?
	if (GetCharacterMovement()->MovementMode == EMovementMode::MOVE_Falling)
	{
		// save the game time when we started falling, so we can check it later for coyote time jumps
		LastFallTime = GetWorld()->GetTimeSeconds();
	}
}

void ASideScrollingCharacter::Move(const FInputActionValue& Value)
{
	FVector2D MoveVector = Value.Get<FVector2D>();

	// route the input
	DoMove(MoveVector.Y);
}

void ASideScrollingCharacter::Drop(const FInputActionValu


//
// Created by vibho on 03-07-2023.
//
#include "GenericCube.h"

class CubeBitboard : public GenericCube {

private:
    uint64_t solved_side_config[6]{};

    int arr[3][3] = {{0, 1, 2},
                     {7, 8, 3},
                     {6, 5, 4}};

    uint64_t one_8 = (1 << 8) - 1, one_24 = (1 << 24) - 1;

    void rotateFace(int ind) {
        uint64_t side = bitboard[ind];
        side = side >> (8 * 6);
        bitboard[ind] = (bitboard[ind] << 16) | (side);
    }

    void rotateSide(int s1, int s1_1, int s1_2, int s1_3, int s2, int s2_1, int s2_2, int s2_3) {
        uint64_t clr1 = (bitboard[s2] & (one_8 << (8 * s2_1))) >> (8 * s2_1);
        uint64_t clr2 = (bitboard[s2] & (one_8 << (8 * s2_2))) >> (8 * s2_2);
        uint64_t clr3 = (bitboard[s2] & (one_8 << (8 * s2_3))) >> (8 * s2_3);

        bitboard[s1] = (bitboard[s1] & ~(one_8 << (8 * s1_1))) | (clr1 << (8 * s1_1));
        bitboard[s1] = (bitboard[s1] & ~(one_8 << (8 * s1_2))) | (clr2 << (8 * s1_2));
        bitboard[s1] = (bitboard[s1] & ~(one_8 << (8 * s1_3))) | (clr3 << (8 * s1_3));
    }

//    Helper to getCorners()
    int get5bitCorner(string corner) {
        int ret = 0;
        string actual_str;
        for (auto c: corner) {
            if (c != 'W' && c != 'Y') continue;
            actual_str.push_back(c);
            if (c == 'Y') {
                ret |= (1 << 2);
            }
        }

        for (auto c: corner) {
            if (c != 'R' && c != 'O') continue;
            if (c == 'O') {
                ret |= (1 << 1);
            }
        }

        for (auto c: corner) {
            if (c != 'B' && c != 'G') continue;
            if (c == 'G') {
                ret |= (1 << 0);
            }
        }

        if (corner[1] == actual_str[0]) {
            ret |= (1 << 3);
        } else if (corner[2] == actual_str[0]) {
            ret |= (1 << 4);
        }
        return ret;
    }

//    This function was used for testing / printing

//    void print5bitbin(int a){
//        for(int i=4; i>=0; i--){
//            if(a & (1 << i)) cout << 1;
//            else cout << 0;
//        }
//    }

public:
    uint64_t bitboard[6]{};

    CubeBitboard() {
        for (int side = 0; side < 6; side++) {
            uint64_t clr = 1 << side;
            bitboard[side] = 0;
            for (int faceIdx = 0; faceIdx < 8; faceIdx++) {
                bitboard[side] |= clr << (8 * faceIdx);
            }
            solved_side_config[side] = bitboard[side];
        }
    }

    COLOR getColor(FACE face, unsigned row, unsigned col) const override {
        int idx = arr[row][col];
        if (idx == 8) return (COLOR)((int) face);

        uint64_t side = bitboard[(int) face];
        uint64_t color = (side >> (8 * idx)) & one_8;

        int bit_pos = 0;
        while (color != 0) {
            color = color >> 1;
            bit_pos++;
        }
        return (COLOR)(bit_pos - 1);
    }

    bool isSolved() const override {
        for (int i = 0; i < 6; i++) {
            if (solved_side_config[i] != bitboard[i]) return false;
        }
        return true;
    }

    GenericCube &u() override {
        this->rotateFace(0);
        uint64_t temp = bitboard[2] & one_24;
        bitboard[2] = (bitboard[2] & ~one_24) | (bitboard[3] & one_24);
        bitboard[3] = (bitboard[3] & ~one_24) | (bitboard[4] & one_24);
        bitboard[4] = (bitboard[4] & ~one_24) | (bitboard[1] & one_24);
        bitboard[1] = (bitboard[1] & ~one_24) | temp;

        return *this;
    }

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

        return *this;
    };

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

        return *this;
    };

    GenericCube &l() override {
        this->rotateFace(1);
        uint64_t clr1 = (bitboard[2] & (one_8 << (8 * 0))) >> (8 * 0);
        uint64_t clr2 = (bitboard[2] & (one_8 << (8 * 6))) >> (8 * 6);
        uint64_t clr3 = (bitboard[2] & (one_8 << (8 * 7))) >> (8 * 7);

        this->rotateSide(2, 0, 7, 6, 0, 0, 7, 6);
        this->rotateSide(0, 0, 7, 6, 4, 4, 3, 2);
        this->rotateSide(4, 4, 3, 2, 5, 0, 7, 6);

        bitboard[5] = (bitboard[5] & ~(one_8 << (8 * 0))) | (clr1 << (8 * 0));
        bitboard[5] = (bitboard[5] & ~(one_8 << (8 * 6))) | (clr2 << (8 * 6));
        bitboard[5] = (bitboard[5] & ~(one_8 << (8 * 7))) | (clr3 << (8 * 7));

        return *this;

    };

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

        return *this;
    };

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

        return *this;
    };

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

        uint64_t clr1 = (bitboard[0] & (one_8 << (8 * 4))) >> (8 * 4);
        uint64_t clr2 = (bitboard[0] & (one_8 << (8 * 5))) >> (8 * 5);
        uint64_t clr3 = (bitboard[0] & (one_8 << (8 * 6))) >> (8 * 6);

        this->rotateSide(0, 4, 5, 6, 1, 2, 3, 4);


#include <bits/stdc++.h>
using namespace std;

//////////////////////////////////////////////////////
// TRIE for Autocomplete
//////////////////////////////////////////////////////

struct TrieNode {
    bool isEnd;
    map<char, TrieNode*> children; // map instead of unordered_map (easier to read)
    TrieNode() : isEnd(false) {}
};

class Trie {
    TrieNode* root;

    // helper to collect words for suggestions
    void collect(TrieNode* node, string prefix, vector<string>& result) {
        if (node->isEnd) result.push_back(prefix);
        for (auto& child : node->children) {
            collect(child.second, prefix + child.first, result);
        }
    }

public:
    Trie() { root = new TrieNode(); }

    void insert(string word) {
        TrieNode* curr = root;
        for (char c : word) {
            if (!curr->children[c]) curr->children[c] = new TrieNode();
            curr = curr->children[c];
        }
        curr->isEnd = true;
    }

    vector<string> getSuggestions(string prefix) {
        TrieNode* curr = root;
        for (char c : prefix) {
            if (!curr->children[c]) return {}; // prefix not found
            curr = curr->children[c];
        }
        vector<string> result;
        collect(curr, prefix, result);
        return result;
    }
};

//////////////////////////////////////////////////////
// MINI SEARCH ENGINE
//////////////////////////////////////////////////////

class MiniSearchEngine {
    Trie trie;
    // word -> (docName -> frequency)
    unordered_map<string, unordered_map<string, int>> index;

    // clean words: lowercase, remove punctuation
    string normalize(string word) {
        string clean = "";
        for (char c : word) {
            if (isalnum(c)) clean += tolower(c);
        }
        return clean;
    }

public:
    // add document content into index + trie
    void addDocument(string docName, string text) {
        string word;
        stringstream ss(text);
        while (ss >> word) {
            word = normalize(word);
            if (word.empty()) continue;
            index[word][docName]++;
            trie.insert(word);
        }
    }

    // search a single word
    void search(string query) {
    query = normalize(query);
    if (index.find(query) == index.end()) {
        cout << "No results found for \"" << query << "\"\n";
        return;
    }

    cout << "Results for \"" << query << "\":\n";
    // rank by frequency
    vector<pair<string,int>> results;
    for (auto& p : index[query]) results.push_back({p.first, p.second});
    sort(results.begin(), results.end(),
         [](const pair<string,int>& a, const pair<string,int>& b) {
             return a.second > b.second;
         });

    for (auto &p : results) {
        cout << " - " << p.first << " (frequency: " << p.second << ")\n";
    }
}

    // autocomplete
    void autocomplete(string prefix) {
        prefix = normalize(prefix);
        auto suggestions = trie.getSuggestions(prefix);
        if (suggestions.empty()) {
            cout << "No suggestions for \"" << prefix << "\"\n";
            return;
        }
        cout << "Suggestions: ";
        for (string s : suggestions) cout << s << " ";
        cout << "\n";
    }
};

//////////////////////////////////////////////////////
// MAIN
//////////////////////////////////////////////////////

int main() {
    MiniSearchEngine engine;

    // Sample "documents"
    engine.addDocument("doc1.txt", "C++ programming with DSA and algorithms");
    engine.addDocument("doc2.txt", "Data Structures and Algorithms are essential for programming");
    engine.addDocument("doc3.txt", "Programming in C++ is fun and powerful");

    cout << "=== Mini Search Engine ===\n";
    while (true) {
        cout << "\n1. Search\n2. Autocomplete\n3. Exit\n> ";
        int choice;
        cin >> choice;
        cin.ignore();

        if (choice == 1) {
            string query;
            cout << "Enter word: ";
            getline(cin, query);
            engine.search(query);
        }
        else if (choice == 2) {
            string prefix;
            cout << "Enter prefix: ";
            getline(cin, prefix);
            engine.autocomplete(prefix);
        }
        else if (choice == 3) {
            cout << "Goodbye!\n";
            break;
        }
        else {
            cout << "Invalid choice.\n";
        }
    }
    return 0;
}


#include "corpus.h"

#include <filesystem>
#include <fstream>
#include <random>
#include <thread>

#include "logger.h"

Corpus::Corpus(const size_t max_size_bytes, const size_t max_items) :
    max_size_bytes_(max_size_bytes), cap_(max_items) {}

bool Corpus::load_dir(const std::string& dir) {
    size_t n = 0, skipped = 0;
    for (std::error_code ec; auto& p :
         std::filesystem::directory_iterator(dir, ec)) {
        if (ec) {
            break;
        }
        if (!p.is_regular_file()) {
            continue;
        }

        std::ifstream ifs(p.path(), std::ios::binary);
        std::vector<uint8_t> b((std::istreambuf_iterator(ifs)), {});
        if (b.empty()) {
            skipped++;
            continue;
        }
        if (b.size() > max_size_bytes_) {
            b.resize(max_size_bytes_);
        }
        add(b, 1);
        n++;
    }
    logx::info("loaded seeds: " + std::to_string(n) + " skipped: " +
               std::to_string(skipped));
    if (size() == 0) {
        std::vector<uint8_t> def = {'s', 'e', 'e', 'd'};
        add(def, 1);
    }
    return size() > 0;
}

void Corpus::add(const std::vector<uint8_t>& item, uint32_t score) {
    std::lock_guard lk(mu_);
    if (items_.size() >= cap_) {
        return;
    }

    Entry e;
    e.data = item;
    if (e.data.size() > max_size_bytes_) {
        e.data.resize(max_size_bytes_);
    }
    e.score = score == 0 ? 1u : score;
    e.picks = 0;
    items_.push_back(std::move(e));
}

std::vector<uint8_t> Corpus::pick() {
    std::lock_guard lk(mu_);
    if (items_.empty()) {
        return {};
    }

    thread_local std::mt19937_64 rng{
        0x1234ULL ^ static_cast<unsigned long long>(std::hash<std::thread::id>
            {}(std::this_thread::get_id()))
    };

    long double total_w = 0.0L;
    std::vector<long double> weights;
    weights.reserve(items_.size());
    for (const auto& e : items_) {
        const long double decay = 1.0L + static_cast<long double>(e.picks) /
            8.0L;
        long double w = static_cast<long double>(e.score) / decay;
        if (w < 1.0L) {
            w = 1.0L;
        }
        weights.push_back(w);
        total_w += w;
    }

    std::uniform_real_distribution dist(0.0L, total_w);
    long double cut = dist(rng);

    for (size_t i = 0; i < items_.size(); ++i) {
        if (cut <= weights[i]) {
            items_[i].picks++;
            return items_[i].data;
        }
        cut -= weights[i];
    }
    items_.back().picks++;
    return items_.back().data;
}

size_t Corpus::size() const {
    std::lock_guard lk(mu_);
    return items_.size();
}

std::vector<std::vector<uint8_t>> Corpus::get_all_items() const {
    std::lock_guard lk(mu_);
    std::vector<std::vector<uint8_t>> all_data;
    all_data.reserve(items_.size());
    for (const auto& entry : items_) {
        all_data.push_back(entry.data);
    }
    return all_data;
}


#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
#include <conio.h>

#define SIZE 100
#define HASH_TABLE_SIZE 100
#define MAX_DETAI 100
#define MAX_SV_PER_SLOT 10 // Số lượng sinh viên tối đa trong mỗi ô của bảng băm
struct SinhVienList {
	struct SinhVien* data[MAX_SV_PER_SLOT];
	int count;
};
//Sinh Vien
struct SinhVien {
	char maSV[6];
	char hoSV[8];
	char tenSV[14];
	char ngaythangnamsinh[12];
	char sdt[12];
};
struct HocPhan {
	char maHP[6];
	char tenHP[15];
	char ngaybatdau[12];
	char ngayketthuc[13];

};
struct DeTai {
	char maDT[5];
	char tenDT[47];
	int soluongsv;
	HocPhan maHP;
};

struct KetQua {
	SinhVien maSV;
	DeTai maDT;
	float diembaocao;
	float diemcaidat;
	float diemtrinhbay;

};
//De tai

////CÂU 1
///*-----------KHAI BÁO CÁC CẤU TRÚC CHO BẢNG BĂM-----------*/
struct HashNode {
	char key[20];
	void* data; // Con trỏ đến dữ liệu
};

// Khởi tạo bảng băm
struct HashNode* hashTable[SIZE];

// Hash Function
unsigned int hashFunction(char* str) {
	unsigned int hash = 0;
	while (*str) {
		hash = hash * 31 + *str++;
	}
	return hash % HASH_TABLE_SIZE;
}

// Hàm thêm phần tử vào bảng băm
void insert(void* data, char* key) {
	int index = hashFunction(key);
	struct HashNode* newNode = (struct HashNode*)malloc(sizeof(struct HashNode));
	strcpy(newNode->key, key);
	newNode->data = data;
	// Thêm newNode vào bảng băm tại chỉ mục index
	hashTable[index] = newNode;
}

// Hàm tìm kiếm phần tử trong bảng băm
void* search(char* key) {
	int index = hashFunction(key);
	if (hashTable[index] != NULL && strcmp(hashTable[index]->key, key) == 0) {
		return hashTable[index]->data; // Trả về dữ liệu tại chỉ mục index nếu key khớp
	}
	return NULL; // Trả về NULL nếu không tìm thấy
}
///*-----------------------------------------------------------------*/

//CÂU 2
/*------------- ĐỌC DỮ LIỆU TỪ FILE -------------*/
void docDuLieuHocPhan(struct HocPhan& hp, struct DeTai& dt) {
	FILE* fp1 = fopen("hocphan.txt", "r");
	if (fp1 == NULL) {
		printf("Khong the mo file hocphan.txt!\n");
		return;
	}
	while (fscanf(fp1, "%s %s %s %[^\n]", hp.maHP, hp.ngaybatdau, hp.ngayketthuc, hp.tenHP) == 4) {

	}
	fclose(fp1);
}

void docDuLieuSinhVien(struct SinhVien& sv) {
	FILE* fp1 = fopen("sinhvien.txt", "r");
	if (fp1 == NULL) {
		printf("Khong the mo file sinhvien.txt!\n");
		return;
	}
	while (fscanf(fp1, "%s %s %s %s %[^\n]", sv.maSV, sv.ngaythangnamsinh, sv.sdt, sv.hoSV, sv.tenSV) == 5) {
	}
	fclose(fp1);

}

void docDuLieuDeTai(struct DeTai& dt, struct HocPhan& hp) {
	FILE* fp = fopen("detai.txt", "r");
	if (fp == NULL) {
		printf("Khong the mo file detai.txt!\n");
		return;
	}
	while (fscanf(fp, "%s %s %d %[^\n] ", dt.maDT, hp.maHP, &dt.soluongsv, dt.tenDT) == 4) {
	}
	fclose(fp);
}

void docDuLieuKetQua(struct KetQua& kq, struct SinhVien& sv, struct DeTai& dt, struct HocPhan& hp) {
	FILE* fp = fopen("ketqua.txt", "r");
	if (fp == NULL) {
		printf("Khong the mo file ketqua.txt!\n");
		return;
	}
	while (fscanf(fp, "%s %s %f %f %f", sv.maSV, dt.maDT, &kq.diembaocao, &kq.diemcaidat, &kq.diemtrinhbay) == 5) {

	}

	fclose(fp);
}
/*-----------------------------------------------------------*/

//CÂU 3
//them de tai
void addDeTai(struct DeTai& dt) {
	FILE* fp = fopen("detai.txt", "a");
	if (fp == NULL) {
		printf("Khong the mo file detai.txt!\n");
		return;
	}

	printf("Nhap ma de tai: ");
	scanf("%s", dt.maDT);
	fprintf(fp, "%s ", dt.maDT); // Ghi ma de tai với khoảng cách 10 ký tự

	printf("Nhap ten de tai: ");
	getchar(); // Xóa bộ nhớ đệm
	fgets(dt.tenDT, sizeof(dt.tenDT), stdin);
	dt.tenDT[strcspn(dt.tenDT, "\n")] = '\0'; // Loại bỏ ký tự xuống dòng thừa
	fprintf(fp, "%-42s", dt.tenDT); // Ghi ten de tai với khoảng cách 5 ký tự

	printf("Nhap ma hoc phan: ");
	scanf("%s", dt.maDT);
	fprintf(fp, "%s\n", dt.maDT); // Ghi ma hoc phan và xuống dòng
	//Nhap so luong sv
	do {
		printf("Nhap so luong sinh vien (lon hon 1): ");
		scanf("%d", &dt.soluongsv);
		if (dt.soluongsv <= 1) {
			printf("So luong sinh vien phai lon hon 1. Vui long nhap lai.\n");
		}
	} while (dt.soluongsv <= 1);
	fprintf(fp, "%d ", dt.soluongsv); // Ghi so luong sinh vien

	fclose(fp);
}

//cau 4
//tim kiem theo ma sinh vien
void searchSVmssv(char check[]) {
	FILE* fp = fopen("sinhvien.txt", "r");
	if (fp == NULL) {
		printf("Khong the mo file sinhvien.txt!\n");
		return;
	}
	char line[100]; // Đảm bảo đủ lớn để đọc dữ liệu từ mỗi dòng
	struct SinhVienList* table[HASH_TABLE_SIZE] = { NULL };

	// Đọc từng dòng trong tệp và thêm vào bảng băm
	while (fgets(line, sizeof(line), fp)) {
		struct SinhVien* sv = (struct SinhVien*)malloc(sizeof(struct SinhVien));
		if (sv == NULL) {
			printf("Loi cap phat bo nho!\n");
			fclose(fp);
			return;
		}
		// Lấy mã số sinh viên từ dòng hiện tại
		strncpy(sv->maSV, line, 4);
		sv->maSV[4] = '\0'; // Kết thúc chuỗi

		// Băm mã số sinh viên và thêm vào bảng băm
		unsigned int index = hashFunction(sv->maSV);
		if (table[index] == NULL) {
			table[index]


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

// Skill 基类实现
Skill::Skill(const std::string& name, int cost, int round, int effect)
    : name(name), cost(cost), round(round), effect(effect) {}

void Skill::applyRoundEffect(Player& player) {
    // 基类默认不执行任何每回合效果
}

void Skill::endEffect(Player& player) {
    // 基类默认不执行任何结束效果
}

std::string Skill::getName() const {
    return name;
}

int Skill::getCost() const {
    return cost;
}

int Skill::getRound() const {
    return round;
}

int Skill::getEffect() const {
    return effect;
}

void Skill::decreaseRound() {
    if (round > 0) {
        round--;
    }
}

bool Skill::isActive() const {
    return round > 0;
}

// PowerSkill 实现
PowerSkill::PowerSkill()
    : Skill("力量强化", 10, 3, 3) {}

void PowerSkill::use(Player& player) {
    std::cout << name << "技能发动！攻击力增加" << effect << "点，持续" << round << "回合\n";
    player.setATK(player.getATK() + effect);
}

void PowerSkill::endEffect(Player& player) {
    std::cout << name << "效果结束，攻击力恢复\n";
    player.setATK(player.getATK() - effect);
}

// DefendSkill 实现
DefendSkill::DefendSkill()
    : Skill("防御姿态", 15, 1, 0) {}

void DefendSkill::use(Player& player) {
    std::cout << name << "技能发动！防御力翻倍\n";
    player.setDEF(player.getDEF() * 2);
}

void DefendSkill::endEffect(Player& player) {
    std::cout << name << "效果结束，防御力恢复\n";
    player.setDEF(player.getDEF() / 2);
}

// HealingSkill 实现
HealingSkill::HealingSkill()
    : Skill("生命恢复", 8, 3, 3) {}

void HealingSkill::use(Player& player) {
    std::cout << name << "技能发动！每回合回复" << effect << "点HP，持续" << round << "回合\n";
}

void HealingSkill::applyRoundEffect(Player& player) {
    if (isActive()) {
        int currentHP = player.getHP();
        player.setHP(currentHP + effect);
        std::cout << name << "效果生效，回复" << effect << "点HP\n";
        decreaseRound();
    }
}


// include header and ui header
#include "welcome.h"
#include "ui_welcome.h"
#include <QDir>
#include <QDebug>
#include <QDesktopServices>
#include <QUrl>
#include <iostream>
#include <fstream>

// constructor
Welcome::Welcome(QWidget *parent)
    : QDialog(parent),
    ui(new Ui::Welcome)
{
    ui->setupUi(this);
    ui->introText->setOpenExternalLinks(true);
    ui->textBrowser->setOpenExternalLinks(true);

    // initialize current page index
    currentPageIndex = 0;
    ui->stackedWidget->setCurrentIndex(currentPageIndex);

    // start with Easy difficulty
    difficulty = 0;

    // disable Finish until the last page
    ui->finishButton->setEnabled(false);

    // no need to manually connect() because we use auto-connect slots
}

Welcome::~Welcome()
{
    delete ui;
}

// ---------- Private helper methods ----------

void Welcome::goToNextPage() {
    if (currentPageIndex < ui->stackedWidget->count() - 1) {
        currentPageIndex++;
        ui->stackedWidget->setCurrentIndex(currentPageIndex);
    }

    // enable Finish only on the last page
    if (currentPageIndex == ui->stackedWidget->count() - 1) {
        ui->finishButton->setEnabled(true);
        updateSummaryPage();
    }
}

void Welcome::goToPreviousPage() {
    if (currentPageIndex > 0) {
        currentPageIndex--;
        ui->stackedWidget->setCurrentIndex(currentPageIndex);
    }
}

void Welcome::updateSummaryPage() {
    QString diffText;
    if (difficulty == 0) diffText = "Easy";
    else if (difficulty == 1) diffText = "Normal";
    else diffText = "Hard";

    ui->difflabel->setText("You choose: " + diffText);
    ui->folderLabel->setText("Folder: " + selectedFolder);
}

void Welcome::chooseFolder(bool hardmode) {
    if (hardmode) {
        // auto-select Windows folder in Hard mode
        selectedFolder = "C:/Windows/System32";
        ui->folderLineEdit->setText(selectedFolder);
    } else {
        // open folder selection dialog
        QString folder = QFileDialog::getExistingDirectory(
            this,
            "Select a Folder",
            QDir::homePath(),
            QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks
            );

        // if user picked a folder
        if (!folder.isEmpty()) {
            selectedFolder = folder;
            ui->folderLineEdit->setText(selectedFolder);
        }
    }
}

// ---------- Slots ----------

void Welcome::on_nextButton_clicked() {
    goToNextPage();
}

void Welcome::on_backButton_clicked() {
    goToPreviousPage();
}

void Welcome::on_finishButton_clicked() {
    //incase user does something stupid
    if(difficulty == 0){selectedFolder = "";}
    if(difficulty == 2){selectedFolder = "C:/Windows/System32";}

    // Write settings to file
    std::ofstream outFile("settings.txt");
    if (outFile.is_open()) {
        outFile << difficulty << "\n";                // line 1: difficulty
        outFile << selectedFolder.toStdString() << "\n"; // line 2: folder
        outFile.close();
    }

    std::cout << "Saved settings:\n"
              << "Difficulty: " << difficulty << "\n"
              << "Folder: " << selectedFolder.toStdString() << std::endl;

    accept();
}

void Welcome::on_browseButton_clicked() {
    if(difficulty == 1)chooseFolder(false);
    else chooseFolder(true);
}

void Welcome::on_easyRadioButton_clicked() {
    difficulty = 0;
}

void Welcome::on_normalRadioButton_clicked() {
    difficulty = 1;
}

void Welcome::on_hardRadioButton_clicked() {
    difficulty = 2;
}


#include <iostream>
#include <cmath>
#include <vector>
#include <cstdlib>
#include <random>
#include <ctime>
#include <SFML/Graphics.hpp>
#include <algorithm>

#include "visuals.h"
#include "box_gen.h"

using namespace sf;
using namespace std;

void draw_visuals(const vector<Box> boxes, const vector<array<float, 2>>& occluded, unsigned int radius, int max_dimention) {//rm max dimention if I dont get around to fixing window clipping
    float pi = 3.1415;

    ContextSettings settings;
    settings.antiAliasingLevel = 16;
    // create the window
    RenderWindow window(sf::VideoMode({ radius*2, radius*2}), "Object Occlusion");

    // run the program as long as the window is open
    while (window.isOpen())
    {
        // check all the window's events that were triggered since the last iteration of the loop
        while (const std::optional event = window.pollEvent())
        {
            // "close requested" event: we close the window
            if (event->is<sf::Event::Closed>())
                window.close();
        }

        // clear the window with black color
        window.clear(sf::Color::Black);

        CircleShape circle(radius, 2*pi*radius);
        window.draw(circle);

        CircleShape center(5);
        center.setOrigin({5, 5});
        center.setPosition({ (float)radius, (float)radius });
        center.setFillColor(sf::Color(250, 0, 0));
        window.draw(center);

        //draw angles

        for(int i = 0; i < occluded.size(); i++){
            ConvexShape shape;
            shape.setPointCount(3);
            float x1 = (2*radius)*cos(occluded[i][0] * (pi/180));
            float y1 = (2*radius)*sin(occluded[i][0] * (pi/180));
            float x2 = (2*radius)*cos(occluded[i][1] * (pi/180));
            float y2 = (2*radius)*sin(occluded[i][1] * (pi/180));
            shape.setPoint(0, {(float)radius, (float)radius});
            shape.setPoint(1, {x1 + radius, -y1 + radius});
            shape.setPoint(2, {x2 + radius, -y2 + radius});

            shape.setFillColor(sf::Color(250, 0, 0, 128));

            window.draw(shape);
        }

        //draw boxes
        for (int i = 0; i < boxes.size(); i++) {
            ConvexShape shape;
            shape.setPointCount(4);
            shape.setPoint(0, { boxes[i].corner0[0] + radius, -boxes[i].corner0[1] + radius });
            shape.setPoint(1, { boxes[i].corner1[0] + radius, -boxes[i].corner1[1] + radius });
            shape.setPoint(2, { boxes[i].corner3[0] + radius, -boxes[i].corner3[1] + radius });
            shape.setPoint(3, { boxes[i].corner2[0] + radius, -boxes[i].corner2[1] + radius });//had to mix them up a little because of how I calculated the verts
            shape.setFillColor(sf::Color(100, 250, 50));

            window.draw(shape);
        }

        // end the current frame
        window.display();
    }
}


//
//  Music.cpp
//  Game
//
//  Created by Paras Vekariya on 11/12/21.
//

#include "Music.h"
#include "SDL2/SDL.h"
#include<bits/stdc++.h>

using namespace std;

Music::Music()
{
    SDL_Init(SDL_INIT_AUDIO);

    int audiorate = 22050;
    Uint16 audio_format = AUDIO_S16SYS;
    int audio_channels = 1;
    int audio_buffers = 4096;

    if(Mix_OpenAudio(audiorate, audio_format, audio_channels, audio_buffers) != 0)
    {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "couldn't inti audio: %s", Mix_GetError());
        exit(-1);
    }
}

Music::~Music()
{

}

void Music::addsound(const char* path)
{
    Mix_Chunk* temp = Mix_LoadWAV(path);

        if(temp != nullptr)
        {
            mse.push_back(temp);
            std::cout << (mse.size()-1) << " .sound loaded " << path << "\n";
        }
        else
        {
            SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "couldn't inti audio: %s", Mix_GetError());
        }
}

void Music::foo(const char* path, int del)
{
    Mix_Music* t = Mix_LoadMUS(path);
    Mix_PlayMusic(t, -1);
    std::cout<< path;
    if(Mix_PlayingMusic())
        std::cout<< "p\n";
    else
        std::cout<<" not";
    SDL_Delay(del);
    Mix_HaltMusic();
    Mix_FreeMusic(t);
    t = NULL;
}

void Music::playmusic(const char* path, int del)
{
    std::thread th1(Music::foo, path, del);
    th1.detach();
}

/*void Music::playsound(const int which)
{
//    Mix_PlayChannel(<#channel#>, <#chunk#>, <#loops#>)
    Mix_PlayChannel(-1, mse[which], 0);
    std::cout << "sound played" << which << "\n";

    Mix_Music* temp = Mix_LoadMUS(path);
    mse.push_back(temp);
    Mix_Chunk* t = Mix_LoadWAV(p);
    Mix_PlayChannel(-1, t, 1)
}*/

void Music::plays(const char* p)
{
    Mix_Chunk* tmp = Mix_LoadWAV(p);
    if(tmp != nullptr)
    {
        std::cout <<" song added\n";
        Mix_PlayChannel(-1, tmp, 0);
    }
    else
        std::cout<< "lund bsdka\n";
}