#define CATCH_CONFIG_MAIN
#include <catch2/catch_all.hpp>
#include <nlohmann/json.hpp>
#include "llama_cpp_tools/tool_registry.h"

#include <thread>
#include <chrono>
#include <cctype>

using json = nlohmann::json;
using namespace lct;

TEST_CASE("Basic types: int, number, string, bool") {
    ToolRegistry reg;

    ToolSpec t_int;
    t_int.name = "t_int";
    t_int.description = "int test";
    t_int.parameters = { {"type","object"}, {"properties", {{"x", {{"type","integer"}}}}}, {"required", {"x"}} };
    t_int.handler = [](const json& args){ return json{{"ok", args.at("x").get<int>() * 2}}; };
    reg.register_tool_spec(t_int);

    ToolSpec t_num;
    t_num.name = "t_num";
    t_num.description = "number test";
    t_num.parameters = { {"type","object"}, {"properties", {{"v", {{"type","number"}}}}}, {"required", {"v"}} };
    t_num.handler = [](const json& args){ return json{{"ok", args.at("v").get<double>() * 1.5}}; };
    reg.register_tool_spec(t_num);

    ToolSpec t_str;
    t_str.name = "t_str";
    t_str.description = "string test";
    t_str.parameters = { {"type","object"}, {"properties", {{"s", {{"type","string"}}}}}, {"required", {"s"}} };
    t_str.handler = [](const json& args){ return json{{"ok", args.at("s").get<std::string>() + "!"}}; };
    reg.register_tool_spec(t_str);

    ToolSpec t_bool;
    t_bool.name = "t_bool";
    t_bool.description = "bool test";
    t_bool.parameters = { {"type","object"}, {"properties", {{"b", {{"type","boolean"}}}}}, {"required", {"b"}} };
    t_bool.handler = [](const json& args){ return json{{"ok", !args.at("b").get<bool>()}}; };
    reg.register_tool_spec(t_bool);

    REQUIRE(reg.invoke("t_int", json{{"x", 5}}).at("ok").get<int>() == 10);
    REQUIRE(reg.invoke("t_num", json{{"v", 2.0}}).at("ok").get<double>() == Catch::Approx(3.0));
    REQUIRE(reg.invoke("t_str", json{{"s", "hi"}}).at("ok").get<std::string>() == "hi!");
    REQUIRE(reg.invoke("t_bool", json{{"b", true}}).at("ok").get<bool>() == false);

    REQUIRE_THROWS_AS(reg.invoke("t_int", json{{"x", "notint"}}), std::exception);

    // large string input
    std::string large(10*1024*1024, 'a');
    auto out = reg.invoke("t_str", json{{"s", large}});
    REQUIRE(out.at("ok").get<std::string>().size() == large.size() + 1);
}

// ------------------ New tests for the added APIs ------------------

TEST_CASE("process_remote_response_and_execute executes tool calls") {
    ToolRegistry reg;

    ToolSpec echo;
    echo.name = "echo";
    echo.description = "echo args";
    echo.parameters = {{"type","object"}, {"properties", {{"msg", {{"type","string"}}}}}, {"required", {"msg"}}};
    echo.handler = [](const json& args){ return json{{"echoed", args.at("msg")}}; };
    reg.register_tool_spec(echo);

    json api_resp = {
        {"choices", {{
            {"message", {
                {"tool_calls", {{
                    {"function", {
                        {"name", "echo"},
                        {"arguments", R"({"msg":"hi"})"}
                    }}
                }}}
            }}
        }}}
    };

    auto results = reg.process_remote_response_and_execute(api_resp);
    REQUIRE(results.size() == 1);
    REQUIRE(results[0].tool_name == "echo");
    REQUIRE(results[0].result.at("echoed") == "hi");
    REQUIRE(results[0].error.empty());
}

TEST_CASE("process_remote_response_and_execute handles errors") {
    ToolRegistry reg;

    ToolSpec bad;
    bad.name = "bad";
    bad.description = "always throws";
    bad.parameters = {{"type","object"}, {"properties", {}}, {"required", json::array() }};
    // <--- Explicit return type so the lambda is convertible to ToolHandler
    bad.handler = [](const json& args) -> json { throw std::runtime_error("fail"); };
    reg.register_tool_spec(bad);

    json api_resp = {
        {"choices", {{
            {"message", {
                {"tool_calls", {{
                    {"function", {
                        {"name", "bad"},
                        {"arguments", "{}"}
                    }}
                }}}
            }}
        }}}
    };

    auto results = reg.process_remote_response_and_execute(api_resp);
    REQUIRE(results.size() == 1);
    REQUIRE(results[0].tool_name == "bad");
    REQUIRE(!results[0].error.empty());
}

TEST_CASE("process_remote_response_and_execute concurrent execution") {
    ToolRegistry reg;

    ToolSpec slow;
    slow.name = "slow";
    slow.description = "sleep then return";
    slow.parameters = {{"type","object"}, {"properties", {{"v", {{"type","integer"}}}}}, {"required", {"v"}}};
    slow.handler = [](const json& args){
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
        return json{{"ok", args.at("v").get<int>()}};
    };
    reg.register_tool_spec(slow);

    json api_resp = {
        {"choices", {{
            {"message", {
                {"tool_calls", {
                    {{"function", {{"name", "slow"}, {"arguments", R"({"v":1})"}}}},
                    {{"function", {{"name",


/**
 * Drift Simulation - Complete physics demonstration
 *
 * This simulation creates a vehicle that performs drifting maneuvers
 * around an obstacle course, demonstrating:
 * - Rigid body dynamics
 * - Vehicle physics with tire model
 * - Collision detection and response
 * - Drift scoring system
 * - Automated control patterns
 */

#include <iostream>
#include <iomanip>
#include <vector>
#include <memory>
#include <cmath>
#include <fstream>
#include <sstream>

// Include physics engine headers
#include "physics/dynamics/PhysicsWorld.h"
#include "physics/dynamics/RigidBody.h"
#include "physics/vehicle/Vehicle.h"
#include "physics/collision/Collision.h"
#include "physics/math/Vector3D.h"
#include "physics/math/Quaternion.h"

using namespace physics;

// ============================================================================
// SIMULATION CONFIGURATION
// ============================================================================

namespace Config {
    // Simulation parameters
    const float SIMULATION_DURATION = 30.0f;    // seconds
    const float FIXED_TIMESTEP = 1.0f / 60.0f;  // 60 Hz physics
    const int LOG_FREQUENCY = 10;               // Log every N frames

    // Vehicle parameters
    const float VEHICLE_MASS = 1200.0f;         // kg
    const float MAX_ENGINE_TORQUE = 400.0f;     // Nm (increased for better drifting)
    const float VEHICLE_START_HEIGHT = 1.0f;    // meters above ground

    // Ground parameters
    const float GROUND_LEVEL = 0.0f;
    const float GROUND_FRICTION = 0.8f;
    const float GROUND_RESTITUTION = 0.1f;

    // Obstacle parameters
    const float CONE_MASS = 5.0f;               // kg
    const float CONE_RADIUS = 0.3f;             // meters
    const float CONE_RESTITUTION = 0.3f;
    const float CONE_FRICTION = 0.6f;

    // Collision parameters
    const float VEHICLE_COLLISION_RADIUS = 2.0f; // Approximate car as sphere

    // Output settings
    const bool VERBOSE_OUTPUT = true;
    const bool CSV_OUTPUT = false;
    const std::string OUTPUT_FILE = "drift_trajectory.csv";
}

// ============================================================================
// OBSTACLE COURSE LAYOUT
// ============================================================================

struct ObstacleDefinition {
    Vector3D position;
    float radius;
    std::string name;
};

std::vector<ObstacleDefinition> createCourseLayout() {
    std::vector<ObstacleDefinition> obstacles;

    // Create a figure-8 course with cones
    // First circle of cones
    float radius1 = 15.0f;
    for (int i = 0; i < 8; i++) {
        float angle = (i / 8.0f) * 2.0f * M_PI;
        obstacles.push_back({
            Vector3D(radius1 * cos(angle) - 10.0f,
                    Config::CONE_RADIUS,
                    radius1 * sin(angle)),
            Config::CONE_RADIUS,
            "Cone_Circle1_" + std::to_string(i)
        });
    }

    // Second circle of cones
    float radius2 = 12.0f;
    for (int i = 0; i < 6; i++) {
        float angle = (i / 6.0f) * 2.0f * M_PI;
        obstacles.push_back({
            Vector3D(radius2 * cos(angle) + 10.0f,
                    Config::CONE_RADIUS,
                    radius2 * sin(angle)),
            Config::CONE_RADIUS,
            "Cone_Circle2_" + std::to_string(i)
        });
    }

    // Add some gates to drift through
    obstacles.push_back({Vector3D(0, Config::CONE_RADIUS, -8), Config::CONE_RADIUS, "Gate1_Left"});
    obstacles.push_back({Vector3D(0, Config::CONE_RADIUS, -12), Config::CONE_RADIUS, "Gate1_Right"});
    obstacles.push_back({Vector3D(0, Config::CONE_RADIUS, 8), Config::CONE_RADIUS, "Gate2_Left"});
    obstacles.push_back({Vector3D(0, Config::CONE_RADIUS, 12), Config::CONE_RADIUS, "Gate2_Right"});

    return obstacles;
}

// ============================================================================
// CONTROL SYSTEM
// ============================================================================

class DriftController {
private:
    float time;
    int phase;
    float phaseTimer;

    // Control state
    float steering;
    float throttle;
    float brake;
    float handbrake;

public:
    DriftController() : time(0), phase(0), phaseTimer(0),
                       steering(0), throttle(0), brake(0), handbrake(0) {}

    void update(float dt, const Vector3D& position, const Vector3D& velocity,
                float driftAngle, float speed) {
        time += dt;
        phaseTimer += dt;

        // Automated drift sequence - Figure 8 pattern
        switch (phase) {
            case 0: // Initial acceleration
                throttle = 0.9f;
                steering = 0.0f;
                brake = 0.0f;
                handbrake = 0.0f;

                if (speed > 15.0f && phaseTimer > 2.0f) {


#include <stdarg.h>
#include "internal_parser.h"
#include "resource.h"

namespace NS_TIEC {
  TiecodeParser::TiecodeParser(PTR<Context> context, PTR<TiecodeSource> source): context_(context), source_(source) {
    this->lexer_ = TiecodeLexer(source_->readContent());
    this->options_ = context->get<Options>(kComponentOptions);
    this->messages_ = context->get<Messages>(kComponentMessages);
  }

  PTR<CompilationUnitTree> TiecodeParser::parseCompilationUnit() {
    PTR<CompilationUnitTree> root = MAKE_PTR<CompilationUnitTree>();
    root->origin_ = currentOrigin();
    List<PTR<ClassTree>> class_defs;
    while (token_ != TiecodeToken::Eof) {
      switch (token_) {
        // 解析注释
        case TiecodeToken::LineComment:
        case TiecodeToken::LongComment:
          comment_ = lexer_.wstr();
          nextTokenSkipBlank();
          break;
        // 解析注解
        case TiecodeToken::At:
          this->annotations_ = parseAnnotationList();
          break;
        // 解析包名
        case TiecodeToken::Package:
          // 包名重复定义
          if (root->pkg_ != nullptr) {
            Position err_start = currentPosition();
            skip(false, false, false, true, false);
            syntaxErrorFromStart(err_start, "parse.package.define.duplicate");
          }
          nextTokenSkipBlank();
          root->pkg_ = parseFullName();
          break;
        default:
          nextTokenSkipBlank();
          break;
      }
    }
    return root;
  }

  PTR<StatementTree> TiecodeParser::parseStatement() {

  }

  PTR<ExpressionTree> TiecodeParser::parseExpression() {

  }

  PTR<ExpressionTree> TiecodeParser::parseType() {

  }

  PTR<CodeTree> TiecodeParser::parseCode() {
    if (!options_->enable_code_) {
      return nullptr;
    }
    return {};
  }

  List<PTR<AnnotationTree>> TiecodeParser::parseAnnotationList() {
    List<PTR<AnnotationTree>> trees;
    while (token_ == TiecodeToken::At) {
      PTR<AnnotationTree> tree = parseAnnotation();
      if (tree != nullptr) {
        trees.add(tree);
      }
      accept(TiecodeToken::Newline, "<换行>");
      if (token_ == TiecodeToken::LineComment || token_ == TiecodeToken::LongComment) {
        nextTokenSkipLine();
      }
    }
    return trees;
  }

  PTR<AnnotationTree> TiecodeParser::parseAnnotation() {
    Origin origin = currentOrigin();
    nextTokenSkipBlank();
    PTR<IdentifierTree> ident = parseName();
    if (ident->name_ == name_pool_->error_) {
      syntaxErrorFromStart(origin.range.start, "parse.expected", "<注解名称>");
      ident.reset();
      return nullptr;
    } else {
      PTR<AnnotationTree> tree = MAKE_PTR<AnnotationTree>();
      tree->origin_ = origin;
      tree->ident_ = ident;
      if (token_ == TiecodeToken::Dot) {
        Position suffix_start = currentPosition();
        nextTokenSkipBlank();
        PTR<IdentifierTree> suffix = parseName();
        if (ident->name_ == name_pool_->error_) {
          syntaxErrorFromStart(suffix_start, "parse.expected", "<注解属性后缀名>");
          suffix.reset();
        } else {
          tree->suffix_ = suffix;
        }
      }
      if (token_ == TiecodeToken::LParen) {
        PTR<ExpressionTree> arg = parseAnnotationArg();
        tree->arg_ = arg;
        accept(TiecodeToken::RParen, ")");
      }
      return tree;
    }
  }

  PTR<ExpressionTree> TiecodeParser::parseAnnotationArg() {
    accept(TiecodeToken::LParen, "(");
    pushExprMode(kExprModeInvokeArgs);
    PTR<ExpressionTree> arg = parseExpression();
    popExprMode();
    return arg;
  }

  PTR<ClassTree> TiecodeParser::parseClass() {
    PTR<ClassTree> tree = MAKE_PTR<ClassTree>();
    tree->origin_ = currentOrigin();
    accept(TiecodeToken::Class, "类");
    PTR<IdentifierTree> class_name = parseName();
    if (class_name->name_ == name_pool_->error_) {
      syntaxErrorToEnd(currentPosition().plusLength(lexer_.wsize()), "parse.expected", "类名标识符");
    }
    tree->ident_ = class_name;
    if (token_ == TiecodeToken::Lt) {
      tree->templates_ = parseClassTemplateArgs();
    }
    return tree;
  }

  List<PTR<IdentifierTree>> TiecodeParser::parseClassTemplateArgs() {

  }

  PTR<ExpressionTree> TiecodeParser::parseClassExtendsClause() {

  }

  void TiecodeParser::parseClassBody(PTR<ClassTree> klass) {

  }

  PTR<IdentifierTree> TiecodeParser::parseName() {
    if (token_ == TiecodeToken::Identifier) {
      PTR<Name> name = name_pool_->getName(lexer_.text());
      PTR<IdentifierTree> tree = MAKE_PTR<IdentifierTree>();
      tree->name_ = name;
      tree->origin_ = currentOrigin();
      Position& start = tree->origin_.range.start;
      tree->origin_.range.end = start.plusLength((UInt32)lexer_.wsize());
      nextTokenSkipBlank();
      return tree;
    }
    PTR<IdentifierTree> err_tree = MAKE_PTR<IdentifierTree>();
    err_tree->name_ = name_pool_->error_;
    err_tree->origin_ = currentOrigin();
    err_tree->origin_.range.end = err_tree->origin_.range.start;
    return err_tree;
  }

  PTR<ExpressionTree> TiecodeParser:


//////////////////////////////////////////////////////////////////////
// SkillEffectMgr.cpp: implementation of the CSkillEffectMgr class.
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "SkillEffectMgr.h"
#include "ZzzLodTerrain.h"
#include "CDirection.h"
#include "ZzzBMD.h"
#include "ZzzObject.h"
#include "ZzzCharacter.h"
#include "ZzzAI.h"
#include "ZzzEffect.h"

CSkillEffectMgr g_SkillEffects;

void MoveEffect( OBJECT *o, int iIndex);

CSkillEffectMgr::CSkillEffectMgr()
{
	DeleteAllEffects();
}

CSkillEffectMgr::~CSkillEffectMgr()
{

}

OBJECT * CSkillEffectMgr::GetEffect(int iIndex)
{
	assert(iIndex < MAX_SKILL_EFFECTS);

	return m_SkillEffects + iIndex;
}

BOOL CSkillEffectMgr::IsSkillEffect(int Type,vec3_t Position,vec3_t Angle,
				  vec3_t Light,int SubType,OBJECT *Owner,short PKKey,WORD SkillIndex,WORD Skill,WORD SkillSerialNum,
				  float Scale, short int sTargetIndex )
{
	if (Owner != &Hero->Object)
		return FALSE;

	switch (Type)
	{
	case BITMAP_BOSS_LASER:
	case MODEL_SKILL_BLAST:
	case MODEL_DARK_SCREAM:
	case BITMAP_SWORD_FORCE:
		return TRUE;
	case MODEL_SKILL_INFERNO:
		if(SubType < 2) return TRUE;
		break;
	case MODEL_CIRCLE:
		if (SubType == 0) return TRUE;
		break;
	case BITMAP_FLAME:
		if ( SubType==0 ) return TRUE;
		break;
	case MODEL_STORM:
		if ( SubType==0 ) return TRUE;
		break;

//     case MODEL_ARROW_DOUBLE:
// 		if(SubType==1) return TRUE;
// 		break;
// 	case MODEL_ARROW:
// 		if( SubType!=3 && SubType!=4 ) return TRUE;
// 		break;
// 	case MODEL_ARROW_BEST_CROSSBOW :
// 	case MODEL_ARROW_STEEL:
// 	case MODEL_ARROW_THUNDER:
// 	case MODEL_ARROW_LASER:
// 	case MODEL_ARROW_V:
// 	case MODEL_ARROW_SAW:
// 	case MODEL_ARROW_NATURE:
// 	case MODEL_ARROW_WING:
//     case MODEL_LACEARROW:
// 	case MODEL_ARROW_SPARK:
// 	case MODEL_ARROW_RING:
// 	case MODEL_ARROW_BOMB:
// 	case MODEL_ARROW_DARKSTINGER:
// 	case MODEL_ARROW_GAMBLE:
// 	case MODEL_ARROW_DRILL:
// 		return TRUE;
	}
	return FALSE;
}

OBJECT * CSkillEffectMgr::CreateEffect()
{
	for(int icntEffect=0;icntEffect<MAX_SKILL_EFFECTS;icntEffect++)
	{
		OBJECT *o = &m_SkillEffects[icntEffect];
		if(!o->Live)
		{
			return o;
		}
	}

	assert(!"½ºÅ³ÀÌÆåÆ® ÇÑ°è µµ´Þ!");
	return &m_SkillEffects[MAX_SKILL_EFFECTS - 1];
}

bool CSkillEffectMgr::DeleteEffect(int Type,OBJECT *Owner, int iSubType)
{
    bool bDelete = false;
	for(int i=0;i<MAX_SKILL_EFFECTS;i++)
	{
		OBJECT *o = &m_SkillEffects[i];
		if(o->Live && o->Type==Type)
		{
			if ( iSubType == -1 || iSubType == o->SubType)
			{
				if(o->Owner==Owner)
                {
					EffectDestructor(o);
                    bDelete = true;
                }
			}
		}
	}

    return bDelete;
}

void CSkillEffectMgr::DeleteEffect( int efftype )
{
	for(int i=0;i<MAX_SKILL_EFFECTS;i++)
	{
		OBJECT *o = &m_SkillEffects[i];
		if(o->Live && o->Type==efftype)
		{
			EffectDestructor(o);
		}
	}
}

void CSkillEffectMgr::DeleteAllEffects()
{
	for(int i=0;i<MAX_SKILL_EFFECTS;i++)
	{
		EffectDestructor(m_SkillEffects + i);
		m_SkillEffects[i].Live = false;
		m_SkillEffects[i].Owner = NULL;
	}
}

bool CSkillEffectMgr::SearchEffect(int iType, OBJECT* pOwner, int iSubType)
{
	for(int i=0; i<MAX_SKILL_EFFECTS; ++i)
	{
		OBJECT *o = &m_SkillEffects[i];
		if(o->Live && o->Type == iType && o->Owner == pOwner)
		{
			if(iSubType == -1 || o->SubType == iSubType)
			{
				return true;
			}
		}
	}

    return false;
}

BOOL CSkillEffectMgr::FindSameEffectOfSameOwner( int iType, OBJECT *pOwner)
{
	for(int i=0;i<MAX_SKILL_EFFECTS;i++)
	{
		OBJECT *o = &m_SkillEffects[i];
		if(o->Live)
		{
			if ( o->Type == iType && o->Owner == pOwner)
			{
				return ( TRUE);
			}
		}
	}

	return ( FALSE);
}

void CSkillEffectMgr::MoveEffects()
{
	for(int i=0;i<MAX_SKILL_EFFECTS;i++)
	{
		OBJECT *o = &m_SkillEffects[i];
		if(o->Live)
		{
			MoveEffect( o, i);
		}
	}
}


/* This source file must have a .cpp extension so that all C++ compilers
   recognize the extension without flags.  Borland does not know .cxx for
   example.  */
#ifndef __cplusplus
# error "A C compiler has been selected for C++."
#endif

#if !defined(__has_include)
/* If the compiler does not have __has_include, pretend the answer is
   always no.  */
#  define __has_include(x) 0
#endif

/* Version number components: V=Version, R=Revision, P=Patch
   Version date components:   YYYY=Year, MM=Month,   DD=Day  */

#if defined(__INTEL_COMPILER) || defined(__ICC)
# define COMPILER_ID "Intel"
# if defined(_MSC_VER)
#  define SIMULATE_ID "MSVC"
# endif
# if defined(__GNUC__)
#  define SIMULATE_ID "GNU"
# endif
  /* __INTEL_COMPILER = VRP prior to 2021, and then VVVV for 2021 and later,
     except that a few beta releases use the old format with V=2021.  */
# if __INTEL_COMPILER < 2021 || __INTEL_COMPILER == 202110 || __INTEL_COMPILER == 202111
#  define COMPILER_VERSION_MAJOR DEC(__INTEL_COMPILER/100)
#  define COMPILER_VERSION_MINOR DEC(__INTEL_COMPILER/10 % 10)
#  if defined(__INTEL_COMPILER_UPDATE)
#   define COMPILER_VERSION_PATCH DEC(__INTEL_COMPILER_UPDATE)
#  else
#   define COMPILER_VERSION_PATCH DEC(__INTEL_COMPILER   % 10)
#  endif
# else
#  define COMPILER_VERSION_MAJOR DEC(__INTEL_COMPILER)
#  define COMPILER_VERSION_MINOR DEC(__INTEL_COMPILER_UPDATE)
   /* The third version component from --version is an update index,
      but no macro is provided for it.  */
#  define COMPILER_VERSION_PATCH DEC(0)
# endif
# if defined(__INTEL_COMPILER_BUILD_DATE)
   /* __INTEL_COMPILER_BUILD_DATE = YYYYMMDD */
#  define COMPILER_VERSION_TWEAK DEC(__INTEL_COMPILER_BUILD_DATE)
# endif
# if defined(_MSC_VER)
   /* _MSC_VER = VVRR */
#  define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100)
#  define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100)
# endif
# if defined(__GNUC__)
#  define SIMULATE_VERSION_MAJOR DEC(__GNUC__)
# elif defined(__GNUG__)
#  define SIMULATE_VERSION_MAJOR DEC(__GNUG__)
# endif
# if defined(__GNUC_MINOR__)
#  define SIMULATE_VERSION_MINOR DEC(__GNUC_MINOR__)
# endif
# if defined(__GNUC_PATCHLEVEL__)
#  define SIMULATE_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__)
# endif

#elif (defined(__clang__) && defined(__INTEL_CLANG_COMPILER)) || defined(__INTEL_LLVM_COMPILER)
# define COMPILER_ID "IntelLLVM"
#if defined(_MSC_VER)
# define SIMULATE_ID "MSVC"
#endif
#if defined(__GNUC__)
# define SIMULATE_ID "GNU"
#endif
/* __INTEL_LLVM_COMPILER = VVVVRP prior to 2021.2.0, VVVVRRPP for 2021.2.0 and
 * later.  Look for 6 digit vs. 8 digit version number to decide encoding.
 * VVVV is no smaller than the current year when a version is released.
 */
#if __INTEL_LLVM_COMPILER < 1000000L
# define COMPILER_VERSION_MAJOR DEC(__INTEL_LLVM_COMPILER/100)
# define COMPILER_VERSION_MINOR DEC(__INTEL_LLVM_COMPILER/10 % 10)
# define COMPILER_VERSION_PATCH DEC(__INTEL_LLVM_COMPILER    % 10)
#else
# define COMPILER_VERSION_MAJOR DEC(__INTEL_LLVM_COMPILER/10000)
# define COMPILER_VERSION_MINOR DEC(__INTEL_LLVM_COMPILER/100 % 100)
# define COMPILER_VERSION_PATCH DEC(__INTEL_LLVM_COMPILER     % 100)
#endif
#if defined(_MSC_VER)
  /* _MSC_VER = VVRR */
# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100)
# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100)
#endif
#if defined(__GNUC__)
# define SIMULATE_VERSION_MAJOR DEC(__GNUC__)
#elif defined(__GNUG__)
# define SIMULATE_VERSION_MAJOR DEC(__GNUG__)
#endif
#if defined(__GNUC_MINOR__)
# define SIMULATE_VERSION_MINOR DEC(__GNUC_MINOR__)
#endif
#if defined(__GNUC_PATCHLEVEL__)
# define SIMULATE_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__)
#endif

#elif defined(__PATHCC__)
# define COMPILER_ID "PathScale"
# define COMPILER_VERSION_MAJOR DEC(__PATHCC__)
# define COMPILER_VERSION_MINOR DEC(__PATHCC_MINOR__)
# if defined(__PATHCC_PATCHLEVEL__)
#  define COMPILER_VERSION_PATCH DEC(__PATHCC_PATCHLEVEL__)
# endif

#elif defined(__BORLANDC__) && defined(__CODEGEARC_VERSION__)
# define COMPILER_ID "Embarcadero"
# define COMPILER_VERSION_MAJOR HEX(__CODEGEARC_VERSION__>>24 & 0x00FF)
# define COMPILER_VERSION_MINOR HEX(__CODEGEARC_VERSION__>>16 & 0x00FF)
# define COMPILER_VERSION_PATCH DEC(__CODEGEARC_VERSION__     & 0xFFFF)

#elif defined(__BORLANDC__)
# define COMPILER_ID "Borland"
  /* __BORLANDC__ = 0xVRR */
# define COMPILER_VERSION_MAJOR HEX(__BORLANDC__>>8)
# define COMPILER_VERSION_MINOR HEX(__BORLANDC__ & 0xFF)

#elif defined(__WATCOMC__) && __WATCOMC__ < 1200
# define COMPILER_ID "Watcom"
   /* __WATCOMC__ = VVRR */
# define COMPILER_VERSION_MAJOR DEC(__WATCOMC__ / 100)
# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10)
# if (__WATCOMC__ % 10) > 0
#  define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10)
# endif

#elif defined(__WATCOMC__)
# define COMPILER_ID "OpenWatcom"
   /* __WATCOMC__ = VVRP + 1100 */
# define COMPILER_VERSION_MAJOR DEC((__WATCOMC__ - 1100) / 100)
# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10)
# if (__WATCOMC__ % 10) > 0
#  define COMPILER_VERSION_PATCH DEC(


// Subarray Analyzer (Cross-Platform Auto Open)
#include <iostream>
#include <fstream>
#include <cstdlib> // for system()
using namespace std;

// ===== Utility to auto-open files cross-platform =====
void openFile(const string &filename) {
    #ifdef _WIN32
        system(("start " + filename).c_str()); // Windows
    #elif __APPLE__
        system(("open " + filename).c_str());  // MacOS
    #else
        system(("xdg-open " + filename).c_str()); // Linux
    #endif
}

// ===== Function to print all subarrays =====
void printSubarrays(int arr[], int n, ofstream &txt, ofstream &csv) {
    txt << "\n🔹 All Subarrays:\n";
    cout << "\n🔹 All Subarrays:\n";

    for (int st = 0; st < n; st++) {
        for (int end = st; end < n; end++) {
            txt << "[ ";
            cout << "[ ";
            for (int i = st; i <= end; i++) {
                txt << arr[i] << " ";
                cout << arr[i] << " ";
            }
            txt << "]\n";
            cout << "]\n";

            // Save in CSV
            for (int i = st; i <= end; i++) {
                csv << arr[i];
                if (i < end) csv << ",";
            }
            csv << "\n";
        }
    }
}

// ===== Function to print subarrays with sum =====
void printSubarraysWithSum(int arr[], int n, ofstream &txt, ofstream &csv) {
    txt << "\n🔹 All Subarrays with Current Sum:\n";
    cout << "\n🔹 All Subarrays with Current Sum:\n";

    for (int st = 0; st < n; st++) {
        int currSum = 0;
        for (int end = st; end < n; end++) {
            currSum += arr[end];

            txt << "[ ";
            cout << "[ ";
            for (int i = st; i <= end; i++) {
                txt << arr[i] << " ";
                cout << arr[i] << " ";
            }
            txt << "]  → Sum = " << currSum << "\n";
            cout << "]  → Sum = " << currSum << "\n";

            // Save subarray + sum in CSV
            for (int i = st; i <= end; i++) {
                csv << arr[i];
                if (i < end) csv << ",";
            }
            csv << "," << currSum << "\n";
        }
    }
}

// ===== Kadane’s Algorithm =====
int maxSubarraySum(int arr[], int n, ofstream &txt, ofstream &csv) {
    int maxSum = arr[0];
    int currSum = arr[0];

    for (int i = 1; i < n; i++) {
        currSum = max(arr[i], currSum + arr[i]);
        maxSum = max(maxSum, currSum);
    }

    txt << "\n✅ Maximum Subarray Sum = " << maxSum << "\n";
    cout << "\n✅ Maximum Subarray Sum = " << maxSum << "\n";

    csv << "MAX_SUBARRAY_SUM," << maxSum << "\n";

    return maxSum;
}

// ===== Main Program =====
int main() {
    int n;
    cout << "📊 Subarray Analyzer Project\n";
    cout << "👨💻 Programmer: THE RAHUL CHAUHAN\n";
    cout << "Enter size of array: ";
    cin >> n;

    int arr[n];
    cout << "Enter " << n << " elements:\n";
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }

    // Open files
    ofstream txt("subarray_report.txt");
    ofstream csv("subarray_report.csv");

    if (!txt || !csv) {
        cout << "⚠ Error: Could not create output files!\n";
        return 1;
    }

    // Add header / credit
    txt << "📊 Subarray Analyzer Report\n";
    txt << "👨💻 Programmer: THE RAHUL CHAUHAN\n\n";
    csv << "Subarray Elements,Sum\n";

    int choice;
    do {
        cout << "\n===== MENU =====\n";
        cout << "1. Print All Subarrays\n";
        cout << "2. Print Subarrays with Current Sum\n";
        cout << "3. Find Maximum Subarray Sum (Kadane)\n";
        cout << "4. Exit\n";
        cout << "Enter your choice: ";
        cin >> choice;

        switch (choice) {
            case 1: printSubarrays(arr, n, txt, csv); break;
            case 2: printSubarraysWithSum(arr, n, txt, csv); break;
            case 3: maxSubarraySum(arr, n, txt, csv); break;
            case 4:
                cout << "Results saved in 'subarray_report.txt' and 'subarray_report.csv' 👌\n";
                txt << "\nReport Generated Successfully ✅\n";
                txt << "👨💻 Programmer: THE RAHUL CHAUHAN\n";
                csv << "REPORT_GENERATED_BY,THE RAHUL CHAUHAN\n";

                // Auto open reports (cross-platform)
                openFile("subarray_report.txt");
                openFile("subarray_report.csv");

                cout << "Opening reports... 📂\nExiting... 👋\n";
                break;
            default: cout << "Invalid choice! Try again.\n";
        }
    } while (choice != 4);

    txt.close();
    csv.close();
    return 0;
}


#include <bits/stdc++.h>
//#include "Model/RubiksCube3dArray.cpp"
//#include "Model/RubiksCube1dArray.cpp"
//#include "Model/RubiksCubeBitboard.cpp"
#include "Solver/DFSSolver.h"
#include "Solver/BFSSolver.h"
#include "Solver/IDDFSSolver.h"
#include "Solver/IDAstarSolver.h"
//#include "PatternDatabases/CornerPatternDatabase.h"
#include "PatternDatabases/CornerDBMaker.h"

using namespace std;

int main() {
//    RubiksCube3dArray object3DArray;
//    RubiksCube1dArray object1dArray;
//    RubiksCubeBitboard objectBitboard;
//
//    object3DArray.print();
//
//    if (object3DArray.isSolved()) cout << "SOLVED\n\n";
//    else cout << "NOT SOLVED\n\n";
//
//    if (object1dArray.isSolved()) cout << "SOLVED\n\n";
//    else cout << "NOT SOLVED\n\n";
//
//    if (objectBitboard.isSolved()) cout << "SOLVED\n\n";
//    else cout << "NOT SOLVED\n\n";
//
//    objectBitboard.u();
//    object3DArray.u();
//    object1dArray.u();
//    objectBitboard.print();
//    object3DArray.print();
//    object1dArray.print();
//
//    objectBitboard.l();
//    object3DArray.l();
//    object1dArray.l();
//    objectBitboard.print();
//    object3DArray.print();
//    object1dArray.print();
//
//    objectBitboard.f();
//    object3DArray.f();
//    object1dArray.f();
//    objectBitboard.print();
//    object3DArray.print();
//    object1dArray.print();
//
//    objectBitboard.r();
//    object3DArray.r();
//    object1dArray.r();
//    objectBitboard.print();
//    object3DArray.print();
//    object1dArray.print();
//
//    objectBitboard.b();
//    object3DArray.b();
//    object1dArray.b();
//    objectBitboard.print();
//    object3DArray.print();
//    object1dArray.print();
//
//    objectBitboard.d();
//    object3DArray.d();
//    object1dArray.d();
//    objectBitboard.print();
//    object3DArray.print();
//    object1dArray.print();
//
//    if (object3DArray.isSolved()) cout << "SOLVED\n\n";
//    else cout << "NOT SOLVED\n\n";
//
//    if (object1dArray.isSolved()) cout << "SOLVED\n\n";
//    else cout << "NOT SOLVED\n\n";
//
//    if (objectBitboard.isSolved()) cout << "SOLVED\n\n";
//    else cout << "NOT SOLVED\n\n";
//
//    objectBitboard.dPrime();
//    object3DArray.dPrime();
//    object1dArray.dPrime();
//    objectBitboard.print();
//    object3DArray.print();
//    object1dArray.print();
//
//    objectBitboard.bPrime();
//    object3DArray.bPrime();
//    object1dArray.bPrime();
//    objectBitboard.print();
//    object3DArray.print();
//    object1dArray.print();
//
//    objectBitboard.rPrime();
//    object3DArray.rPrime();
//    object1dArray.rPrime();
//    objectBitboard.print();
//    object3DArray.print();
//    object1dArray.print();
//
//    objectBitboard.fPrime();
//    object3DArray.fPrime();
//    object1dArray.fPrime();
//    objectBitboard.print();
//    object3DArray.print();
//    object1dArray.print();
//
//    objectBitboard.lPrime();
//    object3DArray.lPrime();
//    object1dArray.lPrime();
//    objectBitboard.print();
//    object3DArray.print();
//    object1dArray.print();
//
//    objectBitboard.uPrime();
//    object3DArray.uPrime();
//    object1dArray.uPrime();
//    objectBitboard.print();
//    object3DArray.print();
//    object1dArray.print();
//
//    if (object3DArray.isSolved()) cout << "SOLVED\n\n";
//    else cout << "NOT SOLVED\n\n";
//
//    if (object1dArray.isSolved()) cout << "SOLVED\n\n";
//    else cout << "NOT SOLVED\n\n";
//
//    if (objectBitboard.isSolved()) cout << "SOLVED\n\n";
//    else cout << "NOT SOLVED\n\n";

    // Create two Cubes ------------------------------------------------------------------------------------------

//    RubiksCube3dArray cube1;
//    RubiksCube3dArray cube2;

//    RubiksCube1dArray cube1;
//    RubiksCube1dArray cube2;

//    RubiksCubeBitboard cube1;
//    RubiksCubeBitboard cube2;

//  Equality and assignment of cubes --------------------------------------------------------------------------

//    if(cube1 == cube2) cout << "Is equal\n";
//    else cout << "Not Equal\n";
//
//    cube1.randomShuffleCube(1);
//
//    if(cube1 == cube2) cout << "Is equal\n";
//    else cout << "Not Equal\n";
//
//    cube2 = cube1;
//
//    if(cube1 == cube2) cout << "Is equal\n";
//    else cout << "Not Equal\n";

//  Unordered_map of Cubes  ------------------------------------------------------------------------------------

//    unordered_map<RubiksCube3dArray, bool, Hash3d> mp1;

//    unordered_map<RubiksCube1dArray, bool, Hash1d> mp1;

//    unordered_map<RubiksCubeBitboard, bool, HashBitboard> mp1;
//
//    mp1[cube1] = true;
//    cube2.randomShuffleCube(8);
//    if (mp1[cube1]) cout << "Cube1 is present\n";
//    else cout << "Cube1 is not present\n";
//
//    if (mp1[cube2]) cout << "Cube2 is present\n";
//    else cout << "Cube2 is not present\n";
//

// DFS Solver Testing __________________________________________________________________________________________
//    RubiksCube3dArray cube;
//    cube.print();
//


#include "uefiext.h"

#define FLAG_IGNORE_SELFMAP  0x1

#define INVALID_PFN  (~0ULL)

//
// ---------------------------------------------------------- AMD64 Definitions
//

#define X64_PAGE_SHIFT  12

#define PTE_PER_PAGE_X64  512
#define PDE_PER_PAGE_X64  512
#define PPE_PER_PAGE_X64  512
#define PXE_PER_PAGE_X64  512
#define PLE_PER_PAGE_X64  512

#define PTI_SHIFT_X64  12
#define PDI_SHIFT_X64  21
#define PPI_SHIFT_X64  30
#define PXI_SHIFT_X64  39
#define PLI_SHIFT_X64  48

#define PTI_MASK_X64  (PTE_PER_PAGE_X64 - 1)
#define PDI_MASK_X64  (PDE_PER_PAGE_X64 - 1)
#define PPI_MASK_X64  (PPE_PER_PAGE_X64 - 1)
#define PXI_MASK_X64  (PXE_PER_PAGE_X64 - 1)
#define PLI_MASK_X64  (PLE_PER_PAGE_X64 - 1)

#define GetPleOffsetX64(va)  ((ULONG)(((ULONG64)(va) >> PLI_SHIFT_X64) & PLI_MASK_X64))
#define GetPxeOffsetX64(va)  ((ULONG)(((ULONG64)(va) >> PXI_SHIFT_X64) & PXI_MASK_X64))
#define GetPpeOffsetX64(va)  ((ULONG)(((ULONG64)(va) >> PPI_SHIFT_X64) & PPI_MASK_X64))
#define GetPdeOffsetX64(va)  ((ULONG)(((ULONG64)(va) >> PDI_SHIFT_X64) & PDI_MASK_X64))
#define GetPteOffsetX64(va)  ((ULONG)(((ULONG64)(va) >> PTI_SHIFT_X64) & PTI_MASK_X64))

typedef struct _HARDWARE_PTE_X64 {
  union {
    struct {
      ULONG64    Valid           : 1;
      ULONG64    Write           : 1;
      ULONG64    Owner           : 1;
      ULONG64    WriteThrough    : 1;
      ULONG64    CacheDisable    : 1;
      ULONG64    Accessed        : 1;
      ULONG64    Dirty           : 1;
      ULONG64    LargePage       : 1;
      ULONG64    Global          : 1;
      ULONG64    reserved0       : 3;
      ULONG64    PageFrameNumber : 40;
      ULONG64    reserved1       : 11;
      ULONG64    NoExecute       : 1;
    };

    ULONG64    AsULong64;
  };
} HARDWARE_PTE_X64, *PHARDWARE_PTE_X64;

#define PTE_SHIFT_X64          3
#define TABLE_DECODE_BITS_X64  9
#define VA_BITS_X64(LEVELS)  ((LEVELS) == 5 ? 57 : 48)
#define VA_MASK_X64(LEVELS)  (((ULONG64)1 << VA_BITS_X64(LEVELS)) - 1)

#undef PTI_SHIFT
#define PTI_SHIFT(LEVELS)  (X64_PAGE_SHIFT + TABLE_DECODE_BITS_X64 * (LEVELS))

//
// ---------------------------------------------------------- ARM64 Definitions
//

#define ARM64_PAGE_SHIFT  12

#define PTE_PER_PAGE_ARM64  512
#define PDE_PER_PAGE_ARM64  512
#define PPE_PER_PAGE_ARM64  512
#define PXE_PER_PAGE_ARM64  512

#define PTE_SHIFT_ARM64  3
#define PTI_SHIFT_ARM64  12
#define PDI_SHIFT_ARM64  21
#define PPI_SHIFT_ARM64  30
#define PXI_SHIFT_ARM64  39

#define PPI_MASK_ARM64  (PPE_PER_PAGE_ARM64 - 1)
#define PXI_MASK_ARM64  (PXE_PER_PAGE_ARM64 - 1)

#define GetPxeOffsetARM64(va)  ((ULONG)(((ULONG64)(va) >> PXI_SHIFT_ARM64) & PXI_MASK_ARM64))
#define GetPpeOffsetARM64(va)  ((ULONG)(((ULONG64)(va) >> PPI_SHIFT_ARM64) & PPI_MASK_ARM64))
#define GetPdeOffsetARM64(va)  ((ULONG)(((ULONG64)(va) >> PDI_SHIFT_ARM64) & (PDE_PER_PAGE_ARM64 - 1)))
#define GetPteOffsetARM64(va)  ((ULONG)(((ULONG64)(va) >> PTI_SHIFT_ARM64) & (PTE_PER_PAGE_ARM64 - 1)))

#define VA_BITS_ARM64  48
#define VA_MASK_ARM64  (((ULONG64)1 << VA_BITS_ARM64) - 1)

#define ARM64_TCR_T0SZ_MASK   0x3f
#define ARM64_TCR_T1SZ_MASK   0x00000000003f0000ULL
#define ARM64_TCR_T0SZ_SHIFT  0
#define ARM64_TCR_T1SZ_SHIFT  16
#define ARM64_TCR_TG1_MASK    0x00000000c0000000ULL
#define ARM64_TCR_TG0_MASK    0x000000000000c000ULL

typedef struct _HARDWARE_PTE_ARM64 {
  union {
    struct {
      ULONGLONG    Valid               : 1;
      ULONGLONG    NotLargePage        : 1;     // ARM Large page bit is inverted !
      ULONGLONG    CacheType           : 3;     // Lower 2 bits for cache type encoding
      ULONGLONG    NonSecure           : 1;
      ULONGLONG    AccessPermissions   : 2;
      ULONGLONG    Shareability        : 2;
      ULONGLONG    Accessed            : 1;
      ULONGLONG    NonGlobal           : 1;
      ULONGLONG    PageFrameNumber     : 38;
      ULONGLONG    GuardedPage         : 1;
      ULONGLONG    DirtyBitModifer     : 1;
      ULONGLONG    ContiguousBit       : 1;
      ULONGLONG    PrivilegedNoExecute : 1;
      ULONGLONG    UserNoExecute       : 1;
      ULONGLONG    Reserved            : 4;
      ULONGLONG    PxnTable            : 1;
      ULONGLONG    UxnTable            : 1;
      ULONGLONG    ApTable             : 2;
      ULONGLONG    NsTable             : 1;
    };

    ULONG64    AsULong64;
  };
} HARDWARE_PTE_ARM64, *PHARDWARE_PTE_ARM64;

//
// ---------------------------------------------------------- Utility Functions
//

std::string
GetArm64SharabilityForPte (
  _In_ PHARDWARE_PTE_ARM64  Pte,
  _In_ ULONG                Level
  )
{
  UCHAR  Sharability;
  PCSTR  Description;

  UNREFERENCED_PARAMETER (Level);

  Sharability = Pte->Shareability;

  switch (Sharability) {
    case 0:
      Description = "None";
      break;
    case 2:
      Description = "Outer";
      break;
    case 3:
      Description = "I


#include "stdafx.h"
#include <fstream>
#include <cwctype>
#include <cstdarg>
#include <ctime>
#include <iostream>

namespace Log {
	LOG getlog(wchar_t logfile[]) {
		LOG log = INITLOG;
		log.stream = new std::ofstream(logfile, std::ios::out | std::ios::app);
		if (!log.stream->is_open()) {
			throw ERROR_THROW(112);
		}
		wcscpy_s(log.logfile, logfile);
		return log;
	}

	void WriteLine(LOG log, char* c, ...) {
		va_list args;
		va_start(args, c);
		char* str = nullptr;
		while ((str = va_arg(args, char*)) != "") {
			if (str[0] == '\0') break;
			*log.stream << str;
		}
		va_end(args);
	}

	void WriteLine(LOG log, wchar_t* c, ...) {
		if (!log.stream || !log.stream->is_open()) return;

		va_list args;
		va_start(args, c);

		wchar_t* wstr = c;

		while (wstr != nullptr && wstr[0] != L'\0') {
			size_t requiredSize = wcslen(wstr) * 4 + 1;
			char* buffer = new char[requiredSize];
			size_t convertedLength = 0;

			errno_t err = wcstombs_s(&convertedLength, buffer, requiredSize, wstr, _TRUNCATE);

			if (err == 0) {
				(*log.stream) << buffer;
			}

			delete[] buffer;
			wstr = va_arg(args, wchar_t*);
		}

		va_end(args);
		(*log.stream) << std::endl;
	}

	void WriteLog(LOG log) {
		time_t now = time(nullptr);
		struct tm localTime;
		localtime_s(&localTime, &now);
		char timeBuffer[100];
		strftime(timeBuffer, sizeof(timeBuffer), "%Y-%m-%d %H:%M:%S", &localTime);
		*log.stream << "-----  Ïðîòîêîë ----- " << timeBuffer << "------\n";
		return;
	}

	void WriteParm(LOG log, Parm::PARM parm) {
		if (!log.stream || !log.stream->is_open()) return;

		*log.stream << "----- Ïàðàìåòðû -----" << std::endl;

		char buffer[PARM_MAX_SIZE * 4];

		auto convert = [&](const wchar_t* src) -> const char* {
			std::memset(buffer, 0, sizeof(buffer));
			size_t converted = 0;

			errno_t err = wcstombs_s(&converted, buffer, sizeof(buffer), src, _TRUNCATE);
			return (err == 0) ? buffer : "[îøèáêà ïðåîáðàçîâàíèÿ]";
			};

		*log.stream << "-log: " << convert(parm.log) << std::endl;
		*log.stream << "-in : " << convert(parm.in) << std::endl;
		*log.stream << "-out: " << convert(parm.out) << std::endl;
	}

	void WriteIn(LOG log, In::IN in) {
		*log.stream << "---- Ñòàòèñòèêà -----" << std::endl;
		*log.stream << "Êîëè÷åñòâî ñèìâîëîâ: " << in.size << std::endl;
		*log.stream << "Ïðîèãíîðèðîâàíî: " << in.ignore << std::endl;
		*log.stream << "Êîëè÷åñòâî ñòðîê: " << in.lines << std::endl;
		return;
	}

	void WriteError(LOG log, Error::ERROR error) {
		using namespace std;
		if (!log.stream->is_open()) {
			std::cout << "Îøèáêà " << error.id << ": " << error.message << std::endl << std::endl;
			if (error.inext.line != -1) {
				std::cout << "ñòðîêà " << error.inext.line << " ïîçèöèÿ " << error.inext.col << std::endl << std::endl;
			}
		}
		else {
			*log.stream << "Îøèáêà " << error.id << ": " << error.message << std::endl << std::endl;
			if (error.inext.line != -1) {
				*log.stream << "ñòðîêà " << error.inext.line << " ïîçèöèÿ " << error.inext.col << std::endl << std::endl;
			}
		}
	}

	void Close(LOG log) {
		log.stream->close();
	}

}


#include<iostream>
using namespace std ;
static int num=0;
class node
{
    public:
    string name;
    node* link;
        node(string v)
        {
            link = NULL;
            num++;
            name = v;
        }
};
node* head=NULL;
class book
{

    public:
        int n;
        string username;
        bool boolen = true;
        void  show()
        {
            cout<<"[1] add the book"<<endl;
            cout<<"[2] show the books"<<endl;
            cout<<"[3] delete the book"<<endl;
            cout<<"[4] number the books"<<endl;
            cout<<"[0] exit"<<endl;
            cin>>n;
            system("clear");
        }
        void reflence()
        {
            if(n==1) add();
            else if(n==2) showw();
            else if(n==3) del();
            else if(n==4) number();
            else if(n==0) boolen =false;
            else
             cout<<"error - enter [0 - 3]"<<endl;
        }
        void add()
        {
            system("clear");
            cout<<"enter name the book"<<endl;
            string  s;
            cin>> s;
            node* temp=head;
            if(head==NULL)
            {
                head =new node(s);
            }
            else
            {
                while(temp->link!=NULL)
                {
                    temp=temp->link;
                }
                temp->link=new node(s);
            }
        }
        void showw()
        {
            system("clear");
            static int i=0;
            node* temp=head;
            while(temp!=NULL)
            {
                cout<<"["<<++i<<"] "<<temp->name<<endl;
                temp =temp->link;
            }
            i=0;
            cout<<endl;
        }
        void del()
        {
            system("clear");
            int n;
            cout<<"enter id the book : ";
            cin>>n;
            if(n>0)
            {
                if (head == NULL)
                {
                    cout << "List is empty.\a" << endl<<endl;
                    return;
                }
                if (n == 1 && head!=NULL)
                {
                    node* temp = head;
                    head = head->link;
                    delete temp;
                    cout << endl << endl;
                    return;
                }
                else if (n>1 && head!=NULL )
                {
                    n--;
                    n--;
                    node* temp=head;
                    for(int i =0 ; i< n;i++)
                    {
                      temp=temp->link;
                    }
                    node* del=temp->link;
                    temp->link=temp->link->link;
                    delete del;
                }
            }

        }
        void number()
        {
            system("clear");
            cout<<"numer the books is : "<<num<<endl<<endl;

        }
        bool loop()
        {
           return boolen;
        }
};
int main ()
{
    book ob;
    cout<<"alslam alykom"<<endl;
    cout<<"enter the name ? ";
    getline(cin,ob.username);
    cout<<"welcome "<<ob.username<<endl;
    system("clear");
    while (ob.loop())
    {
        ob.show();
        ob.reflence();
    }

    return 0;
}


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

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

  ::CoUninitialize();
  return EXIT_SUCCESS;
}


//
// Created by aoe on 25-7-7.
//

#include <AMReX_Math.H>
#include <AMReX_Print.H>

#include <AMReX_ParmParse.H>
#include <AMReX_TagBox.H>
#include <AMReX_Utility.H>
#include <AMReX_PhysBCFunct.H>
#include <AMReX_MLNodeLaplacian.H>
#include <AMReX_FillPatchUtil.H>
#include <iamr_constants.H>

#include "DiffusedIB_Parallel.h"

#include <filesystem>
#include <sstream>
namespace fs = std::filesystem;

#define GHOST_CELLS 2

using namespace amrex;

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                     global variable                           */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#define LOCAL_LEVEL 0

const Vector<std::string> direction_str{"X","Y","Z"};

namespace ParticleProperties{
    Vector<Real> _x{}, _y{}, _z{}, _rho{};
    Vector<Real> Vx{}, Vy{}, Vz{};
    Vector<Real> Ox{}, Oy{}, Oz{};
    Vector<Real> _radius;
    Real rd{0.0};
    Vector<int> TLX{}, TLY{},TLZ{},RLX{},RLY{},RLZ{};
    int euler_finest_level{0};
    int euler_velocity_index{0};
    int euler_force_index{0};
    Real euler_fluid_rho{0.0};
    int verbose{0};
    int loop_ns{2};
    int loop_solid{1};
    int Uhlmann{0};

    Vector<Real> GLO, GHI;
    int start_step{-1};
    int collision_model{0};

    int write_freq{1};
    bool init_particle_from_file{false};

    GpuArray<Real, 3> plo{0.0,0.0,0.0}, phi{0.0,0.0,0.0}, dx{0.0, 0.0, 0.0};
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                     other function                            */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
AMREX_INLINE AMREX_GPU_DEVICE
Real nodal_phi_to_heavi(Real phi)
{
    if (phi <= 0.0) {
        return 0.0;
    }
    return 1.0;
}

void nodal_phi_to_pvf(MultiFab& pvf, const MultiFab& phi_nodal)
{

    // Print() << "In the nodal_phi_to_pvf\n";

    pvf.setVal(0.0);

    // Only set the valid cells of pvf
#ifdef AMREX_USE_OMP
#pragma omp parallel if (Gpu::notInLaunchRegion())
#endif
    for (MFIter mfi(pvf,TilingIfNotGPU()); mfi.isValid(); ++mfi)
    {
        const Box& bx = mfi.tilebox();
        auto const& pvffab   = pvf.array(mfi);
        auto const& pnfab = phi_nodal.array(mfi);
        ParallelFor(bx, [pvffab, pnfab]
        AMREX_GPU_DEVICE(int i, int j, int k) noexcept
        {
            Real num = 0.0;
            for(int kk=k; kk<=k+1; kk++) {
                for(int jj=j; jj<=j+1; jj++) {
                    for(int ii=i; ii<=i+1; ii++) {
                        num += (-pnfab(ii,jj,kk)) * nodal_phi_to_heavi(-pnfab(ii,jj,kk));
                    }
                }
            }
            Real deo = 0.0;
            for(int kk=k; kk<=k+1; kk++) {
                for(int jj=j; jj<=j+1; jj++) {
                    for(int ii=i; ii<=i+1; ii++) {
                        deo += std::abs(pnfab(ii,jj,kk));
                    }
                }
            }
            pvffab(i,j,k) = num / (deo + 1.e-12);
        });
    }

}

void calculate_phi_nodal(MultiFab& phi_nodal, kernel& current_kernel)
{
    phi_nodal.setVal(0.0);

    Real Xp = current_kernel.location[0];
    Real Yp = current_kernel.location[1];
    Real Zp = current_kernel.location[2];
    Real Rp = current_kernel.radius;

    // Only set the valid cells of phi_nodal
    for (MFIter mfi(phi_nodal,TilingIfNotGPU()); mfi.isValid(); ++mfi)
    {
        const Box& bx = mfi.tilebox();
        auto const& pnfab = phi_nodal.array(mfi);
        auto dx = ParticleProperties::dx;
        auto plo = ParticleProperties::plo;
        ParallelFor(bx, [=]
            AMREX_GPU_DEVICE(int i, int j, int k) noexcept
            {
                Real Xn = i * dx[0] + plo[0];
                Real Yn = j * dx[1] + plo[1];
                Real Zn = k * dx[2] + plo[2];

                pnfab(i,j,k) = std::sqrt( (Xn - Xp)*(Xn - Xp)
                        + (Yn - Yp)*(Yn - Yp)  + (Zn - Zp)*(Zn - Zp)) - Rp;
                pnfab(i,j,k) = pnfab(i,j,k) / Rp;

            }
        );
    }
}

// May use ParReduce later, https://amrex-codes.github.io/amrex/docs_html/GPU.html#multifab-reductions
void CalculateSumU_cir (RealVect& sum,
                        const MultiFab& E,
                        const MultiFab& pvf,
                        int EulerVelIndex)
{
    auto const& E_data = E.const_arrays();
    auto const& pvf_data = pvf.const_arrays();
    const Real d = Math::powi<3>(ParticleProperties::dx[0]);
    GpuTuple<Real, Real, Real> tmpSum = ParReduce(TypeList<ReduceOpSum,ReduceOpSum,ReduceOpSum>{}, TypeList<Real, Real, Real>{},E, IntVect{0},
    [=] AMREX_GPU_DEVICE (int box_no, int i, int j, int k) noexcept -> GpuTuple<Real, Real, Real>{
        auto E_ = E_data[box_no];
        auto pvf_ = pvf_data[box_no];
        return {
            E_(i, j, k, EulerVelIndex    ) * d * pvf_(i,j,k),
            E_(i, j, k, EulerVelIndex + 1) * d * pvf_(i,j,k),
            E_(i, j, k, EulerVelIndex + 2) * d * pvf_(i,j,k)
        };
    });
    sum[0] = get<0>(tmpSum);
    sum


/*
 * This code is licensed under the GNU AGPLv3
 * Copyright (c) 2025 GokbakarE
 * Date: 28-08-2025
 */
#include "SuperH3E.hpp"
#include <iostream>
#include <bitset>
#include <unordered_map>
#include <string>
#include <string_view>
#include <format>

static const std::unordered_map<std::string_view, std::string_view> OpcodeMap = {
    {"0011nnnnmmmm1100", "ADD $M, $N"},
    {"0011nnnnmmmm1110", "ADDC $M, $N"},
    {"0011nnnnmmmm1111", "ADDV $M, $N"},
    {"0010nnnnmmmm1001", "AND $M, $N"},
    {"11001001iiiiiiii", "AND #$I, R0"},
    {"11001101iiiiiiii", "AND.B #$I, @(R0, GBR)"},
    {"10001011dddddddd", "BF $D"},
    {"10001111dddddddd", "BF/S $D"},
    {"1010ffffffffffff", "BRA $F"},
    {"0000nnnn00100011", "BRAF $N"},
    {"1011ffffffffffff", "BSR $F"},
    {"0000nnnn00000011", "BSRF $N"},
    {"10001001dddddddd", "BT $D"},
    {"10001101dddddddd", "BT/S $D"},
    {"0000000000101000", "CLRMAC"},
    {"0000000001001000", "CLRS"},
    {"0000000000001000", "CLRT"},
    {"0011nnnnmmmm0000", "CMP/EQ $M, $N"},
    {"0011nnnnmmmm0011", "CMP/GE $M, $N"},
    {"0011nnnnmmmm0111", "CMP/GT $M, $N"},
    {"0011nnnnmmmm0110", "CMP/HI $M, $N"},
    {"0011nnnnmmmm0010", "CMP/HS $M, $N"},
    {"0100nnnn00010101", "CMP/PL $N"},
    {"0100nnnn00010001", "CMP/PZ $N"},
    {"0010nnnnmmmm1100", "CMP/STR $M, $N"},
    {"10001000iiiiiiii", "CMP/EQ #$I, R0"},
    {"0010nnnnmmmm0111", "DIV0S $M, $N"},
    {"0000000000011001", "DIV0U"},
    {"0011nnnnmmmm0100", "DIV1 $M, $N"},
    {"0011nnnnmmmm1101", "DMULS.L $M, $N"},
    {"0011nnnnmmmm0101", "DMULU.L $M, $N"},
    {"0100nnnn00010000", "DT $N"},
    {"0110nnnnmmmm1110", "EXTS.B $M, $N"},
    {"0110nnnnmmmm1111", "EXTS.W $M, $N"},
    {"0110nnnnmmmm1100", "EXTU.B $M, $N"},
    {"0110nnnnmmmm1101", "EXTU.W $M, $N"},
    {"0100nnnn00101011", "JMP @$N"},
    {"0100nnnn00001011", "JSR @$N"},
    {"0100nnnn00001110", "LDC $N, SR"},
    {"0100nnnn00011110", "LDC $N, GBR"},
    {"0100nnnn00101110", "LDC $N, VBR"},
    {"0100nnnn00111110", "LDC $N, SSR"},
    {"0100nnnn01001110", "LDC $N, SPC"},
    {"0100nnnn10001110", "LDC $N, R0_BANK"},
    {"0100nnnn10011110", "LDC $N, R1_BANK"},
    {"0100nnnn10101110", "LDC $N, R2_BANK"},
    {"0100nnnn10111110", "LDC $N, R3_BANK"},
    {"0100nnnn11001110", "LDC $N, R4_BANK"},
    {"0100nnnn11011110", "LDC $N, R5_BANK"},
    {"0100nnnn11101110", "LDC $N, R6_BANK"},
    {"0100nnnn11111110", "LDC $N, R7_BANK"},
    {"0100nnnn00000111", "LDC.L @$N+, SR"},
    {"0100nnnn00010111", "LDC.L @$N+, GBR"},
    {"0100nnnn00100111", "LDC.L @$N+, VBR"},
    {"0100nnnn00110111", "LDC.L @$N+, SSR"},
    {"0100nnnn01000111", "LDC.L @$N+, SPC"},
    {"0100nnnn10000111", "LDC.L @$N+, R0_BANK"},
    {"0100nnnn10010111", "LDC.L @$N+, R1_BANK"},
    {"0100nnnn10100111", "LDC.L @$N+, R2_BANK"},
    {"0100nnnn10110111", "LDC.L @$N+, R3_BANK"},
    {"0100nnnn11000111", "LDC.L @$N+, R4_BANK"},
    {"0100nnnn11010111", "LDC.L @$N+, R5_BANK"},
    {"0100nnnn11100111", "LDC.L @$N+, R6_BANK"},
    {"0100nnnn11110111", "LDC.L @$N+, R7_BANK"},
    {"0100nnnn00001010", "LDS $N, MACH"},
    {"0100nnnn00011010", "LDS $N, MACL"},
    {"0100nnnn00101010", "LDS $N, PR"},
    {"0100nnnn00000110", "LDS.L @$N+, MACH"},
    {"0100nnnn00010110", "LDS.L @$N+, MACL"},
    {"0100nnnn00100110", "LDS.L @$N+, PR"},
    {"0000000000111000", "LDTLB"},
    {"0000nnnnmmmm1111", "MAC.L $M, $N"},
    {"0100nnnnmmmm1111", "MAC.W $M, $N"},
    {"0110nnnnmmmm0011", "MOV $M, $N"},
    {"0010nnnnmmmm0000", "MOV.B $M, @$N"},
    {"0010nnnnmmmm0001", "MOV.W $M, @$N"},
    {"0010nnnnmmmm0010", "MOV.L $M, @$N"},
    {"0110nnnnmmmm0000", "MOV.B @$M, $N"},
    {"0110nnnnmmmm0001", "MOV.W @$M, $N"},
    {"0110nnnnmmmm0010", "MOV.L @$M, $N"},
    {"0010nnnnmmmm0100", "MOV.B $M, @-$N"},
    {"0010nnnnmmmm0101", "MOV.W $M, @-$N"},
    {"0010nnnnmmmm0110", "MOV.L $M, @-$N"},
    {"0110nnnnmmmm0100", "MOV.B @$M+, $N"},
    {"0110nnnnmmmm0101", "MOV.W @$M+, $N"},
    {"0110nnnnmmmm0110", "MOV.L @$M+, $N"},
    {"0000nnnnmmmm0100", "MOV.B $M, @(R0, $N)"},
    {"0000nnnnmmmm0101", "MOV.W $M, @(R0, $N)"},
    {"0000nnnnmmmm0110", "MOV.L $M, @(R0, $N)"},
    {"0000nnnnmmmm1100", "MOV.B @(R0, $M), $N"},
    {"0000nnnnmmmm1101", "MOV.W @(R0, $M), $N"},
    {"0000nnnnmmmm1110", "MOV.L @(R0, $M), $N"},
    {"1110nnnniiiiiiii", "MOV #$I, $N"},
    {"1001nnnnpppppppp", "MOV.W @($P, PC), $N"},
    {"1101nnnnpppppppp", "MOV.L @($P, PC), $N"},
    {"11000100pppppppp", "MOV.B @($P, GBR), R0"},
    {"11000101pppppppp", "MOV.W @($P, GBR), R0"},
    {"11000110pppppppp", "MOV.L @($P, GBR), R0"},
    {"11000000pppppppp", "MOV.B R0, @($P, GBR)"},
    {"11000001pppppppp", "MOV.W R0, @($P, GBR)"},
    {"11000010pppppppp", "MOV.L R0, @($P, GBR)"},
    {"10000000mmmmssss", "MOV.B R0, @($S, $M)"},
    {"10000001mmmmssss", "MOV.W R0, @($S, $M)"},
    {"0001nnnnmmmmssss", "MOV.L $M, @($S, $N)"},
    {"10000100mmmmssss", "MOV.B @($S, $M), R0"},
    {"10000101mmmmssss", "MOV.W @($S, $M), R0"},
    {"0101nnnnmmmmssss", "MOV.L @($S, $N), $M"},


//
//  Калькулятор nlock-кодов для модемов Huawei с новым алгоритмом v201
//
//  Автор - forth32
//  2014 год
//
//  Ветка для вычисления кодов с индексом 7
//

#include "encrypt.h"
#include <cstring>
#include <cstdio>

void rehash7_2(int* hash,int* srcbuf) {

int r4,r5,r6,r7,r10,lr;
int inthash[30];

memcpy(inthash+1,srcbuf,64);  // переносим 16 слов в inthash

r4=hash[0];
r6=hash[1];
r7=hash[2];
r5=hash[3];
//--------- часть 1 --------

#define encpass1(hconst,nbyte,shift,rsum,ra,rb,rc) \
 rsum=ra+rotr32(rsum+inthash[nbyte/4]+((ra&rb)|(rc&(~ra)))+hconst,shift);

// r4=r6+rotr32(r4+inthash[4/4]+(r6&r7|(r5&(~r6)))+0xD76AA478,25);
// rs ra        rs          nb   ra rb  rc   ra               sh

encpass1(0xD76AA478,0x04,25,r4,r6,r7,r5)   // RAM:50D8A7F8
encpass1(0xE8C7B756,0x08,20,r5,r4,r6,r7)   // RAM:50D8A824
encpass1(0x242070DB,0x0c,15,r7,r5,r4,r6)   // RAM:50D8A84c
encpass1(0xC1BDCEEE,0x10,10,r6,r7,r5,r4)   // RAM:50D8A870

encpass1(0xF57C0FAF,0x14,25,r4,r6,r7,r5)   // RAM:50D8A898
encpass1(0x4787C62A,0x18,20,r5,r4,r6,r7)   // RAM:50D8A8c0
encpass1(0xA8304613,0x1c,15,r7,r5,r4,r6)   // RAM:50D8A8ec
encpass1(0xFD469501,0x20,10,r6,r7,r5,r4)   // RAM:50D8A914

encpass1(0x698098D8,0x24,25,r4,r6,r7,r5)   // RAM:50D8A938
encpass1(0x8B44F7AF,0x28,20,r5,r4,r6,r7)   // RAM:50D8A960
encpass1(0xffff5bb1,0x2c,15,r7,r5,r4,r6)   // RAM:50D8A988
encpass1(0x895CD7BE,0x30,10,r6,r7,r5,r4)   // RAM:50D8A9b0

encpass1(0x6B901122,0x34,25,r4,r6,r7,r5)   // RAM:50D8A9d8
encpass1(0xFD987193,0x38,20,r5,r4,r6,r7)   // RAM:50D8AA00
encpass1(0xA679438E,0x3c,15,r7,r5,r4,r6)   // RAM:50D8Aa28
encpass1(0x49B40821,0x40,10,r6,r7,r5,r4)   // RAM:50D8Aa54

//-------- алгоритм 2 --------------

//r4=r6+rotr32(r4+inthash[8/4]+(r6&r5|(r7&(~r5)))+0xF61E2562,27);
//rs ra        rs               ra rb  rc   rb

#define encpass2(hconst,nbyte,shift,rsum,ra,rb,rc) \
 rsum=ra+rotr32(rsum+inthash[nbyte/4]+((ra&rb)|(rc&(~rb)))+hconst,shift);

encpass2(0xF61E2562,0x08,27,r4,r6,r5,r7)   // 50d8aa78
encpass2(0xC040B340,0x1c,23,r5,r4,r7,r6)   // 50d8aa98
encpass2(0x265E5A51,0x30,18,r7,r5,r6,r4)   // 50d8aabc
encpass2(0xE9B6C7AA,0x04,12,r6,r7,r4,r5)   // 50d8aae4

encpass2(0xD62F105D,0x18,27,r4,r6,r5,r7)   // 50d8ab0c
encpass2(0x02441453,0x2c,23,r5,r4,r7,r6)   // 50d8ab38
encpass2(0xD8A1E681,0x40,18,r7,r5,r6,r4)   // 50d8ab5c
encpass2(0xE7D3FBC8,0x14,12,r6,r7,r4,r5)   // 50d8ab80

encpass2(0x21E1CDE6,0x28,27,r4,r6,r5,r7)   // 50d8aba8
encpass2(0xC33707D6,0x3c,23,r5,r4,r7,r6)   // 50d8abcc
encpass2(0xF4D50D87,0x10,18,r7,r5,r6,r4)   // 50d8abf4
encpass2(0x455A14ED,0x24,12,r6,r7,r4,r5)   // 50d8ac20

encpass2(0xA9E3E905,0x38,27,r4,r6,r5,r7)   // 50d8ac44
encpass2(0xFCEFA3F8,0x0c,23,r5,r4,r7,r6)   // 50d8ac6c
encpass2(0x676F02D9,0x20,18,r7,r5,r6,r4)   // 50d8ac94
encpass2(0x8D2A4C8A,0x34,12,r6,r7,r4,r5)   // 50d8acc0

// Алгоритм 3

//r4=r6+rotr32(r4+inthash[0x18/4]+(r5^r7^r6)+0xFFFA3942,28);
//rs  ra       rs                  rb rc ra

#define encpass3(hconst,nbyte,shift,rsum,ra,rb,rc) \
 rsum=ra+rotr32(rsum+inthash[nbyte/4]+(rb^rc^ra)+hconst,shift);

encpass3(0xFFFA3942,0x18,28,r4,r6,r5,r7)  //50D8ACDC
encpass3(0x8771F681,0x24,21,r5,r4,r7,r6)  //50D8Acfc
encpass3(0x6D9D6122,0x30,16,r7,r5,r6,r4)  //50D8Ad18
encpass3(0xFDE5380C,0x3c,9 ,r6,r7,r4,r5)  //50D8Ad34

encpass3(0xA4BEEA44,0x08,28,r4,r6,r5,r7)  //50D8Ad54
encpass3(0x4BDECFA9,0x14,21,r5,r4,r7,r6)  //50D8Ad70
encpass3(0xF6BB4B60,0x20,16,r7,r5,r6,r4)  //50D8AD94
encpass3(0xBEBFBC70,0x2c,9 ,r6,r7,r4,r5)  //50D8ADB0

encpass3(0x289B7EC6,0x38,28,r4,r6,r5,r7)  //50D8ADD0
encpass3(0xEAA127FA,0x04,21,r5,r4,r7,r6)  //50D8ADF0
encpass3(0xD4EF3085,0x10,16,r7,r5,r6,r4)  //50D8AE14
encpass3(0x04881D05,0x1c,9 ,r6,r7,r4,r5)  //50D8AE30

encpass3(0xD9D4D039,0x28,28,r4,r6,r5,r7)  //50D8AE50
encpass3(0xE6DB99E5,0x34,21,r5,r4,r7,r6)  //50D8AE70
encpass3(0x1FA27CF8,0x40,16,r7,r5,r6,r4)  //50D8AE94
encpass3(0xC4AC5665,0x0c,9 ,r6,r7,r4,r5)  //50D8AEB0

// Алгоритм 4
// смена регистра   r4 --> r0

// r0=r6+rotr32(r0+inthash[4/4]+((~r5|r6)^r7)+0xF4292244,26);
// rs ra        rs                 rb ra  rc

#define encpass4(hconst,nbyte,shift,rsum,ra,rb,rc) \
 rsum=ra+rotr32(rsum+inthash[nbyte/4]+((~rb|ra)^rc)+hconst,shift);

encpass4(0xF4292244,0x04,26,r4,r6,r5,r7)  // 50d8aed4
// смена регистра   r5 --> r1
encpass4(0x432AFF97,0x20,22,r5,r4,r7,r6)  // 50d8aef8
encpass4(0xAB9423A7,0x3c,17,r7,r5,r6,r4)  // 50d8af18
encpass4(0xFC93A039,0x18,11,r6,r7,r4,r5)  // 50d8af3c

encpass4(0x655B59C3,0x34,26,r4,r6,r5,r7)  // 50d8af60
encpass4(0x8F0CCC92,0x10,22,r5,r4,r7,r6)  // 50d8aF88
encpass4(0xFFEFF47D,0x2c,17,r7,r5,r6,r4)  // 50d8aFB4
encpass4(0x85845DD1,0x08,11,r6,r7,r4,r5)  // 50d8aFD4

encpass4(0x6FA87E4F,0x24,26,r4,r6,r5,r7)  // 50d8AFFC
encpass4(0xFE2CE6E0,0x40,22,r5,r4,r7,r6)  // 50d8B020
encpass4(0xA3014314,0x1c,17,r7,r5,r6,r4)  // 50d8B044
encpass4(0x4E0811A1,0x38,11,r6,r7,r4,r5)  // 50d8B068

encpass4(0xF7537E82,0x14,26,r4,r6,r5,r7)  // 50d8B088
encpass4(0xBD3AF235,0x30,22,r5,r4,r7,r6)  // 50d8B0A8
encpass4(0x2AD7D2BB


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

struct Token {
    string type;
    string value;
};

struct Node {
    virtual ~Node() = default;
};

struct Declaration : Node {
    string name;
    int value;
    Declaration(string n, int v) : name(n), value(v) {}
};

struct Expression : Node {
    string left, op, right;
    Expression(string l, string o, string r) : left(l), op(o), right(r) {}
};

vector<Token> lexer(const string &input) {
    vector<Token> tokens;
    int cursor = 0, l = input.length();

    while (cursor < l) {
        if (isspace(input[cursor])) { cursor++; continue; }

        if (isalpha(input[cursor])) {
            string word = "";
            while (cursor < l && isalpha(input[cursor])) {
                word += input[cursor++];
            }
            if (word == "number" || word == "is" || word == "and" || word == "give") {
                tokens.push_back({"keyword", word});
            } else {
                tokens.push_back({"identifier", word});
            }
            continue;
        }

        if (isdigit(input[cursor])) {
            string num = "";
            while (cursor < l && isdigit(input[cursor])) {
                num += input[cursor++];
            }
            tokens.push_back({"number", num});
            continue;
        }

        tokens.push_back({"symbol", string(1, input[cursor++])});
    }

    return tokens;
}

int pos = 0;

bool match(vector<Token> &tokens, string type, string value = "") {
    if (pos < tokens.size() && tokens[pos].type == type &&
        (value == "" || tokens[pos].value == value)) {
        pos++;
        return true;
    }
    return false;
}

Token peek(vector<Token> &tokens) {
    if (pos < tokens.size()) return tokens[pos];
    return {"EOF", ""};
}

void expect(vector<Token> &tokens, string type, string value = "") {
    if (!match(tokens, type, value)) {
        exit(1);
    }
}

Declaration* parseDeclaration(vector<Token> &tokens) {
    expect(tokens, "keyword", "number");
    Token id = peek(tokens); expect(tokens, "identifier");
    expect(tokens, "keyword", "is");
    Token num = peek(tokens); expect(tokens, "number");
    return new Declaration(id.value, stoi(num.value));
}

Expression* parseExpression(vector<Token> &tokens) {
    expect(tokens, "keyword", "give");
    Token left = peek(tokens); expect(tokens, "identifier");
    Token op   = peek(tokens); expect(tokens, "symbol");
    Token right= peek(tokens); expect(tokens, "identifier");
    return new Expression(left.value, op.value, right.value);
}

vector<Node*> parseProgram(vector<Token> &tokens) {
    vector<Node*> ast;
    ast.push_back(parseDeclaration(tokens));

    while (match(tokens, "keyword", "and")) {
        if (peek(tokens).value == "number") {
            ast.push_back(parseDeclaration(tokens));
        } else {
            ast.push_back(parseExpression(tokens));
            break;
        }
    }
    return ast;
}

void generateCode(vector<Node*> ast, const string &filename) {
    ofstream out(filename);
    if (!out.is_open()) return;

    out << "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n";

    for (auto node : ast) {
        if (auto decl = dynamic_cast<Declaration*>(node)) {
            out << "    int " << decl->name << " = " << decl->value << ";\n";
        } else if (auto expr = dynamic_cast<Expression*>(node)) {
            out << "    cout << " << expr->left << " " << expr->op << " " << expr->right << " << endl;\n";
        }
    }

    out << "    return 0;\n}\n";
    out.close();
}

int main() {
    string input = "number x is 10 and number y is 20 and give x+y";
    vector<Token> tokens = lexer(input);
    vector<Node*> ast = parseProgram(tokens);
    generateCode(ast, "output.cpp");
    for (auto node : ast) delete node;
    return 0;
}


#include<iostream>
using namespace std;
void linear_search (int array[],int size,int n)
{
    int temp =-1;
    for(int i=0;i<size;i++)
    {
        if(array[i]==n)
        {
          cout<<"Element found of position:"<<i+1<<endl;
          temp =0;
          break;
        }
    }
    if(temp == -1)
    {
        cout<<"Element not found"<<endl;
    }
}
  int linear_search1 (int array[],int size,int n)
{
    int temp =-1;
    for(int i=0;i<size;i++)
    {
        if(array[i]==n)
        {
          temp =0;
          return temp;
        }
    }
    if(temp == -1)
    {
       return temp;
    }
}

int main ()
{
    int size;
    cout<<"enter Size"<<endl;
    cin>>size;
    int array[size];
    cout<<"Enter the element"<<endl;
    for(int i=0;i<size;i++)
    {
        cin>>array[i];
    }

    int number;
    cout<<"enter the element of search"<<endl;
    cin>>number;
    if(linear_search1(array,size,number)==-1)
    {
        cout<<"not found"<<endl;
    }
    else
        cout<<"found"<<endl;

    return 0;

}


#include "stealth_address.h"
#include <iostream>
#include <random>

StealthAddress::StealthAddress() {
  // Constructor
}

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

void StealthAddress::initialize() {
  std::cout << "Initializing Stealth Address system..." << std::endl;
  std::cout << "Generating one-time addresses for each transaction"
            << std::endl;
  std::cout << "Ensuring no link between public address and transactions"
            << std::endl;
}

std::string
StealthAddress::generateAddress(const std::string &recipient_public_key) {
  // In practice, this would use elliptic curve operations
  // to generate a one-time address

  // For demonstration, we'll generate a pseudo-address
  std::random_device rd;
  std::mt19937 gen(rd());
  std::uniform_int_distribution<> dis(0, 15);

  std::string stealth_address = "dg1";
  for (int i = 0; i < 40; i++) {
    char hex_chars[] = "0123456789abcdef";
    stealth_address += hex_chars[dis(gen)];
  }

  std::cout << "Generated stealth address: " << stealth_address << std::endl;
  return stealth_address;
}

std::vector<std::string> StealthAddress::scanTransactions(
    const std::string &view_key,
    const std::vector<std::string> &blockchain_transactions) {
  std::vector<std::string> owned_transactions;

  // In practice, this would use the view key to scan the blockchain
  // and identify which transactions belong to the recipient

  std::cout << "Scanning blockchain with view key..." << std::endl;

  // For demonstration, we'll just return an empty vector
  return owned_transactions;
}

std::pair<std::string, std::string> StealthAddress::generateKeyPair() {
  // In practice, this would generate proper cryptographic key pairs

  // For demonstration, we'll generate pseudo-keys
  std::random_device rd;
  std::mt19937 gen(rd());
  std::uniform_int_distribution<> dis(0, 15);

  std::string private_key = "";
  std::string public_key = "";

  for (int i = 0; i < 64; i++) {
    char hex_chars[] = "0123456789abcdef";
    private_key += hex_chars[dis(gen)];
    public_key += hex_chars[dis(gen)];
  }

  return std::make_pair(private_key, public_key);
}


#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
#include <algorithm>

// Single-header JSON library by nlohmann
#include "json.hpp"

// Single-header BigInt library by matt-42
#include "BigInt.hpp"

// Use nlohmann's json and the BigInt library
using json = nlohmann::json;

// Function to convert a string representation of a number from any base to BigInt
BigInt stringToBigInt(const std::string& s, int base) {
    BigInt res = 0;
    BigInt p = 1;

    for (int i = s.length() - 1; i >= 0; i--) {
        int digit;
        if (s[i] >= '0' && s[i] <= '9') {
            digit = s[i] - '0';
        } else if (s[i] >= 'a' && s[i] <= 'f') {
            digit = s[i] - 'a' + 10;
        } else {
            throw std::invalid_argument("Invalid character in number string");
        }
        if (digit >= base) {
            throw std::invalid_argument("Digit exceeds base");
        }
        res = res + p * digit;
        p = p * base;
    }
    return res;
}

int main() {
    // Read the entire input into a JSON object
    json input;
    try {
        std::cin >> input;
    } catch (json::parse_error& e) {
        std::cerr << "JSON parsing error: " << e.what() << std::endl;
        return 1;
    }

    // Extract k, the number of points needed
    int k = input["keys"]["k"];

    // Store the points (x, y) as BigInts
    std::vector<std::pair<BigInt, BigInt>> points;

    // The keys "1", "2", etc. in the JSON are the x-values.
    // The inner 'base' and 'value' are used to calculate the y-values.
    for (auto& item : input.items()) {
        if (item.key() != "keys") {
            BigInt x = std::stoi(item.key());
            std::string val_str = item.value()["value"];
            int base = std::stoi(item.value()["base"].get<std::string>());
            BigInt y = stringToBigInt(val_str, base);
            points.push_back({x, y});
        }
    }

    // We only need k points to solve for the k coefficients
    if (points.size() < k) {
        std::cerr << "Error: Not enough points provided to solve the polynomial." << std::endl;
        return 1;
    }

    // Construct the augmented matrix [A|b] for the system Ax = b
    // where x is the vector of polynomial coefficients [a0, a1, ..., a(k-1)]
    std::vector<std::vector<BigInt>> matrix(k, std::vector<BigInt>(k + 1));

    for (int i = 0; i < k; ++i) {
        BigInt x = points[i].first;
        BigInt y = points[i].second;

        // The last column is the y value
        matrix[i][k] = y;

        // Fill the powers of x: x^0, x^1, x^2, ...
        BigInt x_pow = 1;
        for (int j = 0; j < k; ++j) {
            matrix[i][j] = x_pow;
            x_pow *= x;
        }
    }

    // --- Gaussian Elimination ---
    // Goal: Convert the matrix to row echelon form (upper triangular)
    for (int i = 0; i < k; ++i) {
        // Find pivot (non-zero element)
        int pivot_row = i;
        while (pivot_row < k && matrix[pivot_row][i] == 0) {
            pivot_row++;
        }

        if (pivot_row == k) {
            std::cerr << "Matrix is singular, cannot solve uniquely." << std::endl;
            return 1;
        }
        std::swap(matrix[i], matrix[pivot_row]);

        // Eliminate column i for all rows below row i
        for (int j = i + 1; j < k; ++j) {
            // To avoid fractions, we use cross-multiplication:
            // Row[j] = Row[j] * pivot_val - Row[i] * current_val
            BigInt pivot_val = matrix[i][i];
            BigInt current_val = matrix[j][i];

            for (int l = i; l <= k; ++l) {
                matrix[j][l] = matrix[j][l] * pivot_val - matrix[i][l] * current_val;
            }
        }
    }

    // --- Back Substitution ---
    // Goal: Solve for the coefficients from the bottom up
    std::vector<BigInt> coeffs(k);
    for (int i = k - 1; i >= 0; --i) {
        BigInt sum = 0;
        for (int j = i + 1; j < k; ++j) {
            sum += matrix[i][j] * coeffs[j];
        }

        // Solve for the coefficient a_i
        // matrix[i][i] * a_i = matrix[i][k] - sum
        coeffs[i] = (matrix[i][k] - sum) / matrix[i][i];
    }

    // The constant term is the first coefficient, a0
    std::cout << "The constant term (secret) is: " << coeffs[0] << std::endl;

    return 0;
}


// NBGameModeBase.cpp
#include "NBGameModeBase.h"

#include "EngineUtils.h"
#include "NBGameStateBase.h"
#include "Player/NBPlayerController.h"
#include "Player/NBPlayerState.h"

void ANBGameModeBase::OnPostLogin(AController* NewPlayer)
{
	Super::OnPostLogin(NewPlayer);

	ANBPlayerController* NBPlayerController = Cast<ANBPlayerController>(NewPlayer);
	if (IsValid(NBPlayerController))
	{
		NBPlayerController->NotificationText = FText::FromString(TEXT("Connected to the Game Server."));
		AllPlayerControllers.Add(NBPlayerController);

		ANBPlayerState* NBPS = NBPlayerController->GetPlayerState<ANBPlayerState>();
		if (IsValid(NBPS))
		{
			NBPS->PlayerNameString = TEXT("Player") + FString::FromInt(AllPlayerControllers.Num());
		}

		ANBGameStateBase* NBGameStateBase = GetGameState<ANBGameStateBase>();
		if (IsValid(NBGameStateBase))
		{
			NBGameStateBase->MulticastRPCBroadcastLoginMessage(NBPS->PlayerNameString);
		}
	}

	// ADD : 첫 번째 플레이어 접속시 최초 턴 시작
	if (AllPlayerControllers.Num() == 1)
	{
		BeginTurn(NBPlayerController);
	}
}

void ANBGameModeBase::BeginPlay()
{
	Super::BeginPlay();
	SecretNumberString = GenerateSecretNumber();
}

void ANBGameModeBase::Logout(AController* Exiting)
{
	Super::Logout(Exiting);

	ANBPlayerController* NBPlayerController = Cast<ANBPlayerController>(Exiting);
	if (IsValid(NBPlayerController))
	{
		if (CurrentTurnPlayer == NBPlayerController)	// 게임 도중 나가면 턴 강제종료
		{
			EndTurn();
		}
		AllPlayerControllers.Remove(NBPlayerController);
	}
}

FString ANBGameModeBase::GenerateSecretNumber()
{
	TArray<int32> Numbers;
	for (int32 i = 1; i <= 9; ++i)
	{
		Numbers.Add(i);
	}

	FMath::RandInit(FDateTime::Now().GetTicks());
	Numbers = Numbers.FilterByPredicate([](int32 Num) { return Num > 0; });	// TODO: 의미가 있나 이 코드가?

	FString Result;
	for (int32 i = 1; i <= 3; ++i)
	{
		int32 Index = FMath::RandRange(0, Numbers.Num() - 1);
		Result.Append(FString::FromInt(Numbers[Index]));
		Numbers.RemoveAt(Index);
	}
	UE_LOG(LogTemp, Warning, TEXT("Secret Number : %s"), *Result);
	return Result;
}

bool ANBGameModeBase::IsGuessNumberString(const FString& InNumberString)
{
	bool bCanPlay = false;

	do
	{
		if (InNumberString.Len() != 3)
		{
			break;
		}
		bool bIsUnique = true;
		TSet<TCHAR> UniqueDigits;
		for (TCHAR C : InNumberString)
		{
			if (!FChar::IsDigit(C) || C == '0')
			{
				bIsUnique = false;
				break;
			}
			UniqueDigits.Add(C);
		}

		if (!bIsUnique)
		{
			break;
		}
		bCanPlay = true;
	}while (false);	// early return 대신 scope를 break로 탈출하기 위함

	return bCanPlay;
}

FString ANBGameModeBase::JudgeResult(const FString& InSecretNumberString, const FString& InGuessNumberString)
{
	int32 StrikeCount = 0, BallCount = 0;

	for (int32 i = 0; i < 3; ++i)
	{
		if (InSecretNumberString[i] == InGuessNumberString[i])
		{
			++StrikeCount;
		}
		else
		{
			FString PlayerGuessChar = FString::Printf(TEXT("%c"), InGuessNumberString[i]);
			if (InSecretNumberString.Contains(PlayerGuessChar))
			{
				++BallCount;
			}
		}
	}

	if (StrikeCount == 0 && BallCount == 0)
	{
		return TEXT("OUT");
	}
	return FString::Printf(TEXT("%dS %dB"), StrikeCount, BallCount);
}

void ANBGameModeBase::PrintChatMessageString(ANBPlayerController* InChattingPlayerController,
	const FString& InChatMessageString)
{
	FString ChatMessageString = InChatMessageString;
	int32 Index = InChatMessageString.Len() - 3;

	FString GuessNumberString = InChatMessageString.RightChop(Index);	// 오른쪽부터 Index 개수만큼 제거해서 새로운 문자열 반환(왼쪽 3개만 남도록)
	if (IsGuessNumberString(GuessNumberString))
	{
		// 새 게임 대기시간에는 정답 외치기 불가
		if (!bIsGamePlaying)
		{
			InChattingPlayerController->ClientRPCPrintChatMessageString(TEXT("새 게임 시작을 기다리는 중입니다."));
			return;
		}

		// 자신의 턴이 아니면 정답 외치기 불가
		if (InChattingPlayerController != CurrentTurnPlayer)
		{
			InChattingPlayerController->ClientRPCPrintChatMessageString(TEXT("지금은 당신의 턴이 아닙니다."));
			return;
		}

		ANBPlayerState* NBPS = InChattingPlayerController->GetPlayerState<ANBPlayerState>();
		if (IsValid(NBPS) && NBPS->TimeRemainingForTurn <= 0)
		{
			InChattingPlayerController->ClientRPCPrintChatMessageString(TEXT("턴 시간이 모두 소진되었습니다."));
			return;
		}

		FString JudgeResultString = JudgeResult(SecretNumberString, GuessNumberString);	// OUT, 1S2B ...
		// EndTurn();	// 정답 1회 외치면 턴 종료, 여기서 GuessCount 증가시키기
		IncreaseGuessCount(InChattingPlayerController);

		// ADD : 업데이트된 PlayerInfoString으로 변경(GuessCount)
		// ANBPlayerState* NBPS = InChattingPlayerController->GetPlayerState<ANBPlayerState>();
		FString PlayerInfoString = TEXT("");
		if (IsValid(NBPS))
		{
			PlayerInfoString = NBPS->GetPlayerInfoString();
			PlayerInfoString = PlayerInfoString + InChatMessageString.RightChop(PlayerInfoString.Len());
		}

		for (TActorIterator<ANBPlayerController> It(GetWorld()); It; ++It)
		{
			ANBPlayerController* NBPlayerController = *It;
			if (IsValid(NBPlayerController))
			{
				// FString CombinedMessageString = InChatMessageString + TEXT(" → ") + JudgeResultString;
				FString CombinedMessageString = PlayerIn


// dear imgui: FreeType font builder (used as a replacement for the stb_truetype builder)
// (code)

// Get the latest version at https://github.com/ocornut/imgui/tree/master/misc/freetype
// Original code by @vuhdo (Aleksei Skriabin). Improvements by @mikesart. Maintained since 2019 by @ocornut.

// CHANGELOG
// (minor and older changes stripped away, please see git history for details)
//  2021/08/23: fixed crash when FT_Render_Glyph() fails to render a glyph and returns NULL.
//  2021/03/05: added ImGuiFreeTypeBuilderFlags_Bitmap to load bitmap glyphs.
//  2021/03/02: set 'atlas->TexPixelsUseColors = true' to help some backends with deciding of a prefered texture format.
//  2021/01/28: added support for color-layered glyphs via ImGuiFreeTypeBuilderFlags_LoadColor (require Freetype 2.10+).
//  2021/01/26: simplified integration by using '#define IMGUI_ENABLE_FREETYPE'.
//              renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API. removed ImGuiFreeType::BuildFontAtlas().
//  2020/06/04: fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails.
//  2019/02/09: added RasterizerFlags::Monochrome flag to disable font anti-aliasing (combine with ::MonoHinting for best results!)
//  2019/01/15: added support for imgui allocators + added FreeType only override function SetAllocatorFunctions().
//  2019/01/10: re-factored to match big update in STB builder. fixed texture height waste. fixed redundant glyphs when merging. support for glyph padding.
//  2018/06/08: added support for ImFontConfig::GlyphMinAdvanceX, GlyphMaxAdvanceX.
//  2018/02/04: moved to main imgui repository (away from http://www.github.com/ocornut/imgui_club)
//  2018/01/22: fix for addition of ImFontAtlas::TexUvscale member.
//  2017/10/22: minor inconsequential change to match change in master (removed an unnecessary statement).
//  2017/09/26: fixes for imgui internal changes.
//  2017/08/26: cleanup, optimizations, support for ImFontConfig::RasterizerFlags, ImFontConfig::RasterizerMultiply.
//  2017/08/16: imported from https://github.com/Vuhdo/imgui_freetype into http://www.github.com/ocornut/imgui_club, updated for latest changes in ImFontAtlas, minor tweaks.

// About Gamma Correct Blending:
// - FreeType assumes blending in linear space rather than gamma space.
// - See https://www.freetype.org/freetype2/docs/reference/ft2-base_interface.html#FT_Render_Glyph
// - For correct results you need to be using sRGB and convert to linear space in the pixel shader output.
// - The default dear imgui styles will be impacted by this change (alpha values will need tweaking).

// FIXME: cfg.OversampleH, OversampleV are not supported (but perhaps not so necessary with this rasterizer).

#include "imgui_freetype.h"
#include "imgui_internal.h"     // ImMin,ImMax,ImFontAtlasBuild*,
#include <stdint.h>
#include <ft2build.h>
#include FT_FREETYPE_H          // <freetype/freetype.h>
#include FT_MODULE_H            // <freetype/ftmodapi.h>
#include FT_GLYPH_H             // <freetype/ftglyph.h>
#include FT_SYNTHESIS_H         // <freetype/ftsynth.h>

#ifdef _MSC_VER
#pragma warning (disable: 4505)     // unreferenced local function has been removed (stb stuff)
#pragma warning (disable: 26812)    // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
#endif

#if defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wpragmas"                  // warning: unknown option after '#pragma GCC diagnostic' kind
#pragma GCC diagnostic ignored "-Wunused-function"          // warning: 'xxxx' defined but not used
#endif

//-------------------------------------------------------------------------
// Data
//-------------------------------------------------------------------------

// Default memory allocators
static void* ImGuiFreeTypeDefaultAllocFunc(size_t size, void* user_data) { IM_UNUSED(user_data); return IM_ALLOC(size); }
static void  ImGuiFreeTypeDefaultFreeFunc(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_FREE(ptr); }

// Current memory allocators
static void* (*GImGuiFreeTypeAllocFunc)(size_t size, void* user_data) = ImGuiFreeTypeDefaultAllocFunc;
static void  (*GImGuiFreeTypeFreeFunc)(void* ptr, void* user_data) = ImGuiFreeTypeDefaultFreeFunc;
static void* GImGuiFreeTypeAllocatorUserData = NULL;

//-------------------------------------------------------------------------
// Code
//-------------------------------------------------------------------------

namespace
{
    // Glyph metrics:
    // --------------
    //
    //                       xmin                     xmax
    //                        |                         |
    //                        |<-------- width -------->|
    //                        |                         |
    //              |         +-------------------------+----------------- ymax
    //              |         |    ggggggggg   ggggg    |     ^        ^
    //              |         |   g:::::::::ggg::


#include <iostream>
#include <vector>
#include <string>

// core components
#include "../include/rocket/core/subscription.hpp"
#include "../include/rocket/core/actor.hpp"
#include "../include/rocket/core/observable.hpp"

// observables
#include "../include/rocket/observables/single.hpp"
#include "../include/rocket/observables/from_array.hpp"

// actors
#include "../include/rocket/actors/logger_actor.hpp"

// operators (corresponding to Julia files)
#include "../include/rocket/operators/simple_map.hpp"
#include "../include/rocket/operators/simple_filter.hpp"
#include "../include/rocket/operators/scan.hpp"
#include "../include/rocket/operators/take.hpp"
#include "../include/rocket/operators/tap.hpp"
#include "../include/rocket/operators/start_with.hpp"
#include "../include/rocket/operators/last.hpp"
#include "../include/rocket/operators/count.hpp"
#include "../include/rocket/operators/reduce.hpp"

int main() {
    std::cout << "=== Julia Operators Conversion Test ===" << std::endl;
    std::cout << "Testing C++ implementations that correspond to Julia Rocket.jl operators\n" << std::endl;

    // test 1: last operator (corresponding to last.jl)
    std::cout << "1. last.jl → last.hpp:" << std::endl;
    auto source1 = rocket::observables::from({1, 2, 3, 4, 5});
    auto last_result = source1 | rocket::operators::last();
    auto logger1 = rocket::actors::make_logger<int>("Last");
    rocket::subscribe(last_result, logger1);

    // test 2: last operator with default (corresponding to last.jl with default)
    std::cout << "\n2. last.jl with default:" << std::endl;
    auto empty_source = rocket::observables::from(std::vector<int>{});
    auto last_with_default = empty_source | rocket::operators::last(42);
    auto logger2 = rocket::actors::make_logger<int>("LastDefault");
    rocket::subscribe(last_with_default, logger2);

    // test 3: count operator (corresponding to count.jl)
    std::cout << "\n3. count.jl → count.hpp:" << std::endl;
    auto source3 = rocket::observables::from({10, 20, 30, 40, 50});
    auto count_result = source3 | rocket::operators::count();
    auto logger3 = rocket::actors::make_logger<int>("Count");
    rocket::subscribe(count_result, logger3);

    // test 4: reduce operator with seed (corresponding to reduce.jl)
    std::cout << "\n4. reduce.jl with seed → reduce.hpp:" << std::endl;
    auto source4 = rocket::observables::from({1, 2, 3, 4, 5});
    auto reduce_sum = source4 | rocket::operators::reduce([](int a, int b) { return a + b; }, 0);
    auto logger4 = rocket::actors::make_logger<int>("ReduceSum");
    rocket::subscribe(reduce_sum, logger4);

    // test 5: reduce operator without seed (corresponding to reduce.jl)
    std::cout << "\n5. reduce.jl without seed → reduce.hpp:" << std::endl;
    auto source5 = rocket::observables::from({1, 2, 3, 4, 5});
    auto reduce_product = source5 | rocket::operators::reduce([](int a, int b) { return a * b; });
    auto logger5 = rocket::actors::make_logger<int>("ReduceProduct");
    rocket::subscribe(reduce_product, logger5);

    // test 6: reduce with type change (corresponding to reduce.jl with type specification)
    std::cout << "\n6. reduce.jl with type change → reduce.hpp:" << std::endl;
    auto source6 = rocket::observables::from({1, 2, 3, 4});
    auto reduce_string = source6 | rocket::operators::reduce<std::string>(
        [](int val, const std::string& acc) {
            return acc + std::to_string(val) + ",";
        },
        std::string("Numbers: ")
    );
    auto logger6 = rocket::actors::make_logger<std::string>("ReduceString");
    rocket::subscribe(reduce_string, logger6);

    // test 7: complex operator chain combining multiple Julia operators
    std::cout << "\n7. Complex Julia operator chain:" << std::endl;
    auto source7 = rocket::observables::from({1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
    auto complex_chain = source7
        | rocket::operators::filter([](int x) { return x % 2 == 0; })  // filter.jl
        | rocket::operators::tap([](int x) {                           // tap.jl
            std::cout << "  [TAP] Even number: " << x << std::endl;
        })
        | rocket::operators::map<int>([](int x) { return x * x; })     // map.jl
        | rocket::operators::take(3)                                   // take.jl
        | rocket::operators::scan([](int a, int b) { return a + b; }, 0); // scan.jl
    auto logger7 = rocket::actors::make_logger<int>("ComplexChain");
    rocket::subscribe(complex_chain, logger7);

    // test 8: terminal operators comparison
    std::cout << "\n8. Terminal operators comparison:" << std::endl;
    auto source8 = rocket::observables::from({10, 5, 8, 3, 12, 7});

    std::cout << "   count(): ";
    auto count8 = source8 | rocket::operators::count();
    auto logger8a = rocket::actors::make_logger<int>("Count8");
    rocket::subscribe(count8, logger8a);

    std::cout << "   last(): ";
    auto last8 = source8 | rocket::operators::last(


#include <iostream>

#include "mlcpppy/classifiers/neighbors/kdtree.h"

int main(int argc, char const *argv[]) {
        double x, y;
        int k;
        if (argc < 4) {
                std::cerr << "Uso: " << argv[0] << " <x> <y> <k>\n";
                x = 7;
                y = 4;
                k = 2;
                // return 1;
        } else {
                x = std::atoi(argv[1]);
                y = std::atoi(argv[2]);
                k = std::atoi(argv[3]);
        }

        std::vector<Point<double, 2>> points = {
            {1.0, 2.0}, {2.0, 1.0}, {3.0, 2.0}, {7.0, 4.0}, {5.0, 9.0},
            {6.0, 1.0}, {0.0, 3.0}, {4.0, 7.0}, {8.0, 2.0}, {3.0, 5.0}};

        auto tree = new KDTree<double, 2>();
        tree->BuildTree(points);
        tree->PrintInorder();

        std::vector<Point<double, 2>> points_knn =
            tree->KNearestNeighbor(Point<double, 2>({x, y}), k);

        for (size_t i = 0; i < points_knn.size(); ++i) {
                std::cout << "Point " << i << ": ";
                for (size_t j = 0; j < points_knn[i].size(); ++j) {
                        std::cout << points_knn[i].data().at(j) << " ";
                }
                std::cout << std::endl;
        }

        std::cout << std::endl;
        std::cout << std::endl;
        std::cout << std::endl;

        tree->Insert({x + 1, y - 1});
        tree->PrintInorder();

        return 0;
}


#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <thread>
#include <atomic>
#include <fcntl.h>
#include <fstream>
#include "json.hpp"
#include <locale>

#include <openssl/ssl.h>
#include <openssl/err.h>
//#include "sb.h"//WDF你tm來搞笑？
//#include <windows.h>

using namespace std;
using json = nlohmann::json;

#define PORT 8080
#define BUFFER_SIZE 1024

#define DEV_MOTD true

atomic<bool> keep_running(true);

/*
enum class SetServerResult {//定義枚舉結果
    SUCCESS
};*/

// 接收訊息的執行緒函式
void receive_thread(int sockfd,string& REMARK_ONLINE, json& config) {
    char buffer[BUFFER_SIZE];
    struct sockaddr_in fromaddr;
    socklen_t addrlen = sizeof(fromaddr);

    int flags = fcntl(sockfd, F_GETFL, 0);
    fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);

    while (keep_running) {
        memset(buffer, 0, BUFFER_SIZE);
        ssize_t bytes_received = recvfrom(sockfd, buffer, BUFFER_SIZE, 0, (struct sockaddr *)&fromaddr, &addrlen);

        if (bytes_received > 0) {
            string sender_ip = inet_ntoa(fromaddr.sin_addr);
            string received_message(buffer, bytes_received);

            string display_name;
            if (!config["REMARK"][sender_ip].is_null())
                display_name = config["REMARK"][sender_ip]; // JSON 裡的固定備註
            else if (!REMARK_ONLINE.empty())
                display_name = REMARK_ONLINE; // 使用最新用戶備註
            else
                display_name = sender_ip; // 默認 IP

            cout << "\n[\033[32m來自 " <<"\033[33m"<< display_name <<"\033[32m"<< " 的訊息\033[0m]: " << received_message << endl;
            cout << "> ";
            fflush(stdout);
        }

        this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}

// 函式：讓使用者輸入並設定伺服器 IP
string set_server_address(sockaddr_in& servaddr, string& ip, json& config) {
    string server_ip;
    cout << "請輸入對象IP或備註: ";
    getline(cin, server_ip);

    // 檢查是否輸入的是備註名稱
    for (auto& [real_ip, remark] : config["REMARK"].items()) {
        if (server_ip == remark) {
            server_ip = real_ip; // 把備註轉換成真實 IP
            break;
        }
    }

    // bro給自己發訊息
    if (server_ip.empty() || server_ip == "localhost" || server_ip == "127.0.0.1") {
        server_ip = "127.0.0.1";
        cout << "Bro,你tm想給你自己發訊息，好吧我原諒你…" << endl;
    }

    // 驗證 IP 格式
    if (inet_pton(AF_INET, server_ip.c_str(), &servaddr.sin_addr) <= 0) {
        perror("無效的 IP 地址");
        return string("false") + ip;
    }

    ip = server_ip;
    return string("true") + ip;
}

string RunningON(){
    string RunningON;

    #if defined(_WIN32) || defined(_WIN64)
        RunningON = "Windows";
    #elif defined(__ANDROID__)
        RunningON = "Android";
    #elif defined(__linux__)
        RunningON = "Linux";
    #elif defined(__APPLE__)
        RunningON = "macOS";
    #else
        RunningON = "ERROR";
    #endif

    return RunningON;
}

string LOC_NAME(){
    string lang = "unknow";
    if (RunningON() == "Linux") {
        locale loc("");
        string loc_name = loc.name(); // 例如 zh_TW.UTF-8
        size_t dot = loc_name.find('.');
        if (dot != string::npos)
            loc_name = loc_name.substr(0, dot); // 去掉 .UTF-8
        lang = loc_name;
    }

    ifstream langfile(lang);
    if(langfile.is_open())
        lang = "en_US";
    return lang;
}
string CONFIG_LINK(){
    string path,lang;
    if (DEV_MOTD == true)
        path = "./";
    else
        path = string(getenv("HOME")) + "/.config/HosinoEJChat/";

    return path;
}
void Detection(){
    cout<<"Self-testing..."<<endl;
    cout<<"COLOR TESTING:\033[31mH\033[32mo\033[33ms\033[34mi\033[35mn\033[36mo\033[37mE\033[38mJ"<<endl;
    //CONFIG_LINK();
    if (DEV_MOTD == true) {
        cout<<"\033[31mPlease note! Debug mode is enabled! This is what developers use when debugging programs! It can cause all sorts of security issues! I don't know how the hell you got this version, so if you want to disable it, please download it again.\033[0m\n";//軟體都能下錯，真是雜魚~
        cout<<"\033[33mYou are running this program in a "<<RunningON()<<" environment"<<endl;
        cout<<"Configuration archive directory:"<<CONFIG_LINK()<<"config.json"<<"\033[0m"<<endl;
    }
    cout<<"Self-tested, Welcome. Ciallo～(∠・ω< )⌒★!"<<endl<<endl;
}

void REMARK(json& config) {
    int in;
    cin>>in;
}

json setting (json& config){//設置
    int setting;

    while (true) {
        cout << "\033[2J\033[1;1H";

        cin>>setting;
        if(setting == 1){//Language
            string lang_index = CONFIG_LINK() + "lang/" + "index.json", setLang;
            json index;
            ifstream index_FL(lang_index);
            index_FL >> index;
            index_FL.close();

            setstart:
            cout<<"請輸入設定的語言：";
            cin>>setLang;
            if(index[setLang] == true){
                run:
                config["set"][


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

class node {
    public :
        string data;
        node* next;
        explicit node (const string &v) : data(v), next(nullptr){}

};

class linkList{
    private :
        node * head;
        node* tail;
        int size;

    public :
        linkList() : head(nullptr), tail(nullptr), size(0){}

        void insert_front(const string &value){
            node* n = new node(value);
            n-> next = head;
            head = n;
            if(!tail) tail = n;
            ++ size;
        }

        void insert_end(const string& value){
            node* n = new node(value);
            if(head == nullptr){
                insert_front(value);
                return;
            }
            tail->next = n;
            tail = n;
            ++ size;
        }

        void display(){
            node * temp = head;
            while(temp != nullptr){
                cout << temp->data <<" -> ";
                temp = temp->next;
            }
            cout <<" NULL"<< endl;
        }

};

int main() {
    linkList colors;
    colors.insert_front("red");
    colors.insert_front("blue");

    colors.insert_end("Green");
    colors.insert_end("Yello");

    colors.display();

    return 0;
}


/*
 *Description: Asks user for word and checks if it's a palindrome
 *Name: Shree Sai Narayan Medisetti
 *Date: 9/5/2025
 */

#include <iostream>
#include <cstring>

using namespace std;

int main() {

  //Set Variables
  char input[81];
  char word[81];
  char reversed[81];

  // Get user input
  cout << "Enter a word: ";
  cin.get(input, 81);

  // Verify Input

  // Set indices
  int inputLength = strlen(input);
  int wordIndex = 0;

  // Loop through and add lower-case alphabets & numbers only
  for (int i = 0; i < inputLength; i++) {
    if (isalnum(input[i])){
	word[wordIndex] = tolower(input[i]);
	wordIndex++;
    }
  }

  word[wordIndex] = '\0';

  // Reverse word

  // Set indices
  int wordLength = strlen(word);
  int reversedIndex = 0;

  // Loop through word in reverse and store it
  for (int i = wordLength - 1; i > -1; i--) {
    reversed[reversedIndex] = word[i];
    reversedIndex++;
  }

  reversed[reversedIndex] = '\0';

  // Compare strings and check for palindrome

  if (strcmp(word, reversed) == 0) {
    cout << "Is a Palindrome!" << endl;
  } else {
    cout << "Not a Palindrome!" << endl;
  }

  return 0;
}