text:
#include <iostream>
#include "pin.H"
#include <fstream>
#include <string>
#include <list>
#include <boost/algorithm/string.hpp>
#include <unordered_map>
#include <exception>

// TODOs can be searched with ----> TODO:

// #define RPB_DEBUG // comment out to disable rbp debugging
// #define RBP_DETECTION // comment out to disable rbp detection
// #define DISASS_DEBUG // comment out to disable disassembly debugging

// key to detect the main Routine
static uint32_t key = 0;

// Map containing Blocks
// The keys are function name and the values are blocks per function
// std::list<struct Block> Blocks;
std::unordered_map <std::string, struct Block*> blocks;

// access bounds
class AccessBounds
{
private:
  int64_t base;
  int64_t bound;
public:
  AccessBounds(int64_t base, int64_t bound){this->base = base; this->bound = bound;}
  int64_t get_base(){return base;}
  int64_t get_bound(){return bound;}
};

// Map to store all bound information globally
// key: owner
std::unordered_map <std::string, AccessBounds*> accessboundsmap;

// Stucture holds the control flow information
class ControlFlowBlock
{
public:
  int64_t rax = -1;
  int64_t rbx = -1;
  int64_t rcx = -1;
  int64_t rdx = -1;
  int64_t r8 = -1;
  int64_t r9 = -1;
  int64_t r10 = -1;
  int64_t r11 = -1;
  int64_t r12 = -1;
  int64_t r13 = -1;
  int64_t r14 = -1;
  int64_t r15 = -1;
  int64_t rsi = -1;
  int64_t rdi = -1;
  // TODO: I am not sure if I have to add rip here
  // TODO: I can set the register values as the stack positions
};

// position relative to the rbp
class RelPos
{
private:
  // value present at the particular location on the stack
  int64_t value;
  // Owner
  std::string owner;
  // other info such as owner can be added here
public:
  RelPos(int64_t value, std::string owner){this->value = value; this->owner = owner;}
  void set_val(int64_t value){this->value = value;}
  void set_owner(int64_t owner){this->owner = owner;}
  int64_t get_value(){return value;}
  std::string get_owner(){return owner;}
};

// Owner infomation of each location
class InsInfo
{
private:
  ADDRINT address;
  std::string owner;
public:
  InsInfo(ADDRINT address, std::string owner) { this->address = address; this->owner = owner;}
  ADDRINT get_address() {return address;}
  std::string get_owner() {return owner;}
};

// Contains the information of all the objects
class ObjInfo
{
private:
  // Location from the base pointer and the upper bound
  int64_t ub;
  // Data Type
  std::string type;
  // Object Type
  std::string obj;
  // Object name
  std::string owner;
  // Object size
  int64_t obj_size;
  // lower bound
  int64_t lb;
public:
  ObjInfo(int64_t ub, std::string type, std::string obj, string owner, int64_t obj_size)
  {
    this->ub = ub;
    this->type = type;
    this->obj = obj;
    this->owner = owner;
    this->obj_size = obj_size;
    // Lower bounds calculated here
    this->lb = ub + obj_size;
  }
  int64_t get_ub() {return ub;}
  std::string get_type() {return type;}
  std::string get_obj() {return obj;}
  std::string get_owner() {return owner;}
  int64_t get_obj_size() {return obj_size;}
  int64_t get_lb() {return lb;}
};

// A structure to store all the file related information
struct Block
{
  // Block name
  std::string name;
  // Allocated stack size
  uint64_t size;
  // Set the rbp value for the particular block
  uint64_t rbp_value;
  // Stucture to store control flow block information
  // TODO: update this per control flow block
  ControlFlowBlock controlflowblock;
  // Object information hash map
  std::unordered_map <std::string, ObjInfo*> objinfostack;
  // static code locations hash map
  std::unordered_map <ADDRINT, InsInfo*> inscodestack;
  // Actual stack (positions related to rbp) hash map
  std::unordered_map <uint64_t, RelPos*> relPosStack;
};

// rbp value Check
VOID rpb_check(uint64_t addr, CONTEXT * ctxt, Block &i, std::string disassins)
{
  if (addr > 0x700000000000)
    return;
  #ifdef DISASS_DEBUG
  std::cout<<std::hex<<addr<<"\t"<<disassins<<dec<<std::endl;
  #endif
  // Set the rbp value for the particular function.
  // Check if the rbp value is 0 which is equivalent to either return or unset
  // If rbp value is changed other than 0 for the function give an error
  if (i.rbp_value == PIN_GetContextReg(ctxt, REG_RBP))
  {
    #ifdef RPB_DEBUG
    std::cout << hex << "rbp: " << i.rbp_value << '\n';
    #endif
  }
  else if (i.rbp_value == 0)
  {
    #ifdef RPB_DEBUG
    std::cout << "return: " << i.rbp_value << '\n';
    #endif
  }
  else
  {
    std::cout << "RBP is changed(!) to: " << i.rbp_value << '\n';
  }
}

// set the value of rbp after detecting using sub rsp, xx instruction
VOID rbp_set(uint64_t addr, CONTEXT * ctxt, Block &i, std::string disassins)
{
  #ifdef RPB_DEBUG
  std::cout << "rbp set: " << i.rbp_value << '\n';
  std::cout << "rbp_routine name: " << i.name << '\n';
  #endif
  // set the rbp value -- This value will stay same throughout the function
  i.rbp_value = PIN_GetContextReg(ctxt, REG_RBP);
  // #ifdef RPB_DEBUG
  std::cout << hex << "rbp set: " << i.rbp_value << dec << '\n';
  // #endif
}

// Pin calls this function every time a new instruction is encountered
VOID Instruction(INS ins, VOID *v)
{
  // First check if the routine is valid
  if (!RTN_Valid(RTN_FindByAddress(INS_Address(ins))))
    return;
  // skip if the address is over 0x700000000000
  if (INS_Address(ins) > 0x700000000000)
    return;
  // Block hash map access
  // Find the current routine
  auto g = blocks.find(RTN_Name(RTN_FindByAddress(INS_Address(ins))));
  if ( g == blocks.end())
    return;
  struct Block *i = blocks[RTN_Name(RTN_FindByAddress(INS_Address(ins)))];
  // Returns the name of the block
  // std::cout << "RTN: " << RTN_Name(RTN_FindByAddress(INS_Address(ins))) << '\n';

  #ifdef RPB_DEBUG
  std::cout << "rbp: " << i->rbp_value << '\n';
  #endif
  #ifdef RBP_DETECTION

  // Detect the mov rbp, rsp instruction
  // This is so that, a function can be detected
  if (INS_Opcode(ins) == XED_ICLASS_MOV && (INS_OperandReg(ins,0) == REG_RBP))
  {
    std::cout << "ins disass: " << INS_Disassemble(ins) << '\n';
    INS_InsertCall(ins, IPOINT_AFTER, (AFUNPTR)rbp_set, IARG_ADDRINT,
    INS_Address(ins), IARG_CONTEXT, IARG_PTR, &(*i), IARG_PTR, new string(INS_Disassemble(ins)), IARG_END);
  }
  #endif
  // std::cout << "Mem dispacement: " << INS_MemoryDisplacement(ins) << '\n';
  // std::cout << hex <<INS_Address(ins)<< "\t" << string(INS_Disassemble(ins)) << dec << '\n';
  // Get the owner for the particular static address
  std::string owner;
  if ( i->inscodestack.find(INS_Address(ins)) == i->inscodestack.end())
  {
    return;
  }
  else
  {
    // std::cout << i->inscodestack[INS_Address(ins)]->get_owner() << '\n';
    owner = i->inscodestack[INS_Address(ins)]->get_owner();
  }
  // Detect sub rbp, rsp instruction
  // if (REG_is_stackptr_type(INS_OperandReg(ins, 0)))
  // {
  //   INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)rbp_set, IARG_ADDRINT,
  //   INS_Address(ins), IARG_CONTEXT, IARG_PTR, i, IARG_PTR, new string(INS_Disassemble(ins)), IARG_END);
  // }

  // Detect the return instruction
  // For rbp detection
  #ifdef RBP_DETECTION
  if (INS_IsRet(ins))
  {
    #ifdef RPB_DEBUG
    std::cout << "Return instruction detected" << '\n';
    #endif
    // Make rbp 0 before each return
    i->rbp_value = 0;
    INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)rpb_check, IARG_ADDRINT,
    INS_Address(ins), IARG_CONTEXT, IARG_PTR, &(*i), IARG_PTR, new string(INS_Disassemble(ins)), IARG_END);

  }
  #endif

  // Detect all memory store instructions (check only fro rbp and not rsp)
  // Array bounds check - not related to the softbounds technique
  // But it protects the array overflow
  if ((INS_Opcode(ins) == XED_ICLASS_MOV) && INS_OperandIsMemory(ins, 0)
  && ((INS_OperandWidth(ins, 0) == 32)
      || (INS_OperandWidth(ins, 0) == 64))
  && ((INS_OperandMemoryBaseReg(ins, 0) == REG_RBP)
  || (INS_OperandMemoryBaseReg(ins, 0) == REG_EBP))
  && INS_OperandIsImmediate(ins, 1))
  {
    std::cout << "BLock name: " << i->name << "\n";
    // Check if the rbp is not changed
    #ifdef RBP_DETECTION
    INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)rpb_check, IARG_ADDRINT,
    INS_Address(ins), IARG_CONTEXT, IARG_PTR, &(*i), IARG_PTR, new string(INS_Disassemble(ins)), IARG_END);
    #endif

    // Now check if the owner has correct stack access, i.e. if the owner is accessible
    // this can be used to validate, otherwise it leads to seg fault
    auto iter = i->objinfostack.find(owner);
    if ( iter == i->objinfostack.end())
    {
        std::cout << "Check your input!" << '\n';
        std::exit(1);
    }
    std::cout << "Owner:: " << i->objinfostack[owner]->get_owner() << '\n';

    // Store the immediate at particular stack position relative to rbp
    // std::cout << "/* message */" << INS_MemoryDisplacement(ins) << '\n';
    // if the value is already in the map
    // TODO: see if this is really required
    // TODO: if the value is not present in the stack, then add the value, but what if the
    // same location is being - but I think it is correctly implemented
    if(i->relPosStack.find(INS_MemoryDisplacement(ins)) != i->relPosStack.end())
    {
      i->relPosStack[INS_MemoryDisplacement(ins)]->set_val(INS_OperandImmediate(ins, 1));
    }
    else
    {
      // set the value and the owner
      // There is no need of the absolute value, as the stack can grow both ways
      std::cout << "/* message: " << INS_MemoryDisplacement(ins) << '\n';
      i->relPosStack.insert(std::make_pair(INS_MemoryDisplacement(ins), new RelPos(INS_OperandImmediate(ins, 1), owner)));
    }

    // Check if the address really has an owner: (this is equivalent to pass in python)
    //while (i->inscodestack[INS_Address(ins)]);
    // Get The lower and upper bounds
    std::cout << "Upper bounds: " << i->objinfostack[owner]->get_ub() << '\n';
    std::cout << "Lower bounds: " << i->objinfostack[owner]->get_lb() << '\n';
    // If the type is array and the access is not within the bounds
    // If rsp is to be detected and rsp + x is equivalent to ebp - (rsp + x)
    if ((INS_MemoryDisplacement(ins) > i->objinfostack[owner]->get_ub() ||
    INS_MemoryDisplacement(ins) < i->objinfostack[owner]->get_lb()) &&
    i->objinfostack[owner]->get_obj() == "array")
    std::cout << "Boundover accessed by " << owner << '\n';
  }

  // If the owner is a pointer
  // First check for the load instruction in the register
  // This will assume that the register will be used in future
  if ((INS_Opcode(ins) == XED_ICLASS_LEA) && (INS_OperandIsReg(ins, 0)) &&
    INS_HasExplicitMemoryReference(ins))
  {
    // std::cout << i->inscodestack[INS_Address(ins)]->get_owner() << '\n';
    std::cout << "disas: " << hex << INS_Disassemble(ins) << dec << '\n';
    // move that value in the
    // INS_MemoryDisplacement(ins) gives the location of the stack and then
    // get_value() gives the value at that particular location of the stack
    // register used in the instruction
    std::string insreg = REG_StringShort(INS_OperandReg(ins, 0));
    // Let the register structure hold the location on the stack for the particular register
    // and not the value
    // set the Register with the apporpriate value
    // TODO: Currently only works for rax, I have to do it for the other registers also
    if ((insreg) == "rax") //|| "eax" || "ax" || "ah" || "al")
      (i->controlflowblock).rax = INS_MemoryDisplacement(ins);
  }

  // If operand is a register - mov QWORD PTR [rbp-0x8],rax
  if ((INS_Opcode(ins) == XED_ICLASS_MOV) && INS_OperandIsMemory(ins, 0)
  && ((INS_OperandWidth(ins, 0) == 32)
      || (INS_OperandWidth(ins, 0) == 64))
  && ((INS_OperandMemoryBaseReg(ins, 0) == REG_RBP)
  || (INS_OperandMemoryBaseReg(ins, 0) == REG_EBP))
  && INS_OperandIsReg(ins, 1))
  {
    // set the value of of the pos stack if the owner is a pointer
    if (REG_StringShort(INS_OperandReg(ins, 1)) == "rax")
    {
      if(i->relPosStack.find(INS_MemoryDisplacement(ins)) != i->relPosStack.end())
      {
        i->relPosStack[INS_MemoryDisplacement(ins)]->set_val((i->controlflowblock).rax);
      }
      else
      {
        // set the value and the owner
        // There is no need of the absolute value, as the stack can grow both ways
        i->relPosStack.insert(std::make_pair(INS_MemoryDisplacement(ins), new RelPos((i->controlflowblock).rax, owner)));
      }
    }

    // Check to see if the owner is a pointer
    if (i->objinfostack[owner]->get_obj() == "pointer")
    {
      // register used in the instruction
      std::string insreg = REG_StringShort(INS_OperandReg(ins, 1));
      // get the Register value
      // TODO: Currently only works for rax, I have to do it for the other registers also
      if ((insreg) == "rax") //|| "eax" || "ax" || "ah" || "al")
      {
          // pointer is getting the address of owner_prop and hence its bounds
          std::string owner_prop = i->relPosStack[(i->controlflowblock).rax]->get_owner();
          accessboundsmap.insert(std::make_pair(owner, new AccessBounds(i->objinfostack[owner_prop]->get_lb(), i->objinfostack[owner_prop]->get_ub())));
          std::cout << "lower bounds: " << accessboundsmap[owner]->get_base() <<'\n';
          std::cout << "Upper bounds: " << accessboundsmap[owner]->get_bound() <<'\n';
      }
    }
  }

  // If the pointer value is loaded
  // rax,QWORD PTR [rbp-0x8]
  if ((INS_Opcode(ins) == XED_ICLASS_MOV) && INS_OperandIsMemory(ins, 1)
  && ((INS_OperandWidth(ins, 1) == 32)
      || (INS_OperandWidth(ins, 1) == 64))
  && ((INS_OperandMemoryBaseReg(ins, 1) == REG_RBP)
  || (INS_OperandMemoryBaseReg(ins, 1) == REG_EBP)))
  {
    if (i->objinfostack[owner]->get_obj() == "pointer")
    {
      std::string insreg = REG_StringShort(INS_OperandReg(ins, 0));
      if ((insreg) == "rax") //|| "eax" || "ax" || "ah" || "al")
      {
        (i->controlflowblock).rax = INS_MemoryDisplacement(ins);
      }
    }
  }

  if ((INS_Opcode(ins) == XED_ICLASS_MOV) && INS_OperandIsMemory(ins, 1)
  && ((INS_OperandWidth(ins, 1) == 32)
      || (INS_OperandWidth(ins, 1) == 64))
  && (INS_OperandIsMemory(ins, 1))
  && ((INS_OperandMemoryBaseReg(ins, 1) != REG_RBP)
  && (INS_OperandMemoryBaseReg(ins, 1) != REG_EBP)))
  {
    if (i->objinfostack[owner]->get_obj() == "scalar")
    {
      std::string insreg = REG_StringShort(INS_OperandMemoryBaseReg(ins, 1));
      if ((insreg) == "rax")
      {
        // Checks can be done here
        // Get the owner
        if (i->objinfostack[i->relPosStack[(i->controlflowblock).rax]->get_owner()]->get_obj() == "pointer")
        {
          if (((accessboundsmap[i->relPosStack[(i->controlflowblock).rax]->get_owner()]->get_base() -
            INS_OperandMemoryDisplacement(ins, 1)) > (accessboundsmap[i->relPosStack[(i->controlflowblock).rax]->get_owner()]->get_base())) ||
            ((accessboundsmap[i->relPosStack[(i->controlflowblock).rax]->get_owner()]->get_base()) - i->objinfostack[owner]->get_obj_size() -
            INS_OperandMemoryDisplacement(ins, 1)) < accessboundsmap[i->relPosStack[(i->controlflowblock).rax]->get_owner()]->get_bound())
          std::cout << "abort" << '\n';
        }
      }
    }
  }

  // if (i->objinfostack[owner]->get_obj() == "pointer")
  // {
  //   std::cout << hex << INS_Disassemble(ins) << dec << '\n';
  //   // if ((INS_Opcode(ins) == XED_ICLASS_MOV) && (INS_OperandIsReg(ins, 1)))
  // }

  // TODO: Is there any need of control flow block?
  // For control flow Blocks
  if (INS_BranchTakenPrefix(ins))
    std::cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << '\n';
  if (INS_IsBranchOrCall(ins))
    std::cout << "Branch: " << hex << INS_Disassemble(ins) << dec << '\n';
  if (!INS_HasFallThrough(ins))
    std::cout<<"\nbranch!\n\n";
}

// This function is called when the application exits
VOID Fini(INT32 code, VOID *v)
{
}

INT32 Usage()
{
    cerr << "This tool counts the number of dynamic instructions executed" << endl;
    cerr << endl << KNOB_BASE::StringKnobSummary() << endl;
    return -1;
}

void readInput(char *filename)
{
  std::string line;
  std::ifstream myfile(filename);
  if (myfile.is_open())
  {
    // Get the count of the total number of blocks
    getline (myfile,line);
    int64_t count = atoi(line.c_str());
    // Ignore newline after the count
    getline (myfile,line);
    while (count)
    {
      // Initialize the structure
      struct Block *block = new Block;
      // for the function name
      getline (myfile,line);
      block->name = line;
      // for the stack size
      getline (myfile,line);
      block->size = atoi(line.c_str());
      block->rbp_value = 0;
      while ( getline (myfile,line) )
      {
        if (line.empty())
        {
            break;
        }
        else
        {
          std::vector<std::string> temp;
          boost::split(temp, line, boost::is_any_of("\t "));
          block->inscodestack.insert(std::make_pair(strtol(temp[0].c_str(), NULL, 16), new InsInfo(strtol(temp[0].c_str(), NULL, 16), temp[1])));
          //std::cout << "temp[1]: " << hex <<strtol(temp[0].c_str(), NULL, 16) << '\n';
        }
      }
      while ( getline (myfile,line) )
      {
        if (line.empty())
        {
            break;
        }
        else
        {
          std::vector<std::string> temp;
          boost::split(temp, line, boost::is_any_of("\t "));
          //ObjInfo *objinfo = new ObjInfo {atoi(temp[0].c_str()), temp[1], temp[2], temp[3], atoi(temp[4].c_str())};
          block->objinfostack.insert(std::make_pair(temp[3], new ObjInfo(atoi(temp[0].c_str()), temp[1], temp[2], temp[3], atoi(temp[4].c_str()))));
        }
      }
      // // make every location zero upon initialization
      // for (uint64_t i = 0; i <= block.size; ++i)
      //   block.relPosStack.insert(std::make_pair(i, new RelPos(0)));
      blocks.insert(std::make_pair(block->name, block));
      --count;
    }
    myfile.close();
  }
  else std::cout << "Unable to open file\n";
}

// Lock Routines
void mutex_lock()
{
  key = 0;
  //std::cout<<"out\n";
}
void mutex_unlock()
{
	key = 1;
	//std::cout<<"in\n";
}

void Image(IMG img, VOID *v)
{
  RTN mainrtn = RTN_FindByName(img, "main");
  if (RTN_Valid(mainrtn))
    {
        std::cout << "Routine " << RTN_Name(mainrtn)<< '\n';
        RTN_Open(mainrtn);
        // Apply the locks to the main routine
        RTN_InsertCall(mainrtn, IPOINT_BEFORE, (AFUNPTR)mutex_unlock, IARG_END);
        RTN_InsertCall(mainrtn, IPOINT_AFTER, (AFUNPTR)mutex_lock, IARG_END);
        RTN_Close(mainrtn);
    }
}

int main(int argc, char * argv[])
{
    // Initialize pin
    PIN_InitSymbols();
    if (PIN_Init(argc, argv)) return Usage();
    // Argv[7] is the name of the input file
    readInput(argv[7]);
    // Register Instruction to be called to instrument instructions
    INS_AddInstrumentFunction(Instruction, 0);

    // Image instrumentation
    IMG_AddInstrumentFunction(Image, 0);

    // Register Fini to be called when the application exits
    PIN_AddFiniFunction(Fini, 0);

    // Start the program, never returns
    PIN_StartProgram();

    return 0;
}


text:
#include "PhysicsTools/Utilities/interface/Likelihood.h"
#include "PhysicsTools/Utilities/interface/BreitWigner.h"
#include "PhysicsTools/Utilities/interface/RootMinuitCommands.h"
#include "PhysicsTools/Utilities/interface/RootMinuit.h"
#include "PhysicsTools/Utilities/interface/Parameter.h"
#include "PhysicsTools/Utilities/interface/rootTf1.h"
#include "PhysicsTools/Utilities/interface/rootPlot.h"
#include "TFile.h"
#include "TH1.h"
#include "TF1.h"
#include "TCanvas.h"
#include "TROOT.h"
#include <boost/shared_ptr.hpp>
#include <iostream>
#include "PhysicsTools/Utilities/interface/Operations.h"
//using namespace std;
//using namespace boost;

int main() {
  gROOT->SetStyle("Plain");
  typedef funct::BreitWigner PDF;
  typedef std::vector<double> Sample;
  typedef funct::Product<funct::Parameter, PDF>::type FitFunction;
  typedef fit::Likelihood<Sample, FitFunction, funct::Parameter> Likelihood;
  try {
    fit::RootMinuitCommands<Likelihood> commands("PhysicsTools/Utilities/test/testZMassFitLikelihood.txt");

    const char* kYield = "Yield";
    const char* kMass = "Mass";
    const char* kGamma = "Gamma";

    funct::Parameter yield(kYield, commands.par(kYield));
    funct::Parameter mass(kMass, commands.par(kMass));
    funct::Parameter gamma(kGamma, commands.par(kGamma));
    funct::BreitWigner bw(mass, gamma);

    PDF pdf = bw;
    FitFunction f = yield * pdf;
    TF1 startFun = root::tf1("startFun", f, 0, 200, yield, mass, gamma);
    TH1D histo("histo", "Z mass (GeV/c)", 200, 0, 200);
    Sample sample;
    sample.reserve(yield);
    for (unsigned int i = 0; i < yield; ++i) {
      double m = startFun.GetRandom();
      histo.Fill(m);
      sample.push_back(m);
    }
    TCanvas canvas;
    startFun.Draw();
    canvas.SaveAs("breitWigner.eps");
    histo.Draw();
    canvas.SaveAs("breitWignerHisto.eps");
    startFun.Draw("same");
    canvas.SaveAs("breitWignerHistoFun.eps");
    histo.Draw("e");
    startFun.Draw("same");

    Likelihood like(sample, f, yield);
    fit::RootMinuit<Likelihood> minuit(like, true);
    commands.add(minuit, yield);
    commands.add(minuit, mass);
    commands.add(minuit, gamma);
    commands.run(minuit);
    ROOT::Math::SMatrix<double, 3, 3, ROOT::Math::MatRepSym<double, 3> > err;
    minuit.getErrorMatrix(err);
    std::cout << "error matrix:" << std::endl;
    for (size_t i = 0; i < 3; ++i) {
      for (size_t j = 0; j < 3; ++j) {
        std::cout << err(i, j) << "\t";
      }
      std::cout << std::endl;
    }
    root::plot<FitFunction>("breitWignerHistoFunFit.eps", histo, f, 80, 120, yield, mass, gamma);
  } catch (std::exception& err) {
    std::cerr << "Exception caught:\n" << err.what() << std::endl;
    return 1;
  }

  return 0;
}

ext: cpp

max_stars_repo_name: NTrevisani/cmssw

max_issues_repo_name: NTrevisani/cmssw

max_forks_repo_name: NTrevisani/cmssw


text:
/*
 *             Copyright Andrey Semashev 2018.
 * Distributed under the Boost Software License, Version 1.0.
 *    (See accompanying file LICENSE_1_0.txt or copy at
 *          http://www.boost.org/LICENSE_1_0.txt)
 */
/*!
 * \file   bcrypt_abi.cpp
 * \author Andrey Semashev
 * \date   09.03.2018
 *
 * \brief  This file contains ABI test for bcrypt.hpp
 */

#include <boost/winapi/bcrypt.hpp>
#include <windows.h>
#include <wchar.h>
#include <boost/predef/platform/windows_uwp.h>
#if (BOOST_USE_WINAPI_VERSION >= BOOST_WINAPI_VERSION_WIN6)
#include <bcrypt.h>
#endif
#include "abi_test_tools.hpp"

int main()
{
#if (BOOST_USE_WINAPI_VERSION >= BOOST_WINAPI_VERSION_WIN6)
#if BOOST_WINAPI_PARTITION_APP_SYSTEM

    BOOST_WINAPI_TEST_TYPE_SAME(BCRYPT_ALG_HANDLE);

    BOOST_WINAPI_TEST_FUNCTION_SIGNATURE(BCryptCloseAlgorithmProvider);
    BOOST_WINAPI_TEST_FUNCTION_SIGNATURE(BCryptGenRandom);
    BOOST_WINAPI_TEST_FUNCTION_SIGNATURE(BCryptOpenAlgorithmProvider);

    BOOST_TEST(wcscmp(BCRYPT_RNG_ALGORITHM, boost::winapi::BCRYPT_RNG_ALGORITHM_) == 0);

#endif // BOOST_WINAPI_PARTITION_APP_SYSTEM
#endif // (BOOST_USE_WINAPI_VERSION >= BOOST_WINAPI_VERSION_WIN6)

    return boost::report_errors();
}


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

#include "basics.hpp"
#include <boost/mpl/list.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/mpl/size.hpp>
#include <boost/type_traits/add_pointer.hpp>

# include <boost/mpl/contains.hpp>

namespace test
{
  namespace mpl = boost::mpl;

  template <class Set>
  struct assert_in_set
  {
      template <class T>
      void operator()(T*)
      {
          BOOST_MPL_ASSERT((mpl::contains<Set,T>));
      }
  };

  template<class Expected, class Params>
  void f_impl(Params const& p BOOST_APPEND_EXPLICIT_TEMPLATE_TYPE(Expected))
  {
      BOOST_MPL_ASSERT_RELATION(
          mpl::size<Expected>::value
        , ==
        , mpl::size<Params>::value
      );

      mpl::for_each<Params, boost::add_pointer<mpl::_1> >(assert_in_set<Expected>());
  }

  template<class Expected, class Tester, class Name, class Value, class Index>
  void f(Tester const& t, const Name& name_,
      const Value& value_, const Index& index_ BOOST_APPEND_EXPLICIT_TEMPLATE_TYPE(Expected))
  {
      f_impl<Expected>(f_parameters()(t, name_, value_, index_));
  }

  template<class Expected, class Tester, class Name, class Value>
  void f(Tester const& t, const Name& name_, const Value& value_ BOOST_APPEND_EXPLICIT_TEMPLATE_TYPE(Expected))
  {
      f_impl<Expected>(f_parameters()(t, name_, value_));
  }

  template<class Expected, class Tester, class Name>
  void f(Tester const& t, const Name& name_ BOOST_APPEND_EXPLICIT_TEMPLATE_TYPE(Expected))
  {
      f_impl<Expected>(f_parameters()(t, name_));
  }

  void run()
  {
      typedef test::tag::tester tester_;
      typedef test::tag::name name_;
      typedef test::tag::value value_;
      typedef test::tag::index index_;

      f<mpl::list4<tester_,name_,value_,index_> >(1, 2, 3, 4);
      f<mpl::list3<tester_,name_,index_> >(1, 2, index = 3);
      f<mpl::list3<tester_,name_,index_> >(1, index = 2, name = 3);
      f<mpl::list2<name_,value_> >(name = 3, value = 4);
      f_impl<mpl::list1<value_> >(value = 4);
  }
}

int main()
{
    test::run();
    return 0;
}


text:
#include <iostream>
#include <boost/json.hpp>
#include <boost/lexical_cast.hpp>

#include "experimental/dataframe.hpp"
#include "experimental/csv-io.hpp"

#include "clip.hpp"
#include "common.hpp"

namespace boostjsn = boost::json;
namespace xpr = experimental;

const char* const METHOD_NAME         = "datafind";
const char* const ARG_METALL_LOCATION = "metall_location";
const char* const ARG_DATAFRAME_KEY   = "dataframe_key";
const char* const ARG_CRITERIA_FUN    = "function";
const char* const ARG_CRITERIA_COL    = "column";

void apiJason(std::ostream& out)
{
  std::size_t pos = 0;

  out << "{\n"
      << "  \"method_name\": \"" << METHOD_NAME << "\",\n"
      << "  \"args\":\n"
      << "  {\n";

      //~ << "      \"" << ARG_METALL_INIT << "\": { \"desc\": \"create or connect\", \"position\":0, \"required\":true, \"type\":\"string\"}\n"
  out << "      \"" << ARG_METALL_LOCATION << "\": { \"desc\": \"location of metall file\", \"position\":" << (pos++) << ", \"required\":true, \"type\":\"string\"},\n";

  out << "      \"" << ARG_DATAFRAME_KEY << "\": { \"desc\": \"dataframe name\", \"position\":" << (pos++) << ", \"required\":true, \"type\":\"string\"},\n";

  out << "      \"" << ARG_CRITERIA_COL << "\": { \"desc\": \"column where the criteria shall be applied\", \"position\":" << (pos++) << ", \"required\":false, \"type\":\"int\"},\n";

  out << "      \"" << ARG_CRITERIA_FUN << "\": { \"desc\": \"criteria (min, max)\", \"position\":" << (pos++) << ", \"required\":false, \"type\":\"int\"}\n";

  out << "  },\n"
      << "  \"returns\": { \"desc\": \"status\", \"type\":\"string\"}\n"
      << "}\n"
      << std::flush;
}

using DataConverter = std::function<xpr::dataframe_variant_t(const std::string& s)>;

template <class DfCellType>
struct ConverterFn
{
  xpr::dataframe_variant_t operator()(const std::string& s)
  {
    DfCellType elem = boost::lexical_cast<DfCellType>(s);

    return elem;
  }

  xpr::DataFrame* df;
};

template <class ColType>
std::string quote(const ColType*) { return ""; }

template<>
std::string quote<xpr::string_t>(const xpr::string_t*) { return "\""; }

template <class ColType>
bool
applyColFunctionIf(std::ostream& os, xpr::DataFrame& df, size_t colnum, const xpr::ColumnDesc& desc, const std::string& funname)
{
  using Iterator = xpr::AnyColumnIterator<ColType>;

  if (desc.column_type != xpr::to_string(xpr::tag<ColType>()))
    return false;

  std::pair<Iterator, Iterator> range = df.get_any_column<ColType>(colnum);
  std::string                   quotes = quote(xpr::tag<ColType>());

  Iterator pos = (funname == "min") ? std::min_element(range.first, range.second)
                                    : std::max_element(range.first, range.second)
                                    ;

  os << "{ \"id\": " << pos.row() << ", \"value\": " << quotes << *pos << quotes
     << "}"
     << std::endl;

  return true;
}

void columnFunction(std::ostream& os, xpr::DataFrame& df, int colnum, const xpr::ColumnDesc& desc, const std::string& funname)
{
  firstMatch
  || applyColFunctionIf<xpr::int_t>   (os, df, colnum, desc, funname)
  || applyColFunctionIf<xpr::uint_t>  (os, df, colnum, desc, funname)
  || applyColFunctionIf<xpr::real_t>  (os, df, colnum, desc, funname)
  || applyColFunctionIf<xpr::string_t>(os, df, colnum, desc, funname)
  || fail("internal error: unexpected column type" + desc.column_type);
}

int main(int argc, char** argv)
{
  std::string arg;

  if (argc > 1) arg = argv[1];

  if (arg == std::string{"--clippy-help"})
  {
    apiJason(std::cout);
    return 0;
  }

  boostjsn::value input = parseFile(std::cin);

  try
  {
    const bool                      make_new_partition  = false;
    std::string                     persistent_location;
    std::string                     dataframe_key;
    std::string                     funname;
    std::string                     colname;

    setValueIfAvail(input, ARG_METALL_LOCATION, persistent_location);
    setValueIfAvail(input, ARG_DATAFRAME_KEY,   dataframe_key);
    setValueIfAvail(input, ARG_CRITERIA_COL,    colname);
    setValueIfAvail(input, ARG_CRITERIA_FUN,    funname);

    clippy_assert<std::runtime_error>(funname == "min" || funname == "max", std::string{"Invalid filter function name: "} + funname);

    std::unique_ptr<xpr::DataFrame> dfp      = makeDataFrame(make_new_partition, persistent_location, dataframe_key);
    xpr::DataFrame&                 df       = *dfp;
    int                             col      = columnIndex(df.get_column_names(), colname);
    std::vector<xpr::ColumnDesc>    colDescs = df.get_column_descriptors(std::vector<int>{col});

    clippy_assert(colDescs.size() == 1, "internal error: unexpected number of columns");

    columnFunction(std::cout, df, col, colDescs.front(), funname);
  }
  catch (const std::exception& err)
  {
    errorJson(std::cout, err.what());
  }

  return 0;
}

max_stars_repo_name: KIwabuchi/clippy-cpp

max_issues_repo_name: KIwabuchi/clippy-cpp

max_forks_repo_name: KIwabuchi/clippy-cpp


text:
//==================================================================================================
/*!
  @file

  @copyright 2016 NumScale SAS

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

**/
//==================================================================================================
#ifndef BOOST_SIMD_EXPONENTIAL_HPP_INCLUDED
#define BOOST_SIMD_EXPONENTIAL_HPP_INCLUDED

namespace boost { namespace simd
{
  /*!
    @ingroup group-functions
    @defgroup group-exponential Exponential functions

    Those functions provide algorithms for computing exponentials
    and logarithms.

      <center>
        |                      |                  |                  |                 |
        |:--------------------:|:----------------:|:----------------:|:---------------:|
        | @ref cbrt            | @ref exp10       | @ref exp2        | @ref exp        |
        | @ref expm1           | @ref exprecneg   | @ref exprecnegc  | @ref expx2      |
        | @ref log10           | @ref log2        | @ref log         | @ref log1p      |
        | @ref nthroot         | @ref pow2        | @ref pow_abs     | @ref pow        |
        | @ref significants    |                  |                  |                 |
       </center>
  **/

} }

#include <boost/simd/function/cbrt.hpp>
#include <boost/simd/function/exp10.hpp>
#include <boost/simd/function/exp2.hpp>
#include <boost/simd/function/exp.hpp>
#include <boost/simd/function/expm1.hpp>
#include <boost/simd/function/exprecnegc.hpp>
#include <boost/simd/function/exprecneg.hpp>
#include <boost/simd/function/expx2.hpp>
#include <boost/simd/function/log10.hpp>
#include <boost/simd/function/log2.hpp>
#include <boost/simd/function/log.hpp>
#include <boost/simd/function/log1p.hpp>
#include <boost/simd/function/nthroot.hpp>
#include <boost/simd/function/pow2.hpp>
#include <boost/simd/function/pow_abs.hpp>
#include <boost/simd/function/pow.hpp>
#include <boost/simd/function/significants.hpp>

#endif

ext: hpp

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran


text:
#ifndef CUKE_HOOKREGISTRAR_HPP_
#define CUKE_HOOKREGISTRAR_HPP_

#include <cucumber-cpp/internal/CukeExport.hpp>
#include "Tag.hpp"
#include "../Scenario.hpp"
#include "../step/StepManager.hpp"

#include <boost/config.hpp>
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>

#include <list>

namespace cucumber {
namespace internal {

class CUCUMBER_CPP_EXPORT CallableStep {
public:
    virtual void call() = 0;
};

class CUCUMBER_CPP_EXPORT Hook {
public:
    void setTags(const std::string &csvTagNotation);
    virtual void invokeHook(Scenario *scenario, CallableStep *step);
    virtual void skipHook();
    virtual void body() = 0;
protected:
    bool tagsMatch(Scenario *scenario);

    template <typename Derived, typename R>
    static R invokeWithArgs(Derived& that, R (Derived::* f)()) {
        return (that.*f)();
    }
private:
    AndTagExpression tagExpression;
};

class CUCUMBER_CPP_EXPORT BeforeHook : public Hook {};

class CUCUMBER_CPP_EXPORT AroundStepHook : public Hook {
public:
    virtual void invokeHook(Scenario *scenario, CallableStep *step);
    virtual void skipHook();
protected:
    CallableStep *step;
};

class CUCUMBER_CPP_EXPORT AfterStepHook : public Hook {};

class CUCUMBER_CPP_EXPORT AfterHook : public Hook {};

class CUCUMBER_CPP_EXPORT UnconditionalHook : public Hook {
public:
    virtual void invokeHook(Scenario *scenario, CallableStep *step);
};

class CUCUMBER_CPP_EXPORT BeforeAllHook : public UnconditionalHook {};

class CUCUMBER_CPP_EXPORT AfterAllHook : public UnconditionalHook {};

class CUCUMBER_CPP_EXPORT HookRegistrar {
public:
    typedef std::list< boost::shared_ptr<Hook> > hook_list_type;
    typedef std::list< boost::shared_ptr<AroundStepHook> > aroundhook_list_type;

    static void addBeforeHook(boost::shared_ptr<BeforeHook> afterHook);
    static void execBeforeHooks(Scenario *scenario);

    static void addAroundStepHook(boost::shared_ptr<AroundStepHook> aroundStepHook);
    static InvokeResult execStepChain(Scenario *scenario, const StepInfo* stepInfo, const InvokeArgs *pArgs);

    static void addAfterStepHook(boost::shared_ptr<AfterStepHook> afterStepHook);
    static void execAfterStepHooks(Scenario *scenario);

    static void addAfterHook(boost::shared_ptr<AfterHook> afterHook);
    static void execAfterHooks(Scenario *scenario);

    static void addBeforeAllHook(boost::shared_ptr<BeforeAllHook> beforeAllHook);
    static void execBeforeAllHooks();

    static void addAfterAllHook(boost::shared_ptr<AfterAllHook> afterAllHook);
    static void execAfterAllHooks();

private:
    static void execHooks(HookRegistrar::hook_list_type &hookList, Scenario *scenario);

protected:
    static hook_list_type& beforeAllHooks();
    static hook_list_type& beforeHooks();
    static aroundhook_list_type& aroundStepHooks();
    static hook_list_type& afterStepHooks();
    static hook_list_type& afterHooks();
    static hook_list_type& afterAllHooks();

private:
    // We're a singleton so don't allow instances
    HookRegistrar()
#ifndef BOOST_NO_DELETED_FUNCTIONS
        = delete
#endif
        ;
};

class CUCUMBER_CPP_EXPORT StepCallChain {
public:
    StepCallChain(Scenario *scenario, const StepInfo* stepInfo, const InvokeArgs *pStepArgs, HookRegistrar::aroundhook_list_type &aroundHooks);
    InvokeResult exec();
    void execNext();
private:
    void execStep();

    Scenario *scenario;
    const StepInfo* stepInfo;
    const InvokeArgs *pStepArgs;

    HookRegistrar::aroundhook_list_type::iterator nextHook;
    HookRegistrar::aroundhook_list_type::iterator hookEnd;
    InvokeResult result;
};

class CUCUMBER_CPP_EXPORT CallableStepChain : public CallableStep {
public:
    CallableStepChain(StepCallChain *scc);
    void call();
private:
    StepCallChain *scc;
};

template<class T>
static int registerBeforeHook(const std::string &csvTagNotation) {
   boost::shared_ptr<T> hook(boost::make_shared<T>());
   hook->setTags(csvTagNotation);
   HookRegistrar::addBeforeHook(hook);
   return 0; // We are not interested in the ID at this time
}

template<class T>
static int registerAroundStepHook(const std::string &csvTagNotation) {
   boost::shared_ptr<T> hook(boost::make_shared<T>());
   hook->setTags(csvTagNotation);
   HookRegistrar::addAroundStepHook(hook);
   return 0;
}

template<class T>
static int registerAfterStepHook(const std::string &csvTagNotation) {
   boost::shared_ptr<T> hook(boost::make_shared<T>());
   hook->setTags(csvTagNotation);
   HookRegistrar::addAfterStepHook(hook);
   return 0;
}

template<class T>
static int registerAfterHook(const std::string &csvTagNotation) {
   boost::shared_ptr<T> hook(boost::make_shared<T>());
   hook->setTags(csvTagNotation);
   HookRegistrar::addAfterHook(hook);
   return 0;
}

template<class T>
static int registerBeforeAllHook() {
   HookRegistrar::addBeforeAllHook(boost::make_shared<T>());
   return 0;
}

template<class T>
static int registerAfterAllHook() {
   HookRegistrar::addAfterAllHook(boost::make_shared<T>());
   return 0;
}

}
}

#endif /* CUKE_HOOKREGISTRAR_HPP_ */

max_stars_repo_name: tsundberg/bdd-cpp-europe

max_issues_repo_name: tsundberg/bdd-cpp-europe

max_forks_repo_name: tsundberg/bdd-cpp-europe


text:
/*    Copyright (c) 2010-2019, Delft University of Technology
 *    All rigths reserved
 *
 *    This file is part of the Tudat. Redistribution and use in source and
 *    binary forms, with or without modification, are permitted exclusively
 *    under the terms of the Modified BSD license. You should have received
 *    a copy of the license with this file. If not, please or visit:
 *    http://tudat.tudelft.nl/LICENSE.
 *
 */

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN

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

#include <limits>
#include <vector>
#include <cmath>

#include "tudat/basics/testMacros.h"
#include "tudat/io/matrixTextFileReader.h"

#include "tudat/math/interpolators/linearInterpolator.h"
#include "tudat/math/interpolators/multiLinearInterpolator.h"
#include "tudat/io/basicInputOutput.h"

namespace tudat
{
namespace unit_tests
{

BOOST_AUTO_TEST_SUITE( test_multi_linear_interpolation )

// Test 1: Comparison to MATLAB solution of the example provided in matlab's interp2 function
// documentation.
BOOST_AUTO_TEST_CASE( test2Dimensions )
{
    // Create independent variable vector.
    std::vector< std::vector< double > > independentValues;

    // Resize independent variable vector to two dimensions and assign values.
    independentValues.resize( 2 );
    for ( int i = 0; i < 5; i++ )
    {
        independentValues[ 0 ].push_back( 1950.0 + static_cast< double >( i ) * 10.0 );
    }

    for ( int i = 0; i < 3; i++ )
    {
        independentValues[ 1 ].push_back( 10.0 + static_cast< double >( i ) * 10.0 );
    }

    // Create two-dimensional array for dependent values.
    boost::multi_array< double, 2 > dependentValues;
    dependentValues.resize( boost::extents[ 5 ][ 3 ] );

    dependentValues[ 0 ][ 0 ] = 150.697;
    dependentValues[ 0 ][ 1 ] = 199.592;
    dependentValues[ 0 ][ 2 ] = 187.625;
    dependentValues[ 1 ][ 0 ] = 179.323;
    dependentValues[ 1 ][ 1 ] = 195.072;
    dependentValues[ 1 ][ 2 ] = 250.287;
    dependentValues[ 2 ][ 0 ] = 203.212;
    dependentValues[ 2 ][ 1 ] = 179.092;
    dependentValues[ 2 ][ 2 ] = 322.767;
    dependentValues[ 3 ][ 0 ] = 226.505;
    dependentValues[ 3 ][ 1 ] = 153.706;
    dependentValues[ 3 ][ 2 ] = 426.730;
    dependentValues[ 4 ][ 0 ] = 249.633;
    dependentValues[ 4 ][ 1 ] = 120.281;
    dependentValues[ 4 ][ 2 ] = 598.243;

    // Initialize interpolator.
    interpolators::MultiLinearInterpolator< double, double, 2 > twoDimensionalInterpolator(
                independentValues, dependentValues );

    // Set interpolation target's independent values.
    std::vector< double > targetValue( 2 );
    targetValue[ 0 ] = 1975.0;
    targetValue[ 1 ] = 15.0;

    // Declare interpolated dependent variable value and execute interpolation.
    const double interpolationResult = twoDimensionalInterpolator.interpolate( targetValue );

    // Check if equal to MATLAB result up to machine precision.
    BOOST_CHECK_CLOSE_FRACTION( 190.62875, interpolationResult,
                                std::numeric_limits< double >::epsilon( ) );
}

// Test 2: 4-dimensional test. Comparison to matlab interpolated solution of analytical function.
BOOST_AUTO_TEST_CASE( test4Dimensions )
{
    // Create independent variable vector.
    std::vector< std::vector< double > > independentValues;

    // Resize independent variable vector to two dimensions and assign values.
    independentValues.resize( 4 );
    for ( int i = 0; i < 11; i++ )
    {
        independentValues[ 0 ].push_back( -1.0 + static_cast< double >( i ) * 0.2 );
        independentValues[ 1 ].push_back( -1.0 + static_cast< double >( i ) * 0.2 );
        independentValues[ 2 ].push_back( -1.0 + static_cast< double >( i ) * 0.2 );
    }

    for ( int i = 0; i < 6; i++ )
    {
        independentValues[ 3 ].push_back( static_cast< double >( i ) * 2.0 );
    }

    // Create four-dimensional array for dependent values based on analytical function
    // f = t*e^(-x^2 - y^2 - z^2 ).
    boost::multi_array< double, 4 > dependentValues;
    dependentValues.resize( boost::extents[ 11 ][ 11 ][ 11 ][ 6 ] );

    for ( int i = 0; i < 11; i++ )
    {
        for ( int j = 0; j < 11; j++ )
        {
            for ( int k = 0; k < 11; k++ )
            {
                for ( int l = 0; l < 6; l++ )
                {
                    dependentValues[ i ][ j ][ k ][ l ] =
                            independentValues[ 3 ][ l ] *
                            std::exp( -std::pow( independentValues[ 0 ][ i ], 2 ) -
                            std::pow( independentValues[ 1 ][ j ], 2 ) -
                            std::pow( independentValues[ 2 ][ k ], 2 ) );
                }
            }
        }
    }

    // Initialize interpolator.
    interpolators::MultiLinearInterpolator< double, double, 4 > fourDimensionalInterpolator(
                independentValues, dependentValues );

    // Set interpolation target's independent values.
    std::vector< double > targetValue( 4 );
    targetValue[ 0 ] = -1.0;
    targetValue[ 1 ] = 0.1;
    targetValue[ 2 ] = 0.5;
    targetValue[ 3 ] = 7.0;

    // Declare interpolated dependent variable value and execute interpolation.
    const double interpolationResult = fourDimensionalInterpolator.interpolate( targetValue );

    // Check if equal to MATLAB result up to machine precision
    BOOST_CHECK_CLOSE_FRACTION( 1.956391733957447, interpolationResult,
                                std::numeric_limits< double >::epsilon( ) );
}

// Test 3: 2 dimensions, with independent variables out of range
BOOST_AUTO_TEST_CASE( test2DimensionsBoundaryCase )
{
    using namespace tudat::interpolators;

    // Create independent variable vector.
    std::vector< std::vector< double > > independentValues;

    // Resize independent variable vector to two dimensions and assign values.
    independentValues.resize( 2 );
    for ( int i = 0; i < 5; i++ )
    {
        independentValues[ 0 ].push_back( 1950.0 + static_cast< double >( i ) * 10.0 );
    }

    for ( int i = 0; i < 3; i++ )
    {
        independentValues[ 1 ].push_back( 10.0 + static_cast< double >( i ) * 10.0 );
    }

    // Create two-dimensional array for dependent values.
    boost::multi_array< double, 2 > dependentValues;
    dependentValues.resize( boost::extents[ 5 ][ 3 ] );

    dependentValues[ 0 ][ 0 ] = 150.697;
    dependentValues[ 0 ][ 1 ] = 199.592;
    dependentValues[ 0 ][ 2 ] = 187.625;
    dependentValues[ 1 ][ 0 ] = 179.323;
    dependentValues[ 1 ][ 1 ] = 195.072;
    dependentValues[ 1 ][ 2 ] = 250.287;
    dependentValues[ 2 ][ 0 ] = 203.212;
    dependentValues[ 2 ][ 1 ] = 179.092;
    dependentValues[ 2 ][ 2 ] = 322.767;
    dependentValues[ 3 ][ 0 ] = 226.505;
    dependentValues[ 3 ][ 1 ] = 153.706;
    dependentValues[ 3 ][ 2 ] = 426.730;
    dependentValues[ 4 ][ 0 ] = 249.633;
    dependentValues[ 4 ][ 1 ] = 120.281;
    dependentValues[ 4 ][ 2 ] = 598.243;

    // Set interpolation target's independent values.
    std::vector< std::vector< double > > targetValue( 5 );
    targetValue[ 0 ].resize( 2 );
    targetValue[ 0 ][ 0 ] = independentValues.at( 0 ).front( ) - 10.0;
    targetValue[ 0 ][ 1 ] = 15.0;
    targetValue[ 1 ].resize( 2 );
    targetValue[ 1 ][ 0 ] = independentValues.at( 0 ).back( ) + 10.0;
    targetValue[ 1 ][ 1 ] = 15.0;
    targetValue[ 2 ].resize( 2 );
    targetValue[ 2 ][ 0 ] = 1975.0;
    targetValue[ 2 ][ 1 ] = independentValues.at( 1 ).front( ) - 2.5;
    targetValue[ 3 ].resize( 2 );
    targetValue[ 3 ][ 0 ] = 1975.0;
    targetValue[ 3 ][ 1 ] = independentValues.at( 1 ).back( ) + 2.5;
    targetValue[ 4 ].resize( 2 );
    targetValue[ 4 ][ 0 ] = independentValues.at( 0 ).front( ) - 10.0;
    targetValue[ 4 ][ 1 ] = independentValues.at( 1 ).back( ) + 2.5;

    // Expected results
    std::vector< double > boundaryResults( 5 ); // computed with MATLAB
    boundaryResults[ 0 ] = 175.1445;
    boundaryResults[ 1 ] = 184.957;
    boundaryResults[ 2 ] = 214.8585;
    boundaryResults[ 3 ] = 374.7485;
    boundaryResults[ 4 ] = 187.625;
    std::vector< double > extrapolationResults( 5 ); // computed with MATLAB
    extrapolationResults[ 0 ] = 163.0915;
    extrapolationResults[ 1 ] = 179.8085;
    extrapolationResults[ 2 ] = 226.973375;
    extrapolationResults[ 3 ] = 426.835875;
    extrapolationResults[ 4 ] = 105.17575;

    // Loop over test cases and boundary handling methods.
    bool exceptionIsCaught;
    double interpolatedValue;
    for( unsigned int i = 0; i < 7; i++ )
    {
        // Initialize interpolator.
        MultiLinearInterpolator< double, double, 2 > twoDimensionalInterpolator(
                    independentValues, dependentValues, huntingAlgorithm,
                    static_cast< BoundaryInterpolationType >( i ) );

        for ( unsigned int j = 0; j < 5; j++ )
        {
            if( static_cast< BoundaryInterpolationType >( i ) == throw_exception_at_boundary )
            {
                exceptionIsCaught = false;
                try
                {
                    twoDimensionalInterpolator.interpolate( targetValue.at( j ) );
                }
                catch( std::runtime_error const& )
                {
                    exceptionIsCaught = true;
                }
                BOOST_CHECK_EQUAL( exceptionIsCaught, true );
            }
            else if( ( static_cast< BoundaryInterpolationType >( i ) == use_boundary_value ) ||
                     ( static_cast< BoundaryInterpolationType >( i ) == use_boundary_value_with_warning ) )
            {
                interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( j ) );
                BOOST_CHECK_CLOSE_FRACTION( interpolatedValue, boundaryResults.at( j ), 1.0E-15 );
            }
            else if( ( static_cast< BoundaryInterpolationType >( i ) == extrapolate_at_boundary ) ||
                     ( static_cast< BoundaryInterpolationType >( i ) == extrapolate_at_boundary_with_warning ) )
            {
                interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( j ) );
                BOOST_CHECK_CLOSE_FRACTION( interpolatedValue, extrapolationResults.at( j ), 1.0E-15 );
            }
            else if( ( static_cast< BoundaryInterpolationType >( i ) == use_default_value ) ||
                     ( static_cast< BoundaryInterpolationType >( i ) == use_default_value_with_warning ) )
            {
                interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( j ) );
                BOOST_CHECK_CLOSE_FRACTION( interpolatedValue, 0.0, 1.0E-15 );
            }
        }
    }
}

// Test linear interpolation outside of independent variable range and compare with 1D linear interpolator
BOOST_AUTO_TEST_CASE( test1DimensionBoundaryCase )
{
    using namespace interpolators;

    // Load input data used for generating matlab interpolation.
    Eigen::MatrixXd inputData = input_output::readMatrixFromFile(
                tudat::paths::getTudatTestDataPath( ) +
                "/interpolator_test_input_data.dat","," );

    // Put data in STL vectors.
    std::vector< double > independentVariableValues;
    std::vector< std::vector< double > > independentVariableValuesMulti;
    std::vector< double > dependentVariableValues;
    boost::multi_array< double, 1 > dependentVariableValuesMulti( boost::extents[ inputData.rows( ) ] );

    for ( int i = 0; i < inputData.rows( ); i++ )
    {
        independentVariableValues.push_back( inputData( i, 0 ) );
        dependentVariableValues.push_back( inputData( i, 1 ) );
        dependentVariableValuesMulti[ i ] = inputData( i, 1 );
    }
    independentVariableValuesMulti.push_back( independentVariableValues );

    // Create linear interpolator using hunting algorithm.
    double valueOffset = 2.0;
    double valueBelowMinimumValue = independentVariableValues[ 0 ] - valueOffset;
    std::vector< double > valueBelowMinimumValueVector = { valueBelowMinimumValue };
    double valueAboveMaximumValue = independentVariableValues[ inputData.rows( ) - 1 ] + valueOffset;
    std::vector< double > valueAboveMaximumValueVector = { valueAboveMaximumValue };
    double linearInterpolatedValue;
    double multiLinearInterpolatedValue;

    for ( unsigned int i = 1; i < 5; i++ )
    {
        // Initialize interpolatos.
        LinearInterpolatorDouble linearInterpolator(
                    independentVariableValues, dependentVariableValues, huntingAlgorithm,
                    static_cast< BoundaryInterpolationType >( i ) );
        MultiLinearInterpolator< double, double, 1 > multiLinearInterpolator(
                    independentVariableValuesMulti, dependentVariableValuesMulti, huntingAlgorithm,
                    static_cast< BoundaryInterpolationType >( i ) );

        if ( ( static_cast< BoundaryInterpolationType >( i ) == use_boundary_value ) ||
             ( static_cast< BoundaryInterpolationType >( i ) == use_boundary_value_with_warning ) )
        {
            linearInterpolatedValue = linearInterpolator.interpolate( valueBelowMinimumValue );
            multiLinearInterpolatedValue = multiLinearInterpolator.interpolate( valueBelowMinimumValueVector );
            BOOST_CHECK_CLOSE_FRACTION( linearInterpolatedValue, multiLinearInterpolatedValue, 1.0E-15 );

            linearInterpolatedValue = linearInterpolator.interpolate( valueAboveMaximumValue );
            multiLinearInterpolatedValue = multiLinearInterpolator.interpolate( valueAboveMaximumValueVector );
            BOOST_CHECK_CLOSE_FRACTION( linearInterpolatedValue, multiLinearInterpolatedValue, 1.0E-15 );

        }
        else if ( ( static_cast< BoundaryInterpolationType >( i ) == extrapolate_at_boundary ) ||
                  ( static_cast< BoundaryInterpolationType >( i ) == extrapolate_at_boundary_with_warning ) )
        {
            linearInterpolatedValue = linearInterpolator.interpolate( valueBelowMinimumValue );
            multiLinearInterpolatedValue = multiLinearInterpolator.interpolate( valueBelowMinimumValueVector );
            BOOST_CHECK_CLOSE_FRACTION( linearInterpolatedValue, multiLinearInterpolatedValue, 1.0E-15 );

            linearInterpolatedValue = linearInterpolator.interpolate( valueAboveMaximumValue );
            multiLinearInterpolatedValue = multiLinearInterpolator.interpolate( valueAboveMaximumValueVector );
            BOOST_CHECK_CLOSE_FRACTION( linearInterpolatedValue, multiLinearInterpolatedValue, 1.0E-15 );
        }
    }
}

// Test linear interpolation outside of independent variable range with default extrapolation value
BOOST_AUTO_TEST_CASE( test2DimensionsDefaultExtrapolationCase )
{
    using namespace interpolators;

    // Create independent variable vector.
    std::vector< std::vector< double > > independentValues;

    // Resize independent variable vector to two dimensions and assign values.
    independentValues.resize( 2 );
    for ( int i = 0; i < 5; i++ )
    {
        independentValues[ 0 ].push_back( 1950.0 + static_cast< double >( i ) * 10.0 );
    }

    for ( int i = 0; i < 3; i++ )
    {
        independentValues[ 1 ].push_back( 10.0 + static_cast< double >( i ) * 10.0 );
    }

    // Create two-dimensional array for dependent values.
    boost::multi_array< double, 2 > inputData;
    inputData.resize( boost::extents[ 5 ][ 3 ] );

    inputData[ 0 ][ 0 ] = 150.697;
    inputData[ 0 ][ 1 ] = 199.592;
    inputData[ 0 ][ 2 ] = 187.625;
    inputData[ 1 ][ 0 ] = 179.323;
    inputData[ 1 ][ 1 ] = 195.072;
    inputData[ 1 ][ 2 ] = 250.287;
    inputData[ 2 ][ 0 ] = 203.212;
    inputData[ 2 ][ 1 ] = 179.092;
    inputData[ 2 ][ 2 ] = 322.767;
    inputData[ 3 ][ 0 ] = 226.505;
    inputData[ 3 ][ 1 ] = 153.706;
    inputData[ 3 ][ 2 ] = 426.730;
    inputData[ 4 ][ 0 ] = 249.633;
    inputData[ 4 ][ 1 ] = 120.281;
    inputData[ 4 ][ 2 ] = 598.243;

    // Set interpolation target's independent values.
    std::vector< std::vector< double > > targetValue( 2 );
    targetValue[ 0 ].resize( 2 );
    targetValue[ 0 ][ 0 ] = independentValues.at( 0 ).front( ) - 10.0;
    targetValue[ 0 ][ 1 ] = 15.0;
    targetValue[ 1 ].resize( 2 );
    targetValue[ 1 ][ 0 ] = independentValues.at( 0 ).front( ) - 10.0;
    targetValue[ 1 ][ 1 ] = independentValues.at( 1 ).back( ) + 2.5;

    // Test with long double
    {
        // Put data in STL vectors.
        boost::multi_array< long double, 2 > dependentValues;
        dependentValues.resize( boost::extents[ 5 ][ 3 ] );
        for ( size_t i = 0; i < inputData.shape( )[ 0 ]; i++ )
        {
            for ( size_t j = 0; j < inputData.shape( )[ 1 ]; j++ )
            {
                dependentValues[ i ][ j ] = static_cast< long double >( inputData[ i ][ j ] );
            }
        }
        long double interpolatedValue;

        for( unsigned int i = 5; i < 7; i++ )
        {
            MultiLinearInterpolator< double, long double, 2 > twoDimensionalInterpolator(
                        independentValues, dependentValues, huntingAlgorithm,
                        static_cast< BoundaryInterpolationType >( i ) );

            interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( 0 ) );
            BOOST_CHECK_CLOSE_FRACTION( interpolatedValue, 0.0L, 1.0E-15 );

            interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( 1 ) );
            BOOST_CHECK_CLOSE_FRACTION( interpolatedValue, 0.0L, 1.0E-15 );
        }
    }

    // Test with Eigen::Vector3d
    {
        // Put data in STL vectors.
        boost::multi_array< Eigen::Vector3d, 2 > dependentValues;
        dependentValues.resize( boost::extents[ 5 ][ 3 ] );
        Eigen::Vector3d tempData = Eigen::Vector3d::Zero( );
        for ( size_t i = 0; i < inputData.shape( )[ 0 ]; i++ )
        {
            for ( size_t j = 0; j < inputData.shape( )[ 1 ]; j++ )
            {
                tempData[ 0 ] = inputData[ i ][ j ];
                dependentValues[ i ][ j ] = tempData;
            }
        }
        Eigen::Vector3d interpolatedValue;

        for( unsigned int i = 5; i < 7; i++ )
        {
            MultiLinearInterpolator< double, Eigen::Vector3d, 2 > twoDimensionalInterpolator(
                        independentValues, dependentValues, huntingAlgorithm,
                        static_cast< BoundaryInterpolationType >( i ) );

            interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( 0 ) );
            BOOST_CHECK_SMALL( ( interpolatedValue - Eigen::Vector3d::Zero( ) ).norm( ), 1.0E-15 );

            interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( 1 ) );
            BOOST_CHECK_SMALL( ( interpolatedValue - Eigen::Vector3d::Zero( ) ).norm( ), 1.0E-15 );
        }
    }

    // Test with Eigen::Matrix3d
    {
        boost::multi_array< Eigen::Matrix3d, 2 > dependentValues;
        dependentValues.resize( boost::extents[ 5 ][ 3 ] );
        Eigen::Matrix3d tempData = Eigen::Matrix3d::Zero( );
        for ( size_t i = 0; i < inputData.shape( )[ 0 ]; i++ )
        {
            for ( size_t j = 0; j < inputData.shape( )[ 1 ]; j++ )
            {
                tempData( 0, 2 ) = inputData[ i ][ j ];
                dependentValues[ i ][ j ] = tempData;
            }
        }
        Eigen::Matrix3d interpolatedValue;

        for( unsigned int i = 5; i < 7; i++ )
        {
            MultiLinearInterpolator< double, Eigen::Matrix3d, 2 > twoDimensionalInterpolator(
                        independentValues, dependentValues, huntingAlgorithm,
                        static_cast< BoundaryInterpolationType >( i ) );

            interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( 0 ) );
            BOOST_CHECK_SMALL( ( interpolatedValue - Eigen::Matrix3d::Zero( ) ).norm( ), 1.0E-15 );

            interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( 1 ) );
            BOOST_CHECK_SMALL( ( interpolatedValue - Eigen::Matrix3d::Zero( ) ).norm( ), 1.0E-15 );
        }
    }
}

// Test linear interpolation outside of independent variable range with extrapolation value given by user
BOOST_AUTO_TEST_CASE( test2DimensionsUserExtrapolationCase )
{
    using namespace interpolators;

    // Create independent variable vector.
    std::vector< std::vector< double > > independentValues;

    // Resize independent variable vector to two dimensions and assign values.
    independentValues.resize( 2 );
    for ( int i = 0; i < 5; i++ )
    {
        independentValues[ 0 ].push_back( 1950.0 + static_cast< double >( i ) * 10.0 );
    }

    for ( int i = 0; i < 3; i++ )
    {
        independentValues[ 1 ].push_back( 10.0 + static_cast< double >( i ) * 10.0 );
    }

    // Create two-dimensional array for dependent values.
    boost::multi_array< double, 2 > inputData;
    inputData.resize( boost::extents[ 5 ][ 3 ] );

    inputData[ 0 ][ 0 ] = 150.697;
    inputData[ 0 ][ 1 ] = 199.592;
    inputData[ 0 ][ 2 ] = 187.625;
    inputData[ 1 ][ 0 ] = 179.323;
    inputData[ 1 ][ 1 ] = 195.072;
    inputData[ 1 ][ 2 ] = 250.287;
    inputData[ 2 ][ 0 ] = 203.212;
    inputData[ 2 ][ 1 ] = 179.092;
    inputData[ 2 ][ 2 ] = 322.767;
    inputData[ 3 ][ 0 ] = 226.505;
    inputData[ 3 ][ 1 ] = 153.706;
    inputData[ 3 ][ 2 ] = 426.730;
    inputData[ 4 ][ 0 ] = 249.633;
    inputData[ 4 ][ 1 ] = 120.281;
    inputData[ 4 ][ 2 ] = 598.243;

    // Set interpolation target's independent values.
    std::vector< std::vector< double > > targetValue( 2 );
    targetValue[ 0 ].resize( 2 );
    targetValue[ 0 ][ 0 ] = independentValues.at( 0 ).front( ) - 10.0;
    targetValue[ 0 ][ 1 ] = 15.0;
    targetValue[ 1 ].resize( 2 );
    targetValue[ 1 ][ 0 ] = independentValues.at( 0 ).front( ) - 10.0;
    targetValue[ 1 ][ 1 ] = independentValues.at( 1 ).back( ) + 2.5;

    // Test with long double
    {
        // Put data in STL vectors.
        boost::multi_array< long double, 2 > dependentValues;
        dependentValues.resize( boost::extents[ 5 ][ 3 ] );
        for ( size_t i = 0; i < inputData.shape( )[ 0 ]; i++ )
        {
            for ( size_t j = 0; j < inputData.shape( )[ 1 ]; j++ )
            {
                dependentValues[ i ][ j ] = static_cast< long double >( inputData[ i ][ j ] );
            }
        }
        long double interpolatedValue;
        long double extrapolationValue = 1.0L;

        for( unsigned int i = 5; i < 7; i++ )
        {
            MultiLinearInterpolator< double, long double, 2 > twoDimensionalInterpolator(
                        independentValues, dependentValues, huntingAlgorithm,
                        static_cast< BoundaryInterpolationType >( i ), extrapolationValue );

            interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( 0 ) );
            BOOST_CHECK_CLOSE_FRACTION( interpolatedValue, extrapolationValue, 1.0E-15 );

            interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( 1 ) );
            BOOST_CHECK_CLOSE_FRACTION( interpolatedValue, extrapolationValue, 1.0E-15 );
        }
    }

    // Test with Eigen::Vector3d
    {
        // Put data in STL vectors.
        boost::multi_array< Eigen::Vector3d, 2 > dependentValues;
        dependentValues.resize( boost::extents[ 5 ][ 3 ] );
        Eigen::Vector3d tempData = Eigen::Vector3d::Zero( );
        for ( size_t i = 0; i < inputData.shape( )[ 0 ]; i++ )
        {
            for ( size_t j = 0; j < inputData.shape( )[ 1 ]; j++ )
            {
                tempData[ 0 ] = inputData[ i ][ j ];
                dependentValues[ i ][ j ] = tempData;
            }
        }
        Eigen::Vector3d interpolatedValue;
        Eigen::Vector3d extrapolationValue;
        extrapolationValue[ 0 ] = 1.5;
        extrapolationValue[ 1 ] = -3;
        extrapolationValue[ 2 ] = 0;

        for( unsigned int i = 5; i < 7; i++ )
        {
            MultiLinearInterpolator< double, Eigen::Vector3d, 2 > twoDimensionalInterpolator(
                        independentValues, dependentValues, huntingAlgorithm,
                        static_cast< BoundaryInterpolationType >( i ), extrapolationValue );

            interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( 0 ) );
            BOOST_CHECK_SMALL( ( interpolatedValue - extrapolationValue ).norm( ), 1.0E-15 );

            interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( 1 ) );
            BOOST_CHECK_SMALL( ( interpolatedValue - extrapolationValue ).norm( ), 1.0E-15 );
        }
    }

    // Test with Eigen::Matrix3d
    {
        boost::multi_array< Eigen::Matrix3d, 2 > dependentValues;
        dependentValues.resize( boost::extents[ 5 ][ 3 ] );
        Eigen::Matrix3d tempData = Eigen::Matrix3d::Zero( );
        for ( size_t i = 0; i < inputData.shape( )[ 0 ]; i++ )
        {
            for ( size_t j = 0; j < inputData.shape( )[ 1 ]; j++ )
            {
                tempData( 0, 2 ) = inputData[ i ][ j ];
                dependentValues[ i ][ j ] = tempData;
            }
        }
        Eigen::Matrix3d interpolatedValue;
        Eigen::Matrix3d extrapolationValue = Eigen::Matrix3d::Random( );

        for( unsigned int i = 5; i < 7; i++ )
        {
            MultiLinearInterpolator< double, Eigen::Matrix3d, 2 > twoDimensionalInterpolator(
                        independentValues, dependentValues, huntingAlgorithm,
                        static_cast< BoundaryInterpolationType >( i ), extrapolationValue );

            interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( 0 ) );
            BOOST_CHECK_SMALL( ( interpolatedValue - extrapolationValue ).norm( ), 1.0E-15 );

            interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( 1 ) );
            BOOST_CHECK_SMALL( ( interpolatedValue - extrapolationValue ).norm( ), 1.0E-15 );
        }
    }
}

BOOST_AUTO_TEST_SUITE_END( )

} // namespace unit_tests
} // namespace tudat


text:
#ifndef __IRODS_HASH_HPP__
#define __IRODS_HASH_HPP__

// =-=-=-=-=-=-=-
// hash_map include
#include <boost/unordered_map.hpp>
#define HASH_TYPE boost::unordered_map

#include <string>
#include "irods_stacktrace.hpp"
#include "irods_log.hpp"

namespace irods {

    struct irods_string_hash {
        enum {
            // parameters for hash table
            bucket_size = 4, // 0 < bucket_size
            min_buckets = 8

        }; // min_buckets = 2 ^^ N, 0 < N

        size_t operator()( const std::string& s1 ) const {
            if ( s1.empty() ) {
                std::cerr << irods::stacktrace().dump();
                rodsLog(
                    LOG_NOTICE,
                    "irods_string_hash - empty string value" );
                return 0;
            }

            // hash string s1 to size_t value
            const unsigned char *p = ( const unsigned char * )s1.c_str();
            size_t hashval = 0;

            while ( *p != '\0' ) {
                hashval = 31 * hashval + ( *p++ );    // or whatever
            }

            return hashval;
        }

        bool operator()( const std::string s1, const std::string s2 ) const {
            return s1 < s2;
        }

        ~irods_string_hash() {
        }

    }; // struct irods_string_hash

}; // namespace irods

#endif // __IRODS_HASH_HPP__

max_stars_repo_name: tempoz/irods

max_issues_repo_name: tempoz/irods

max_forks_repo_name: tempoz/irods


text:
#include "Day20-ParticleSwarm.h"

#include "Particle.h"
#include "ParticleSystem.h"

#include <AdventOfCodeCommon/DisableLibraryWarningsMacros.h>

__BEGIN_LIBRARIES_DISABLE_WARNINGS
#include <boost/algorithm/string.hpp>
__END_LIBRARIES_DISABLE_WARNINGS

namespace
{

const unsigned NUM_SIMULATION_STEPS = 1'000;

}

namespace AdventOfCode
{
namespace Year2017
{
namespace Day20
{

std::vector<Particle> createParticlesFromLines(const std::vector<std::string>& particleLines)
{
    const auto allSeparatorsPredicate = boost::is_any_of("pva=<>, ");
    std::vector<Particle> particles;

    unsigned particleID = 0;

    for (auto particleLine : particleLines)
    {
        // Remove leading and trailing separators
        boost::trim_if(particleLine, allSeparatorsPredicate);

        std::vector<std::string> tokens;
        boost::split(tokens, particleLine, allSeparatorsPredicate, boost::token_compress_on);

        if (tokens.size() != 9)
        {
            throw std::runtime_error("Expected exactly 9 tokens.");
        }

        Particle::Vector3D position{std::stoi(tokens[0]), std::stoi(tokens[1]), std::stoi(tokens[2])};
        Particle::Vector3D velocity{std::stoi(tokens[3]), std::stoi(tokens[4]), std::stoi(tokens[5])};
        Particle::Vector3D acceleration{std::stoi(tokens[6]), std::stoi(tokens[7]), std::stoi(tokens[8])};

        particles.emplace_back(particleID++, std::move(position), std::move(velocity), std::move(acceleration));
    }

    return particles;
}

unsigned particleIDClosestToOriginLongTerm(const std::vector<std::string>& particleLines)
{
    std::vector<Particle> particles = createParticlesFromLines(particleLines);

    ParticleSystem particleSystem{std::move(particles)};

    particleSystem.simulate(NUM_SIMULATION_STEPS);
    return particleSystem.particleIDClosestToOrigin();
}

unsigned numParticlesLeftAfterCollisions(const std::vector<std::string>& particleLines)
{
    std::vector<Particle> particles = createParticlesFromLines(particleLines);

    ParticleSystem particleSystem{std::move(particles)};

    particleSystem.simulateWithCollisions(NUM_SIMULATION_STEPS);
    return particleSystem.numParticles();
}

}
}
}

max_stars_repo_name: dbartok/advent-of-code-cpp

max_issues_repo_name: dbartok/advent-of-code-cpp

max_forks_repo_name: dbartok/advent-of-code-cpp


text:
//Note that according to the python documentation,
//the Python.h header file should be included first, before any other header file.
#include <Python.h>
#include <iostream>
#include <dlib/opencv.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <dlib/image_processing/frontal_face_detector.h>
#include <dlib/image_processing/render_face_detections.h>
#include <dlib/image_processing.h>
#include <fstream>
#include <unistd.h>
#include <cmath>
#include <stdio.h>
#include <time.h>

//Intrisics can be calculated using opencv sample code under opencv/sources/samples/cpp/tutorial_code/calib3d
//Normally, you can also apprximate fx and fy by image width, cx by half image width, cy by half image height instead
double K[9] = {7.3530833553043510e+02, 0.0, 320.0, 0.0, 7.3530833553043510e+02, 240.0, 0.0, 0.0, 1.0};
double D[5] = {-2.3528667558034226e-02, 1.3301431879108856e+00, 0.0, 0.0,
    -6.0786673300480434e+00};
const int debounce_camera_time_delay = 1;
const double centimeter_to_inch_conversion = 1/2.54;

int main(int argc, char *argv[]){

  //The python documentation explains much of the python code (see "Extending and Embedding
  //Python")
    wchar_t *program = Py_DecodeLocale(argv[0], NULL);
    if (program == NULL) {
        fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
        exit(1);
    }
    Py_SetProgramName(program);  /* optional but recommended */
    Py_Initialize();
    //Make the serial connection via the Python interpreter
    PyRun_SimpleString("import serial\n");
    PyRun_SimpleString("ser = serial.Serial('/dev/ttyACM0', 9600, timeout=5)");
    cv::VideoCapture cap(1);
    if (!cap.isOpened())
        {
        std::cout << "Unable to connect to camera" << std::endl;
        return EXIT_FAILURE;
        }
    //Load face detection and pose estimation models (dlib).
    dlib::frontal_face_detector detector;
    dlib::shape_predictor predictor;
    detector = dlib::get_frontal_face_detector();
    dlib::deserialize("../data/face_model_68_points.dat") >> predictor;
     //fill in cam intrinsics and distortion coefficients
    cv::Mat cam_matrix = cv::Mat(3, 3, CV_64FC1, K);
    cv::Mat dist_coeffs = cv::Mat(5, 1, CV_64FC1, D);
    //fill in 3D ref points(world coordinates), model referenced from http://aifi.isr.uc.pt/Downloads/OpenGL/glAnthropometric3DModel.cpp
    std::vector<cv::Point3d> object_pts;

    object_pts.push_back(cv::Point3d(6.825897, 6.760612, 4.402142));     //#33 left brow left corner
    object_pts.push_back(cv::Point3d(1.330353, 7.122144, 6.903745));     //#29 left brow right corner
    object_pts.push_back(cv::Point3d(-1.330353, 7.122144, 6.903745));    //#34 right brow left corner
    object_pts.push_back(cv::Point3d(-6.825897, 6.760612, 4.402142));    //#38 right brow right corner
    object_pts.push_back(cv::Point3d(5.311432, 5.485328, 3.987654));     //#13 left eye left corner
    object_pts.push_back(cv::Point3d(1.789930, 5.393625, 4.413414));     //#17 left eye right corner
    object_pts.push_back(cv::Point3d(-1.789930, 5.393625, 4.413414));    //#25 right eye left corner
    object_pts.push_back(cv::Point3d(-5.311432, 5.485328, 3.987654));    //#21 right eye right corner
    object_pts.push_back(cv::Point3d(2.005628, 1.409845, 6.165652));     //#55 nose left corner
    object_pts.push_back(cv::Point3d(-2.005628, 1.409845, 6.165652));    //#49 nose right corner
    object_pts.push_back(cv::Point3d(2.774015, -2.080775, 5.048531));    //#43 mouth left corner
    object_pts.push_back(cv::Point3d(-2.774015, -2.080775, 5.048531));   //#39 mouth right corner
    object_pts.push_back(cv::Point3d(0.000000, -3.116408, 6.097667));    //#45 mouth central bottom corner
    object_pts.push_back(cv::Point3d(0.000000, -7.415691, 4.070434));    //#6 chin corner

    //2D ref points(image coordinates), referenced from detected facial feature
    std::vector<cv::Point2d> image_pts;

    //result
    cv::Mat rotation_vec;                           //3 x 1
    cv::Mat rotation_mat;                           //3 x 3 R
    cv::Mat translation_vec;                        //3 x 1 T
    cv::Mat pose_mat = cv::Mat(3, 4, CV_64FC1);     //3 x 4 R | T
    cv::Mat euler_angle = cv::Mat(3, 1, CV_64FC1);

    //reproject 3D points world coordinate axis to verify result pose
    std::vector<cv::Point3d> reprojectsrc;
    reprojectsrc.push_back(cv::Point3d(10.0, 10.0, 10.0));
    reprojectsrc.push_back(cv::Point3d(10.0, 10.0, -10.0));
    reprojectsrc.push_back(cv::Point3d(10.0, -10.0, -10.0));
    reprojectsrc.push_back(cv::Point3d(10.0, -10.0, 10.0));
    reprojectsrc.push_back(cv::Point3d(-10.0, 10.0, 10.0));
    reprojectsrc.push_back(cv::Point3d(-10.0, 10.0, -10.0));
    reprojectsrc.push_back(cv::Point3d(-10.0, -10.0, -10.0));
    reprojectsrc.push_back(cv::Point3d(-10.0, -10.0, 10.0));

    //reprojected 2D points
    std::vector<cv::Point2d> reprojectdst;
    reprojectdst.resize(8);

    //temp buf for decomposeProjectionMatrix()
    cv::Mat out_intrinsics = cv::Mat(3, 3, CV_64FC1);
    cv::Mat out_rotation = cv::Mat(3, 3, CV_64FC1);
    cv::Mat out_translation = cv::Mat(3, 1, CV_64FC1);

    //text on screen
    std::ostringstream outtext;
    bool still_roll = false;
    bool still_pitch = false;
    bool still_yaw = false;
    bool still_y = false;
    bool still_x = false;
    time_t time_since_still_roll = 0;
    time_t time_since_still_pitch = 0;
    time_t time_since_still_yaw = 0;
    time_t time_since_still_y = 0;
    time_t time_since_still_x = 0;
    //Loop until the escape key is pressed.
    while (1)
    {
      //usleep(500000);
        // Grab a frame
        cv::Mat temp;
        cap >> temp;

        dlib::cv_image<dlib::bgr_pixel> cimg(temp);

        // Detect faces
        std::vector<dlib::rectangle> faces = detector(cimg);

        // Find the pose of each face
        if (faces.size() > 0)
            {
            //std::cout << "DETECTED " << faces.size() << std::endl << std::endl;
            //track features
            dlib::full_object_detection shape = predictor(cimg, faces[0]);

            //draw features
            for (unsigned int i = 0; i < 68; ++i)
                {
                cv::circle(temp, cv::Point(shape.part(i).x(), shape.part(i).y()), 2, cv::Scalar(0, 0, 255), -1);
                }

            //fill in 2D ref points, annotations follow https://ibug.doc.ic.ac.uk/resources/300-W/

            image_pts.push_back(cv::Point2d(shape.part(17).x(), shape.part(17).y())); //#17 left brow left corner
            image_pts.push_back(cv::Point2d(shape.part(21).x(), shape.part(21).y())); //#21 left brow right corner
            image_pts.push_back(cv::Point2d(shape.part(22).x(), shape.part(22).y())); //#22 right brow left corner
            image_pts.push_back(cv::Point2d(shape.part(26).x(), shape.part(26).y())); //#26 right brow right corner
            image_pts.push_back(cv::Point2d(shape.part(36).x(), shape.part(36).y())); //#36 left eye left corner
            image_pts.push_back(cv::Point2d(shape.part(39).x(), shape.part(39).y())); //#39 left eye right corner
            image_pts.push_back(cv::Point2d(shape.part(42).x(), shape.part(42).y())); //#42 right eye left corner
            image_pts.push_back(cv::Point2d(shape.part(45).x(), shape.part(45).y())); //#45 right eye right corner
            image_pts.push_back(cv::Point2d(shape.part(31).x(), shape.part(31).y())); //#31 nose left corner
            image_pts.push_back(cv::Point2d(shape.part(35).x(), shape.part(35).y())); //#35 nose right corner
            image_pts.push_back(cv::Point2d(shape.part(48).x(), shape.part(48).y())); //#48 mouth left corner
            image_pts.push_back(cv::Point2d(shape.part(54).x(), shape.part(54).y())); //#54 mouth right corner
            image_pts.push_back(cv::Point2d(shape.part(57).x(), shape.part(57).y())); //#57 mouth central bottom corner
            image_pts.push_back(cv::Point2d(shape.part(8).x(), shape.part(8).y()));   //#8 chin corner

            //calc pose
            cv::solvePnP(object_pts, image_pts, cam_matrix, dist_coeffs, rotation_vec, translation_vec);

            //reproject
            cv::projectPoints(reprojectsrc, rotation_vec, translation_vec, cam_matrix, dist_coeffs, reprojectdst);

            //draw axis
            cv::line(temp, reprojectdst[0], reprojectdst[1], cv::Scalar(0, 0, 255));
            cv::line(temp, reprojectdst[1], reprojectdst[2], cv::Scalar(0, 0, 255));
            cv::line(temp, reprojectdst[2], reprojectdst[3], cv::Scalar(0, 0, 255));
            cv::line(temp, reprojectdst[3], reprojectdst[0], cv::Scalar(0, 0, 255));
            cv::line(temp, reprojectdst[4], reprojectdst[5], cv::Scalar(0, 0, 255));
            cv::line(temp, reprojectdst[5], reprojectdst[6], cv::Scalar(0, 0, 255));
            cv::line(temp, reprojectdst[6], reprojectdst[7], cv::Scalar(0, 0, 255));
            cv::line(temp, reprojectdst[7], reprojectdst[4], cv::Scalar(0, 0, 255));
            cv::line(temp, reprojectdst[0], reprojectdst[4], cv::Scalar(0, 0, 255));
            cv::line(temp, reprojectdst[1], reprojectdst[5], cv::Scalar(0, 0, 255));
            cv::line(temp, reprojectdst[2], reprojectdst[6], cv::Scalar(0, 0, 255));
            cv::line(temp, reprojectdst[3], reprojectdst[7], cv::Scalar(0, 0, 255));

            //This line of code finds the point that is located at the center of the face that
            //is being detected.
            cv::Point2d my_point = ((reprojectdst[0] + reprojectdst[1] + reprojectdst[2] + reprojectdst[3] + reprojectdst[4] + reprojectdst[5] + reprojectdst[6] + reprojectdst[7])/8);
            //Get the x and y coordinates of the point at the center of the face that is being
            //detected.
            double my_x = my_point.x;
            double my_y = my_point.y;
            double x_for_pose = my_x/temp.cols;
            double y_for_pose = my_y/temp.rows;
            //std::cout << x_for_pose << std::endl;
            //std::cout << y_for_pose << std::endl;
            x_for_pose = x_for_pose -0.5;
            y_for_pose = y_for_pose -0.5;
            double x_distance = -translation_vec.at<double>(1,1)*atan(27.6*3.14159265/180)*x_for_pose/0.5;
            double y_distance = translation_vec.at<double>(1,1)*atan(20*3.14159265/180)*y_for_pose/0.5;

            //calc euler angle
            cv::Rodrigues(rotation_vec, rotation_mat);
            cv::hconcat(rotation_mat, translation_vec, pose_mat);
            cv::decomposeProjectionMatrix(pose_mat, out_intrinsics, out_rotation, out_translation, cv::noArray(), cv::noArray(), cv::noArray(), euler_angle);

                          //show angle result
            //outtext << "X: " << std::setprecision(3) << euler_angle.at<double>(0);
            double z_pos = -translation_vec.at<double>(1, 1)*centimeter_to_inch_conversion;
            outtext << "Distance from camera [in]: " << std::setprecision(3) << z_pos;
            cv::putText(temp, outtext.str(), cv::Point(50, 40), cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(0, 0, 0));
            outtext.str("");
            double x_pos = x_distance*centimeter_to_inch_conversion;
            outtext << "x position [in]: " << std::setprecision(3) << x_pos;
            //outtext << "Y: " << std::setprecision(3) << euler_angle.at<double>(1);
            cv::putText(temp, outtext.str(), cv::Point(50, 60), cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(0, 0, 0));
            outtext.str("");
            //outtext << "Z: " << std::setprecision(3) << euler_angle.at<double>(2);
            double y_pos = y_distance*centimeter_to_inch_conversion;
            outtext << "y position [in]: " << std::setprecision(3) << y_pos;
            cv::putText(temp, outtext.str(), cv::Point(50, 80), cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(0, 0, 0));
            outtext.str("");
            //outtext << "rot_vec 1: " << std::setprecision(3) << rotation_vec.at<double>(1, 1);
            double pitch = euler_angle.at<double>(0);
            outtext << "Pitch in degrees: " << std::setprecision(3) << pitch;
            cv::putText(temp, outtext.str(), cv::Point(50, 100), cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(0, 0, 0));
            outtext.str("");
            //outtext << "rot_vec 2: " << std::setprecision(3) << rotation_vec.at<double>(2, 1);
            double yaw = euler_angle.at<double>(1);
            outtext << "Yaw in degrees: " << std::setprecision(3) << yaw;
            cv::putText(temp, outtext.str(), cv::Point(50, 120), cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(0, 0, 0));
            outtext.str("");
            //outtext << "rot_vec 3: " << std::setprecision(3) << rotation_vec.at<double>(3, 1);
            double roll = euler_angle.at<double>(2);
            outtext << "Roll in degrees: " << std::setprecision(3) << roll;
            cv::putText(temp, outtext.str(), cv::Point(50, 140), cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(0, 0, 0));
            outtext.str("");
            char buffer[100];
            ////////////////////////// roll /////////////////////////////////// #
            if(still_roll)
            {
              time_since_still_roll = time(NULL);
            }
            if(abs(roll) < 5)
            {
              roll = 0.0;
              still_roll = true;
            }
            else
            {
              still_roll = false;
            }
            if(time(NULL) < time_since_still_roll + debounce_camera_time_delay)
            {
              roll = 0.0;
            }
            sprintf(buffer,"ser.write('#%+03d\\x00'.encode())", (int)(roll*-2));
            PyRun_SimpleString(buffer);
            PyRun_SimpleString("ser.flush()");

            ///////////////////////// pitch ////////////////////////////////// &
            if(still_pitch)
            {
              time_since_still_pitch = time(NULL);
            }
            if(abs(pitch) < 5)
            {
              pitch = 0.0;
              still_pitch = true;
            }
            else
            {
              still_pitch = false;
            }
            if(time(NULL) < time_since_still_pitch + debounce_camera_time_delay)
            {
              pitch = 0.0;
            }
            sprintf(buffer,"ser.write('&%+03d\\x00'.encode())", (int)(pitch*2));

            PyRun_SimpleString(buffer);
            PyRun_SimpleString("ser.flush()");

            outtext << buffer;
            cv::putText(temp, outtext.str(), cv::Point(100, 200), cv::FONT_HERSHEY_SIMPLEX, 1.5, cv::Scalar(255, 255, 255), 3);
            outtext.str("");

            ///////////////////////// yaw ///////////////////////////////////// *
            if(still_yaw)
            {
              time_since_still_yaw = time(NULL);
            }
            if(abs(yaw) < 5)
            {
              yaw = 0.0;
              still_yaw = true;
            }
            else
            {
              still_yaw = false;
            }
            if(time(NULL) < time_since_still_yaw + debounce_camera_time_delay)
            {
              yaw = 0.0;
            }
            sprintf(buffer,"ser.write('*%+03d\\x00'.encode())", (int)(yaw*-2));
            PyRun_SimpleString(buffer);
            PyRun_SimpleString("ser.flush()");

            ///////////////////////// y /////////////////////////////////////// $
            if(still_y)
            {
              time_since_still_y = time(NULL);
            }
            if(abs(y_pos) <= 3)
            {
              y_pos = 0;
              still_y = true;
            }
            else
            {
              still_y = false;
            }
            if(time(NULL) < time_since_still_y + debounce_camera_time_delay)
            {
              y_pos = 0.0;
            }

            sprintf(buffer,"ser.write('$%+03d\\x00'.encode())", (int)(y_pos*-2));
            PyRun_SimpleString(buffer);
            PyRun_SimpleString("ser.flush()");

            /////////////////////// x //////////////////////////////////////// ^
            if(still_x)
            {
              time_since_still_x = time(NULL);
            }
            if(abs(x_pos) <= 3)
            {
              x_pos = 0;
              still_x = true;
            }
            else
            {
              still_x = false;
            }
            if(time(NULL) < time_since_still_x + debounce_camera_time_delay)
            {
              x_pos = 0.0;
            }

            sprintf(buffer,"ser.write('^%+03d\\x00'.encode())", (int)(-x_pos));
            PyRun_SimpleString(buffer);
            PyRun_SimpleString("ser.flush()");

            ////////////////// clear image points ////////////////
            image_pts.clear();
            }
 //press esc to end
        cv::namedWindow( "demo", cv::WINDOW_NORMAL);
        cv::imshow("demo", temp);
        unsigned char key = cv::waitKey(1);
        if (key == 27)
            {
            break;
            }
    }
    PyMem_RawFree(program);
    return 0;
}

max_stars_repo_name: JoshuaCall/rasm-software

max_issues_repo_name: JoshuaCall/rasm-software

max_forks_repo_name: JoshuaCall/rasm-software