#include "main.h"
// using namespace std;

int main ()
{
    Comanda* head = nullptr;
    Comanda* head_vip = nullptr;
    int n = 0;
    unsigned int selectare_meniu = 0;
    bool afisare_meniu = true;
    int temp_IDnumber = 0;
    std::string temp_nume;
    float temp_suma = 0;
    int temp_ora = 0;

    while (afisare_meniu==true)
    {
        std::cout<<std::endl;
        std::cout<<"Selecteaza o optiune:"<<'\n';
        std::cout<<"1 - Introdu comenzile deja existente:"<<'\n';
        std::cout<<"2 - Introdu o comanda noua:"<<'\n';
        std::cout<<"3 - Afiseaza lista de comenzi:"<<'\n';
        std::cout<<"4 - Sterge o comanda in functie de ID:"<<'\n';
        std::cout<<"5 - Sorteaza comenzile in functie de suma:"<<'\n';
        std::cout<<"6 - Sorteaza comenzile in functie de ora:"<<'\n';
        std::cout<<"7 - Cauta o comanda in functie de numele clientului:"<<'\n';
        std::cout<<"8 - Calculeaza venitul total in intervalul orar:"<<'\n';
        std::cout<<"9 - Muta comenzile VIP:"<<'\n';
        std::cout<<"10 - Afiseaza comenzile VIP:"<<'\n';
        std::cout<<"11 - Iesire din meniu:"<<'\n';
        std::cout<<"Introdu optiunea:";
        std::cin>>selectare_meniu;
        std::cout<<std::endl;
        switch (selectare_meniu)
        {
            case 1:
                std::cout  << "Numar comenzi:";
                std::cin >> n;
                // introduci o lista de n noduri
                while (n>0)
                {
                    n--;
                    std::cout << "ID unic: ";
                    std::cin >> temp_IDnumber;
                    while (!verifyID(head, temp_IDnumber))
                    {
                        std::cout << "ID-ul nu este unic, reintrodu ID";
                        std::cin >> temp_IDnumber;
                    }
                    std::cout << "Nume client: ";
                    std::cin >> temp_nume;
                    std::cout << "Suma comanda: ";
                    std::cin >> temp_suma;
                    std::cout << "Ora comanda: ";
                    std::cin >> temp_ora;
                    if (temp_ora > 1439)
                    {
                        std::cout << "Ora introdusa nu exista, reintrodu ora:";
                        std::cin >> temp_ora;
                    }
                    insertAtEnd(head, temp_IDnumber, temp_nume, temp_suma, temp_ora);
                }
                break;
            case 2:
                std::cout<<"Introdu o comanda noua:";

                std::cout << "ID unic: ";
                std::cin >> temp_IDnumber;
                while (!verifyID(head, temp_IDnumber))
                {
                    std::cout << "ID-ul nu este unic, reintrodu ID";
                    std::cin >> temp_IDnumber;
                }
                std::cout << "Nume client: ";
                std::cin >> temp_nume;
                std::cout << "Suma comanda: ";
                std::cin >> temp_suma;
                std::cout << "Ora comanda: ";
                std::cin >> temp_ora;
                if (temp_ora > 1439)
                {
                    std::cout << "Ora introdusa nu exista, reintrodu ora:";
                    std::cin >> temp_ora;
                }
                insertAtEnd(head, temp_IDnumber, temp_nume, temp_suma, temp_ora);
                break;
            case 3:
                if (head)
                {
                    display(head);
                } else {
                    std::cout<<"Introdu intai lista de comenzi";
                    std::cout<<std::endl;
                }
                break;
            case 4:
                if (head)
                {
                    int insert_ID = 0;
                    std::cout << "Insereaza ID:";
                    std::cin >> insert_ID;
                    Comanda* current = head;
                    if (deleteByID(head, insert_ID))
                    {
                        std::cout << "Commanda cu ID-ul: " << insert_ID << " a fost stearsa";
                    } else {
                        std::cout << "Id-ul nu exista. Reintrodu ID";
                    }
                } else {
                    std::cout<<"Introdu intai lista de comenzi";
                    std::cout<<std::endl;
                }
                break;
            case 5:
                if (head)
                {
                    sortarebySum(head);
                    std::cout<< "Sortarea a fost realizata cu success";
                } else {
                    std::cout<<"Introdu intai lista de comenzi";
                    std::cout<<std::endl;
                }
                break;
            case 6:
                if (head)
                {
                    sortByHour(head);
                    std::cout << "Sortarea a fost realizata cu success";
                } else {
                    std::cout<<"Introdu intai lista de comenzi";
                    std::cout<<std::endl;


#include "InstrumentationScopeStore.hpp"

#include <utility>

namespace ottrelite::interop::otel
{
    std::size_t TupleHash::operator()(const std::tuple<std::string, std::string, std::string> &t) const
    {
        auto h1 = std::hash<std::string>{}(std::get<0>(t));
        auto h2 = std::hash<std::string>{}(std::get<1>(t));
        auto h3 = std::hash<std::string>{}(std::get<2>(t));
        return h1 ^ (h2 << 1) ^ (h3 << 2);
    }

    const opentelemetry::sdk::instrumentationscope::InstrumentationScope &InstrumentationScopeStore::getOrCreate(
        const std::string &name, const std::string &version, const std::string &schemaUrl)
    {
        // create a key for lookup
        ScopeKey key = std::make_tuple(name, version, schemaUrl);

        // check if we already have this scope & return it, if cache hit
        auto it = scopes_.find(key);
        if (it != scopes_.end())
        {
            return *it->second;
        }

        // create new scope
        auto scope =
            opentelemetry::sdk::instrumentationscope::InstrumentationScope::Create(name, version, schemaUrl, {});

        // store and return reference
        const auto &scopeRef = *scope;
        scopes_[key] = std::move(scope);
        return scopeRef;
    }

    std::unordered_map<ScopeKey, std::unique_ptr<opentelemetry::sdk::instrumentationscope::InstrumentationScope>,
                       TupleHash>
        InstrumentationScopeStore::scopes_;
} // namespace ottrelite::interop::otel


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

#include "TranslatorObjects/MoveComponentToTranslatorObject.h"
#include "BlueprintNativizationLibrary.h"
#include "BlueprintNativizationSubsystem.h"

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

	if (EntryPinName == "Move")
	{
		TSet<FString>  NewPreparations;
		FGenerateResultStruct TargetComponent = NativizationV2Subsystem->GenerateInputParameterCodeForNode(Node, UBlueprintNativizationLibrary::GetPinByName(Node->Pins, "Component"), 0, MacroStack);
		FGenerateResultStruct TargetRelativeLocation = NativizationV2Subsystem->GenerateInputParameterCodeForNode(Node, UBlueprintNativizationLibrary::GetPinByName(Node->Pins, "TargetRelativeLocation"), 0, MacroStack);
		FGenerateResultStruct TargetRelativeRotation = NativizationV2Subsystem->GenerateInputParameterCodeForNode(Node, UBlueprintNativizationLibrary::GetPinByName(Node->Pins, "TargetRelativeRotation"), 0, MacroStack);
		FGenerateResultStruct bEaseOut = NativizationV2Subsystem->GenerateInputParameterCodeForNode(Node, UBlueprintNativizationLibrary::GetPinByName(Node->Pins, "bEaseOut"), 0, MacroStack);
		FGenerateResultStruct bEaseIn = NativizationV2Subsystem->GenerateInputParameterCodeForNode(Node, UBlueprintNativizationLibrary::GetPinByName(Node->Pins, "bEaseIn"), 0, MacroStack);
		FGenerateResultStruct OverTime = NativizationV2Subsystem->GenerateInputParameterCodeForNode(Node, UBlueprintNativizationLibrary::GetPinByName(Node->Pins, "OverTime"), 0, MacroStack);
		FGenerateResultStruct ForceShortestRotationPath = NativizationV2Subsystem->GenerateInputParameterCodeForNode(Node, UBlueprintNativizationLibrary::GetPinByName(Node->Pins, "bForceShortestRotationPath"), 0, MacroStack);

		NewPreparations.Append(TargetComponent.Preparations);
		NewPreparations.Append(TargetRelativeLocation.Preparations);
		NewPreparations.Append(TargetRelativeRotation.Preparations);
		NewPreparations.Append(bEaseOut.Preparations);
		NewPreparations.Append(bEaseIn.Preparations);
		NewPreparations.Append(OverTime.Preparations);
		NewPreparations.Append(ForceShortestRotationPath.Preparations);

		Content += GenerateNewPreparations(Preparations, NewPreparations);
		Preparations.Append(NewPreparations);
		Content += FString::Format(
			TEXT("GetWorld()->GetSubsystem<UMoveComponentSubsystem>()->EnqueueMove({0}, {1}, {2}, {3}, {4}, {5}, {6});"),
			{ TargetComponent.Code, TargetRelativeLocation.Code, TargetRelativeRotation.Code, OverTime.Code, bEaseOut.Code, bEaseIn.Code, ForceShortestRotationPath.Code});

	}
	else if (EntryPinName == "Stop")
	{
		FGenerateResultStruct TargetComponent = NativizationV2Subsystem->GenerateInputParameterCodeForNode(Node, UBlueprintNativizationLibrary::GetPinByName(Node->Pins, "Component"), 0, MacroStack);

		Content += GenerateNewPreparations(Preparations, TargetComponent.Preparations);
		Content += FString::Format(
			TEXT("GetWorld()->GetSubsystem<UMoveComponentSubsystem>()->Stop({0});"),
			{ TargetComponent.Code }
		);

	}
	else if (EntryPinName == "Return")
	{
		FGenerateResultStruct TargetComponent = NativizationV2Subsystem->GenerateInputParameterCodeForNode(Node, UBlueprintNativizationLibrary::GetPinByName(Node->Pins, "Component"), 0, MacroStack);

		Content += GenerateNewPreparations(Preparations, TargetComponent.Preparations);
		Content += FString::Format(
			TEXT("GetWorld()->GetSubsystem<UMoveComponentSubsystem>()->Return({0});"),
			{ TargetComponent.Code }
		);
	}

	return Content;
}

void UMoveComponentToTranslatorObject::GenerateNewFunction(UK2Node* InputNode, TArray<UK2Node*> Path, TArray<FGenerateFunctionStruct>& EntryNodes, UNativizationV2Subsystem* NativizationV2Subsystem)
{
	UEdGraphPin* Pin = UBlueprintNativizationLibrary::GetFilteredPins(
		InputNode,
		EPinOutputOrInputFilter::Ouput,
		EPinExcludeFilter::None,
		EPinIncludeOnlyFilter::ExecPin)[0];

	TArray<UK2Node*> MacroStack;
	UEdGraphPin* NonKnotPin = UBlueprintNativizationLibrary::GetFirstNonKnotPin(Pin,0, true, MacroStack, NativizationV2Subsystem);
	if (!NonKnotPin)
	{
		return;
	}

	UK2Node* TargetNode = Cast<UK2Node>(NonKnotPin->GetOwningNode());
	if (!TargetNode)
	{
		return;
	}

	FGenerateFunctionStruct OutGenerateFunctionStruct;
	if (!UBlueprintNativizationDataLibrary::FindGenerateFunctionStructByNode(EntryNodes, TargetNode, OutGenerateFunctionStruct))
	{
		FGenerateFunctionStruct NewStruct;
		NewStruct.Node = TargetNode;
		NewStruct.Name = *UBlueprintNativizationLibrary::GetUniqueEntryNodeName(TargetNode, EntryNodes, TEXT("MoveComponent"));
		EntryNodes.Add(NewStruct);
	}
}

void UMoveComponentSubsystem::Initialize(FSubsystemCollectionBase& Collection)
{
	Super::Initialize(Collection);
}

void UMoveComponentSubsystem::Deinitialize()
{
	Super::Deinitialize();
}

v


#include "MysqlMgr.h"

MysqlMgr::~MysqlMgr() {

}

int MysqlMgr::RegUser(const std::string& name, const std::string& email, const std::string& pwd)
{
	return _dao.RegUser(name, email, pwd);
}

bool MysqlMgr::CheckEmail(const std::string& name, const std::string& email) {
	return _dao.CheckEmail(name, email);
}

bool MysqlMgr::UpdatePwd(const std::string& name, const std::string& pwd) {
	return _dao.UpdatePwd(name, pwd);
}

MysqlMgr::MysqlMgr() {
}

bool MysqlMgr::CheckPwd(const std::string& name, const std::string& pwd, UserInfo& userInfo) {
	return _dao.CheckPwd(name, pwd, userInfo);
}

bool MysqlMgr::AddFriendApply(const int& from, const int& to)
{
	return _dao.AddFriendApply(from, to);
}

bool MysqlMgr::AuthFriendApply(const int& from, const int& to) {
	return _dao.AuthFriendApply(from, to);
}

bool MysqlMgr::AddFriend(const int& from, const int& to, std::string back_name) {
	return _dao.AddFriend(from, to, back_name);
}

std::shared_ptr<UserInfo> MysqlMgr::GetUser(int uid)
{
	return _dao.GetUser(uid);
}

std::shared_ptr<UserInfo> MysqlMgr::GetUser(std::string name)
{
	return _dao.GetUser(name);
}

bool MysqlMgr::GetApplyList(int touid,
	std::vector<std::shared_ptr<ApplyInfo>>& applyList, int begin, int limit) {

	return _dao.GetApplyList(touid, applyList, begin, limit);
}

bool MysqlMgr::GetFriendList(int self_id, std::vector<std::shared_ptr<UserInfo> >& user_info) {
	return _dao.GetFriendList(self_id, user_info);
}


#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <windows.h>
#include <cstdlib>
#include <conio.h>
#include <filesystem>

using std :: cout;
using std :: cin;
using std :: string;

std :: vector <string> parser( const string& command ) {
  std :: vector <string> args;
  std :: istringstream iss( command );
  string token;
  while (iss >> token) {
    args.push_back( token );
  }
  return args;
}
void printError( const string& error ) {

  cout << error << "\n";

}
string removeQuote( const string& command ) {
  string output;
  for (auto ch : command) {
    if ( ch == '"') {
      output+="\"";
    }
    else output+=ch;
  }
  return output;
}
int main() {
  string command;
  std :: vector <std :: string> history;
  while (true) {
    std::filesystem::path path=std::filesystem::current_path();
    cout << (path.string()) << "|->";
    std :: getline(cin, command);
    if ( command.empty() ) {
      continue;
    }
    if (command == "history") {
      int x = 0;
      int Hsize=history.size();
      while ( (x < 5) && ( ( (Hsize-1) -x) >= 0) ){
        cout << history[( Hsize - 1 ) - x]<<"\n";
        x++;
      }
      continue;
    }
    history.push_back( command );
    std :: vector <string> parsed = parser(command);
    if ( parsed.empty() ) continue;
    if ( parsed[0] == "quit" || parsed[0] == "exit" ) {
      break;
    }
    if ( parsed[0] == "echo" ) {
      for (int i = 1;i < parsed.size(); i++) {
          cout << parsed[i] << " ";
      }
      cout<<"\n";
      continue;
    }
    if (parsed[0] == "cd") {
      const char* dir = (parsed.size()>1) ? (parsed[1].c_str()) : (getenv("USERPROFILE"));
      if ( dir == nullptr) cout << "No directory specified or Home directory not set \n";
      if (SetCurrentDirectoryA(dir) == 0) {
        printError("cd Failed");
      }
      continue;
    }
    string pwrShllcmd = "powershell -Command \""+ removeQuote(command) + "\"";
    int returnValue = system(pwrShllcmd.c_str());
    if (returnValue != 0) {
      printError("Command Failed with exit code: "+ std::to_string(returnValue));
      continue;
    }
  }
}


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

#include <android-base/file.h>
#include <android-base/logging.h>
#include <android-base/result.h>
#include <android-base/unique_fd.h>
#include <apex_file.h>
#include <fcntl.h>
#include <sys/sendfile.h>

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

#include "erofs.h"
#include "ext4.h"
#include "list.h"

using android::apex::ApexFile;
using android::base::ErrnoError;
using android::base::Error;
using android::base::Result;
using android::base::unique_fd;

using namespace std::string_literals;

struct Args {
  std::string apex_file;
  bool show_security_context;
};

Result<void> PrintList(Args args) {
  auto apex_file = OR_RETURN(ApexFile::Open(args.apex_file));

  // If the apex is .capex, decompress it first.
  TemporaryDir temp_dir;
  if (apex_file.IsCompressed()) {
    auto original_apex_path = std::string(temp_dir.path) + "/original.apex";
    OR_RETURN(apex_file.Decompress(original_apex_path));
    apex_file = OR_RETURN(ApexFile::Open(original_apex_path));
  }

  if (!apex_file.GetFsType().has_value())
    return Error() << "Invalid apex: no fs type";
  if (!apex_file.GetImageSize().has_value())
    return Error() << "Invalid apex: no image size";
  if (!apex_file.GetImageOffset().has_value())
    return Error() << "Invalid apex: no image offset";

  std::map lister = {
      std::pair{"ext4"s, &Ext4List},
      std::pair{"erofs"s, &ErofsList},
  };
  auto fs_type = *apex_file.GetFsType();
  if (!lister.contains(fs_type)) {
    return Error() << "Invalid filesystem type: " << fs_type;
  }

  // Extract apex_payload.img
  TemporaryFile temp_file;
  {
    unique_fd src(open(apex_file.GetPath().c_str(), O_RDONLY | O_CLOEXEC));
    off_t offset = *apex_file.GetImageOffset();
    size_t size = *apex_file.GetImageSize();
    if (sendfile(temp_file.fd, src, &offset, size) < 0) {
      return ErrnoError()
             << "Failed to create a temporary file for apex payload";
    }
  }

  for (const auto& entry : OR_RETURN(lister[fs_type](temp_file.path))) {
    std::cout << entry.path;
    if (args.show_security_context) {
      std::cout << " " << entry.security_context;
    }
    std::cout << "\n";
  }
  return {};
}

Result<Args> ParseArgs(std::vector<std::string> args) {
  if (args.size() == 2) {
    return Args{
        .apex_file = args[1],
        .show_security_context = false,
    };
  }
  if (args.size() == 3 && args[1] == "-Z") {
    return Args{
        .apex_file = args[2],
        .show_security_context = true,
    };
  }
  return Error() << "Invalid args\n"
                 << "usage: " << args[0] << " [-Z] APEX_FILE\n";
}

Result<void> TryMain(std::vector<std::string> args) {
  auto parse_args = OR_RETURN(ParseArgs(args));
  OR_RETURN(PrintList(parse_args));
  return {};
}

int main(int argc, char** argv) {
  android::base::SetMinimumLogSeverity(android::base::ERROR);
  if (auto st = TryMain(std::vector<std::string>{argv, argv + argc});
      !st.ok()) {
    std::cerr << st.error() << "\n";
    return 1;
  }
  return 0;
}


#include<iostream>
using namespace std;
using std::cout;
using std::cin;
using std::endl;

#define tab "\t"
#define delimiter "\n---------------------------------\n"

class List
{
	class Element
	{
		int Data;
		Element* pNext;
		Element* pPrev;
	public:
		Element(int Data, Element* pNext = nullptr, Element* pPrev = nullptr)
			:Data(Data), pNext(pNext), pPrev(pPrev)
		{
			cout << "EConstructor:\t" << this << endl;
		}
		~Element()
		{
			cout << "EDestructor:\t" << this << endl;
		}
		friend class List;
	}*Head, * Tail; //Îáúåêòû êëàññîâ è ñòðóêòóð è óêàçàòåëè íà ýòè îáúåêòû ìîæíî îáúÿâëÿòü
					//íåïîññðåäñòâåííî ïîñëå îïèñàíèÿ êëàññîâ è ñòðóêòóð
	size_t size;	//Ðàçìåð ñïèñêà. size_t - ýòî typedef íà unsigned int
	class ConstBaseIterator
	{
		//ýòîò êëàññ îáþáùàåò ñâîéñòâà ðàçíûõ èòåðàòîðîâ
	protected:
		Element* Temp;
	public:
		ConstBaseIterator(Element* Temp = nullptr):Temp(Temp){}
		~ConstBaseIterator(){}

		// comparison
		bool operator==(const ConstBaseIterator& other)const
		{
			return this->Temp == other.Temp;
		}
		bool operator!=(const ConstBaseIterator& other)const
		{
			return this->Temp != other.Temp;
		}

		int operator*()const//â êîíñòàíòíîì èòåðàòîðå äîëæåí áûòü êîíñòàíòíûé îïåðàòîð ðàçèìåíîâàíèÿ
			//	çäåñü íè â êîåì ñëó÷àå íå äîëæíî áûòü îáû÷íîãî îïåðàòîðà ðàçèìåíîâàíèÿ
		{
			return Temp->Data;
		}
	};
public:
	class ConstIterator:public ConstBaseIterator
	{
	public:
		ConstIterator(Element* Temp=nullptr):ConstBaseIterator(Temp){}
		~ConstIterator(){}
		ConstIterator& operator++()
		{
			Temp = Temp->pNext;
			return *this;
		}
		ConstIterator& operator++(int)
		{
			ConstIterator old = *this;
			Temp = Temp->pNext;
			return old;
		}
		ConstIterator operator--()
		{
			Temp = Temp->pPrev;
			return *this;
		}
		ConstIterator operator--(int)
		{
			ConstIterator old = *this;
			Temp = Temp->pPrev;
			return old;
		}
	};
	class ConstReverseIterator:public ConstBaseIterator
	{
	public:
		ConstReverseIterator(Element* Temp = nullptr):ConstBaseIterator(Temp){}
		~ConstReverseIterator(){}
		//Incr/Decr
			ConstReverseIterator& operator++()
		{
			Temp = Temp->pPrev;
			return *this;
		}
		ConstReverseIterator operator++(int)
		{
			ConstReverseIterator old = *this;
			Temp = Temp->pPrev;
			return old;
		}
		ConstReverseIterator& operator--()
		{
			Temp = Temp->pNext;
			return *this;
		}
		ConstReverseIterator operator--(int)
		{
			ConstReverseIterator old = *this;
			Temp = Temp->pNext;
			return old;
		}
	};
	class Iterator :public ConstIterator
	{
	public:
		Iterator(Element* Temp): ConstIterator(Temp){}
		~Iterator(){}
		int& operator*()
		{
			return Temp->Data;
		}
	};
	class ReverseIterator :public ConstReverseIterator
	{
	public:
		ReverseIterator(Element * Temp) :ConstReverseIterator(Temp) {}
		~ReverseIterator() {}
		int& operator*()
		{
			return Temp->Data;
		}
	};
	ConstIterator begin()const
	{
		return Head;
	}
	ConstIterator end()const
	{
		return nullptr;
	}
	ConstReverseIterator rbegin()const
	{
		return Tail;
	}
	ConstReverseIterator rend()const
	{
		return nullptr;
	}
	Iterator begin()
	{
		return Head;
	}
	Iterator end()
	{
		return nullptr;
	}
	ReverseIterator rbegin()
	{
		return Tail;
	}
	ReverseIterator rend()
	{
		return nullptr;
	}

	List()
	{
		Head = Tail = nullptr;
		size = 0;
		cout << "LConstructor:\t" << this << endl;
	}
	List(const std::initializer_list<int>& il) :List()
	{
		for (int const* it = il.begin(); it != il.end(); ++it)
		{
			push_back(*it);
		}
		cout << "ILConstructor:\t" << this << endl;

	}
	List(const List& other) :List()
	{
		*this = other;
		cout << "LCopyConstructor:\t" << this << endl;
	}
	~List()
	{
		//while (Head)pop_front();
		while (Tail)pop_back();

		cout << "LDestructor:\t" << this << endl;
	}
	///// Operators:

	List& operator=(const List& other)
	{
		if (this == &other)return *this;
		while (Head)pop_front();
		for (Element* Temp = other.Head; Temp; Temp = Temp->pNext)
			push_back(Temp->Data);
		cout << "LCopyAssignment:\t" << this << endl;
		return *this;
	}

	//   ADDING ELEMENTS
	void push_front(int Data)
	{
		Element* New = new Element(Data);
		if (Head == nullptr && Tail == nullptr)Head = Tail = New; else
		{
			//Ñîçäàåì ýëåìåíò â êîòîðîì áóäåò õðàíèòüñÿ äîáàâëÿåìîå çíà÷åíèå
			//2.Ïðèñòûêîâûâàåì íîâûé ýëåìåíò ê ñïèñêó:
			New->pNext = Head;
			//3.Ïðèñòûêîâûâàåì íà÷àëüíûé ýëåìåíò ñïèñêà ê íîâîìó ýëåìåíòó:
			Head->pPrev = New;
			//4.Äåëàåì íîâûé ýëåìåíò íà÷àëüíûì ýëåìåíòîì ñïèñêà:
			Head = New;
		}
		size++;
	}
	void push_back(int Data)
	{
		Element* New = new Element(Data);
		if (Head == nullptr && Tail == nullptr)
		{
			Head = Tail = New;
		}
		else
		{
			//öåïëÿåì íîâûé ýëåìåíò çà õâîñò ñïèñêà:
			New->pPrev = Tail;
			//Ïðèñòûêîâûâàåì ñïèñîê ê íîâîìó ýëåìåíòó:
			Tail->pNext = New;
			//Äåëàåì íîâûé ýëåìåíò õâîñòîì ñïèñêà:
			Tail = New;
		}
		size++;

	}
	void insert(int Data, int Index)
	{
		if (Index < 0)return;
		if (Index == 0||size==0)return push_front(Data);
		if (Index >= size)return push_back(Dat


// paste.cpp - Paste shortcuts.
// Copyright (c) KALX, LLC. All rights reserved. No warranty made.
#include "xll.h"
#include "macrofun.h"

using namespace xll;

/*
#define XLL_RGB_COLOR_ENUM(a, b, c) XLL_CONST(LONG, ENUM_COLOR_ ## a, b, "Color", "XLL Enum", "https://en.wikipedia.org/wiki/RGB_color_model");
XLL_RGB_COLOR(XLL_RGB_COLOR_ENUM)
#undef XLL_RGB_COLOR_ENUM
*/

// Define style for handles.
int red = 0;
int Handle = 0;
AddIn xai_handle_style(
	Macro(L"xll_handle_style", L"XLL.HANDLE.STYLE")
);
// Add red to color palette and define Handle style.
int WINAPI xll_handle_style()
{
#pragma XLLEXPORT
	if (!red) {
		red = EditColor(XLL_RGB_COLOR_RED);
		// Handle style.
		if (!Handle) {
			DefineStyle(L"Handle")
				.Number(L"\"0x\"#")
				.FormatFont(FormatFont(false).Size(8).Color(red))
				.Alignment(Alignment(false).Horizontal(Alignment::Horizontal::Center))
				.Alignment(Alignment(false).Vertical(Alignment::Vertical::Center));
		}
		Handle = 1;
	}

	return 1;
}
On<xlcOnSheet> xlos_handle_style("", "XLL.HANDLE.STYLE", true);

// Strip off leading '='
OPER Uneval(const XLOPER12& val)
{
	return isMissing(val) || isNil(val) ? OPER(L"")
		: StartsWith(val, L'=') ? OPER(view(val).substr(1))
		: isUDF(val) ? val & OPER(L"()")
		: val;
}

// Construct formula from Args default values.
OPER Formula(const Args* pargs)
{
	OPER formula = OPER(L"=") & pargs->functionText & OPER(L"(");
	OPER comma(L"");
	for (int i = 0; i < size(pargs->argumentInit); ++i) {
		formula &= comma;
		formula &= Excel(xlfText, Uneval(pargs->argumentInit[i]), L"General");

		comma = L", ";
	}
	formula &= OPER(L")");

	return formula;
}

// Translate by r rows and c columns.
OPER Move(const XLOPER12& o, int r, int c, int w = 1, int h = 1)
{
	OPER sel = Excel(xlfOffset, o, r, c, w, h);
	OPER s = Excel(xlcSelect, sel);
	return sel;
}

// Expand active to size of ref.
OPER Reshape(const OPER& active, const OPER& ref)
{
	return OPER(reshape(SRef(active), rows(ref), columns(ref)));
}

// Set value and return selection.
OPER Set(const OPER& ref, const OPER& val)
{
	OPER res = ref;

	if (isFormula(val)) {
		OPER eval = Excel(xlfEvaluate, val);
		if (isMulti(eval)) {
			res = Reshape(ref, eval);
			Excel(xlSet, res, eval);
		}
		else {
			Excel(xlcFormula, val, res);
		}
	}
	else {
		Excel(xlSet, ref, val);
	}

	return res;
}

// Paste function with default arguments.
AddIn xai_pasteb(
	Macro("xll_pasteb", "XLL.PASTEB")
);
int WINAPI xll_pasteb()
{
#pragma XLLEXPORT
	int result = TRUE;

	try {
		OPER active = Excel(xlfActiveCell);
		OPER cell = Excel(xlCoerce, active);
		const Args* pargs = AddIn::find(cell);
		ensure(pargs || !"xll_pasteb: add-in not found");

		OPER formula = Formula(pargs);
		Excel(xlcFormula, formula, active);
		if (isHandle(pargs->functionText)) {
			Excel(xlcApplyStyle, L"Handle");
		}
		//		OPER res = Excel(xlfEvaluate, formula);
//		OPER out = Reshape(active, res);
//		Excel(xlcSelect, out);
//		Excel(xlcApplyStyle, isHandle(text) ? L"Handle" : L"Output");
	}
	catch (const std::exception& ex) {
		result = FALSE;
		XLL_ERROR(ex.what());
	}
	catch (...) {
		result = FALSE;
		XLL_ERROR("xll_pasteb: unknown exception");
	}

	return result;
}
On<xlcOnKey> xok_pasteb(ON_CTRL ON_SHIFT "B", "XLL.PASTEB");

// Paste function with default arguments below.
AddIn xai_pastec(
	Macro("xll_pastec", "XLL.PASTEC")
);
int WINAPI xll_pastec()
{
#pragma XLLEXPORT
	int result = TRUE;

	try {
		OPER caller = Excel(xlfActiveCell);
		OPER text = Excel(xlCoerce, caller);
		const Args* pargs = AddIn::find(text);
		ensure (pargs || !"xll_pastec: add-in not found");
		text = pargs->functionText;

		// Expand caller to size of formula output.
		OPER output = Reshape(caller, Excel(xlfEvaluate, Formula(pargs)));
		OPER active = Move(caller, rows(output), 0);

		OPER formula = OPER(L"=") & text & OPER(L"(");
		OPER comma(L"");
		for (int i = 0; i < size(pargs->argumentInit); ++i) {
			formula &= comma;

			if (isNil(pargs->argumentInit[i])) {
				formula &= Excel(xlfRelref, active, caller);
				active = Move(active, 1, 0);
			}
			else {
				const OPER ref = Set(active, pargs->argumentInit[i]);
				formula &= Excel(xlfRelref, Reshape(active, ref), caller);
				active = Move(active, rows(ref), 0);
			}

			comma = L", ";
		}
		formula &= OPER(L")");

		Excel(xlcFormula, formula, output);
		Excel(xlcSelect, output);
		if (isHandle(text)) {
			Excel(xlcApplyStyle, L"Handle");
		}
//		Excel(xlcApplyStyle, isHandle(text) ? L"Handle" : L"Output");
	}
	catch (const std::exception& ex) {
		result = FALSE;
		XLL_ERROR(ex.what());
	}
	catch (...) {
		result = FALSE;
		XLL_ERROR("xll_pasteb: unknown exception");
	}

	return result;
}
On<xlcOnKey> xok_pastec(ON_CTRL ON_SHIFT "C", "XLL.PASTEC");

// Paste function and define names.
AddIn xai_pasted(
	Macro("xll_pasted", "XLL.PASTED")
);
int WINAPI xll_pasted()
{
#pragma XLLEXPORT
	int result = TRUE;

	try {
		OPER caller = Excel(xlfActiveCell);
		OPER text = Excel(xlCoerce, caller);
		const Args* pargs = AddIn::find


#include<iostream>
#include<string.h>
#include<climits>
#include<fstream>
#include<unistd.h>

using namespace std;
#define INF 999
int mindistance(float distance[],bool stat[])
{
	float minimum=INT_MAX;
    int ind;
	for(int k=0;k<25;k++)
	{
		if(stat[k]==false && distance[k]<=minimum)
		{
			minimum=distance[k];
			ind=k;
		}
	}
	return ind;
}

void dijkstra(float graph[25][25], int source, string stations[24]) {
    float distance[25];
    bool stat[25];
    int previous[25];  // To track the previous station for reconstructing the path

    for (int k = 0; k < 25; k++) {
        distance[k] = INT_MAX;
        stat[k] = false;
        previous[k] = -1;  // Initialize previous stations to -1
    }
    distance[source] = 0;

    for (int k = 0; k < 25; k++) {
        int m = mindistance(distance, stat);
        stat[m] = true;

        for (int k = 0; k < 25; k++) {
            if (!stat[k] && graph[m][k] && distance[m] != INT_MAX &&
                distance[m] + graph[m][k] < distance[k]) {
                distance[k] = distance[m] + graph[m][k];
                previous[k] = m;  // Track the previous station
            }
        }
    }

    cout << "\n\n\nMinimum Number of Stations from "
         << "[" << stations[source] << "]"
         << " To every station\n\n\n" << endl;

    for (int k = 0; k < 24; k++) {
        cout << "Enter " << k << " To Check Distance Between "
             << stations[source] << " To "
             << "[" << stations[k] << "] Station" << endl;
    }

    int n;
    cout << "Enter Station to check distance to Each other:" << endl;
    cin >> n;

    cout << "Total Distance from "
         << "[" << stations[source] << "]"
         << " To " << stations[n] << " are "
         << "[" << distance[n] << "] KM" << endl;

    // Calculate the number of intermediate stations
    int count = 0;
    int temp = n;
    while (previous[temp] != -1) {
        count++;
        temp = previous[temp];
    }
    cout << "Number of Intermediate Stations: " << count << endl;

    // Calculate the fare based on the distance
    int fare = 0;
    if (distance[n] <= 2)
        fare = 10;
    else if (distance[n] <= 5)
        fare = 20;
    else if (distance[n] <= 12)
        fare = 30;
    else if (distance[n] <= 21)
        fare = 40;
    else if (distance[n] <= 32)
        fare = 50;
    else
        fare = 60;

    cout << "Fare for the trip: Rs " << fare << "/-" << endl;

    cout << "Route: "<< endl;

    for(int k=source+1;k<=n;k++){

	cout<<stations[source]<<" -> "<<stations[k]<<" "<<"Station"<<"["<<distance[k]<<"]"<<"KM"<<endl;
    }
    cout << endl;

}

int login()
{
    char dum,u_name[30],name[30],g_pwd[30],pwd[30];
    int flag=0,s=1;
 cout<<"\n\n\n\n\n\n\t\t\t\t\t  \xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb"<<endl;
    cout<<"\t\t\t\t\t\t*WELLCOME TO LOGIN*"<<endl;
    cout<<"\t\t\t\t\t  \xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb\xdb "<<endl;
    if(s==1){

cout<<"Enter your USER NAME  : "<<endl;
          string phrase = "Enter your USER NAME And PASSWORD: ";
        string command = "espeak \"" + phrase + "\"";
    const char *charCommand = command.c_str();
        system(charCommand);
    cin>>name;
}

        cout<< "Enter the PASSWORD   : "<<endl;
//        string command = "espeak \"" + phrase + "\"";
//    const char *charCommand = command.c_str();
//        system(charCommand);
    cin>>pwd;
    fstream f;
    f.open("user_logins.txt",ios::in);
    f.seekg(0);
    while(f)
    {
        f.get(dum);
        f.get(u_name,30);
        f.get(dum);
        f.get(g_pwd,30);
        if(strcmp(u_name,name)==0&&strcmp(pwd,g_pwd)==0)
        {
            flag=1;
             string phrase = "\n\t\t\tYou have Successfully LOGGED IN ";
        string command = "espeak \"" + phrase + "\"";
    const char *charCommand = command.c_str();
        system(charCommand);
            break;
        }
        else if(strcmp(u_name,name)==0&&strcmp(pwd,g_pwd)!=0)
        {
            do
            {
                 string phrase = "\t\t\t----INCORRECT PASSWORD!!!----";
        string command = "espeak \"" + phrase + "\"";
    const char *charCommand = command.c_str();
        system(charCommand);

                           cout<<"Re-Enter the PASSWORD : "<<endl;

                cin>>pwd;
            }while(strcmp(pwd,g_pwd)!=0);

        string phrase = "\n\t\t\tYou have Successfully LOGGED IN";
        string command = "espeak \"" + phrase + "\"";
    const char *charCommand = command.c_str();
        system(charCommand);
            flag=1;
            break;
        }
    }
    if(flag==0)
        cout<<"\n\t\t\tSORRY!!! USER NAME and PASSWORD does not Exist"<<endl;
    system("clear");
    f.close();
    return flag;
}

void signup()
{
 cout<<"\n\n\n\n\n\n\t\t\t\t\t  \xdb\xdb\xdb\xdb\xdb\xdb\xdb\


#include <iostream>
#include <string>
#include <nlohmann/json.hpp>  // Assuming nlohmann/json is installed (via vcpkg install nlohmann-json)

// Needs to be compiled with C++11, use: g++ interface_sim.cpp -I./include -std=c++11 -o interface_sim to compile,.\interface_sim.exe to run

// Mock hardware function to simulate AXI write
int write_to_axi(uint32_t addr, uint8_t value) {
    std::cout << "Mock AXI write: Address = " << addr << ", Value = " << static_cast<int>(value) << std::endl;
    return 0;  // Success
}

// Mock function to simulate reading odometer
uint32_t read_odometer() {
    std::cout << "Mock odometer read: Returning simulated value 42" << std::endl;
    return 42;  // Simulated value
}

// Function to parse and process SCPI command with JSON validation
void process_scpi_command(const std::string& scpi_cmd, const std::string& component_id, const nlohmann::json& config_json) {
    // Validate SCPI command (basic check: must start with "PATH:SELECT ")
    if (scpi_cmd.rfind("PATH:SELECT ", 0) != 0) {
        std::cout << "Invalid command format. Must be 'PATH:SELECT <number>'" << std::endl;
        return;
    }

    // Extract the path number (e.g., "3" from "PATH:SELECT 3")
    std::string path_str = scpi_cmd.substr(12); // Skip "PATH:SELECT "
    int id_num;
    try {
        id_num = std::stoi(path_str);
        if (id_num < 0 || id_num > 255) { // Assume 8-bit paths (0-255)
            std::cout << "Invalid path number. Must be 0-255" << std::endl;
            return;
        }
    } catch (...) {
        std::cout << "Invalid path number format" << std::endl;
        return;
    }

    // Validate against JSON configuration (assume JSON has a "paths" array with id, component_id, address, gpio_value)
    if (!config_json.contains("paths") || !config_json["paths"].is_array()) {
        std::cout << "JSON does not contain valid 'paths' array" << std::endl;
        return;
    }

    bool path_found = false;
    for (const auto& path : config_json["paths"]) {
        if (path["id"].get<int>() == id_num && path["component_id"].get<std::string>() == component_id) {
            path_found = true;
            // Extract address and gpio_value from the JSON
            uint32_t addr = path["address"].get<uint32_t>(); // Assume JSON has "address" field
            uint8_t gpio_value = path["gpio_value"].get<uint8_t>(); // Assume JSON has "gpio_value" field
            // Call mock hardware function
            if (write_to_axi(addr, gpio_value) == 0) {
                uint32_t odometer = read_odometer(); // Call mock read
                std::cout << "Success: Path " << id_num << " (" << component_id << ") activated. Odometer: " << odometer << std::endl;
            } else {
                std::cout << "Mock hardware write failed" << std::endl;
            }
            break;
        }
    }

    if (!path_found) {
        std::cout << "Path " << id_num << " with component_id " << component_id << " not found in JSON configuration" << std::endl;
    }
}

int main() {
    // Simulate receiving a SCPI command (hardcoded for standalone execution)
    std::string scpi_cmd = "PATH:SELECT 3";

    // Simulate component_id as a separate argument
    std::string component_id = "switch1";

    // Simulate a JSON configuration (hardcoded; in real scenario, load from file)
    std::string json_str = R"({
        "paths": [
            {"id": 1, "component_id": "switch1", "address": 268436224, "gpio_value": 1},
            {"id": 2, "component_id": "switch1", "address": 268436224, "gpio_value": 2},
            {"id": 3, "component_id": "switch1", "address": 268436224, "gpio_value": 3},
            {"id": 1, "component_id": "switch2", "address": 268436480, "gpio_value": 1}
        ]
    })";

    nlohmann::json config_json = nlohmann::json::parse(json_str);

    // Process the command
    process_scpi_command(scpi_cmd, component_id, config_json);

    return 0;
}


/****************************************************************************
** Meta object code from reading C++ file 'MediaPlayer.h'
**
** Created by: The Qt Meta Object Compiler version 69 (Qt 6.10.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/

#include "../../../core/MediaPlayer.h"
#include <QtCore/qmetatype.h>

#include <QtCore/qtmochelpers.h>

#include <memory>

#include <QtCore/qxptype_traits.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'MediaPlayer.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 69
#error "This file was generated using the moc from 6.10.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif

#ifndef Q_CONSTINIT
#define Q_CONSTINIT
#endif

QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
QT_WARNING_DISABLE_GCC("-Wuseless-cast")
namespace {
struct qt_meta_tag_ZN14VlcMediaPlayerE_t {};
} // unnamed namespace

template <> constexpr inline auto VlcMediaPlayer::qt_create_metaobjectdata<qt_meta_tag_ZN14VlcMediaPlayerE_t>()
{
    namespace QMC = QtMocConstants;
    QtMocHelpers::StringRefStorage qt_stringData {
        "VlcMediaPlayer",
        "backward",
        "",
        "buffering",
        "buffer",
        "end",
        "error",
        "forward",
        "lengthChanged",
        "length",
        "mediaChanged",
        "libvlc_media_t*",
        "media",
        "nothingSpecial",
        "opening",
        "pausableChanged",
        "pausable",
        "paused",
        "playing",
        "positionChanged",
        "position",
        "seekableChanged",
        "seekable",
        "snapshotTaken",
        "filename",
        "stopped",
        "timeChanged",
        "time",
        "titleChanged",
        "title",
        "vout",
        "count",
        "stateChanged",
        "setTime",
        "setPosition",
        "pos",
        "setPlaybackRate",
        "rate",
        "play",
        "pause",
        "togglePause",
        "resume",
        "stop"
    };

    QtMocHelpers::UintData qt_methods {
        // Signal 'backward'
        QtMocHelpers::SignalData<void()>(1, 2, QMC::AccessPublic, QMetaType::Void),
        // Signal 'buffering'
        QtMocHelpers::SignalData<void(float)>(3, 2, QMC::AccessPublic, QMetaType::Void, {{
            { QMetaType::Float, 4 },
        }}),
        // Signal 'buffering'
        QtMocHelpers::SignalData<void(int)>(3, 2, QMC::AccessPublic, QMetaType::Void, {{
            { QMetaType::Int, 4 },
        }}),
        // Signal 'end'
        QtMocHelpers::SignalData<void()>(5, 2, QMC::AccessPublic, QMetaType::Void),
        // Signal 'error'
        QtMocHelpers::SignalData<void()>(6, 2, QMC::AccessPublic, QMetaType::Void),
        // Signal 'forward'
        QtMocHelpers::SignalData<void()>(7, 2, QMC::AccessPublic, QMetaType::Void),
        // Signal 'lengthChanged'
        QtMocHelpers::SignalData<void(int)>(8, 2, QMC::AccessPublic, QMetaType::Void, {{
            { QMetaType::Int, 9 },
        }}),
        // Signal 'mediaChanged'
        QtMocHelpers::SignalData<void(libvlc_media_t *)>(10, 2, QMC::AccessPublic, QMetaType::Void, {{
            { 0x80000000 | 11, 12 },
        }}),
        // Signal 'nothingSpecial'
        QtMocHelpers::SignalData<void()>(13, 2, QMC::AccessPublic, QMetaType::Void),
        // Signal 'opening'
        QtMocHelpers::SignalData<void()>(14, 2, QMC::AccessPublic, QMetaType::Void),
        // Signal 'pausableChanged'
        QtMocHelpers::SignalData<void(bool)>(15, 2, QMC::AccessPublic, QMetaType::Void, {{
            { QMetaType::Bool, 16 },
        }}),
        // Signal 'paused'
        QtMocHelpers::SignalData<void()>(17, 2, QMC::AccessPublic, QMetaType::Void),
        // Signal 'playing'
        QtMocHelpers::SignalData<void()>(18, 2, QMC::AccessPublic, QMetaType::Void),
        // Signal 'positionChanged'
        QtMocHelpers::SignalData<void(float)>(19, 2, QMC::AccessPublic, QMetaType::Void, {{
            { QMetaType::Float, 20 },
        }}),
        // Signal 'seekableChanged'
        QtMocHelpers::SignalData<void(bool)>(21, 2, QMC::AccessPublic, QMetaType::Void, {{
            { QMetaType::Bool, 22 },
        }}),
        // Signal 'snapshotTaken'
        QtMocHelpers::SignalData<void(const QString &)>(23, 2, QMC::AccessPublic, QMetaType::Void, {{
            { QMetaType::QString, 24 },
        }}),
        // Signal 'stopped'
        QtMocHelpers::SignalData<void()>(25, 2, QMC::AccessPublic, QMetaType::Void),
        // Signal 'timeChanged'
        QtMocHelpers::SignalData<void(int)>(26, 2, QMC::AccessPublic, QMetaType::Void, {{
            { QMetaType::Int, 27 },
        }}),
        // Signal 'titleChanged'
        QtMocHelpers::SignalData<void(int)>(28, 2, QMC::AccessPublic, QMetaType::Void, {{
            { QMetaType::Int, 29 },
        }}),
        // Signal 'vout'
        QtMocHelpers::SignalData<void(i


#include "chartwindow.h"
#include <QtCharts>
#include <QVBoxLayout>
#include <QPushButton>

ChartWindow::ChartWindow(const QMap<int, int>& data, QWidget* parent)
    : QMainWindow(parent) {
    // Настройка окна
    setWindowTitle("График мотоциклов");
    resize(800, 600);

    // Создаем главный виджет
    QWidget* centralWidget = new QWidget(this);
    setCentralWidget(centralWidget);

    // Создаем вертикальный layout
    QVBoxLayout* layout = new QVBoxLayout(centralWidget);

    // Создаем график
    setupChart(data);

    // Создаем кнопку "Закрыть"
    QPushButton* closeButton = new QPushButton("Закрыть", this);
    connect(closeButton, &QPushButton::clicked, this, &ChartWindow::close);

    // Добавляем кнопку в layout
    layout->addWidget(closeButton);
}

void ChartWindow::setupChart(const QMap<int, int>& data) {
    QBarSet* set = new QBarSet("Мотоциклы");
    QStringList categories;

    for (auto it = data.begin(); it != data.end(); ++it) {
        *set << it.value();
        categories << QString::number(it.key());
    }

    QBarSeries* series = new QBarSeries();
    series->append(set);

    QChart* chart = new QChart();
    chart->addSeries(series);
    chart->setTitle("Количество мотоциклов по годам производства");
    chart->setAnimationOptions(QChart::SeriesAnimations);

    QBarCategoryAxis* axisX = new QBarCategoryAxis();
    axisX->append(categories);
    chart->addAxis(axisX, Qt::AlignBottom);
    series->attachAxis(axisX);

    QValueAxis* axisY = new QValueAxis();
    chart->addAxis(axisY, Qt::AlignLeft);
    series->attachAxis(axisY);

    QChartView* chartView = new QChartView(chart);
    chartView->setRenderHint(QPainter::Antialiasing);

    centralWidget()->layout()->addWidget(chartView);
}


#include <vector>
#include <memory>
#include <string>
#include <algorithm>
#include <functional>
#include <iterator>
#include <stdexcept>
#include <queue>
#include <stack>
#include <type_traits>

template <typename T>
class NaryTreeAutoRebalancing {
public:
    class Node {
        friend class NaryTreeAutoRebalancing<T>;
    private:
        T data_;
        std::vector<std::unique_ptr<Node>> children_;
        Node* parent_;

    public:
        explicit Node(T data, Node* parent = nullptr)
            : data_(std::move(data)), parent_(parent) {}

        ~Node() = default;

        // Move and copy semantics
        Node(const Node&) = delete;
        Node& operator=(const Node&) = delete;
        Node(Node&&) = default;
        Node& operator=(Node&&) = default;

        // Data access
        const T& data() const noexcept { return data_; }
        T& data() noexcept { return data_; }
        void set_data(T new_data) { data_ = std::move(new_data); }

        // Child management with automatic rebalancing
        Node& add_child(T child_data) {
            auto child = std::make_unique<Node>(std::move(child_data), this);
            Node* child_ptr = child.get();
            children_.push_back(std::move(child));

            // Trigger rebalancing at tree level after modification
            // This will be handled by the tree's add_child method

            return *child_ptr;
        }

        void add_child(std::unique_ptr<Node> child) {
            if (child) {
                child->parent_ = this;
                children_.push_back(std::move(child));
                // Rebalancing will be triggered at tree level
            }
        }

        bool remove_child(const Node* child) {
            auto it = std::find_if(children_.begin(), children_.end(),
                [child](const std::unique_ptr<Node>& ptr) { return ptr.get() == child; });

            if (it != children_.end()) {
                children_.erase(it);
                // Rebalancing will be triggered at tree level
                return true;
            }
            return false;
        }

        void remove_all_children() {
            children_.clear();
            // Rebalancing will be triggered at tree level
        }

        // Child access
        size_t child_count() const noexcept { return children_.size(); }
        bool is_leaf() const noexcept { return children_.empty(); }

        Node& child(size_t index) {
            if (index >= children_.size()) {
                throw std::out_of_range("Child index out of range");
            }
            return *children_[index];
        }

        const Node& child(size_t index) const {
            if (index >= children_.size()) {
                throw std::out_of_range("Child index out of range");
            }
            return *children_[index];
        }

        // Parent access
        Node* parent() noexcept { return parent_; }
        const Node* parent() const noexcept { return parent_; }
        bool is_root() const noexcept { return parent_ == nullptr; }

        // Tree navigation
        size_t depth() const {
            size_t max_depth = 0;
            for (const auto& child : children_) {
                max_depth = std::max(max_depth, child->depth());
            }
            return max_depth + 1;
        }

        size_t height_from_root() const {
            size_t height = 0;
            const Node* current = this;
            while (current->parent_ != nullptr) {
                current = current->parent_;
                ++height;
            }
            return height;
        }

        size_t total_nodes() const {
            size_t count = 1;
            for (const auto& child : children_) {
                count += child->total_nodes();
            }
            return count;
        }

        // Tree traversal
        template<typename Func>
        void for_each_preorder(Func&& func) {
            func(*this);
            for (auto& child : children_) {
                child->for_each_preorder(std::forward<Func>(func));
            }
        }

        template<typename Func>
        void for_each_postorder(Func&& func) {
            for (auto& child : children_) {
                child->for_each_postorder(std::forward<Func>(func));
            }
            func(*this);
        }

        template<typename Func>
        void for_each_levelorder(Func&& func) {
            std::queue<Node*> queue;
            queue.push(this);

            while (!queue.empty()) {
                Node* current = queue.front();
                queue.pop();
                func(*current);

                for (auto& child : current->children_) {
                    queue.push(child.get());
                }
            }
        }


#include "asymptoticVariance.h"

// Custom GSL error handler
void gsl_custom_error_handler(const char *reason, const char *file, int line, int gsl_errno) {
    // std::cout << "GSL Error: " << reason << " at " << file << ":" << line << " (Error code: " << gsl_errno << ")" << std::endl;
    throw std::runtime_error(reason);
}

// Call this function before using GSL functions
void set_gsl_custom_handler() {
    gsl_set_error_handler(&gsl_custom_error_handler);
}

arma::vec softmax (arma::vec pi_arr) {
    int n_support = pi_arr.n_elem + 1;
    arma::vec pi_trans(n_support);

    double temp = 0;
    for (int i = 0; i < n_support - 1; i++) {
        pi_trans(i) = (1 - temp) * pi_arr(i);
        temp += pi_trans(i);
    }

    pi_trans(n_support - 1) = 1 - temp;

    return pi_trans;
}

arma::mat x_matrix(const arma::vec& alloc, int n_support, int n_factor, int n_unit) {
    if ((double)(alloc.n_elem + 1) / (double)n_support != (n_factor + 1)) {
        Rcpp::Rcout << "Number of supports and given allocation do not match." << std::endl;
        return arma::mat(1, 1, arma::fill::zeros);
    }

    arma::vec levels, pi_arr, level_pi;
    if (n_support <= 1) {
        levels = alloc;
        level_pi = {1};
    } else {
        levels = alloc.subvec(0, alloc.n_elem - n_support);
        pi_arr = alloc.subvec(alloc.n_elem - n_support + 1, alloc.n_elem - 1);
        level_pi = softmax(pi_arr);
    }

    // Calculate the number of units for each level
    level_pi = arma::round(level_pi * n_unit);
    level_pi(n_support - 1) = n_unit - sum(level_pi.head(n_support - 1));

    // Create the measure matrix with an intercept
    arma::mat measure_matrix(n_support, n_factor + 2);
    measure_matrix.col(0).ones();
    for (int i = 0; i < n_factor; ++i) {
        measure_matrix.col(i + 1) = levels.subvec(i * n_support, (i + 1) * n_support - 1);
    }
    measure_matrix.col(n_factor + 1) = level_pi;

    return measure_matrix;
}

arma::vec std_failure_time(double failure_time, const arma::mat& x_matrix, double sigma, const arma::vec& coef) {
    int n_var = coef.n_elem;
    int x_var = x_matrix.n_cols;
    int n_support = x_matrix.n_rows;
    if (n_var != x_var) {
        return {0};
    }

    arma::vec std_time(n_support, arma::fill::zeros);
    for (int i = 0; i < n_support; ++i) {
        double mu = arma::dot(x_matrix.row(i), coef);
        std_time(i) = (log(failure_time) - mu) / sigma;
    }
    return std_time;
}

arma::vec p_failure_time(const arma::vec& std_time, int distribution) {
    int n_support = std_time.n_elem;
    arma::vec phi_z(n_support, arma::fill::zeros);
    for (int i = 0; i < n_support; ++i) {
        if (distribution == 1) {
            phi_z(i) = 1 - exp(-exp(std_time(i))); // CDF of SEV distribution
        } else if (distribution == 2) {
            phi_z(i) = gsl_cdf_gaussian_P(std_time(i), 1); // CDF of normal distribution
        }
    }
    return phi_z;
}

double z_sqr_exp_z (double z, void * params) {
    (void)(params);
    return pow(log(z), 2) * z * exp(-z);
}

double z_exp_z (double z, void * params) {
    (void)(params);
    return log(z) * z * exp(-z);
}

double integrate_z_sqr_exp_z (double lower,
                             double upper) {

    gsl_set_error_handler(&gsl_custom_error_handler);

    double result, error;

    gsl_integration_workspace *workspace = gsl_integration_workspace_alloc(constants::INTEG_WORK_ALLOC);
    gsl_function F;
    F.function = &z_sqr_exp_z;
    F.params = nullptr;

    int status = gsl_integration_qags(&F, lower, upper, constants::INTEG_REL_TOL, constants::INTEG_ABS_TOL, constants::INTEG_WORK_ALLOC, workspace, &result, &error);
    gsl_integration_workspace_free(workspace);

    if (status != GSL_SUCCESS) {
        throw std::runtime_error("GSL Integration Failed");
    }

    return result;
}

double integrate_z_exp_z (double lower,
                         double upper) {

    gsl_set_error_handler(&gsl_custom_error_handler);

    double result, error;

    gsl_integration_workspace *workspace = gsl_integration_workspace_alloc(constants::INTEG_WORK_ALLOC);
    gsl_function F;
    F.function = &z_exp_z;
    F.params = nullptr;

    int status = gsl_integration_qags(&F, lower, upper, constants::INTEG_REL_TOL, constants::INTEG_ABS_TOL, constants::INTEG_WORK_ALLOC, workspace, &result, &error);
    gsl_integration_workspace_free(workspace);

    if (status != GSL_SUCCESS) {
        throw std::runtime_error("GSL Integration Failed");
    }

    return result;
}

double expected_hes_sigma(const arma::vec& std_censor,
                          const arma::vec& p_censor,
                          const arma::vec& alloc_unit,
                          double sigma,
                          int distribution) {
    int n_support = std_censor.n_elem;
    double n_info = 0;

    for (int i = 0; i < n_support; i++) {
        if (distribution == 1) {
            double expected_z_sqr_exp_z = integrate_z_sqr_exp_z(0, exp(std_censor[i]));


#include <chrono>
#include <iostream>
#include <stdexcept>
#include <string>

#include "FizzBuzz.hpp"

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        std::cerr << "An integer argument is required to run this program!\n"
                  << "Example: \"" << argv[0] << " 100\"\n";
        return 1;
    }

    int n;
    try
    {
        n = std::stoi(argv[1]);
    }
    catch (const std::invalid_argument& ia)
    {
        std::cerr << "Error: Invalid argument. Not a number: " << argv[1] << "\n";
        return 1;
    }
    catch (const std::out_of_range& oor)
    {
        std::cerr << "Error: Argument out of range: " << argv[1] << "\n";
        return 1;
    }

    const auto start = std::chrono::high_resolution_clock::now();
    FizzBuzz(n);
    const auto end = std::chrono::high_resolution_clock::now();
    const auto durationMicroseconds = std::chrono::duration_cast<std::chrono::microseconds>(end - start);

    std::cout << "Program execution time: " << durationMicroseconds.count() << " Microseconds" << "\n";

    return 0;
}


#include "kernel/h/echo.h"
#include "kernel/h/context.h"
#include "kernel/h/setofid.h"
#include "storage/h/subject.h"

#include "message/comanmsg.h"
#include "message/groupmsg.h"
#include "enum/spaceenum.h"

#include "i/route.i"
#include "i/commander.i"

#define HANDLE int
#include "storage\h\savefile.h"

#define MAX_MEMBER 250
#define GROUP_MAX_ROUTE_NUM 4

s_ELN commanderMsgNames[] =
 {
   s_ELN(COMMANDER_ADD_MEMBER_N,"COMMANDER_ADD_MEMBER_N"),
   s_ELN(com_EV_GROUP_REACHED,"com_EV_GROUP_REACHED"),
   s_ELN(com_EV_GROUP_TARGET_DESTROYED,"com_EV_GROUP_TARGET_DESTROYED"),
   s_ELN(com_EV_GROUP_YOUR_MY_MEMBER,"com_EV_GROUP_YOUR_MY_MEMBER"),
   s_ELN(com_EV_PLANE0,"com_EV_PLANE0"),
   s_ELN()
 };

s_ELNTable commanderMsgTable("Commander messages",commanderMsgNames);

class GroupMember{
public:
    GroupMember() {  m_routeCnt = m_curRoute = 0; m_patrol = 0; }

	KR_ObjectID m_id;
	int m_patrol;
	int m_routeCnt;
	int m_curRoute;
	struct Route
        {
	    KR_ObjectID id;
	    int repCnt;
	    int repeated;
	    int patrol;
	    int curNode;
	    int nodeCnt;
	    int dir;
	    double waitNext;

            void reset()
            {
                repCnt    =
                repeated =
                waitNext =
                nodeCnt  =
                curNode  = 0;
                dir = 1;
                patrol = FALSE;
            }

            Route()
            {
                reset();
            }
	}
          m_route[GROUP_MAX_ROUTE_NUM];

        void reset()
        {
            m_id = KR_ObjectID::NUL();
            m_patrol   = 0;
            m_routeCnt = 0;
            m_curRoute = 0;

            for( int i = 0; i < GROUP_MAX_ROUTE_NUM; ++i )
                 m_route[i].reset();
        }
};

typedef struct {
	GroupMember  m_member[MAX_MEMBER];
    int          m_memberQnty;

    double       m_xMoving,m_zMoving;
    int          m_wMoving,m_dMoving;

	KR_SetOfID	 m_hostileCommanders;
	KR_SetOfID	 m_friendlyCommanders;

} CommanderData;

class com_Commander:	public ICommander,
						public ct_Object,
						public CommanderData
 {
 public:

	void *queryInterface( int interNum );

    virtual void addNotify();
    virtual int  receiveEvent(KR_Event &event);

    void LoadRoute(int rNum, const char *fName, const char *rName, int partol);
    int  loadRoute(const char *rName, const char *fName);
    void addRoute(int mNum,const char *rName, int patrol);
    void clrRoute(int mNum);
    void setToStart(int mNum,double ts);

	virtual bool	shouldDump () { return true; }
	virtual bool	dump(PIN_SaveFile & sf);
	virtual bool	load(PIN_SaveFile & sf);
	virtual void	loadNotify();

    virtual void       setFriendly(KR_ObjectID &);
    virtual void       setHostile (KR_ObjectID &);

    virtual int       isFriendly(KR_ObjectID &);
    virtual int       isHostile (KR_ObjectID &);

	//virtual void	  removeMember(KR_ObjectID &);

 };

class com_CommanderTable: public ct_ClassTable
 {
 private:
    com_Commander *m_table;
 public:
    com_CommanderTable()
    {
       registerClass("Commander");
    }
    virtual  void allocObjects( int objectQnty );
    virtual  void freeObjects();
    virtual  ct_Object  *getObjectPTR( int index );
 };

com_CommanderTable CommanderTable;

 /******************************
  *
  *       Commander
  *
  ******************************/

IRouteObject *newRoute( SimulationContext *c, const char *rname )
{
    KR_ObjectID rID = g_arena.newObject("Route",rname);
    if(  rID.isNUL()  )
         return 0;
    return (IRouteObject *)(c->queryInterface(rID,IRouteObjectIID));
}

void *com_Commander::queryInterface( int interNum )
{
    switch( interNum )
    {
    case IUnknownIID:   return (KR_Object  *) this;
    case ICommanderIID: return (ICommander *) this;
    }

    return 0;
}

//============================================================================
void com_Commander::addNotify()
 {
    m_memberQnty = 0;
    m_xMoving =  2060;
    m_zMoving = -2390;
    m_wMoving = 100;
    m_dMoving = 100;
 }
//============================================================================

/*void com_Commander::removeMember(KR_ObjectID &mID)
{
	for (int i = 0; i < m_memberQnty; i++)
		if (mID == m_member[i].m_id)
		{
			for (int j = i; j < m_memberQnty - 1; j++)
			{
				m_member[j] = m_member[j+1];
			}
			m_memberQnty--;
			break;
		}
}*/

//============================================================================
void com_Commander::LoadRoute(int rNum, const char *fName, const char *rName, int patrol){
	IRouteObject *route;

	route = newRoute(context, rName);
        if(  route==0  )
             return;

	route->Load(fName);
	m_member[rNum].m_route[m_member[rNum].m_routeCnt].id      = route->getID();
	m_member[rNum].m_route[m_member[rNum].m_routeC


// TractorInputsReal.cpp (or wherever this class lives)
// Complete, drop-in implementation using ESP32 PCNT for RPM measurement.

#include "TractorInputs.h"
#include <Arduino.h>
#include <math.h>
#include "driver/pcnt.h"

#ifndef ENABLE_SW_EMULATOR
#define ENABLE_SW_EMULATOR 1
#endif

// ========================= Tunables =========================
static constexpr int   PULSES_PER_REV = 2;      // Set per your source (coil/alt/crank)
static constexpr int   WINDOW_MS      = 100;    // Window for frequency over time
static constexpr float EMA_ALPHA      = 0.20f;  // Smoothing for display stability
// PCNT glitch filter: APB clock cycles (classic ESP32 APB ~80 MHz).
// 1000 cycles ≈ 12.5 µs. Tune to reject ignition noise without clipping legit pulses.
static constexpr uint16_t PCNT_GLITCH = 800;    // start ~8–12 µs; adjust after testing

// PCNT counter limits (int16 range on classic PCNT)
static constexpr int PCNT_H_LIM = 32767;
static constexpr int PCNT_L_LIM = -32768;

// ========================= Implementation =========================
class TractorInputsReal : public ITractorInputs {
public:
  void begin() override {
    // Discrete inputs (adjust polarity in read())
    pinMode(PIN_OIL,  INPUT_PULLUP);
    pinMode(PIN_BL_L, INPUT_PULLUP);
    pinMode(PIN_BL_R, INPUT_PULLUP);
    pinMode(PIN_HEAD, INPUT_PULLUP);
    pinMode(PIN_GLOW, INPUT_PULLUP);
    pinMode(PIN_BATT, INPUT_PULLUP);

    // RPM input — explicit is good practice even though PCNT will mux it
    pinMode(PIN_RPM, INPUT_PULLUP);

    setup_pcnt_();

    // Prime first update so the first read() computes immediately (avoids an initial 0)
    last_tick_ms_ = millis() - WINDOW_MS;
  }

  TractorState read() override {
    TractorState s{};

    // --------- RPM via PCNT (non-blocking windowed count) ---------
    if (pcnt_ok_) {
      const uint32_t now = millis();
      const uint32_t elapsed = now - last_tick_ms_;

      if (elapsed >= (uint32_t)WINDOW_MS) {
        // Commit a proper window sample: read & clear the hardware counter
        int16_t count = 0;
        pcnt_get_counter_value(PCNT_UNIT_0, &count);
        pcnt_counter_clear(PCNT_UNIT_0);
        last_tick_ms_ = now;

        // pulses/sec = count / (WINDOW_MS/1000)  ⇒  RPM = (pps * 60) / PPR
        const float pps = static_cast<float>(count) * (1000.0f / static_cast<float>(WINDOW_MS));
        const float rpm = (pps * 60.0f) / static_cast<float>(PULSES_PER_REV);

        // EMA smoothing for display/gauge stability
        rpm_filtered_ += EMA_ALPHA * (rpm - rpm_filtered_);
      } else if (elapsed >= 10) {
        // Optional: provisional estimate between windows (light touch)
        int16_t count_now = 0;
        pcnt_get_counter_value(PCNT_UNIT_0, &count_now);
        const float pps = static_cast<float>(count_now) * (1000.0f / static_cast<float>(elapsed));
        const float rpm = (pps * 60.0f) / static_cast<float>(PULSES_PER_REV);
        const float beta = 0.05f;  // gentle nudge; keeps non-blocking freshness
        rpm_filtered_ += beta * (rpm - rpm_filtered_);
      }

      s.rpm = static_cast<int>(roundf(rpm_filtered_));
    } else {
      // PCNT init failed; provide a safe default (or keep last)
      s.rpm = 0;
    }

    // --------- ADCs (placeholder scaling) ---------
    // NOTE: tune these scale factors to your actual sender curves.
    s.fuel_pct = constrain((analogRead(PIN_FUEL_ADC) / 4095.0f) * 100.0f, 0.0f, 100.0f);
    s.temp_c   = (analogRead(PIN_TEMP_ADC) / 4095.0f) * 120.0f;

    // --------- Digital inputs (adjust polarity to your wiring) ---------
    s.oil_ok     = (digitalRead(PIN_OIL)  == HIGH);
    s.bl_left    = (digitalRead(PIN_BL_L) == LOW);
    s.bl_right   = (digitalRead(PIN_BL_R) == LOW);
    s.headlights = (digitalRead(PIN_HEAD) == LOW);

    // Assumptions: glow indicator ON when signal LOW; battery OK when HIGH
    s.glow_on    = (digitalRead(PIN_GLOW) == LOW);
    s.battery_ok = (digitalRead(PIN_BATT) == HIGH);

    return s;
  }

private:
  void setup_pcnt_() {
    // Configure PCNT to count rising edges on PIN_RPM
    pcnt_config_t cfg{};
    cfg.pulse_gpio_num = static_cast<gpio_num_t>(PIN_RPM);
    cfg.ctrl_gpio_num  = PCNT_PIN_NOT_USED;
    cfg.unit           = PCNT_UNIT_0;
    cfg.channel        = PCNT_CHANNEL_0;
    cfg.pos_mode       = PCNT_COUNT_INC;   // count rising edges
    cfg.neg_mode       = PCNT_COUNT_DIS;   // ignore falling edges
    cfg.lctrl_mode     = PCNT_MODE_KEEP;
    cfg.hctrl_mode     = PCNT_MODE_KEEP;
    cfg.counter_h_lim  = PCNT_H_LIM;
    cfg.counter_l_lim  = PCNT_L_LIM;

    esp_err_t err = pcnt_unit_config(&cfg);
    if (err != ESP_OK) {
      pcnt_ok_ = false;
      return;
    }

    // Optional glitch filter to reject coil ringing / EMI
    if (PCNT_GLITCH > 0) {
      pcnt_set_filter_value(PCNT_UNIT_0, PCNT_GLITCH);
      pcnt_filter_enable(PCNT_UNIT_0);
    } else {
      pcnt_filter_disable(PCNT_UNIT_0);
    }

    pcnt_counter_clear(PCNT_UNIT_0);
    pcnt_counter_resume(PCNT_UNIT_0);
    pc


#include <iostream>
using namespace std;

// Q1) Menu-Driven Program for Array Operations
void menuDrivenArrayOperations() {
    int arr1[100], n1=0, choice1, pos1, val1, key1;
    while (true) {
        std::cout << "\n1.CREATE\n2.DISPLAY\n3.INSERT\n4.DELETE\n5.LINEAR SEARCH\n6.EXIT\nEnter choice: ";
        cin >> choice1;
        switch(choice1) {
            case 1:
                std::cout << "Enter size: "; cin >> n1;
                std::cout << "Enter elements: " << std::endl;
                for(int i=0;i<n1;i++) std::cin >> arr1[i];
                break;
            case 2:
                for(int i=0;i<n1;i++) std::cout << arr1[i] << " ";
                std::cout << std::endl;
                break;
            case 3:
                std::cout << "Enter position & value: "; std::cin >> pos1 >> val1;
                for(int i=n1;i>pos1;i--) arr1[i]=arr1[i-1];
                arr1[pos1]=val1; n1++;
                break;
            case 4:
                std::cout << "Enter position: "; std::cin >> pos1;
                for(int i=pos1;i<n1;i++) arr1[i]=arr1[i+1];
                n1--;
                break;
            case 5:
                std::cout << "Enter key: "; std::cin >> key1;
                for(int i=0;i<n1;i++) {
                    if(arr1[i]==key1) { std::cout << "Found at index " << i << std::endl; break; }
                    if(i==n1-1) std::cout << "Not Found\n";
                }
                break;
            case 6:
                return;
        }
    }
}

// Q2) Remove Duplicates
void removeDuplicates() {
    int n2; cin >> n2;
    int arr2[100];
    for(int i=0;i<n2;i++) cin >> arr2[i];
    for(int i=0;i<n2;i++) {
        for(int j=i+1;j<n2;j++) {
            if(arr2[i]==arr2[j]) {
                for(int k=j;k<n2-1;k++) arr2[k]=arr2[k+1];
                n2--; j--;
            }
        }
    }
    for(int i=0;i<n2;i++) std::cout << arr2[i] << " ";
    std::cout << std::endl;
}

// Q3) Predict Output => 10000
void predictOutput() {
    std::cout<< "Output of given program: 10000" << endl;
}

// Q4a) Reverse Array
void reverseArray() {
    int n4a; cin >> n4a;
    int arr4a[100];
    for(int i=0;i<n4a;i++) cin >> arr4a[i];
    for(int i=0,j=n4a-1;i<j;i++,j--) swap(arr4a[i],arr4a[j]);
    for(int i=0;i<n4a;i++) cout << arr4a[i] << " ";
    cout << endl;
}

// Q4b) Matrix Multiplication
void matrixMultiplication() {
    int r1,c1,r2,c2;
    cin >> r1 >> c1 >> r2 >> c2;
    if(c1!=r2) {
        cout << "Invalid dimensions" << endl;
        return;
    }
    int a[100][100], b[100][100], c[100][100]={0};
    for(int i=0;i<r1;i++) for(int j=0;j<c1;j++) cin >> a[i][j];
    for(int i=0;i<r2;i++) for(int j=0;j<c2;j++) cin >> b[i][j];
    for(int i=0;i<r1;i++)
        for(int j=0;j<c2;j++)
            for(int k=0;k<c1;k++)
                c[i][j]+=a[i][k]*b[k][j];
    for(int i=0;i<r1;i++){
        for(int j=0;j<c2;j++) cout<<c[i][j]<<" ";
        cout<<endl;
    }
}

// Q4c) Transpose of Matrix
void transposeMatrix() {
    int r4c,c4c; cin >> r4c >> c4c;
    int a4c[100][100];
    for(int i=0;i<r4c;i++) for(int j=0;j<c4c;j++) cin >> a4c[i][j];
    for(int i=0;i<c4c;i++){
        for(int j=0;j<r4c;j++) cout << a4c[j][i] << " ";
        cout << endl;
    }
}

// Q5) Row & Column Sum
void rowColSum() {
    int r5,c5;
    cin >> r5 >> c5;
    int a5[100][100];
    for(int i=0;i<r5;i++) for(int j=0;j<c5;j++) cin >> a5[i][j];
    for(int i=0;i<r5;i++){
        int sum=0;
        for(int j=0;j<c5;j++) sum+=a5[i][j];
        cout<<"Row "<<i<<" Sum: "<<sum<<endl;
    }
    for(int j=0;j<c5;j++){
        int sum=0;
        for(int i=0;i<r5;i++) sum+=a5[i][j];
        cout<<"Col "<<j<<" Sum: "<<sum<<endl;
    }
}

int main() {
    cout << "Choose a function to run:\n";
    cout << "1. Menu-driven Array Operations\n";
    cout << "2. Remove Duplicates\n";
    cout << "3. Predict Output\n";
    cout << "4. Reverse Array\n";
    cout << "5. Matrix Multiplication\n";
    cout << "6. Matrix Transpose\n";
    cout << "7. Row & Column Sum\n";
    cout << "8. Exit\n";
    int ch;
    while(true) {
        cout << "\nEnter choice: ";
        cin >> ch;
        switch(ch) {
            case 1: menuDrivenArrayOperations(); break;
            case 2: removeDuplicates(); break;
            case 3: predictOutput(); break;
            case 4: reverseArray(); break;
            case 5: matrixMultiplication(); break;
            case 6: transposeMatrix(); break;
            case 7: rowColSum(); break;
            case 8: return 0;
            default: cout << "Invalid choice!\n";
        }
    }
}


#include "logger.h"
#include<time.h>
#include<iostream>

//获取日志单例
Logger& Logger::GetInstance()
{
    static Logger logger;
    return logger;
}

Logger::Logger()
{
    //启动专门的写日志线程,使用lambda表达式
    std::thread writeLogTask([&](){
        for(;;)
        {
            //获取当天的日期，然后去取日志信息，写入相应的日志文件当中
            time_t now=time(nullptr);
            tm *nowtm=localtime(&now);

            char filename[128];
            sprintf(filename,"%d-%d-%d-log.txt",nowtm->tm_year+1900,nowtm->tm_mon+1,nowtm->tm_mday);

            FILE* pf=fopen(filename,"a+");
            if(pf==nullptr)
            {
                std::cout<<"logger file:"<<filename<<" open error!"<<std::endl;
                exit(EXIT_FAILURE);
            }

            std::string msg=m_lckQueue.Pop();

            //加入时分秒
            char time_buf[128]={0};
            sprintf(time_buf,"%d:%d:%d => [%s] ",
                    nowtm->tm_hour,
                    nowtm->tm_min,
                    nowtm->tm_sec,
                    (m_loglevel==INFO?"info":"error"));

            msg.insert(0,time_buf);
            msg.append("\n");

            fputs(msg.c_str(),pf);
            fclose(pf);
        }
    });
    writeLogTask.detach();//设置分离线程。相当于守护线程
}

//设置日志级别
void Logger::StLogLevel(LogLevel level)
{
    m_loglevel=level;
}

//写日志,把日志信息写入LockQueue缓冲区当中
void Logger::Log(std::string msg)
{
    m_lckQueue.Push(msg);
}


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

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

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

class Stack
{
private:
    Node *top;
    int height;

public:
    Stack(int value)
    {
        Node *newNode = new Node(value);
        top = newNode;
        height = 1;
    }

    void getTop()
    {
        cout << "TOP :" << top->value << endl;
    }

    void getHeight()
    {
        cout << "HEIGHT : " << height << endl;
    }

    void push(int value)
    {
        Node *newNode = new Node(value);
        // if empty; - no need to create if statements because the top already points to NULL in case of empty stack.
        if (top == NULL)
        {
            top = newNode;
            return;
            // if not empty;
        }
        else
        {
            newNode->next = top;
            top = newNode;
        }
        height++;
        return;
    }

    void printStack()
    {
        if(height == 0){
            cout << "empty stack" << endl;
            return;
        }

        Node *temp = top;
        while (temp != NULL)
        {
            cout << temp->value << " -> ";
            temp = temp->next;
        }
        cout << "END" << endl;
    }

    int pop(){
        // same as delete first
        // if empty
        if(top == NULL){
            return INT_MIN;
        }

        // if not empty
        Node* temp = top;
        int popped_value = top->value;
        top = top->next;
        delete temp;
        height--;

        return popped_value;
    }

    int count(){
        // basically no of items in stack == height
        // but programmatically
        int count_ = 0;
        Node* temp = top;
        while(temp!=NULL){
            count_++;
            temp = temp->next;
        }

        return count_;
    }

    void peek(){
        cout << top->value << endl;
    }

    void change(int index, int new_value){
        if(index < 0 || index >=height){
            cout << "invalid index" << endl;
            return;
        }

        if(index == 0){
            top->value = new_value;
        }else{
            Node* temp = top;
            for(int i=0;i<index;i++){
                temp = temp->next;
            }
            temp->value = new_value;
        }
    }
};

int main()
{
    Stack *s = new Stack(0);
    s->push(1);
    s->push(2);
    s->push(3);
    s->push(4);
    s->printStack();
    cout << s->count() << endl;
    s->peek();
    s->change(0,100);
    s->printStack();
}


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

using namespace std;

int main() {
    //create zoto app facade
    Zoto* zoto = new Zoto();

    //simulate a user comming in (happy flow)
    User*user = new User(101, "Aditya", "Delhi");
    cout << "User: " << user->getName() << " is active." << endl;

    //user searches for restaurant by location
    vector<Restaurant*> restaurantList = zoto->searchRestaurants("Delhi");

    if(restaurantList.empty()) {
        cout << "No restaurant found!!" << endl;
        return 0;
    }

    cout << "Found Restauarnts: " << endl;
    for(auto restauarnt : restaurantList) {
        cout << "-" << restauarnt->getName() << endl;
    }

    // user selects a restaurant
    zoto->selectRestauarnt(user, restaurantList[0]);
    cout << "selected restauarnt: " << restaurantList[0]->getName() << endl;

    //user adds item to cart
    zoto->addToCart(user, "p1");
    zoto->addToCart(user, "p2");

    zoto->printUserCart(user);

    //user checkout the cart
    Order* order = zoto->checkOutNow(user, "Delivery", new UpiPaymentStrategy("1234567890"));

    //user pay for cart.if payment is success, notification is sent
    zoto->payForOrder(user, order);

    //clenup code
    delete zoto;
    delete user;

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

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

  ::CoUninitialize();
  return EXIT_SUCCESS;
}


// Boost.Range library
//
//  Copyright Neil Groves 2010. Use, modification and
//  distribution is subject to the Boost Software License, Version
//  1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//
//
// For more information, see http://www.boost.org/libs/range/
//
#include <boost/range/algorithm_ext/is_sorted.hpp>

#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test.hpp>

#include <boost/range/iterator.hpp>
#include <algorithm>
#include <list>
#include <vector>

namespace
{
    template< class Container >
    void test_is_sorted_impl()
    {
        Container ascending;
        Container descending;

        // Empty ranges are regarded as sorted against any predicate.
        BOOST_CHECK( boost::is_sorted(ascending) );
        BOOST_CHECK( boost::is_sorted(ascending, std::less<std::size_t>()) );
        BOOST_CHECK( boost::is_sorted(ascending, std::greater<std::size_t>()) );

        for (std::size_t i = 0; i < 10; ++i)
        {
            ascending.push_back(i);
            descending.push_back(9 - i);
        }

        BOOST_CHECK( boost::is_sorted(ascending) );
        BOOST_CHECK( !boost::is_sorted(descending) );
        BOOST_CHECK( !boost::is_sorted(ascending, std::greater<std::size_t>()) );
        BOOST_CHECK( boost::is_sorted(descending, std::greater<std::size_t>()) );
    }

    void test_is_sorted()
    {
        test_is_sorted_impl< std::vector<std::size_t> >();
        test_is_sorted_impl< std::list<std::size_t> >();
    }
}

boost::unit_test::test_suite*
init_unit_test_suite(int argc, char* argv[])
{
    boost::unit_test::test_suite* test
        = BOOST_TEST_SUITE( "RangeTestSuite.algorithm_ext.is_sorted" );

    test->add( BOOST_TEST_CASE( &test_is_sorted ) );

    return test;
}


// core/lexer.cpp generated by reflex 5.1.0 from ../assets/lex/tiecode.l

#define REFLEX_VERSION "5.1.0"

////////////////////////////////////////////////////////////////////////////////
//                                                                            //
//  OPTIONS USED                                                              //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////

#undef REFLEX_OPTION_debug
#undef REFLEX_OPTION_dotall
#undef REFLEX_OPTION_graphs_file
#undef REFLEX_OPTION_header_file
#undef REFLEX_OPTION_lex
#undef REFLEX_OPTION_lexer
#undef REFLEX_OPTION_namespace
#undef REFLEX_OPTION_outfile
#undef REFLEX_OPTION_perf_report
#undef REFLEX_OPTION_unicode

#define REFLEX_OPTION_debug               true
#define REFLEX_OPTION_dotall              true
#define REFLEX_OPTION_graphs_file         "../assets/lex/tiecode.gv"
#define REFLEX_OPTION_header_file         "include/lexer.h"
#define REFLEX_OPTION_lex                 lex
#define REFLEX_OPTION_lexer               TiecodeLexer
#define REFLEX_OPTION_namespace           NS_TIEC
#define REFLEX_OPTION_outfile             "core/lexer.cpp"
#define REFLEX_OPTION_perf_report         true
#define REFLEX_OPTION_unicode             true

// --debug option enables ASSERT:
#define ASSERT(c) assert(c)

// --perf-report option requires a timer:
#include <reflex/timer.h>

////////////////////////////////////////////////////////////////////////////////
//                                                                            //
//  SECTION 1: %top user code                                                 //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////

#line 3 "../assets/lex/tiecode.l"

#include <stdio.h>
#include "macro.h"
#include "token.h"
#include "lexer.h"

////////////////////////////////////////////////////////////////////////////////
//                                                                            //
//  LEXER CLASS INCLUDE                                                       //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////

#include "include/lexer.h"

////////////////////////////////////////////////////////////////////////////////
//                                                                            //
//  SECTION 1: %{ user code %}                                                //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////

#line 12 "../assets/lex/tiecode.l"
/* main character classes */
#line 18 "../assets/lex/tiecode.l"
/* comments */
#line 24 "../assets/lex/tiecode.l"
/* identifiers */
#line 27 "../assets/lex/tiecode.l"
/* integer literals */
#line 37 "../assets/lex/tiecode.l"
/* floating point literals */
#line 45 "../assets/lex/tiecode.l"
/* string and character literals */

////////////////////////////////////////////////////////////////////////////////
//                                                                            //
//  SECTION 2: rules                                                          //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////

int NS_TIEC::TiecodeLexer::lex(void)
{
  static const char REGEX_INITIAL[40885] = { '(', '?', 'm', 's', ')', '(', '(', '?', ':', '\\','Q', -27, -116, -123, -27, -112, -115, '\\','E', ')', ')', '|', '(', '(', '?', ':', '\\','Q', -25, -79, -69, '\\','E', ')', ')', '|', '(', '(', '?', ':', '\\','Q', -25, -69, -89, -26, -119, -65, '\\','E', ')', ')', '|', '(', '(', '?', ':', '\\','Q', -27, -113, -104, -23, -121, -113, '\\','E', ')', ')', '|', '(', '(', '?', ':', '\\','Q', -27, -72, -72, -23, -121, -113, '\\','E', ')', ')', '|', '(', '(', '?', ':', '\\','Q', -28, -72, -70, '\\','E', ')', ')', '|', '(', '(', '?', ':', '\\','Q', -26, -100, -84, -27, -81, -71, -24, -79, -95, '\\','E', ')', ')', '|', '(', '(', '?', ':', '\\','Q', -25, -120, -74, -27, -81, -71, -24, -79, -95, '\\','E', ')', ')', '|', '(', '(', '?', ':', '\\','Q', -27, -79, -98, -28, -70, -114, '\\','E', ')', ')', '|', '(', '(', '?', ':', '\\','Q', -27, -120, -101, -27, -69, -70, '\\','E', ')', ')', '|', '(', '(', '?', ':', '\\','Q', -24, -65, -108, -27, -101, -98, '\\','E', ')', ')', '|', '(', '(', '?', ':', '\\','Q', -25, -69, -109, -26, -99, -97, '\\','E', ')', ')', '|', '(', '(', '?', ':', '\\','Q', -27, -79, -98, -26, -128, -89, '\\','E', ')', ')', '|', '(', '(', '?', ':', '\\','Q', -28, -70, -117, -28, -69, -74, '\\','E', ')', ')', '|', '(', '(', '?', ':', '\\','Q', -27, -82, -102, -28, -71, -119, -28, -70, -117, -28, -6


/****************************************************************
 *  stainless_calculator.c
 *  不锈钢多型材理论重量计算器
 *  支持: 板、圆钢、六角钢、方钢、扁钢、角钢、圆管、方管、矩形管
 *  编译: gcc stainless_calculator.c -o stainless
 ****************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

/* ----------------------------------------------------------
 *  根据钢种返回密度值
 * ----------------------------------------------------------*/
static double get_density(const char *grade)
{
    /* 7.93 组 */
    if (strstr("201,202,301,302,304,304L,305,321", grade))
        return 7.93;
    /* 7.75 组 */
    if (strstr("405,410,420,420J2,430,431", grade))
        return 7.75;
    /* 7.98 组 */
    if (strstr("309S,310S,316,316L,316Ti,347", grade))
        return 7.98;
    /* 未知则按最常用的 304 */
    return 7.93;
}

/* ----------------------------------------------------------
 *  菜单
 * ----------------------------------------------------------*/
static void menu(void)
{
    puts("\n========== 不锈钢理论重量计算器 =========");
    puts("1  不锈钢板");
    puts("2  不锈钢圆钢");
    puts("3  不锈钢六角钢");
    puts("4  不锈钢方钢");
    puts("5  不锈钢扁钢");
    puts("6  不锈钢角钢");
    puts("7  不锈钢圆管");
    puts("8  不锈钢方管");
    puts("9  不锈钢矩形管");
    puts("0  退出");
    printf("请选择型材类型: ");
}

/* ----------------------------------------------------------
 *  各型材计算函数
 * ----------------------------------------------------------*/
static void plate(void)
{
    double t, w, l;
    char grade[16];
    printf("厚度(mm) 宽度(mm) 长度(mm): ");
    scanf("%lf%lf%lf", &t, &w, &l);
    printf("钢种(如304): ");
    scanf("%15s", grade);
    double rho = get_density(grade);
    double kg = t * w * l * rho / 1e6;   /* 公式：t*w*l*ρ，结果kg/张 */
    printf("理论重量: %.3f kg/张\n", kg);
}

static void rod_round(void)
{
    double d, l;
    char grade[16];
    printf("直径(mm) 长度(m): ");
    scanf("%lf%lf", &d, &l);
    printf("钢种(如304): ");
    scanf("%15s", grade);
    double factor = (strstr("410,420,430", grade)) ? 0.00609 : 0.00623;
    double kg_m = d * d * factor;        /* kg/m */
    printf("理论重量: %.3f kg/m，共 %.3f kg\n", kg_m, kg_m * l);
}

static void hex(void)
{
    double s, l;
    printf("对边(mm) 长度(m): ");
    scanf("%lf%lf", &s, &l);
    double kg_m = s * s * 0.00686;
    printf("理论重量: %.3f kg/m，共 %.3f kg\n", kg_m, kg_m * l);
}

static void square_bar(void)
{
    double a, l;
    printf("边宽(mm) 长度(m): ");
    scanf("%lf%lf", &a, &l);
    double kg_m = a * a * 0.00793;
    printf("理论重量: %.3f kg/m，共 %.3f kg\n", kg_m, kg_m * l);
}

static void flat_bar(void)
{
    double t, w, l;
    printf("厚度(mm) 宽度(mm) 长度(m): ");
    scanf("%lf%lf%lf", &t, &w, &l);
    double kg_m = t * w * 0.00793;
    printf("理论重量: %.3f kg/m，共 %.3f kg\n", kg_m, kg_m * l);
}

static void angle(void)
{
    double a, t, l;
    char way;
    printf("角钢算法：\n"
           "  a) 边长*边长*7.8*0.000198\n"
           "  b) (边宽+边宽-边厚)*边厚*0.00793\n"
           "请选择(a/b): ");
    scanf(" %c", &way);
    if (way == 'a') {
        printf("边长(mm) 长度(m): ");
        scanf("%lf%lf", &a, &l);
        double kg_m = a * a * 7.8 * 0.000198;
        printf("理论重量: %.3f kg/m，共 %.3f kg\n", kg_m, kg_m * l);
    } else {
        printf("边宽(mm) 边厚(mm) 长度(m): ");
        scanf("%lf%lf%lf", &a, &t, &l);
        double kg_m = (a + a - t) * t * 0.00793;
        printf("理论重量: %.3f kg/m，共 %.3f kg\n", kg_m, kg_m * l);
    }
}

static void pipe_round(void)
{
    double od, t, l;
    printf("外径(mm) 壁厚(mm) 长度(m): ");
    scanf("%lf%lf%lf", &od, &t, &l);
    double kg_m = (od - t) * t * 0.02491;
    printf("理论重量: %.3f kg/m，共 %.3f kg\n", kg_m, kg_m * l);
}

static void pipe_square(void)
{
    double a, t, l;
    printf("外边长(mm) 壁厚(mm) 长度(m): ");
    scanf("%lf%lf%lf", &a, &t, &l);
    double kg_m = (a * 4 / 3.1415926 - t) * t * 0.02491;
    printf("理论重量: %.3f kg/m，共 %.3f kg\n", kg_m, kg_m * l);
}

static void pipe_rect(void)
{
    double a, b, t, l;
    printf("外边长1(mm) 外边长2(mm) 壁厚(mm) 长度(m): ");
    scanf("%lf%lf%lf%lf", &a, &b, &t, &l);
    double kg_m = 0.0246615 * ((a + b) * 2 / 3.1415926 - t) * t;
    printf("理论重量: %.3f kg/m，共 %.3f kg\n", kg_m, kg_m * l);
}

/* ----------------------------------------------------------
 *  主循环
 * ----------------------------------------------------------*/
int main(void)
{
    int choice;
    while (1) {
        menu();
        if (scanf("%d", &choice) != 1) break;
        switch (choice) {
            case 1: plate();        break;
            case 2: rod_round();    break;
            case 3: hex();          break;
            case 4: square_bar();   break;
            case 5: flat_bar();     break;
            case 6: angle();        break;
            case 7: pipe_round();   break;
            case 8: pipe_square();  break;
            case 9: pipe_rect();    break;
            case 0: puts("Bye!");   return 0;
            de


// find_icons.cpp

#include <QApplication>
#include <QDebug>
#include <QDir>
#include <QDirIterator>
#include <QFileInfo>
#include <QIcon>
#include <QStandardPaths>
#include <QSvgRenderer>
#include <QImage>
#include <QPixmap>
#include <QPainter>
#include <QStyle>

static const QStringList allowedExts = { "png", "svg", "xpm", "ico", "bmp" };

void scanFilesystemRecursive(const QString &root, const QString &iconName, QVector<QString> &out) {
    if (!QDir(root).exists()) return;
    QStringList filters;
    for (const QString &e : allowedExts) filters << QString("*.%1").arg(e);
    QDirIterator it(root, filters, QDir::Files | QDir::NoSymLinks, QDirIterator::Subdirectories);
    while (it.hasNext()) {
        QString path = it.next();
        if (QFileInfo(path).baseName().compare(iconName, Qt::CaseInsensitive) == 0)
            out.append(path);
    }
}

void scanResourcesRecursive(const QString &iconName, QVector<QString> &out) {
    // iterate over the resource tree (":/") recursively
    QStringList filters;
    for (const QString &e : allowedExts) filters << QString("*.%1").arg(e);
    QDirIterator it(":/", filters, QDir::Files | QDir::NoSymLinks, QDirIterator::Subdirectories);
    while (it.hasNext()) {
        QString path = it.next();
        // debug looping resource files
        /*
        if (
            // !path.startsWith(":/icons/breeze/") &&
            !path.startsWith(QString(":/icons/%1/").arg(QIcon::themeName())) &&
            !path.startsWith(":/qt-project.org/") &&
            true
        ) {
            qDebug() << "scanResourcesRecursive: path = " << path;
        }
        */
        if (QFileInfo(path).baseName().compare(iconName, Qt::CaseInsensitive) == 0)
            out.append(path);
    }
}

QImage loadCandidateImage(const QString &path, int size) {
    QString suf = QFileInfo(path).suffix().toLower();
    if (suf == "svg") {
        QSvgRenderer renderer(path);
        if (!renderer.isValid()) return QImage();
        QImage img(size, size, QImage::Format_ARGB32);
        img.fill(Qt::transparent);
        QPainter p(&img);
        renderer.render(&p);
        return img;
    } else {
        QImage img;
        if (!img.load(path)) return QImage();
        if (img.size() != QSize(size, size))
            img = img.scaled(size, size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
        return img;
    }
}

int main(int argc, char **argv) {
    QApplication app(argc, argv);

    QString iconName = "koi_tray";
    bool doCompare = false;
    for (int i = 1; i < argc; ++i) {
        QString a = QString::fromLocal8Bit(argv[i]);
        if (a == "--compare") doCompare = true;
        else iconName = a;
    }

    qDebug() << "Searching for icon name:" << iconName;
    qDebug() << "QIcon theme name:" << QIcon::themeName();
    qDebug() << "QIcon theme search paths:";
    for (auto path : QIcon::themeSearchPaths()) {
        qDebug().noquote().nospace() << "  " << path;
    }

    // Build a list of candidate filesystem roots:
    QStringList roots = QIcon::themeSearchPaths();

    // Add common extra dirs and standard locations (no duplicates)
    QStringList extras = {
        "/usr/share/icons",
        "/usr/local/share/icons",
        "/usr/share/pixmaps",
    };
    for (const QString &loc : QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation)) {
        extras << QDir(loc).filePath("icons");
        extras << QDir(loc).filePath("pixmaps");
    }
    for (const QString &p : extras)
        if (!p.isEmpty() && !roots.contains(p)) roots << p;

    // Search filesystem recursively
    QVector<QString> found;
    for (const QString &root : roots) {
        scanFilesystemRecursive(root, iconName, found);
    }

    // Search resources (qrc)
    scanResourcesRecursive(iconName, found);

    if (found.isEmpty()) {
        qDebug() << "No matching files found in theme paths or resources.";
    } else {
        qDebug() << "Found candidates:";
        for (const QString &f : found) qDebug() << " -" << f;
    }

    if (doCompare) {
        qDebug() << "\nComparing to QIcon::fromTheme(...) pixmap:";
        QIcon themeIcon = QIcon::fromTheme(iconName);
        qDebug() << "  fromTheme().isNull() =" << themeIcon.isNull();
        qDebug() << "  available sizes =" << themeIcon.availableSizes();

        int compareSize = QApplication::style()->pixelMetric(QStyle::PM_SmallIconSize);
        qDebug() << "  using compare size =" << compareSize;

        QPixmap themePixmap = themeIcon.pixmap(QSize(compareSize, compareSize));
        QImage themeImage = themePixmap.toImage();
        if (themeImage.isNull()) qDebug() << "  (theme produced no pixmap at that size)";

        for (const QString &candidate : found) {
            QImage cand = loadCandidateImage(candidate, compareSize);
            if (cand.isNull()) {
                qDebug() << "  cannot load candidate (or invalid):" << candidate;
                continue;
            }
            if (themeImage == cand) {


#include <gtest/gtest.h>
#include "histogram/Histogram.hpp"
#include "histogram/CDF.hpp"
#include "histogram/GaussianFilter.hpp"
#include "histogram/SVGExporter.hpp"
#include <vector>
#include <random>
#include <tuple>

#if __has_include(<filesystem>)
#include <filesystem>
namespace fs = std::filesystem;
#else
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
#endif

class HistogramTest : public ::testing::Test {
protected:
    void SetUp() override {
        // 创建测试输出目录
        fs::create_directories("test_output");
    }

    void TearDown() override {
        // 清理测试文件
        // fs::remove_all("test_output");
    }
};

// 测试Histogram基本功能
TEST_F(HistogramTest, BasicFunctionality) {
    histogram::Histogram hist(0.0f, 10.0f, 10);

    // 测试空直方图
    EXPECT_EQ(hist.getTotalCount(), 0);
    EXPECT_EQ(hist.getResolution(), 10);
    EXPECT_FLOAT_EQ(hist.getBinWidth(), 1.0f);

    // 添加数据
    hist.addData(2.5f);
    hist.addData(3.5f);
    hist.addData(2.8f);
    hist.addData(7.2f);

    EXPECT_EQ(hist.getTotalCount(), 4);

    // 测试bin计数
    EXPECT_EQ(hist.getBinCount(2), 2); // 2.5和2.8应该在bin 2
    EXPECT_EQ(hist.getBinCount(3), 1); // 3.5应该在bin 3
    EXPECT_EQ(hist.getBinCount(7), 1); // 7.2应该在bin 7

    // 测试超出范围的数据
    hist.addData(-1.0f); // 小于min
    hist.addData(11.0f); // 大于max
    EXPECT_EQ(hist.getTotalCount(), 4); // 计数不应增加
}

// 测试CDF计算
TEST_F(HistogramTest, CDFComputation) {
    histogram::Histogram hist(0.0f, 10.0f, 10);

    // 添加均匀分布的数据
    for (int i = 0; i < 10; ++i) {
        hist.addData(static_cast<float>(i));
    }

    histogram::CDF cdf;
    cdf.computeFromHistogram(hist);

    // 测试累计概率
    EXPECT_FLOAT_EQ(cdf.getCumulativeProbability(0.0f), 0.1f);
    EXPECT_FLOAT_EQ(cdf.getCumulativeProbability(2.0f), 0.3f);
    EXPECT_FLOAT_EQ(cdf.getCumulativeProbability(9.0f), 1.0f);

    // 测试百分位
    EXPECT_FLOAT_EQ(cdf.getPercentile(10.0f), 1.0f);
    EXPECT_FLOAT_EQ(cdf.getPercentile(50.0f), 5.0f);
    EXPECT_FLOAT_EQ(cdf.getPercentile(90.0f), 9.0f);
}

// 测试高斯滤波
TEST_F(HistogramTest, GaussianFilter) {
    histogram::GaussianFilter filter(1.0f);

    // 创建测试数据（脉冲）
    std::vector<float> testData(10, 0.0f);
    testData[5] = 1.0f;

    auto filtered = filter.filter(testData);

    // 滤波后应该是一个平滑的高斯分布
    EXPECT_EQ(filtered.size(), testData.size());

    // 中心值应该最大
    EXPECT_GT(filtered[5], filtered[4]);
    EXPECT_GT(filtered[5], filtered[6]);

    // 对称性检查（使用近似比较，因为浮点数计算有精度差异）
    EXPECT_NEAR(filtered[4], filtered[6], 1e-3f);
    EXPECT_NEAR(filtered[3], filtered[7], 1e-3f);
}

// 测试SVG导出
TEST_F(HistogramTest, SVGExport) {
    histogram::Histogram hist(0.0f, 10.0f, 10);

    // 添加一些测试数据
    std::mt19937 gen(42);
    std::normal_distribution<float> dist(5.0f, 2.0f);

    for (int i = 0; i < 100; ++i) {
        hist.addData(dist(gen));
    }

    // 测试直方图导出
    EXPECT_NO_THROW({
        histogram::SVGExporter::exportHistogram(hist, "test_output/histogram.svg", 800, 600);
    });

    // 测试文件是否存在
    EXPECT_TRUE(fs::exists("test_output/histogram.svg"));

    // 测试CDF导出
    histogram::CDF cdf;
    cdf.computeFromHistogram(hist);

    EXPECT_NO_THROW({
        histogram::SVGExporter::exportCDF(cdf, "test_output/cdf.svg");
    });
    EXPECT_TRUE(fs::exists("test_output/cdf.svg"));

    // 测试滤波直方图导出
    histogram::GaussianFilter gaussianFilter(0.5f);
    auto filtered = gaussianFilter.filterCounts(hist.getBinCounts());

    EXPECT_NO_THROW({
        histogram::SVGExporter::exportFilteredHistogram(hist, filtered, "test_output/filtered.svg");
    });
    EXPECT_TRUE(fs::exists("test_output/filtered.svg"));
}

// 测试边界条件
TEST_F(HistogramTest, EdgeCases) {
    // 测试无效参数
    EXPECT_THROW(histogram::Histogram(10.0f, 0.0f, 10), std::invalid_argument);
    EXPECT_THROW(histogram::Histogram(0.0f, 10.0f, 0), std::invalid_argument);

    // 测试空直方图的CDF
    histogram::Histogram emptyHist(0.0f, 10.0f, 5);
    histogram::CDF emptyCDF;
    EXPECT_THROW(emptyCDF.computeFromHistogram(emptyHist), std::runtime_error);

    // 测试无效百分位
    histogram::Histogram hist(0.0f, 10.0f, 5);
    hist.addData(5.0f);
    histogram::CDF cdf;
    cdf.computeFromHistogram(hist);

    EXPECT_THROW(cdf.getPercentile(-1.0f), std::invalid_argument);
    EXPECT_THROW(cdf.getPercentile(101.0f), std::invalid_argument);
}

// 测试高斯滤波参数
TEST_F(HistogramTest, GaussianFilterParameters) {
    EXPECT_THROW(histogram::GaussianFilter(0.0f), std::invalid_argument);
    EXPECT_THROW(histogram::GaussianFilter(-1.0f), std::invalid_argument);

    histogram::GaussianFilter filter(1.0f);
    EXPECT_THROW(filter.setSigma(0.0f), std::invalid_argument);
}

// 测试波峰检测功能
TEST_F(HistogramTest, PeakDetection) {
    // 创建多峰值直方图
    histogram::Histogram hist(0.0f, 20.0f, 40);

    // 生成三个正态分布的混合数据
    std::mt19937 gen(123);
    std::normal_distribution<float> dist1(4.0f, 0.8f);
    std::normal_distribution<float> dist2(10.0f, 1.2