#include "rclcpp/rclcpp.hpp"
#include "kinect_ros2/kinect_ros2_component.hpp"
#include "class_loader/class_loader.hpp"
#include "ament_index_cpp/get_package_prefix.hpp"
#include "rclcpp_components/node_factory.hpp"

std::vector<class_loader::ClassLoader *> _loaders;
std::vector<rclcpp_components::NodeInstanceWrapper> _node_wrappers;

rclcpp::node_interfaces::NodeBaseInterface::SharedPtr get_depth_image_proc_component()
{
  auto path_prefix = ament_index_cpp::get_package_prefix("depth_image_proc");
  auto loader = new class_loader::ClassLoader(path_prefix + "/lib/libdepth_image_proc.so");
  auto classes = loader->getAvailableClasses<rclcpp_components::NodeFactory>();

  rclcpp::NodeOptions options;
  options.use_intra_process_comms(true);
  std::vector<std::string> arguments {
    "image_rect:=depth/image_raw",
    "camera_info:=depth/camera_info"
  };
  options.arguments(arguments);

  rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node;
  for (auto clazz : classes) {
    auto node_factory = loader->createInstance<rclcpp_components::NodeFactory>(clazz);
    auto wrapper = node_factory->create_node_instance(options);
    if (clazz == "rclcpp_components::NodeFactoryTemplate<depth_image_proc::PointCloudXyzNode>") {
      node = wrapper.get_node_base_interface();
      _node_wrappers.push_back(wrapper);
      break;
    }
  }
  if (node != nullptr) {
    _loaders.push_back(loader);
    return node;
  }
  throw std::invalid_argument("depth_image_proc::PointCloudXyzNode not found");
}

int main(int argc, char * argv[])
{
  rclcpp::init(argc, argv);

  rclcpp::executors::SingleThreadedExecutor exec;
  rclcpp::NodeOptions options;
  options.use_intra_process_comms(true);

  auto kinect_component = std::make_shared<kinect_ros2::KinectRosComponent>(options);
  auto depth_image_proc_component = get_depth_image_proc_component();

  exec.add_node(kinect_component);
  exec.add_node(depth_image_proc_component);

  exec.spin();

  for (auto wrapper : _node_wrappers) {
    exec.remove_node(wrapper.get_node_base_interface());
  }
  _node_wrappers.clear();

  rclcpp::shutdown();

  return 0;
}


#include "imports.h"
#include "globals.h"
#include "misc/security.h"

#include "hooks.hpp"
HINSTANCE DllHandle;

#define WIN32_LEAN_AND_MEAN

DWORD WINAPI InitExec() {
    std::cout << _XOR_("[-] MainThread +\n");
    if (MH_Initialize() != MH_OK) {
        return 0;
    }
    std::cout << _XOR_("[HOOKLIB] +\n");

    if (MH_CreateHookApi(L"kernel32.dll", _XOR_("GetThreadContext"), &hookedGetThreadContext, reinterpret_cast<void**>(&pGetThreadContext)) != MH_OK) {
        MessageBoxA(NULL, _XOR_("Failed To Hook GetThreadContext"), "", MB_OK);
    }
    else {
        std::cout << _XOR_("[security-enabled] GetThreadContext->dr. for HW Breakpoints\n");
    }

    if (MH_CreateHookApi(L"ntdll.dll", _XOR_("NtRaiseHardError"), &hookedNtRaiseHardError, reinterpret_cast<void**>(&pNtRaiseHardError)) != MH_OK) {
        MessageBoxA(NULL, _XOR_("Failed To Hook NtRaisedHardError"), "", MB_OK);
    }
    else {
        std::cout << _XOR_("[security-enabled] GetThreadContext->dr. for HW Breakpoints\n");
    }

    if (MH_CreateHookApi(L"kernel32.dll", _XOR_("WriteProcessMemory"), &hookedWriteProcessMemory, reinterpret_cast<void**>(&pWriteProcessMemory)) != MH_OK) {
        MessageBoxA(NULL, _XOR_("Failed To Hook WriteProcessMemory"), "", MB_OK);
    }
    else {
        std::cout << _XOR_("[enabled] WriteProcessMemory Dumper\n");
    }

    if (MH_CreateHookApi(L"kernel32.dll", _XOR_("ReadProcessMemory"), &hookedReadProcessMemory, reinterpret_cast<void**>(&pReadProcessMemory)) != MH_OK) {
        MessageBoxA(NULL, _XOR_("Failed To Hook ReadProcessMemory"), "", MB_OK);
    }
    else {
        std::cout << _XOR_("[enabled] ReadProcessMemory Dumper\n");
    }

    if (MH_CreateHookApi(L"kernel32.dll", _XOR_("DeleteFileW"), &hookedDeleteFileW, reinterpret_cast<void**>(&pDeleteFileW)) != MH_OK) {
        MessageBoxA(NULL, _XOR_("Failed To Hook DeleteFileW"), "", MB_OK);
    }
    else {
        std::cout << _XOR_("[enabled] DeleteFileW Dumper\n");
    }

    if (MH_CreateHookApi(L"kernel32.dll", _XOR_("DeleteFileA"), &hookedDeleteFileA, reinterpret_cast<void**>(&pDeleteFileA)) != MH_OK) {
        MessageBoxA(NULL, _XOR_("Failed To Hook DeleteFileA"), "", MB_OK);
    }
    else {
        std::cout << _XOR_("[enabled] DeleteFileA Dumper\n");
    }

    MH_EnableHook(MH_ALL_HOOKS);
    while (true) {
        Sleep(50);
        if (GetAsyncKeyState(VK_END) & 1) {
            break;
        }
    }

    return 0;
}

int __stdcall DllMain(const HMODULE hModule, const std::uintptr_t reason, const void* reserved) {
    if (reason == 1) {
        if (globals::AllocateConsole == true) {
            AllocConsole();
            FILE* fp;
            freopen_s(&fp, "CONOUT$", "w", stdout);
        }

        DisableThreadLibraryCalls(hModule);
        std::cout << _XOR_("[-] AllocConsole - freopen_s | SET\n");
        DllHandle = hModule;

        hyde::CreateThread(InitExec, DllHandle);
        std::cout << _XOR_("[-] Started Main Thread...\n");

        return true;
    }
    return true;
}


#include <vector>

template <typename T = long long>
class Point {
public:
  T x, y;
  Point() : x(0), y(0) {}
  Point(T _x, T _y) : x(_x), y(_y) {}

  friend bool operator==(const Point& a, const Point& b) {
    return a.x == b.x && a.y == b.y;
  }

  friend bool operator!=(const Point& a, const Point& b) { return !(a == b); }

  Point operator-() { return Point(-x, -y); }

  Point& operator+=(const Point& a) {
    x += a.x;
    y += a.y;
    return *this;
  }

  Point& operator-=(const Point& a) {
    x -= a.x;
    y -= a.y;
    return *this;
  }

  Point& operator*=(T a) {
    x *= a;
    y *= a;
    return *this;
  }

  Point& operator/=(T a) {
    x /= a;
    y /= a;
    return *this;
  }

  friend bool operator<(const Point& a, const Point& b) {
    return (a.x == b.x ? a.y < b.y : a.x < b.x);
  }

  friend Point operator+(const Point& a, const Point& b) {
    return Point(a.x + b.x, a.y + b.y);
  }

  friend Point operator-(const Point& a, const Point& b) {
    return Point(a.x - b.x, a.y - b.y);
  }

  friend Point operator*(const Point& a, T b) {
    return Point(a.x * b, a.y * b);
  }

  friend Point operator*(T b, const Point& a) {
    return Point(a.x * b, a.y * b);
  }

  friend Point operator/(const Point& a, T b) {
    return Point(a.x / b, a.y / b);
  }

  friend T dot(const Point& o, const Point& a, const Point& b) {
    return (a.x - o.x) * (b.x - o.x) + (a.y - o.y) * (b.y - o.y);
  }

  friend T dot(const Point& a, const Point& b) {
    return dot(Point<T>(0, 0), a, b);
  }

  friend T cross(const Point& o, const Point& a, const Point& b) {
    return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
  }

  friend T cross(const Point& a, const Point& b) {
    return cross(Point<T>(0, 0), a, b);
  }

  friend long double dist(const Point& a, const Point& b) {
    return hypot<long double>(a.x - b.x, a.y - b.y);
  }

  long double norm() { return dist(Point<T>(0, 0), *this); }
};

template <typename T>
std::vector<Point<T>> convex_hull(std::vector<Point<T>> ps) {
  int n = ps.size();
  sort(ps.begin(), ps.end());
  std::vector<Point<T>> res;
  for (auto p : ps) {
    while ((int)res.size() >= 2 and cross(res.end()[-1], res.end()[-2], p) >= 0)
      res.pop_back();
    res.push_back(p);
  }
  int t = res.size();
  for (int i = n - 2; i >= 0; --i) {
    auto p = ps[i];
    while ((int)res.size() > t and cross(res.end()[-1], res.end()[-2], p) >= 0)
      res.pop_back();
    res.push_back(p);
  }
  return res;
}


#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <unordered_map>
#include <cctype>

using namespace std;

// Trim spaces from start and end of string
string trim(const string& s) {
    size_t start = s.find_first_not_of(" \t\r\n");
    if (start == string::npos) return "";
    size_t end = s.find_last_not_of(" \t\r\n");
    return s.substr(start, end - start + 1);
}

// Extract integer value from a line (assumes first number in line)
int getValueFromLine(const string& line) {
    for (size_t i = 0; i < line.size(); i++) {
        if (isdigit(line[i]) || (line[i] == '-' && i + 1 < line.size() && isdigit(line[i+1]))) {
            size_t start = i;
            size_t end = start + 1;
            while (end < line.size() && isdigit(line[end])) end++;
            return stoi(line.substr(start, end - start));
        }
    }
    cerr << "Error: No digits found in line: " << line << endl;
    exit(1);
}

// Parse n and k values from lines starting at startLine (looking for lines with "n" and "k")
void parseKeys(const vector<string>& lines, int startLine, int &n, int &k) {
    n = -1;
    k = -1;
    for (int i = startLine; i < (int)lines.size(); i++) {
        string line = lines[i];
        if (line.find("\"n\"") != string::npos) {
            n = getValueFromLine(line);
        } else if (line.find("\"k\"") != string::npos) {
            k = getValueFromLine(line);
        }
        if (n != -1 && k != -1) break;
    }
    if (n == -1 || k == -1) {
        cerr << "Error: Could not find n or k in input." << endl;
        exit(1);
    }
}

// Convert digit character to integer value (supports 0-9, a-f, A-F)
int charToDigit(char c) {
    if (c >= '0' && c <= '9') return c - '0';
    if (c >= 'a' && c <= 'f') return 10 + (c - 'a');
    if (c >= 'A' && c <= 'F') return 10 + (c - 'A');
    cerr << "Invalid digit character: " << c << endl;
    exit(1);
}

// Convert string number from base to decimal (as unsigned long long)
unsigned long long baseToDecimal(const string& val, int base) {
    unsigned long long result = 0;
    for (char c : val) {
        int digit = charToDigit(c);
        if (digit >= base) {
            cerr << "Digit " << c << " invalid for base " << base << endl;
            exit(1);
        }
        result = result * base + digit;
    }
    return result;
}

int main() {
    ifstream fin("input.json");
    if (!fin.is_open()) {
        cerr << "Error: Could not open input.json file" << endl;
        return 1;
    }

    vector<string> lines;
    string line;
    while (getline(fin, line)) {
        line = trim(line);
        if (!line.empty())
            lines.push_back(line);
    }
    fin.close();

    // Find line containing "keys"
    int keysLine = -1;
    for (int i = 0; i < (int)lines.size(); i++) {
        if (lines[i].find("\"keys\"") != string::npos) {
            keysLine = i;
            break;
        }
    }
    if (keysLine == -1) {
        cerr << "Error: No \"keys\" found in input" << endl;
        return 1;
    }

    int n, k;
    parseKeys(lines, keysLine, n, k);

    cout << "Parsed n = " << n << ", k = " << k << endl;

    // Now parse the roots (keys are integers as strings, e.g. "1", "2", "3", ...)
    // After the "keys" block, we have the roots
    // We will store root as map<int rootID, pair<int base, string value>>
    unordered_map<int, pair<int, string>> roots;

    for (int i = keysLine + 1; i < (int)lines.size(); i++) {
        string curLine = lines[i];

        // Root key line example: "1": {
        if (curLine.size() > 3 && curLine[0] == '"' && isdigit(curLine[1])) {
            // Extract root ID number
            int rootID = 0;
            size_t pos = 1;
            while (pos < curLine.size() && isdigit(curLine[pos])) {
                rootID = rootID * 10 + (curLine[pos] - '0');
                pos++;
            }

            // Read base and value in next few lines
            // Expecting lines:
            // "base": "10",
            // "value": "4"
            int base = -1;
            string value;

            // Safety check to not go out of range
            if (i + 2 >= (int)lines.size()) {
                cerr << "Input incomplete for root " << rootID << endl;
                return 1;
            }

            // Parse base line
            string baseLine = lines[i + 1];
            size_t bstart = baseLine.find("\"base\"");
            if (bstart == string::npos) {
                cerr << "Missing base for root " << rootID << endl;
                return 1;
            }
            size_t q1 = baseLine.find("\"", bstart + 6);
            size_t q2 = baseLine.find("\"", q1 + 1);
            if (q1 == string::npos || q2 == string::npos) {
                cerr << "Malformed base line for root " << rootID << endl;
                return 1;
            }
            string baseStr = baseLine.substr(q1 + 1, q2 - q1 - 1);
            base = stoi(baseStr);

            // Parse value line
            stri


#include<iostream>
#include<fstream>
using namespace std;
struct createaccount{
    string name;
    int account_number;
    int pin;
    int balance;
};

struct transaction{
    string type[10];
    int amount[10];
    string transfer_name[10];
    int balance[10];
};

void saveUsersToFile(createaccount user[],int size){
    ofstream file("users.txt");
    for(int i =0;i< size;i++){
        file<<user[i].name<<" "<<user[i].account_number<<" "<< user[i].pin<<" "<<user[i].balance<<endl;
  }
    file.close();
}

void loadUsersFromFile(createaccount user[],int &size){
    ifstream file("users.txt");
    if(!file){
        cout<<"No user data found. Please create users in users.txt."<<endl;
        return;
    }
    size=0;
    while(file>>user[size].name>>user[size].account_number>>user[size].pin>>user[size].balance){
    size++;
    }
    file.close();
}

void withdrawAmount(createaccount user[],int index,int user_count,int &a,transaction &receipt) {
    double withdraw;
    cout << "\n\tAmount You Want to Withdraw: ";
    cin >> withdraw;
    if(withdraw> 0 && user[index].balance>= withdraw) {
        user[index].balance-= withdraw;
        saveUsersToFile(user,user_count);
        receipt.type[a] = "Withdraw";
        receipt.amount[a] = withdraw;
        receipt.transfer_name[a] = user[index].name;
        receipt.balance[a] = user[index].balance;
        a++;
        cout<<"\n\t Your Current Balance is: "<<user[index].balance<<endl;
    } else{
        cout<<"You Don't Have Enough Money to Withdraw or Invalid Amount."<<endl;
    }
}

void transferAmount(createaccount user[], int sender_index,int user_count,int &a,transaction &receipt){
    int receiver_account, receiver_index= -1;
    cout<<"\n\tEnter the Account Number to Transfer To: ";
    cin>>receiver_account;
    for(int i= 0; i< user_count;i++) {
        if(user[i].account_number == receiver_account){
            receiver_index = i;
            break;
        }
    }
    if(receiver_index == -1) {
        cout << "\n\tInvalid Account Number. Transfer Failed." << endl;
    } else if(receiver_index == sender_index){
        cout << "You cannot transfer amount to yourself." << endl;
    } else{
        double transfer_amount;
        cout << "\n\tEnter the Amount to Transfer: ";
        cin >> transfer_amount;
        if (user[sender_index].balance >= transfer_amount && transfer_amount > 0) {
            user[sender_index].balance -= transfer_amount;
            user[receiver_index].balance += transfer_amount;
            saveUsersToFile(user, user_count);

            receipt.type[a] = "Transfer";
            receipt.amount[a] = transfer_amount;
            receipt.transfer_name[a] = user[receiver_index].name;
            receipt.balance[a] = user[sender_index].balance;
            a++;
            cout << "\n\tTransfer Successful! Your Current Balance is: " << user[sender_index].balance << endl;
        } else {
            cout << "\n\tYou Don't Have Enough Balance to Transfer or Invalid Amount." << endl;
        }
    }
}

void displayMiniStatement(transaction receipt, int a){
    if(a ==0){
        cout<< "\n\tNo Transaction Display\n";
    }else{
        cout<< "\n\tMini Statement";
        cout<< "\n\t-------------------";
        for (int i = 0; i < a; i++) {
            cout << "\n\tType : " << receipt.type[i];
            cout << "\n\tAmount : " << receipt.amount[i];
            if (receipt.type[i] == "Withdraw") {
                cout << "\n\tAccount Holder Name : " << receipt.transfer_name[i];
            } else {
                cout << "\n\tTransferred to : " << receipt.transfer_name[i];
            }
            cout<< "\n\tCurrent Balance: "<< receipt.balance[i]<<"\n\t-----------------";
        }
    }
}

int displayMenu(){
    int option;
    cout<<"\n\t*************Menu*************";
    cout<<"\n\t*                            *";
    cout<<"\n\t*       1. Check Balance     *";
    cout<<"\n\t*       2. Withdraw          *";
    cout<<"\n\t*       3. Transfer Amount   *";
    cout<<"\n\t*       4. Mini Statement    *";
    cout<<"\n\t*       5. Exit              *";
    cout<<"\n\t*                            *";
    cout<<"\n\t******************************";
    cout<<"\n\t Please Enter an Option: ";
    cin>>option;
    return option;
}

int main() {
    createaccount user[10];
    int user_count=0;
    loadUsersFromFile(user, user_count);
    transaction receipt;
    int a= 0;

    int option,pin,count=0,account,error=1,b=0;
    cout<<"Welcome to Virtual ATM system."<<endl;
    do{
        cout<<"Enter Your Account Number: ";
        cin>>account;
        bool account_found=false;
        for(int i = 0;i <user_count;i++){
            if(account== user[i].account_number){
            b=i;
             account_found = true;
            cout<<


//=================================================================================================
// Copyright (c) 2012, Johannes Meyer, TU Darmstadt
// All rights reserved.

// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Flight Systems and Automatic Control group,
//       TU Darmstadt, nor the names of its contributors may be used to
//       endorse or promote products derived from this software without
//       specific prior written permission.

// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//=================================================================================================

#include <hector_gazebo_plugins/gazebo_ros_gps.h>
#include <gazebo/physics/physics.hh>
#include <gazebo/common/SphericalCoordinates.hh>

// WGS84 constants
static const double equatorial_radius = 6378137.0;
static const double flattening = 1.0/298.257223563;
static const double excentrity2 = 2*flattening - flattening*flattening;

// default reference position
static const double DEFAULT_REFERENCE_LATITUDE  = 49.9;
static const double DEFAULT_REFERENCE_LONGITUDE = 8.9;
static const double DEFAULT_REFERENCE_HEADING   = 0.0;
static const double DEFAULT_REFERENCE_ALTITUDE  = 0.0;
namespace gazebo {

GazeboRosGps::GazeboRosGps()
{
}

////////////////////////////////////////////////////////////////////////////////
// Destructor
GazeboRosGps::~GazeboRosGps()
{
  updateTimer.Disconnect(updateConnection);

  dynamic_reconfigure_server_position_.reset();
  dynamic_reconfigure_server_velocity_.reset();
  dynamic_reconfigure_server_status_.reset();

  node_handle_->shutdown();
  delete node_handle_;
}

////////////////////////////////////////////////////////////////////////////////
// Load the controller
void GazeboRosGps::Load(physics::ModelPtr _model, sdf::ElementPtr _sdf)
{
  world = _model->GetWorld();

  // load parameters
  if (!_sdf->HasElement("robotNamespace"))
    namespace_.clear();
  else
    namespace_ = _sdf->GetElement("robotNamespace")->GetValue()->GetAsString();

  if (!_sdf->HasElement("bodyName"))
  {
    link = _model->GetLink();
    link_name_ = link->GetName();
  }
  else {
    link_name_ = _sdf->GetElement("bodyName")->GetValue()->GetAsString();
    link = _model->GetLink(link_name_);
  }

  if (!link)
  {
    ROS_FATAL("GazeboRosGps plugin error: bodyName: %s does not exist\n", link_name_.c_str());
    return;
  }

  // default parameters
  frame_id_ = "/world";
  fix_topic_ = "fix";
  velocity_topic_ = "fix_velocity";

  reference_latitude_  = DEFAULT_REFERENCE_LATITUDE;
  reference_longitude_ = DEFAULT_REFERENCE_LONGITUDE;
  reference_heading_   = DEFAULT_REFERENCE_HEADING * M_PI/180.0;
  reference_altitude_  = DEFAULT_REFERENCE_ALTITUDE;

  if (_sdf->HasElement("useWorldSphericalCoordinates"))
  {
    bool use_world_coords = false;
    if (_sdf->GetElement("useWorldSphericalCoordinates")->GetValue()->Get(use_world_coords) && use_world_coords)
    {
      common::SphericalCoordinatesPtr spherical_coords = world->SphericalCoords();
      reference_latitude_ = spherical_coords->LatitudeReference().Degree();
      reference_longitude_ = spherical_coords->LongitudeReference().Degree();
      // SDF specifies heading counter-clockwise from east, but here it's measured clockwise from north
      reference_heading_ = (M_PI / 2.0) - spherical_coords->HeadingOffset().Radian();
      reference_altitude_ = spherical_coords->GetElevationReference();
    }
  }

  fix_.status.status  = sensor_msgs::NavSatStatus::STATUS_FIX;
  fix_.status.service = 0;

  if (_sdf->HasElement("frameId"))
    frame_id_ = _sdf->GetElement("frameId")->GetValue()->GetAsString();

  if (_sdf->HasElement("topicName"))
    fix_topic_ = _sdf->GetElement("topicName")->GetValue()->GetAsString();

  if (_sdf->HasElement("velocityTopicNa


#include "Cafe/HW/Latte/Renderer/Renderer.h"
#include "Cafe/HW/Latte/Renderer/OpenGL/RendererShaderGL.h"

#include "Cemu/FileCache/FileCache.h"

#include "config/ActiveSettings.h"
#include "config/LaunchSettings.h"

extern std::atomic_int g_compiled_shaders_total;
extern std::atomic_int g_compiled_shaders_async;

bool s_isLoadingShaders{false};

bool RendererShaderGL::loadBinary()
{
	if (!s_programBinaryCache)
		return false;
	if (m_isGameShader == false || m_isGfxPackShader)
		return false; // only non-custom
	if (!glProgramBinary)
		return false; // OpenGL program binaries not supported

	cemu_assert_debug(m_baseHash != 0);
	uint64 h1, h2;
	GenerateShaderPrecompiledCacheFilename(m_type, m_baseHash, m_auxHash, h1, h2);
	std::vector<uint8> cacheFileData;
	if (!s_programBinaryCache->GetFile({h1, h2 }, cacheFileData))
		return false;
	if (cacheFileData.size() <= sizeof(uint32))
		return false;

	uint32 shaderBinFormat = *(uint32*)(cacheFileData.data());

	m_program = glCreateProgram();
	glProgramBinary(m_program, shaderBinFormat, cacheFileData.data()+4, cacheFileData.size()-4);

	int status = -1;
	glGetProgramiv(m_program, GL_LINK_STATUS, &status);
	if (status != GL_TRUE)
	{
		glDeleteProgram(m_program);
		m_program = 0;
		return false;
	}
	m_isCompiled = true;
	return true;
}

void RendererShaderGL::storeBinary()
{
	if (!s_programBinaryCache)
		return;
	if (!glGetProgramBinary)
		return;
	if (m_program == 0)
		return;
	if (!m_isGameShader || m_isGfxPackShader)
		return;

	GLint binaryLength = 0;
	glGetProgramiv(m_program, GL_PROGRAM_BINARY_LENGTH, &binaryLength);
	if (binaryLength > 0)
	{
		uint64 h1, h2;
		GenerateShaderPrecompiledCacheFilename(m_type, m_baseHash, m_auxHash, h1, h2);
		// build stored shader data (4 byte format + binary data)
		std::vector<uint8> storedBinary(binaryLength+sizeof(uint32), 0);
		GLenum binaryFormat = 0;
		glGetProgramBinary(m_program, binaryLength, NULL, &binaryFormat, storedBinary.data()+sizeof(uint32));
		*(uint32*)(storedBinary.data() + 0) = binaryFormat;
		// store
		s_programBinaryCache->AddFileAsync({h1, h2 }, storedBinary.data(), storedBinary.size());
	}
}

RendererShaderGL::RendererShaderGL(ShaderType type, uint64 baseHash, uint64 auxHash, bool isGameShader, bool isGfxPackShader, const std::string& glslSource)
	: RendererShader(type, baseHash, auxHash, isGameShader, isGfxPackShader), m_glslSource(glslSource)
{
	GLenum glShaderType;
	switch (type)
	{
	case ShaderType::kVertex:
		glShaderType = GL_VERTEX_SHADER;
		break;
	case ShaderType::kFragment:
		glShaderType = GL_FRAGMENT_SHADER;
		break;
	case ShaderType::kGeometry:
		glShaderType = GL_GEOMETRY_SHADER;
		break;
	default:
		cemu_assert_debug(false);
	}

	if (s_isLoadingShaders)
	{
		if (loadBinary())
		{
			m_glslSource.clear();
			m_glslSource.shrink_to_fit();
			return;
		}
	}

	m_shader_object = glCreateShader(glShaderType);

	const char *c_str = m_glslSource.c_str();
	const GLint size = (GLint)m_glslSource.size();
	glShaderSource(m_shader_object, 1, &c_str, &size);
	glCompileShader(m_shader_object);

	GLint log_length;
	glGetShaderiv(m_shader_object, GL_INFO_LOG_LENGTH, &log_length);
	if (log_length > 0)
	{
		char log[2048]{};
		GLsizei log_size;
		glGetShaderInfoLog(m_shader_object, std::min<uint32>(log_length, sizeof(log) - 1), &log_size, log);
		cemuLog_log(LogType::Force, "Error/Warning in shader:");
		cemuLog_log(LogType::Force, log);
	}

	// set debug name
	if (LaunchSettings::NSightModeEnabled())
	{
		auto objNameStr = fmt::format("shader_{:016x}_{:016x}", m_baseHash, m_auxHash);
		glObjectLabel(GL_SHADER, m_shader_object, objNameStr.size(), objNameStr.c_str());
	}

	m_program = glCreateProgram();
	glProgramParameteri(m_program, GL_PROGRAM_SEPARABLE, GL_TRUE);
	glProgramParameteri(m_program, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE);
	glAttachShader(m_program, m_shader_object);
	m_shader_attached = true;
	glLinkProgram(m_program);

	storeBinary();

	// count shader compilation
	if (!s_isLoadingShaders)
		++g_compiled_shaders_total;

	// we can throw away the GLSL code to conserve RAM
	m_glslSource.clear();
	m_glslSource.shrink_to_fit();
}

RendererShaderGL::~RendererShaderGL()
{
	if (m_shader_object != 0 && m_shader_attached)
		glDetachShader(m_program, m_shader_object);

	if (m_shader_object != 0)
		glDeleteShader(m_shader_object);

	if (m_program != 0)
		glDeleteProgram(m_program);
}

void RendererShaderGL::PreponeCompilation(bool isRenderThread)
{
	// the logic for initiating compilation is currently in the constructor
	// here we only guarantee that it is finished before we return
	if (m_isCompiled)
		return;
	WaitForCompiled();
}

bool RendererShaderGL::IsCompiled()
{
	cemu_assert_debug(false);
	return true;
}

bool RendererShaderGL::WaitForCompiled()
{
	char infoLog[8 * 1024];
	if (m_isCompiled)
		return true;
	// check if compilation was successful
	GLint compileStatus = GL_FALSE;
	glGetShaderiv(m_shader_object, GL_COMPILE_STATUS, &compileStatus);
	if (compileStatus == 0)
	{
		uint32 infoL


#include<iostream>
using namespace std;

class Node{
    public:
        int data;
        Node *next;
};

class LinkedList{
    Node
        *HEAD,
        *newNode,
        *nextNode;
    public:
        LinkedList(){
            this -> HEAD =
            this -> newNode =
            this -> nextNode =
                NULL;
        }

        void insert_at_beginning(int data){
            if (this -> HEAD == NULL){
                this -> HEAD = new Node;
                this -> HEAD -> next = NULL;
            } else {
                this -> newNode = new Node;
                this -> newNode -> next = HEAD;
                HEAD = newNode;
                newNode = NULL;
            }
            this -> HEAD -> data = data;
            cout << "Inserted the values at the beginning of the list" << endl;
        }

        void insert_at_pos(int key, int data){
            if (key < 0){
                cout << "Invalid key" << endl;
            }
            else {
                int count = 0;
                Node* ptr = HEAD;
                while (ptr != NULL){
                    ptr = ptr -> next;
                    count++;
                }

                if (key >= count)
                    cout << "key overflow" << endl;

                else {
                    newNode = new Node;
                    newNode -> data = data;
                    ptr = HEAD;
                    for (int i = 0; i < key; i++){
                        nextNode = ptr;
                        ptr = ptr -> next;
                    }
                    newNode -> next = ptr;

                    if (nextNode != NULL)
                        nextNode -> next = newNode;

                    if (key == 0){
                        HEAD = newNode;
                    }
                    cout << "Inserted an element at pos: " << key << endl;
                }
                nextNode = newNode = ptr = NULL;
            }
        }

        void search(int key){
            Node* ptr = HEAD;
            for (int i = 0; i < key; i++)
                if (ptr != NULL)
                    ptr = ptr -> next;

            if (ptr == NULL)
                cout << "Node key overflow" << endl;
            cout << "Searched data is " << ptr -> data << endl;

        }

        void delete_node(int key){
            if (key < 0)
                cout << "Invalid key number: " << key << endl;
            else {
                Node* ptr = HEAD;
                if (key == 0){
                    ptr = ptr -> next;
                    delete HEAD;
                    HEAD = ptr;
                }
                else {
                    ptr = HEAD;
                    for (int i = 0; i < key - 1; i++)
                        if (ptr != NULL)
                            ptr = ptr -> next;
                        else
                            cout << "Node key overflow" << endl;

                    nextNode = ptr -> next -> next;
                    delete ptr -> next;
                    ptr -> next = nextNode;
                    nextNode = NULL;
                    ptr = NULL;
                    cout << "Deleted the node from key: " << key << endl;
                }
            }
        }

        void pop(){
            if (HEAD == NULL){
                cout << "No value is present" << endl;
            }
            else if (HEAD -> next == NULL){
                delete HEAD;
                HEAD = NULL;
                cout << "Popped (deleted from end) back node" << endl;
            }
            else {
                Node* ptr = HEAD, *prev;
                while (ptr -> next != NULL){
                    prev = ptr;
                    ptr = ptr -> next;
                }
                delete ptr;
                prev -> next = NULL;
                cout << "Popped (deleted from end) back node" << endl;
            }
        }

        void delete_node_by_value(int data){
            Node* ptr = HEAD;
            if (ptr -> data == data){
                ptr = ptr -> next;
                delete HEAD;
                HEAD = ptr;
            }
            else {
                Node* prev = NULL;
                Node* deleteNode = NULL;
                while (ptr != NULL && deleteNode == NULL){
                    if (ptr -> data == data)
                        deleteNode = ptr;
                    else {
                        prev = ptr;
                        ptr = ptr -> next;
                    }
                }
                if (deleteNode == NULL)
                    cout << "Couldn't find a node by value: " << data << endl;
                else {
                    prev -> next = ptr -> next;
                    delete ptr;
                    cout << "Successfully deleted a node by value: " << data << endl;
                }
                prev = deleteNode = NULL;
            }
            ptr = NULL;
        }

        void reverse()


#include "../../core/include/lexer.h"
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
#include <unordered_set>
#include <chrono>
#include <ctime>
#include <filesystem>
#include <sstream>

// Structure to hold expected token info
struct ExpectedToken {
    TokenType type;
    std::string value;
    size_t line;
    size_t column;
};

// Converts TokenType to string for output
std::string tokenTypeToString(TokenType type) {
    switch (type) {
        case TokenType::Identifier: return "Identifier";
        case TokenType::Keyword: return "Keyword";
        case TokenType::Number: return "Number";
        case TokenType::String: return "String";
        case TokenType::Operator: return "Operator";
        case TokenType::Arrow: return "Arrow";
        case TokenType::TagOpen: return "TagOpen";
        case TokenType::TagClose: return "TagClose";
        case TokenType::TagSelfClose: return "TagSelfClose";
        case TokenType::TagEnd: return "TagEnd";
        case TokenType::AttributeName: return "AttributeName";
        case TokenType::AttributeValue: return "AttributeValue";
        case TokenType::Text: return "Text";
        case TokenType::Comment: return "Comment";
        case TokenType::ExpressionStart: return "ExpressionStart";
        case TokenType::ExpressionEnd: return "ExpressionEnd";
        case TokenType::Equals: return "Equals";
        case TokenType::BraceOpen: return "BraceOpen";
        case TokenType::BraceClose: return "BraceClose";
        case TokenType::Colon: return "Colon";
        case TokenType::SemiColon: return "SemiColon";
        case TokenType::ParenOpen: return "ParenOpen";
        case TokenType::ParenClose: return "ParenClose";
        case TokenType::SquareBracketOpen: return "SquareBracketOpen";
        case TokenType::SquareBracketClose: return "SquareBracketClose";
        case TokenType::Comma: return "Comma";
        case TokenType::Dot: return "Dot";
        case TokenType::AtModifier: return "AtModifier";
        case TokenType::ValueBinding: return "ValueBinding";
        case TokenType::StyleProperty: return "StyleProperty";
        case TokenType::EOFToken: return "EOFToken";
        case TokenType::Unknown: return "Unknown";
        case TokenType::Error: return "Error";
        case TokenType::ErrorRecovery: return "ErrorRecovery";
        default: return "Unknown";
    }
}

// Compute expected type/value logically for each token
void computeExpected(const Token& token, std::string& expectedType, std::string& expectedValue) {
    static const std::unordered_set<std::string> keywords = {
        "async", "component", "import", "extern", "for", "if", "else", "while", "return", "break", "continue", "yield", "await", "throw", "try", "catch", "finally",
        "render", "script", "function", "fn", "method", "type", "interface", "struct", "enum", "union", "from", "export", "use", "pub", "mod", "namespace",
        "move", "copy", "ref", "deref", "owned", "borrowed", "shared", "weak", "true", "false", "null", "none", "undefined", "this", "super", "self", "Self", "match", "case", "default",
        "let", "const", "var", "new", "delete", "as", "is", "typeof", "print", "println"
    };

    // Predict expected type for comments
    if (token.type == TokenType::Comment) {
        expectedType = "Comment";
        expectedValue = token.value;
        return;
    }

    // Predict expected type for keywords
    if (keywords.count(token.value)) {
        expectedType = "Keyword";
        expectedValue = token.value;
        return;
    }

    // Predict expected type for numbers
    if (token.type == TokenType::Number) {
        expectedType = "Number";
        expectedValue = token.value;
        return;
    }

    // Predict expected type for strings
    if (token.type == TokenType::String) {
        expectedType = "String";
        expectedValue = token.value;
        return;
    }

    // Predict expected type for identifiers
    if (token.type == TokenType::Identifier) {
        expectedType = "Identifier";
        expectedValue = token.value;
        return;
    }

    // Predict expected type for operators and arrows
    if (token.type == TokenType::Operator || token.type == TokenType::Arrow) {
        expectedType = tokenTypeToString(token.type);
        expectedValue = token.value;
        return;
    }

    // Predict expected type for tags
    if (token.type == TokenType::TagOpen || token.type == TokenType::TagClose || token.type == TokenType::TagSelfClose || token.type == TokenType::TagEnd) {
        expectedType = tokenTypeToString(token.type);
        expectedValue = token.value;
        return;
    }

    // Predict expected type for attributes
    if (token.type == TokenType::AttributeName || token.type == TokenType::AttributeValue) {
        expectedType = tokenTypeToString(token.type);
        expectedValue = token.value;
        return;
    }

    // Predict expected type for text
    if (token.type == T


#include "utils.h"

#include <flutter_windows.h>
#include <io.h>
#include <stdio.h>
#include <windows.h>

#include <iostream>

void CreateAndAttachConsole() {
  if (::AllocConsole()) {
    FILE *unused;
    if (freopen_s(&unused, "CONOUT$", "w", stdout)) {
      _dup2(_fileno(stdout), 1);
    }
    if (freopen_s(&unused, "CONOUT$", "w", stderr)) {
      _dup2(_fileno(stdout), 2);
    }
    std::ios::sync_with_stdio();
    FlutterDesktopResyncOutputStreams();
  }
}

std::vector<std::string> GetCommandLineArguments() {
  // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use.
  int argc;
  wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc);
  if (argv == nullptr) {
    return std::vector<std::string>();
  }

  std::vector<std::string> command_line_arguments;

  // Skip the first argument as it's the binary name.
  for (int i = 1; i < argc; i++) {
    command_line_arguments.push_back(Utf8FromUtf16(argv[i]));
  }

  ::LocalFree(argv);

  return command_line_arguments;
}

std::string Utf8FromUtf16(const wchar_t* utf16_string) {
  if (utf16_string == nullptr) {
    return std::string();
  }
  unsigned int target_length = ::WideCharToMultiByte(
      CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
      -1, nullptr, 0, nullptr, nullptr)
    -1; // remove the trailing null character
  int input_length = (int)wcslen(utf16_string);
  std::string utf8_string;
  if (target_length == 0 || target_length > utf8_string.max_size()) {
    return utf8_string;
  }
  utf8_string.resize(target_length);
  int converted_length = ::WideCharToMultiByte(
      CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
      input_length, utf8_string.data(), target_length, nullptr, nullptr);
  if (converted_length == 0) {
    return std::string();
  }
  return utf8_string;
}


#include <bits/stdc++.h>
#include "json.hpp"  // download json.hpp from nlohmann and place it here
using namespace std;
using json = nlohmann::json;

// Convert string in given base -> decimal
long long toDecimal(const string &val, int base) {
    long long result = 0;
    for (char c : val) {
        int digit;
        if (isdigit(c)) digit = c - '0';
        else if (isalpha(c)) digit = toupper(c) - 'A' + 10;
        else digit = 0;
        result = result * base + digit;
    }
    return result;
}

// Lagrange interpolation polynomial coefficients
vector<double> lagrangeInterpolation(const vector<pair<double,double>> &points, int k) {
    vector<double> coeff(k, 0.0); // degree k-1 polynomial

    for (int i = 0; i < k; i++) {
        vector<double> basis(k, 0.0);
        basis[0] = 1.0;
        double denom = 1.0;

        for (int j = 0; j < k; j++) {
            if (i == j) continue;
            denom *= (points[i].first - points[j].first);

            // multiply basis by (x - x_j)
            for (int d = k-1; d >= 1; d--) {
                basis[d] = basis[d] * (-points[j].first) + basis[d-1];
            }
            basis[0] *= -points[j].first;
        }

        for (int d = 0; d <= k; d++) {
            coeff[d] += (points[i].second / denom) * basis[d];
        }
    }
    return coeff;
}

// Process one JSON case
void processCase(const string &jsonText) {
    json j = json::parse(jsonText);

    int n = j["keys"]["n"];
    int k = j["keys"]["k"];

    vector<pair<double,double>> points;
    for (auto it = j.begin(); it != j.end(); ++it) {
        string key = it.key();
        if (key == "keys") continue;
        auto val = it.value();

        int x = stoi(key);
        int base = stoi(val["base"].get<string>());
        string value = val["value"];
        long long y = toDecimal(value, base);
        points.push_back({x, y});
    }

    sort(points.begin(), points.end()); // keep in order
    points.resize(k); // take only k points

    auto coeff = lagrangeInterpolation(points, k);

    // Print only highest coefficient (ak-1)
    cout << coeff[k-1] << "\n";
}

int main() {
    // Case 1
    string case1 = R"(
    {
        "keys": {
            "n": 4,
            "k": 3
        },
        "1": { "base": "10", "value": "4" },
        "2": { "base": "2", "value": "111" },
        "3": { "base": "10", "value": "12" },
        "6": { "base": "4", "value": "213" }
    }
    )";

    // Case 2
    string case2 = R"(
    {
        "keys": {
            "n": 10,
            "k": 7
        },
        "1":  { "base": "6",  "value": "13444211440455345511" },
        "2":  { "base": "15", "value": "aed7015a346d635" },
        "3":  { "base": "15", "value": "6aeeb69631c227c" },
        "4":  { "base": "16", "value": "e1b5e05623d881f" },
        "5":  { "base": "8",  "value": "316034514573652620673" },
        "6":  { "base": "3",  "value": "2122212201122002221120200210011020220200" },
        "7":  { "base": "3",  "value": "20120221122211000100210021102001201112121" },
        "8":  { "base": "6",  "value": "20220554335330240002224253" },
        "9":  { "base": "12", "value": "45153788322a1255483" },
        "10": { "base": "7",  "value": "1101613130313526312514143" }
    }
    )";

    cout << "Case 1: ";
    processCase(case1);

    cout << "Case 2: ";
    processCase(case2);

    return 0;
}


#include "msgHandler.h"

#include "databaseManager.h"
#include "logManager.h"
#include "msg.pb.h"
#include "msg_header.pb.h"
#include "networkMsg.h"

#include <iostream>

msg_header::ServerMsgHeader GetServerMsgHeader()
{
    msg_header::ServerMsgHeader header;
    header.set_timestamp(
        std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count());
    return header;
}

std::tuple<ClientID, MsgType, std::string> GetInvalidMessageErrorResponse(const ClientID &client)
{
    msg::InvalidMessageError invalidMsgError;
    invalidMsgError.mutable_header()->CopyFrom(GetServerMsgHeader());
    std::string msg;
    invalidMsgError.SerializeToString(&msg);
    return std::make_tuple(client, MsgType::INVALID_MESSAGE_ERROR, msg);
}

std::tuple<ClientID, MsgType, std::string> HandleLoginRequest(const ClientID &client, const std::string &message)
{
    // Parse the message using protobuf
    msg::LoginRequest loginReq;
    if (!loginReq.ParseFromString(message))
    {
        LOG_ERROR(networkLogger, "Failed to parse login request");
        return GetInvalidMessageErrorResponse(client);
    }

    // Check credentials
    DatabaseManager::ResultCode result =
        DatabaseManager::instance()->authenticateUser(loginReq.username(), loginReq.password());

    // Prepare response
    msg::LoginResponse loginResp;
    loginResp.mutable_header()->CopyFrom(GetServerMsgHeader());
    if (result == DatabaseManager::SUCCESS)
    {
        loginResp.set_state(msg::LoginResponse::USER_VERIFICATION_SUCCESS);
        loginResp.set_session_id("session_abc123");
        LOG_INFO(networkLogger, "Login successful: " + loginReq.username());
    }
    else
    {
        loginResp.set_state(msg::LoginResponse::USER_VERIFICATION_FAILED);
        loginResp.set_session_id("");
        LOG_INFO(networkLogger, "Login failed: " + loginReq.username());
    }
    std::string msg;
    loginResp.SerializeToString(&msg);

    return std::make_tuple(client, MsgType::LOGIN_RESPONSE, msg);
}

std::tuple<ClientID, MsgType, std::string> HandleSignUpRequest(const ClientID &client, const std::string &message)
{
    // Parse the message using protobuf
    msg::SignUpRequest signUpReq;
    if (!signUpReq.ParseFromString(message))
    {
        LOG_ERROR(networkLogger, "Failed to parse sign up request");
        return GetInvalidMessageErrorResponse(client);
    }

    // Try to create the user
    DatabaseManager::ResultCode result =
        DatabaseManager::instance()->createUser(signUpReq.username(), signUpReq.password());

    // Prepare response
    msg::SignUpResponse signUpResp;
    signUpResp.mutable_header()->CopyFrom(GetServerMsgHeader());
    if (result == DatabaseManager::SUCCESS)
    {
        signUpResp.set_state(msg::SignUpResponse::USER_CREATED);
        LOG_INFO(networkLogger, "Sign up successful: " + signUpReq.username());
    }
    else if (result == DatabaseManager::USER_ALREADY_EXISTS)
    {
        signUpResp.set_state(msg::SignUpResponse::USER_EXIST);
        LOG_INFO(networkLogger, "Sign up failed: " + signUpReq.username() + " already exists");
    }
    else
    {
        signUpResp.set_state(msg::SignUpResponse::USER_CREATE_FAILED);
        LOG_INFO(networkLogger, "Sign up failed: " + signUpReq.username());
    }
    std::string msg;
    signUpResp.SerializeToString(&msg);

    return std::make_tuple(client, MsgType::SIGN_UP_RESPONSE, msg);
}


// SPDX-FileCopyrightText: 2020 - 2023 Berkeley Lab
//
// SPDX-License-Identifier: LicenseRef-OpenSource

#include <NavierStokesBase.H>

using namespace amrex;

//--------------------------------------------------------------------
// "On the fly" time averaging of the velocity
//
//  Just put ns.avg_interval = something (>0) to activate the feature.
//  avg_interval controls the interval of time-steps when a solution is taken into account.
//  The average is dumped in each plotfile.
//
//  Do not forget to add "velocity_average" in amr.derive_plot_vars.
//
//  If "compute_fluctuations" is turned on, it is going to compute RMS of velocity fluctuations.
//  The good practice is to start computing RMS of fluctuations
//  when the average of the velocity has reached convergence.
//---------------------------------------------------------------------

void
NavierStokesBase::time_average(amrex::Real&  a_time_avg, amrex::Real&  a_time_avg_fluct, amrex::Real&  a_dt_avg, const Real& dt_level)

{
  a_dt_avg = a_dt_avg + dt_level;

  if (parent->levelSteps(0)%avg_interval == 0)
  {
    MultiFab& Sstate = get_new_data(State_Type);
    MultiFab& Savg   = get_new_data(Average_Type);
    MultiFab& Savg_old   = get_old_data(Average_Type);

#ifdef _OPENMP
#pragma omp parallel if (Gpu::notInLaunchRegion())
#endif
    for (MFIter mfi(Savg,TilingIfNotGPU()); mfi.isValid(); ++mfi)
    {
       const Box& bx = mfi.tilebox();
       auto const& S_state = Sstate.array(mfi,Xvel);
       auto const& S_avg   = Savg.array(mfi);
       auto const& S_avg_old   = Savg_old.array(mfi);
       int loc_compute_fluctuations = compute_fluctuations; //NavierStokesBase class cannot be accessed directly from device

       amrex::ParallelFor(bx, AMREX_SPACEDIM, [S_state, S_avg, S_avg_old, a_dt_avg, a_time_avg, loc_compute_fluctuations]
       AMREX_GPU_DEVICE (int i, int j, int k, int n) noexcept
       {
          S_avg(i,j,k,n) = S_avg_old(i,j,k,n) + a_dt_avg * S_state(i,j,k,n);
          S_avg_old(i,j,k,n) = S_avg(i,j,k,n);

          if (loc_compute_fluctuations == 1){
            amrex::Real vel_prime = S_state(i,j,k,n) - (S_avg(i,j,k,n)/(a_time_avg + a_dt_avg));
            S_avg(i,j,k,n+AMREX_SPACEDIM) = S_avg_old(i,j,k,n+AMREX_SPACEDIM) + a_dt_avg * vel_prime * vel_prime;
          }
          else{
            S_avg(i,j,k,n+AMREX_SPACEDIM) = 0.;
          }
          S_avg_old(i,j,k,n+AMREX_SPACEDIM) = S_avg(i,j,k,n+AMREX_SPACEDIM);
       });
    }

    a_time_avg = a_time_avg + a_dt_avg;
    if (compute_fluctuations == 1){
      a_time_avg_fluct = a_time_avg_fluct + a_dt_avg;
    }else{
      a_time_avg_fluct = 0.;
    }

    a_dt_avg = 0;

  }
}


///////////////////////////////////////////////////////////////////////////////////
// TODO:: Add any needed includes
///////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <random>
#include <future>

// Include file and line numbers for memory leak detection for visual studio in debug mode
#if defined _MSC_VER && defined _DEBUG
	#include <crtdbg.h>
	#define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
	#define ENABLE_LEAK_DETECTION() _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF)
#else
	#define ENABLE_LEAK_DETECTION()
#endif

class UniformRandInt
{
public:
	void Init(int min, int max)
	{
		// Seed our random number generator with a non-deterministic random value. If no such capabilities exist then
		//   the number will be pulled from a pseudo random number generator.
		randEngine.seed(randDevice());

		// We want to generate values in the range of [min, max] (inclusive) with a uniform distribution.
		distro = std::uniform_int_distribution<int>(min, max);
	}

	int operator()()
	{
		return distro(randEngine);
	}

private:
	std::random_device randDevice;
	std::mt19937 randEngine;
	std::uniform_int_distribution<int> distro;
};

struct ThreadStruct
{
	int id;									// thread number
	UniformRandInt myRand;					// random number generator for this thread

	///////////////////////////////////////////////////////////////////////////////////
	// TODO:: Any new data to pass to thread should be put here
	///////////////////////////////////////////////////////////////////////////////////
	bool* endDetachedThreads;
	std::mutex* mtx;
	int* detachedThreadCount;
	std::condition_variable* condV;
};

///////////////////////////////////////////////////////////////////////////////////
// Prompts the user to press enter and waits for user input
///////////////////////////////////////////////////////////////////////////////////
void Pause()
{
	printf("Press enter to continue\n");
	getchar();
}

////////////////////////////////////////////////////////////////////////////////////
// TODO:: Create a function to process (in this case just print) the 'work'
//   generated by the Joinable and Detached threads that were created in main. The
//   purpose of this function is to delay the printing of 'work' until it's been generated.
//   You must also print out the thread ID along with the work value.
//
// Note: You are required to use a std::promise to implement this logic.
////////////////////////////////////////////////////////////////////////////////////
void ExecuteWork(int id, std::future<int> workFuture)
{
	// get waits for worker thread
	int work = workFuture.get();
	printf("PROCESS: Thread %d, processed work value %d\n", id, work);
}

///////////////////////////////////////////////////////////////////////////////////
// Entry point for joinable threads.
//
// Arguments:
//   threadData - Pointer to the thread specific data
///////////////////////////////////////////////////////////////////////////////////
void JoinableThreadEntrypoint(ThreadStruct *threadData)
{
	////////////////////////////////////////////////////////////////////////////////////
	// TODO:: Create a joinable thread to print the value of 'work' once it's generated.
	//   The printer (or "process work") thread MUST be created before 'work' is initialized and it must not
	//   print until 'work' has been generated by this thread.
	//
	// Note: You are required to use a std::promise to implement the printing logic.
	////////////////////////////////////////////////////////////////////////////////////
	std::promise<int> workPromise;
	std::future<int> workFuture = workPromise.get_future();
	std::thread printerThread(ExecuteWork, threadData->id, std::move(workFuture));

	int workLimit = (threadData->id + 1) + (threadData->myRand());
	int work = 0;

	// Performs some arbitrary amount of work.
	printf("START: Joinable Thread %d, starting limit = %d\n", threadData->id, workLimit);
	for (int i = 0; i < workLimit; i += (threadData->id + 1))
	{
		work++;
	}

	workPromise.set_value(work); // signals worker thread
	printerThread.join();

	printf("FINISH: Joinable thread %d, finished with value %d\n", threadData->id, work);

	///////////////////////////////////////////////////////////////////////////////////
	// TODO:: The 'work' has been generated and the printing thread should be waiting
	//   on the promised work to be set. Set it now so the printing thread can resume.
	///////////////////////////////////////////////////////////////////////////////////
	// moved above finish print for clarity

}

///////////////////////////////////////////////////////////////////////////////////
// Entry point for detached threads.
//
// Arguments:
//   threadData - Pointer to the thread specific data
///////////////////////////////////////////////////////////////////////////////////
void DetachedThreadEntrypoint(ThreadStruct *t


#include "scanner/Hasher.hpp"

#include <stdexcept>
#include <sstream>
#include <iomanip>
#include <fstream>
#include <vector>

namespace scanner {

Hasher::Hasher(size_t chunk_size) : chunk_size_(chunk_size ? chunk_size : (1u << 20)) {
    ctx_ = EVP_MD_CTX_new();
    if (!ctx_)
        throw std::runtime_error("Creation context failed");
    reset();
}

Hasher::~Hasher() {
    if (ctx_) {
        EVP_MD_CTX_free(ctx_);
        ctx_ = nullptr;
    }
}

Hasher::Hasher(Hasher&& other) noexcept : ctx_(other.ctx_), chunk_size_(other.chunk_size_), inited_(other.inited_){
    other.ctx_ = nullptr;
    other.inited_ = false;
}

Hasher& Hasher::operator=(Hasher&& other) noexcept {
    if (this != &other) {
        ctx_ = other.ctx_;
        chunk_size_ = other.chunk_size_;
        inited_ = other.inited_;
        other.inited_ = false;
        other.ctx_ = nullptr;
    }
    return *this;
}

void Hasher::reset() {
    if (EVP_DigestInit_ex(ctx_, EVP_md5(), nullptr) != 1)
        throw std::runtime_error("EVP_DigestInit_ex failed");
    inited_ = true;
}

void Hasher::update(const void* data, size_t len) {
    if (!inited_)
        reset();
    if (len == 0)
        return;
    if (EVP_DigestUpdate(ctx_, data, len) != 1)
        throw std::runtime_error("Update failed");
}

std::array<unsigned char, 16> Hasher::finish_raw() {
    if (!inited_)
        reset();
    std::array<unsigned char, 16> out;
    unsigned int md_len;

    if (EVP_DigestFinal_ex(ctx_, out.data(), &md_len) != 1 || md_len != out.size())
        throw std::runtime_error("EVP_DigestFinal_ex failed");

    inited_ = false;
    return out;
}

std::string Hasher::finish_hex() {
    auto raw = finish_raw();
    return to_hex(raw.data(), raw.size());
}

std::string Hasher::md5_file(const std::filesystem::path& path) {
    std::ifstream in(path, std::ios::binary);
    if (!in)
        throw std::runtime_error("cannot open file: " + path.generic_string());

    reset();
    std::vector<unsigned char> buf(chunk_size_);
    while (in) {
        in.read(reinterpret_cast<char*>(buf.data()),
            static_cast<std::streamsize>(buf.size()));
        std::streamsize got = in.gcount();
        if (got > 0)
            update(buf.data(), static_cast<size_t>(got));
    }

    if (!in.eof() && in.fail())
        throw std::runtime_error("I/O error during read: " + path.generic_string());

    return finish_hex();
}

std::string Hasher::to_hex(const unsigned char* data, size_t len) {
    std::ostringstream oss;
    oss << std::hex << std::setfill('0');
    for (size_t i = 0; i < len; ++i)
        oss << std::setw(2) << static_cast<int>(data[i]);
    return oss.str();
}

} // namespace scanner


#include <bits/stdc++.h>
using namespace std;
using int128 = __int128_t; // for safe intermediate multiplications

struct Rat {
    long long num{0}, den{1};
    Rat()=default;
    Rat(long long n):num(n),den(1){}
    Rat(long long n,long long d):num(n),den(d){ normalize(); }

    static long long cgcd(long long a,long long b){
        if(a<0) a=-a; if(b<0) b=-b;
        while(b){ long long t=a%b; a=b; b=t; }
        return a;
    }
    void normalize(){
        if(den<0){ den=-den; num=-num; }
        long long g=cgcd(num,den);
        if(g) { num/=g; den/=g; }
    }
    bool isInt() const { return den==1; }
};
Rat operator+(const Rat&a,const Rat&b){ Rat r((long long)((int128)a.num*b.den+(int128)b.num*a.den), (long long)((int128)a.den*b.den)); r.normalize(); return r;}
Rat operator-(const Rat&a,const Rat&b){ Rat r((long long)((int128)a.num*b.den-(int128)b.num*a.den), (long long)((int128)a.den*b.den)); r.normalize(); return r;}
Rat operator*(const Rat&a,const Rat&b){ Rat r((long long)((int128)a.num*b.num), (long long)((int128)a.den*b.den)); r.normalize(); return r;}
Rat operator/(const Rat&a,const Rat&b){ Rat r((long long)((int128)a.num*b.den), (long long)((int128)a.den*b.num)); r.normalize(); return r;}

int digit_of(char c){
    if('0'<=c&&c<='9') return c-'0';
    if('a'<=c&&c<='z') return 10+(c-'a');
    if('A'<=c&&c<='Z') return 10+(c-'A');
    return -1;
}
long long parse_in_base(const string&s,int base){
    long long acc=0;
    for(char c:s){
        int d=digit_of(c);
        acc=acc*base+d;
    }
    return acc;
}
Rat lagrange(const vector<pair<int,long long>>&pts,int xq){
    Rat acc(0);
    int k=pts.size();
    for(int i=0;i<k;i++){
        int xi=pts[i].first;
        long long yi=pts[i].second;
        Rat num(1),den(1);
        for(int j=0;j<k;j++) if(i!=j){
            int xj=pts[j].first;
            num=num*Rat(xq-xj);
            den=den*Rat(xi-xj);
        }
        acc=acc+Rat(yi)*(num/den);
    }
    return acc;
}
bool next_comb(vector<int>&idx,int n){
    int k=idx.size();
    for(int i=k-1;i>=0;i--){
        if(idx[i]!=i+n-k){
            idx[i]++;
            for(int j=i+1;j<k;j++) idx[j]=idx[j-1]+1;
            return true;
        }
    }
    return false;
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    string input((istreambuf_iterator<char>(cin)), {});
    int n=0,k=0;
    {
        regex rn("\"n\"\\s*:\\s*([0-9]+)");
        regex rk("\"k\"\\s*:\\s*([0-9]+)");
        smatch m;
        regex_search(input,m,rn); n=stoi(m[1]);
        regex_search(input,m,rk); k=stoi(m[1]);
    }
    regex rblock("\"([0-9]+)\"\\s*:\\s*\\{([^}]*)\\}");
    regex rbase("\"base\"\\s*:\\s*\"([0-9]+)\"");
    regex rval("\"value\"\\s*:\\s*\"([^\"]+)\"");
    vector<pair<int,long long>> pts;
    auto it=input.cbegin(),end=input.cend(); smatch m;
    while(regex_search(it,end,m,rblock)){
        int idx=stoi(m[1]); string inner=m[2];
        smatch mb,mv;
        if(regex_search(inner,mb,rbase)&&regex_search(inner,mv,rval)){
            int base=stoi(mb[1]); string val=mv[1];
            long long y=parse_in_base(val,base);
            pts.push_back({idx,y});
        }
        it=m.suffix().first;
    }
    sort(pts.begin(),pts.end());

    int best=-1; long long secret=0;
    vector<int> comb(k); iota(comb.begin(),comb.end(),0);
    auto eval=[&](const vector<int>&c){
        vector<pair<int,long long>> sub; for(int id:c) sub.push_back(pts[id]);
        Rat sec=lagrange(sub,0);
        if(!sec.isInt()) return pair<int,long long>{-1,0};
        int match=0;
        for(auto&p:pts){
            Rat v=lagrange(sub,p.first);
            if(v.den==1&&v.num==p.second) match++;
        }
        return pair<int,long long>{match,(long long)sec.num};
    };
    while(true){
        auto [mch,sec]=eval(comb);
        if(mch>best){best=mch; secret=sec;}
        if(!next_comb(comb,n)) break;
    }
    cout<<secret<<"\n";
}


//
// Created by FANGG3 on 25-7-24.
// 自定义符号解析器实现 - 替代 xDL 依赖的独立符号解析实现
//

#include "symbolResolver.h"
#include "logger.h"
#include <algorithm>
#include <cstring>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>

// 静态成员初始化
std::unique_ptr<SymbolResolver> GlobalSymbolResolver::instance_ = nullptr;
std::once_flag GlobalSymbolResolver::once_flag_;

SymbolResolver& GlobalSymbolResolver::getInstance() {
    std::call_once(once_flag_, []() {
        instance_ = std::make_unique<SymbolResolver>();
    });
    return *instance_;
}

SymbolResolver::SymbolResolver() : totalResolves_(0), cacheHits_(0) {
    LOGD("SymbolResolver created");
}

SymbolResolver::~SymbolResolver() {
    // 清理 dlopen 句柄和文件映射
    for (auto& pair : modules_) {
        if (pair.second->handle) {
            dlclose(pair.second->handle);
        }
        // 文件映射由 ModuleInfo 析构函数处理
    }
    LOGD("SymbolResolver destroyed");
}

bool SymbolResolver::initialize() {
    LOGD("Initializing symbol resolver...");

    // 使用 dl_iterate_phdr 发现所有已加载的模块
    int result = dl_iterate_phdr(moduleDiscoveryCallback, this);
    LOGD("dl_iterate_phdr returned %d, found %zu modules", result, modules_.size());

    // 即使 dl_iterate_phdr 返回0，只要找到了模块就继续
    if (modules_.empty()) {
        LOGE("No modules discovered");
        return false;
    }

    // 按地址排序模块列表以优化查找
    modulesByAddress_.clear();
    modulesByAddress_.reserve(modules_.size());

    for (auto& pair : modules_) {
        modulesByAddress_.push_back(pair.second.get());
    }

    std::sort(modulesByAddress_.begin(), modulesByAddress_.end(),
              [](const ModuleInfo* a, const ModuleInfo* b) {
                  return a->baseAddress < b->baseAddress;
              });

    LOGD("Symbol resolver initialized with %zu modules", modules_.size());
    return true;
}

int SymbolResolver::moduleDiscoveryCallback(struct dl_phdr_info *info, size_t size, void *data) {
    SymbolResolver* resolver = static_cast<SymbolResolver*>(data);

    // 跳过没有名称的模块
    if (!info->dlpi_name || strlen(info->dlpi_name) == 0) {
        return 0;
    }

    // 计算模块的地址范围
    uint64_t baseAddr = info->dlpi_addr;
    uint64_t endAddr = baseAddr;

    for (int i = 0; i < info->dlpi_phnum; ++i) {
        const ElfW(Phdr)* phdr = &info->dlpi_phdr[i];
        if (phdr->p_type == PT_LOAD) {
            uint64_t segmentEnd = baseAddr + phdr->p_vaddr + phdr->p_memsz;
            if (segmentEnd > endAddr) {
                endAddr = segmentEnd;
            }
        }
    }

    // 创建模块信息
    auto moduleInfo = std::make_unique<ModuleInfo>();
    moduleInfo->path = info->dlpi_name;
    moduleInfo->baseAddress = baseAddr;
    moduleInfo->endAddress = endAddr;

    // 尝试使用 dlopen 获取句柄（用于符号查找）
    moduleInfo->handle = dlopen(info->dlpi_name, RTLD_LAZY | RTLD_NOLOAD);

    // 解析 ELF 符号表
    resolver->parseElfSymbols(moduleInfo.get());

    resolver->modules_[info->dlpi_name] = std::move(moduleInfo);

    LOGD("Discovered module: %s [0x%lx-0x%lx]", info->dlpi_name, baseAddr, endAddr);
    return 0;
}

bool SymbolResolver::parseElfSymbols(ModuleInfo* moduleInfo) {
    if (!moduleInfo) return false;

    // 尝试打开 ELF 文件
    int fd = open(moduleInfo->path.c_str(), O_RDONLY);
    if (fd < 0) {
        LOGW("Cannot open ELF file: %s", moduleInfo->path.c_str());
        return false;
    }

    // 获取文件大小
    off_t fileSize = lseek(fd, 0, SEEK_END);
    if (fileSize <= 0) {
        close(fd);
        return false;
    }

    // 映射文件到内存
    void* fileData = mmap(nullptr, fileSize, PROT_READ, MAP_PRIVATE, fd, 0);
    close(fd);

    if (fileData == MAP_FAILED) {
        LOGW("Failed to mmap ELF file: %s", moduleInfo->path.c_str());
        return false;
    }

    // 保存文件映射信息供后续使用
    moduleInfo->fileData = fileData;
    moduleInfo->fileSize = fileSize;

    // 解析 ELF 头
    const ElfW(Ehdr)* ehdr = static_cast<const ElfW(Ehdr)*>(fileData);
    if (memcmp(ehdr->e_ident, ELFMAG, SELFMAG) != 0) {
        munmap(fileData, fileSize);
        return false;
    }

    // 查找节头表
    const ElfW(Shdr)* shdrs = reinterpret_cast<const ElfW(Shdr)*>(
        static_cast<const char*>(fileData) + ehdr->e_shoff);

    // 查找字符串表节
    const ElfW(Shdr)* strtabShdr = &shdrs[ehdr->e_shstrndx];
    const char* strtab = static_cast<const char*>(fileData) + strtabShdr->sh_offset;

    // 查找符号表和字符串表
    for (int i = 0; i < ehdr->e_shnum; ++i) {
        const ElfW(Shdr)* shdr = &shdrs[i];
        const char* sectionName = strtab + shdr->sh_name;

        if (shdr->sh_type == SHT_DYNSYM && strcmp(sectionName, ".dynsym") == 0) {
            // 找到动态符号表
            moduleInfo->dynSymbols = reinterpret_cast<const ElfW(Sym)*>(
                static_cast<const char*>(fileData) + shdr->sh_offset);
            moduleInfo->dynSymCount = shdr->sh_size / sizeof(ElfW(Sym));

            // 查找对应的字符串表
            if (shdr->sh_link < ehdr->e_shnum) {


#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"coffee_card", origin, size)) {
    return EXIT_FAILURE;
  }
  window.SetQuitOnClose(true);

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

  ::CoUninitialize();
  return EXIT_SUCCESS;
}


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

bool f(ll mid, ll h, ll w, ll n) {
    return (mid / h) * (mid / w) >= n;
}

ll bin_search(ll n, ll h, ll w) {
    ll l = 1, r = n * w;
    ll mid = (l + r) / 2;
    while (r - l > 1) {
        mid = (l + r) / 2;
        if (f(mid, h, w, n)) {
            r = mid;
        } else {
            l = mid;
        }
    }
    return r;
}

ll time_revers(string t) {
    return (int(int(t[0]) - 48) * 10 + int(int(t[1]) - 48)) * 60 + (int(int(t[3]) - 48) * 10 + int(int(t[4]) - 48));
}

void time_revers(ll t) {
    if (t / 60 < 10) {
        cout << 0;
    }
    cout << t / 60 << ":";
    if (t % 60) {
        cout << 0;
    }
    cout << t % 60;
}

int main()
{
    ll speed, break_time, n, dist, sm_time = 0, time, global_dist = 0;
    string str;
    cin >> speed >> break_time >> n;
    for (ll i = 0; i < n; ++i) {
        cin >> dist >> str;

        time = (dist - global_dist) / speed;
        if ((dist - global_dist) % speed != 0) {
            ++time;
        }
        global_dist += dist;
        time = max(time, time_revers(str));
        sm_time += time + break_time;
        // cout << time_revers(str) << "\n";
        // time_revers(time_revers(str));
        // cout << "\n";
    }
    ll go_back = global_dist / speed;
    if (global_dist % speed != 0) {
        ++go_back;
    }
    time_revers(sm_time + go_back);

    return 0;
}


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
#include <bits/stdc++.h>
using namespace std;

struct ListNode
{
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution
{
    static bool cmp(ListNode *a, ListNode *b)
    {
        return a->val > b->val;
    }

public:
    ListNode *mergeKLists(vector<ListNode *> &lists)
    {
        ListNode *res = new ListNode();
        ListNode *cur = res;
        priority_queue<ListNode *, vector<ListNode *>, decltype(&cmp)> pq(&cmp);
        for (int i = 0, n = lists.size(); i < n; i++)
            if (lists[i])
                pq.push(lists[i]);

        while (!pq.empty())
        {
            ListNode *node = pq.top();
            pq.pop();
            cur->next = node;
            cur = cur->next;
            if (node->next != nullptr)
                pq.push(node->next);
        }
        return res->next;
    }
};

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    Solution sol;
    // lists = [[1,4,5],[1,3,4],[2,6]]
    vector<ListNode *> lists;
    lists.push_back(new ListNode(1, new ListNode(4, new ListNode(5))));
    lists.push_back(new ListNode(1, new ListNode(3, new ListNode(4))));
    lists.push_back(new ListNode(2, new ListNode(6)));

    ListNode *node = sol.mergeKLists(lists);
    while (node != nullptr)
    {
        cout << node->val << " ";
        node = node->next;
    }
    return 0;
}


#include "Shader.hpp"

#include <glad/glad.h>

Shader::Shader(const std::string &vertexSource, const std::string &fragmentSource)
{
    unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER);
    CompileShader(vertexShader, vertexSource);

    unsigned int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    CompileShader(fragmentShader, fragmentSource);

    m_RendererID = glCreateProgram();

    glAttachShader(m_RendererID, vertexShader);
    glAttachShader(m_RendererID, fragmentShader);

    LinkProgram(m_RendererID);

    glDeleteShader(vertexShader);
    glDeleteShader(fragmentShader);
}

Shader::~Shader()
{
    glDeleteProgram(m_RendererID);
}

void Shader::Bind() const
{
    glUseProgram(m_RendererID);
}

void Shader::Unbind() const
{
    glUseProgram(0);
}

void Shader::CompileShader(unsigned int shaderID, const std::string &source)
{
    const char *sourceCStr = source.c_str();
    glShaderSource(shaderID, 1, &sourceCStr, nullptr);
    glCompileShader(shaderID);

    int success;
    char infoLog[512];
    glGetShaderiv(shaderID, GL_COMPILE_STATUS, &success);
    if (!success)
    {
        glGetShaderInfoLog(shaderID, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::COMPILATION_FAILED\n" << infoLog << std::endl;
    }
}

void Shader::LinkProgram(unsigned int programID)
{
    glLinkProgram(programID);

    int success;
    char infoLog[512];
    glGetProgramiv(programID, GL_LINK_STATUS, &success);
    if (!success)
    {
        glGetProgramInfoLog(programID, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
    }
}


class Solution {
public:
    // Merge Sort function
    void merge(vector<int>& nums, int left, int mid, int right) {
        int n1 = mid - left + 1;
        int n2 = right - mid;

        // Temporary arrays
        vector<int> leftArr(n1), rightArr(n2);

        // Copy data to temp arrays
        for (int i = 0; i < n1; i++)
            leftArr[i] = nums[left + i];
        for (int i = 0; i < n2; i++)
            rightArr[i] = nums[mid + 1 + i];

        // Merge the temp arrays back into the original array
        int i = 0, j = 0, k = left;
        while (i < n1 && j < n2) {
            if (leftArr[i] <= rightArr[j]) {
                nums[k++] = leftArr[i++];
            } else {
                nums[k++] = rightArr[j++];
            }
        }

        // Copy the remaining elements of leftArr, if any
        while (i < n1) {
            nums[k++] = leftArr[i++];
        }

        // Copy the remaining elements of rightArr, if any
        while (j < n2) {
            nums[k++] = rightArr[j++];
        }
    }

    // Recursive function to implement Merge Sort
    void mergeSort(vector<int>& nums, int left, int right) {
        if (left < right) {
            int mid = left + (right - left) / 2;

            // Recursively sort the two halves
            mergeSort(nums, left, mid);
            mergeSort(nums, mid + 1, right);

            // Merge the sorted halves
            merge(nums, left, mid, right);
        }
    }

    vector<int> sortArray(vector<int>& nums) {
        mergeSort(nums, 0, nums.size() - 1);
        return nums;
    }
};


// g++ cli\main.cpp -o main;./main.exe test/main.doyt -p -d

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <chrono>
#include <optional>
#include <charconv>
#include <iomanip>
#include <fmt/core.h>
#include "../include/dlex.hpp"
#include "../src/dlex.cpp"

using namespace std;

inline void disp_help(){
    cerr << "\nFlags:\n -d : debug messages\n -p : print tokens\n -h : help\n";
}

inline string format_bytes(size_t bytes){
    if (bytes < 2048) return to_string(bytes) + "B";
    return to_string(bytes / 1024) + "KB";
};

int main(int argc, char *argv[])
{
    if (argc < 2)
    {
        cerr << "\nMust input a filepath!\n";
        disp_help();
        return 1;
    };

    int flags = 0b0000; // [show display messages][print tokens]
    string filepath;
    if (argc > 1){
        for (int argi = 1; argi<argc; argi++){
            switch (argv[argi][0]){
                case '-':
                    switch (*(argv[argi]+1)){
                        case 'd': flags |= 0b0001; break;
                        case 'p': flags |= 0b0010; break;
                        case 'h':
                            disp_help();
                            return 0;
                        default: cerr << "Unrecognised flag '" << argv[argi] << "'!\n"; return 1;
                    }; break;
                default: filepath = argv[argi]; break;
            };
        };
    };

    auto lexctx = LexContext::from_filepath(filepath);

    cout << "\nReading: " << filepath << ", Source Size: " << lexctx.src_size;

    bool success = true;
    auto bench_start = chrono::high_resolution_clock::now();

    if (lexctx.src_size == 0){
        cout << "\n\033[1;38;2;255;165;0mCan't interpret empty source!\033[0m";
        return 1;
    };

    try{
        token_lctx(lexctx, flags);
    }
    catch(runtime_error &e){
        success = false;
        cerr << e.what();
    }
    catch(exception &e){
        success = false;
        cerr << "\nTokenizer unexpected error: " << e.what();
    };
    auto bench_end = chrono::high_resolution_clock::now();

    double duration = chrono::duration_cast<chrono::microseconds>(bench_end - bench_start).count();

    if (!success){
        cout << "\n\033[1;38;2;255;165;0mFailed to fully tokenize!\033[0m";
    }

    cout << '\n' << lexctx.tok_size << " Tokens generated!";
    cout << fmt::format(
        " Took: {:.3f}ms ({:.1f}ns/token, {:.1f}ns/char) Char/Tok: {:.2f}, B/Char: {:.2f}",
        duration / 1000.0,
        duration / lexctx.tok_size * 1000,
        duration / lexctx.src_size * 1000,
        static_cast<double>(lexctx.src_size) / lexctx.tok_size,
        static_cast<double>(lexctx.arena.total) / lexctx.src_size
    );

    cout << "\nArena occupied " + to_string(lexctx.arena.blockindex) + " blocks with a total of " + format_bytes(lexctx.arena.total) + "!";
    cout << "\ndlex Arena Data:";
    for (int i = 0; i < lexctx.arena.blockindex; i++){
        auto &block = lexctx.arena.blockset[i];
        size_t capacity = block.end - block.start;
        size_t used = block.cursor - block.start;
        int perc = (used * 100) / (capacity);
        cout << "\n  Block " + to_string(i) << ": " + format_bytes(used) + " / " + format_bytes(capacity) + " (" + to_string(perc) + "%)";
    };

    if (flags & 0b0010){
        int i = 0;
        int lastline = 0;
        ostringstream oss;
        for (size_t t_id = 0; t_id < lexctx.tok_size; t_id++){
            i+=1;
            Token &tok = *lexctx.tokstream[t_id];

            if (tok.line != lastline){
                lastline = tok.line;
                oss << "\n\x1b[38;5;226m[" + to_string(lastline) + "]\033[0m ";
            }

            if (tok.type == TK_EOF){
                oss << "\x1b[38;5;203m" << "EOF" << "\033[0m ";
            } else if (tok.type == TK_EMPTY){
                oss << "\x1b[38;5;68m" << "EMPTY" << "\033[0m ";
            } else if (tok.type == TK_INVALID){
                oss << "\x1b[38;5;88m" << "INVALID" << "\033[0m ";
            } else if (i % 2 == 0){
                oss << "\x1b[38;5;8m" << t_str(tok) << "\033[0m ";
            } else {
                oss << "\x1b[38;5;7m" << t_str(tok) << "\033[0m ";
            }

            if (lastline % 5 == 0){
                cout << oss.str();
                oss.str(""); oss.clear();
            }
        }

        oss << '\n';
        cout << oss.str();
    }

    return 0;
}


/*
SoftwareSerial.cpp (formerly NewSoftSerial.cpp) -
Multi-instance software serial library for Arduino/Wiring
-- Interrupt-driven receive and other improvements by ladyada
   (http://ladyada.net)
-- Tuning, circular buffer, derivation from class Print/Stream,
   multi-instance support, porting to 8MHz processors,
   various optimizations, PROGMEM delay tables, inverse logic and
   direct port writing by Mikal Hart (http://www.arduiniana.org)
-- Pin change interrupt macros by Paul Stoffregen (http://www.pjrc.com)
-- 20MHz processor support by Garrett Mace (http://www.macetech.com)
-- ATmega1280/2560 support by Brett Hagman (http://www.roguerobotics.com/)

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

The latest version of this library can always be found at
http://arduiniana.org.
*/

// When set, _DEBUG co-opts pins 11 and 13 for debugging with an
// oscilloscope or logic analyzer.  Beware: it also slightly modifies
// the bit times, so don't rely on it too much at high baud rates
#define _DEBUG 0
#define _DEBUG_PIN1 11
#define _DEBUG_PIN2 13
//
// Includes
//
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <Arduino.h>
#include <SoftwareSerial.h>

#if defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MKL26Z64__) || defined(__MK64FX512__) || defined(__MK66FX1M0__) || defined(__IMXRT1052__) || defined(__IMXRT1062__)

// Teensy LC, 3.0, 3.1, 3.2
#if defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MKL26Z64__)
  #define SS1_RX  0
  #define SS1_TX  1
  #define SS2_RX  9
  #define SS2_TX 10
  #define SS3_RX  7
  #define SS3_TX  8

// Teensy 3.5, 3.6
#elif defined(__MK64FX512__) || defined(__MK66FX1M0__)
  #define SS1_RX  0
  #define SS1_TX  1
  #define SS2_RX  9
  #define SS2_TX 10
  #define SS3_RX  7
  #define SS3_TX  8
  #define SS4_RX 31
  #define SS4_TX 32
  #define SS5_RX 34
  #define SS5_TX 33
  #define SS6_RX 47
  #define SS6_TX 48

// Teensy 4.0
#elif defined(__IMXRT1062__) && defined(ARDUINO_TEENSY40)
  #define SS1_RX  0
  #define SS1_TX  1
  #define SS2_RX  7
  #define SS2_TX  8
  #define SS3_RX 15
  #define SS3_TX 14
  #define SS4_RX 16
  #define SS4_TX 17
  #define SS5_RX 21
  #define SS5_TX 20
  #define SS6_RX 25
  #define SS6_TX 24
  #define SS7_RX 28
  #define SS7_TX 29

// Teensy 4.1
#elif defined(__IMXRT1062__) && defined(ARDUINO_TEENSY41)
  #define SS1_RX  0
  #define SS1_TX  1
  #define SS2_RX  7
  #define SS2_TX  8
  #define SS3_RX 15
  #define SS3_TX 14
  #define SS4_RX 16
  #define SS4_TX 17
  #define SS5_RX 21
  #define SS5_TX 20
  #define SS6_RX 25
  #define SS6_TX 24
  #define SS7_RX 28
  #define SS7_TX 29
  #define SS8_RX 34
  #define SS8_TX 35

// Teensy MICROMOD
#elif defined(__IMXRT1062__) && defined(ARDUINO_TEENSY_MICROMOD)
  #define SS1_RX  0
  #define SS1_TX  1
  #define SS2_RX 16
  #define SS2_TX 17
  #define SS3_RX 15
  #define SS3_TX 14
  #define SS4_RX  7
  #define SS4_TX  8
  #define SS5_RX 21
  #define SS5_TX 20
  #define SS6_RX 25
  #define SS6_TX 24
  #define SS7_RX 28
  #define SS7_TX 29

#endif

SoftwareSerial::SoftwareSerial(uint8_t rxPin, uint8_t txPin, bool inverse_logic /* = false */)
{
	buffer_overflow = false;

#if defined(SS1_RX) && defined(SS1_TX)
	if (rxPin == SS1_RX && txPin == SS1_TX) {
		port = &Serial1;
		return;
	}
#endif
#if defined(SS2_RX) && defined(SS2_TX)
	if (rxPin == SS2_RX && txPin == SS2_TX) {
		port = &Serial2;
		return;
	}
#endif
#if defined(SS3_RX) && defined(SS3_TX)
	if (rxPin == SS3_RX && txPin == SS3_TX) {
		port = &Serial3;
		return;
	}
#endif
#if defined(SS4_RX) && defined(SS4_TX)
	if (rxPin == SS4_RX && txPin == SS4_TX) {
		port = &Serial4;
		return;
	}
#endif
#if defined(SS5_RX) && defined(SS5_TX)
	if (rxPin == SS5_RX && txPin == SS5_TX) {
		port = &Serial5;
		return;
	}
#endif
#if defined(SS6_RX) && defined(SS6_TX)
	if (rxPin == SS6_RX && txPin == SS6_TX) {
		port = &Serial6;
		return;
	}
#endif
#if defined(SS7_RX) && defined(SS7_TX)
	if (rxPin == SS7_RX && txPin == SS7_TX) {
		port = &Serial7;
		return;
	}
#endif
#if defined(SS8_RX) && defined(SS8_TX)
	if (rxPin == SS8_RX && txPin == SS8_TX) {
		port = &Serial8;
		return;
	}
#endif
	port = NULL;
	txpin = txPin;
	rxpin = rxPin;
#if defined(__IMXRT1052__) || defined(__IMXRT1062__)
	tx_clear_reg = portClearRegister(digitalPinToPort(txPin));
	tx_set_reg = portSetRegister(digitalPinToPort(txPin));
	tx_bit


// Fill out your copyright notice in the Description page of Project Settings.

#include "Bullet.h"

#include "PlayerFire.h"
#include "TPS.h"
#include "TPSPlayer.h"
#include "Components/SphereComponent.h"
#include "GameFramework/ProjectileMovementComponent.h"
#include "Kismet/GameplayStatics.h"

// Sets default values
ABullet::ABullet()
{
	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;

	// root
	collisionComp = CreateDefaultSubobject<USphereComponent>(TEXT("collisionComp"));
	RootComponent = collisionComp;
	collisionComp->SetCollisionProfileName(TEXT("BlockAll"));

	bodyMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("bodyMesh"));
	bodyMesh->SetupAttachment(collisionComp);
	bodyMesh->SetRelativeScale3D(FVector(0.62f));

	moveComp = CreateDefaultSubobject<UProjectileMovementComponent>(TEXT("playerMove"));
	moveComp->InitialSpeed = speed;
	moveComp->MaxSpeed = speed;
	moveComp->bShouldBounce = true;
	moveComp->Bounciness = 0.2f;

	moveComp->SetUpdatedComponent(collisionComp);

	// InitialLifeSpan = 2.0f;
}

// Called when the game starts or when spawned
void ABullet::BeginPlay()
{
	Super::BeginPlay();

	// auto playerMain = Cast<ATPSPlayer>(UGameplayStatics::GetActorOfClass(GetWorld(), ATPSPlayer::StaticClass()));
	// player = Cast<UPlayerFire>(playerMain->playerFire);
}

// Called every frame
void ABullet::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

	// currentTime += DeltaTime;
	// if (currentTime > destroyTime)
	// {
	// 	Destroy();
	// }
}

void ABullet::SetActive(bool bActive)
{
	if (bActive)
	{
		// Rendering
		bodyMesh->SetVisibility(true);
		// collision
		collisionComp->SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics);
		// 다시 발사 속도 세팅
		moveComp->Velocity = GetActorForwardVector() * moveComp->InitialSpeed;

		// 타이머 이용해서 제거 되도록 처리
		// 무명함수 (Lambda)
		auto DieLambda = [this]()->void
		{
			// Destroy();
			// 탄창에 넣어주자
			if (player)
			{
				SetActive(false);
				player->bulletPool.Add(this);
			}
		};

		FTimerHandle handle;
		GetWorldTimerManager().SetTimer(handle, FTimerDelegate::CreateLambda(DieLambda), destroyTime, false);
	}
	else
	{
		// Rendering
		bodyMesh->SetVisibility(false);
		// collision
		collisionComp->SetCollisionEnabled(ECollisionEnabled::NoCollision);
	}
}

void ABullet::PostEditChangeProperty(
	struct FPropertyChangedEvent& PropertyChangedEvent)
{
	Super::PostEditChangeProperty(PropertyChangedEvent);

	// speed 값이 수정이 됐는지 체크
	if (PropertyChangedEvent.GetPropertyName() == TEXT("speed"))
	{
		moveComp->InitialSpeed = speed;
		moveComp->MaxSpeed = speed;
	}
}


#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"proyek_flutter_pertama", origin, size)) {
    return EXIT_FAILURE;
  }
  window.SetQuitOnClose(true);

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

  ::CoUninitialize();
  return EXIT_SUCCESS;
}


#include <ArduinoOTA.h>
#include "logging.h"
#include "util.h"
#include "declarations.h"
#include "display.h"

void setupOTA(const char* hostname) {
    ArduinoOTA.setHostname(hostname);
    ArduinoOTA.onStart([]() {
        String type;
        if (ArduinoOTA.getCommand() == U_FLASH)
            type = "sketch";
        else // U_SPIFFS
            type = "filesystem";

        ota_in_progress = true;
        render_matrix();
        logInfo("Start updating " + type);
        playSound(3, 100, 100);
    });
    ArduinoOTA.onEnd([]() {
        ota_in_progress = false;
        playSound(5, 100, 100);
        logInfo("End");
    });
    ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
        logInfo("Progress: " + String((progress / (total / 100))) + "%");
        if ( (progress / (total / 100)) % 10 ==0 ){
            playSound(1, 100, 100);
        }
    });
    ArduinoOTA.onError([](ota_error_t error) {
        ota_in_progress = false;
        playSound(1, 300, 300);
        logError("Error[" + String(error) + "]: ");
        if (error == OTA_AUTH_ERROR) logError("Auth Failed");
        else if (error == OTA_BEGIN_ERROR) logError("Begin Failed");
        else if (error == OTA_CONNECT_ERROR) logError("Connect Failed");
        else if (error == OTA_RECEIVE_ERROR) logError("Receive Failed");
        else if (error == OTA_END_ERROR) logError("End Failed");
    });
    ArduinoOTA.begin();
}

void handleOTA() {
    ArduinoOTA.handle();
}


// Client-side implementation in C++ for a chat server with private messages and group messaging

#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <arpa/inet.h>

#define BUFFER_SIZE 1024

std::mutex cout_mutex;

void handle_server_messages(int server_socket) {
    char buffer[BUFFER_SIZE];
    while (true) {
        memset(buffer, 0, BUFFER_SIZE);
        int bytes_received = recv(server_socket, buffer, BUFFER_SIZE, 0);
        if (bytes_received <= 0) {
            std::lock_guard<std::mutex> lock(cout_mutex);
            std::cout << "Disconnected from server." << std::endl;
            close(server_socket);
            exit(0);
        }
        std::lock_guard<std::mutex> lock(cout_mutex);
        std::cout << buffer << std::endl;
    }
}

int main() {
    int client_socket;
    sockaddr_in server_address{};

    client_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (client_socket < 0) {
        std::cerr << "Error creating socket." << std::endl;
        return 1;
    }

    server_address.sin_family = AF_INET;
    server_address.sin_port = htons(12345);
    server_address.sin_addr.s_addr = inet_addr("127.0.0.1");

    if (connect(client_socket, (sockaddr*)&server_address, sizeof(server_address)) < 0) {
        std::cerr << "Error connecting to server." << std::endl;
        return 1;
    }

    std::cout << "Connected to the server." << std::endl;

    // Authentication
    std::string username, password;
    char buffer[BUFFER_SIZE];

    memset(buffer, 0, BUFFER_SIZE);
    recv(client_socket, buffer, BUFFER_SIZE, 0); // Receive the message "Enter the user name" for the server
    // You should have a line like this in the server.cpp code: send_message(client_socket, "Enter username: ");

    std::cout << buffer;
    std::getline(std::cin, username);
    send(client_socket, username.c_str(), username.size(), 0);

    memset(buffer, 0, BUFFER_SIZE);
    recv(client_socket, buffer, BUFFER_SIZE, 0); // Receive the message "Enter the password" for the server
    std::cout << buffer;
    std::getline(std::cin, password);
    send(client_socket, password.c_str(), password.size(), 0);

    memset(buffer, 0, BUFFER_SIZE);
    // Depending on whether the authentication passes or not, receive the message "Authentication Failed" or "Welcome to the server"
    recv(client_socket, buffer, BUFFER_SIZE, 0);
    std::cout << buffer << std::endl;

    if (std::string(buffer).find("Authentication failed") != std::string::npos) {
        close(client_socket);
        return 1;
    }

    // Start thread for receiving messages from server
    std::thread receive_thread(handle_server_messages, client_socket);
    // We use detach because we want this thread to run in the background while the main thread continues running
    receive_thread.detach();

    // Send messages to the server
    while (true) {
        std::string message;
        std::getline(std::cin, message);

        if (message.empty()) continue;

        send(client_socket, message.c_str(), message.size(), 0);

        if (message == "/exit") {
            close(client_socket);
            break;
        }
    }

    return 0;
}


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

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

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

class DLL{
    private:
        int length;
        Node* head;
        Node* tail;

    public:
        DLL(int value){
            Node* newNode = new Node(value);
            head = tail = newNode;
            length = 1;
        }

        void printList(){
            Node* temp = head;
            while(temp!= NULL){
                cout << temp->value << " -> ";
                temp = temp->next;
            }
            cout << "null" << endl;
        }

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

        void deleteLast(){
            if(head == NULL){
                cout << "invalid operation on empty list" << endl;
                return;
            }

            if(head->next == NULL){
                delete head;
                head = tail = NULL;
                length--;
                return;
            }else{
                Node* temp = tail;
                tail = tail->prev;
                tail->next = NULL;
                delete temp;
            }
            length--;
        }
};

int main(){
    DLL * d1 = new DLL(1);
    d1->append(2);
    d1->append(3);
    d1->append(4);
    d1->append(5);
    d1->printList();
    d1->deleteLast();
    d1->deleteLast();
    d1->deleteLast();
    d1->deleteLast();
    d1->deleteLast();
    d1->printList();
}


/*
Tenzing Norbu
Sept 15, 2025
lab 6, nested conditional statement and switch
*/
#include<iostream>
#include<string>

using namespace std;

int main() {
    cout<<"\n ------ Example 1: nested conditional statement -----"<<endl;
    int n = 5;
    if(n>0) {
        cout<<"The number is positive"<<endl;
        if(n%2==0) {
            cout<<"The number is positive and EVEN"<<endl;
        }
        else{
            cout<<"The number is positive and ODD"<<endl;
        }
    }
    else if(n<0) {
        cout<<"The number is positive"<<endl;
        if(n%2==0) {
            cout<<"The number is positive and EVEN"<<endl;
        }
        else{
            cout<<"The number is positive and ODD"<<endl;
        }
        cout<<"The number is negative"<<endl;
    }
    else {
        cout<<"The number is zero"<<endl;
    }

    cout<<"\n ------ Example 2: organize three numbers in decreasing order -----"<<endl;
    // declare the identifiers(variable names)
    int num1, num2, num3;

    // display a message and collect the three numbers
    cout<<"Enter three numbers: ";
    cin>>num1>>num2>>num3;

    // check if num1 is greater than num2 and num3
    if(num1>num2 && num1>num3) {
        if(num2>num3)
            cout<<num1<<"\t"<<num2<<"\t"<<num3<<endl;
        else
            cout<<num1<<"\t"<<num3<<"\t"<<num2<<endl;
    }
    // check if num2 is the greatest
    else if (num2>num1 && num2>num3) {
        if(num1>num3)
            cout<<num2<<"\t"<<num1<<"\t"<<num2<<endl;
        else
            cout<<num2<<"\t"<<num3<<"\t"<<num1<<endl;
    }
    // check if num3 is the greatest
    else if(num3>num2 && num3>num1) {
        if(num1>num2)
            cout<<num3<<"\t"<<num1<<"\t"<<num2<<endl;
        else
            cout<<num3<<"\t"<<num2<<"\t"<<num1<<endl;
    }
    else{
        cout<<"All three numbers are the same!"<<endl;
    }

    cout<<"\n ------ Example 3: Switch Statement -----"<<endl;
    // select a day-off using switch-case statement
    int dayoff;
    cout<<"Select a day-off: "<<endl;
    cout<<"1 for Monday"<<endl;
    cout<<"2 for Tuesday"<<endl;
    cout<<"3 for Wednesday"<<endl;
    cout<<"4 for Thursday"<<endl;
    cout<<"5 for Friday"<<endl;
    cin>>dayoff;

    switch(dayoff)
    {
    case 1:
        cout<<"You are off on Monday"<<endl;
        break;
    case 2:
        cout<<"You are off on Tuesday"<<endl;
        break;
    case 3:
        cout<<"You are off on Wednesday"<<endl;
        break;
    case 4:
        cout<<"You are off on Thursday"<<endl;
        break;
    case 5:
        cout<<"You are off on Friday"<<endl;
        break;
    default:
        cout<<"Unable to read the day-off"<<endl;
        break;
    }

    cout<<"\n ------ Example 4: Switch to select a gender -----"<<endl;
    char gender = ' ';
    cout<<"Enter your gender: "<<endl;
    cout<<"m or M for male"<<endl;
    cout<<"f or F for female"<<endl;
    cout<<"o or O for others"<<endl;
    cin>>gender;

    switch (gender)
    {
    case 'm':case 'M':
        cout<<"Gender = MALE"<<endl;
        break;

    case 'f':case 'F':
        cout<<"Gender = FEMALE"<<endl;
        break;

    case 'o': case 'O':
        cout<<"Gender = OTHERS"<<endl;
        break;

    default:
        cout<<"Gender = Undefined"<<endl;
        break;

    }

    cout<<"\n ------ Exercise 1 -----"<<endl;
    int savings;
    cout<<"How much is your savings?"<<endl;
    cin>>savings;
    if(savings > 0 && savings <= 199999){
        cout<<"Keep saving!"<<endl;
    }
    else if(savings >= 200000 && savings <= 500000) {
        if(savings >= 200000 && savings <= 300000) {
            cout<<"With "<<savings<<" you can afford an apartment or co-op with  a studio"<<endl;
        }
        else if(savings >= 300001 && savings <= 400000) {
            cout<<"With "<<savings<<" you can afford an apartment or co-op with  one bedroom and one bathroom"<<endl;
        }
        else {
            cout<<"With "<<savings<<" you can afford an apartment or co-op with  two bedrooms and one bathroom"<<endl;
        }
    }
    else if(savings >= 500001 && savings <= 1000000) {
        if(savings >= 500001 && savings <= 700000) {
            cout<<"With "<<savings<<" you can afford a house with  two bedrooms and two bathrooms"<<endl;
        }
        else {
            cout<<"With "<<savings<<" you can afford a house with  three bedrooms and three bathrooms"<<endl;
        }
    }
    else if(savings>=1000001) {
        cout<<"With "<<savings<<" you can afford a mansion"<<endl;
    }
    else
        cout<<"Have some savings!"<<endl;

    cout<<"\n ------ Exercise 2 -----"<<endl;
    char twice = ' ';
    int num = 0;
    cout<<"\nEnter a number: ";
    cin>>num;
    cout<<"If you want "<<num<<" doubled, type 'Y' or 'y' for yes or 'N' or 'n' for no: ";
    cin>>twice;

    switch (twice)
    {
        case 'Y':case 'y':
        num *= 2;
        cout<<"The number is set to "<<num<<endl;
        break;

        case 'N':case 'n':


#include "register_types.h"

#include <gdextension_interface.h>
#include <godot_cpp/core/class_db.hpp>
#include <godot_cpp/core/defs.hpp>
#include <godot_cpp/godot.hpp>

#include "rope.h"
#include "rope_appearance.h"
#include "rope_positions.h"

using namespace godot;

void initialize_gdextension_types(ModuleInitializationLevel p_level) {
	if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) {
		return;
	}
	GDREGISTER_CLASS(Rope);
	GDREGISTER_CLASS(RopePositions);
	GDREGISTER_CLASS(RopeAppearance);
}

void uninitialize_gdextension_types(ModuleInitializationLevel p_level) {
	if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) {
		return;
	}
}

extern "C" {
// Initialization
GDExtensionBool GDE_EXPORT halyard_library_init(
		GDExtensionInterfaceGetProcAddress p_get_proc_address,
		GDExtensionClassLibraryPtr p_library,
		GDExtensionInitialization *r_initialization) {
	GDExtensionBinding::InitObject init_obj(p_get_proc_address, p_library, r_initialization);
	init_obj.register_initializer(initialize_gdextension_types);
	init_obj.register_terminator(uninitialize_gdextension_types);
	init_obj.set_minimum_library_initialization_level(MODULE_INITIALIZATION_LEVEL_SCENE);

	return init_obj.init();
}
}