text:
/******************************************************************************
 *
 * AMDiS - Adaptive multidimensional simulations
 *
 * Copyright (C) 2013 Dresden University of Technology. All Rights Reserved.
 * Web: https://fusionforge.zih.tu-dresden.de/projects/amdis
 *
 * Authors:
 * Simon Vey, Thomas Witkowski, Andreas Naumann, Simon Praetorius, et al.
 *
 * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
 * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 *
 * This file is part of AMDiS
 *
 * See also license.opensource.txt in the distribution.
 *
 ******************************************************************************/

// Created by Roman Weissflog & Philipp Schulz

/** \file Bubble.h */

#ifndef AMDIS_BUBBLE_H
#define AMDIS_BUBBLE_H

#include <list>
#include <boost/numeric/mtl/mtl.hpp>
#include "AbstractFunction.h"
#include "BasisFunction.h"
#include "FixVec.h"

namespace AMDiS
{

  /** \ingroup FEMSpace
  * \brief
  * Lagrange basis functions plus Bubble function. Sub class of BasisFunction
  */

  class Bubble : public BasisFunction
  {
  public:
    /// Creator class used in the BasisFunctionCreatorMap.
    class Creator : public BasisFunctionCreator
    {
    public:
      virtual ~Creator() {}

      /// Returns a new Lagrange object.
      BasisFunction* create()
      {
        return getBubble(this->dim, this->dim + 1); // has to be generalized in later versions of bubble functions
      }
    };

  protected:
    /// Constructs lagrange/bubble basis functions with the given dim and degree.
    /// Constructor is protected to avoid multiple instantiation of identical
    /// basis functions. Use \ref getBubble instead.
    Bubble(int dim_, int degree_);

    /** \brief
    * destructor
    */
    virtual ~Bubble();

  public:
    /// Returns a pointer to lagrange and bubble basis functions with the given dim and
    /// degree. Multiple instantiation of identical basis functions is avoided
    /// by rembering once created basis functions in \ref allBasFcts.
    static Bubble* getBubble(int dim, int degree);

    /// Implements BasisFunction::interpol
    void interpol(const ElInfo*, int, const int*,
                  AbstractFunction<double, WorldVector<double>>*,
                  mtl::dense_vector<double>&) const override;

    /// Implements BasisFunction::interpol
    void interpol(const ElInfo*, int,
                  const int* b_no,
                  AbstractFunction<WorldVector<double>, WorldVector<double>>*,
                  mtl::dense_vector<WorldVector<double>>&) const override;

    /// Returns the barycentric coordinates of the i-th basis function.
    DimVec<double>* getCoords(int i) const override;

    /// Implements BasisFunction::getBound
    void getBound(const ElInfo*, BoundaryType*) const override;

    /** \brief
    * Calculates the local vertex indices which are involved in evaluating
    * the nodeIndex-th DOF at the positionIndex-th part of type position
    * (VERTEX/EDGE/FACE/CENTER). nodeIndex determines the permutation
    * of the involved vertices. So in 1d for lagrange4 there are two DOFs at
    * the CENTER (which is an edge in this case). Then vertices[0] = {0, 1} and
    * vertices[1] = {1, 0}. This allows to use the same local basis function
    * for all DOFs at the same position.
    */
    static void setVertices(int dim, int degree,
                            GeoIndex position, int positionIndex, int nodeIndex,
                            int** vertices);

    /// Implements BasisFunction::refineInter
    inline void refineInter(DOFIndexed<double>* drv, RCNeighbourList* list, int n) override
    {
      if (refineInter_fct)
        (*refineInter_fct)(drv, list, n, this);
    }

    /// Implements BasisFunction::coarseRestrict
    inline void coarseRestr(DOFIndexed<double>* drv, RCNeighbourList* list, int n) override
    {
      if (coarseRestr_fct)
        (*coarseRestr_fct)(drv, list, n, this);
    }

    /// Implements BasisFunction::coarseInter
    inline void coarseInter(DOFIndexed<double>* drv, RCNeighbourList* list, int n) override
    {
      if (coarseInter_fct)
        (*coarseInter_fct)(drv, list, n, this);
    }

    /// Implements BasisFunction::getLocalIndices().
    void getLocalIndices(const Element* el,
                         const DOFAdmin* admin,
                         std::vector<DegreeOfFreedom>& dofs) const override;

    /// Implements BasisFunction::getLocalDofPtrVec()
    /// Returns an vector filled with all DOFs per position
    void getLocalDofPtrVec(const Element* el,
                           const DOFAdmin* admin,
                           std::vector<const DegreeOfFreedom*>& vec) const override;

    /// Implements BasisFunction::l2ScpFctBas
    void l2ScpFctBas(Quadrature* q,
                     AbstractFunction<double, WorldVector<double>>* f,
                     DOFVector<double>* fh) override;

    /// Implements BasisFunction::l2ScpFctBas
    void l2ScpFctBas(Quadrature* q,
                     AbstractFunction<WorldVector<double>, WorldVector<double>>* f,
                     DOFVector<WorldVector<double>>* fh) override;

    static void clear();

    /// Implements BasisFunction::isnodal
    bool isNodal() const override
    {
      return false;
    }

  protected:
    /// sets the barycentric coordinates (stored in \ref bary) of the local
    /// basis functions.
    void setBary();

    /// Implements BasisFunction::setNDOF
    void setNDOF() override;

    /// Sets used function pointers
    void setFunctionPointer();

    /// Used by \ref getVec
    int* orderOfPositionIndices(const Element* el,
                                GeoIndex position,
                                int positionIndex) const override;

  private:
    /// barycentric coordinates of the locations of all basis functions
    std::vector<DimVec<double>*>* bary;

    /** \name static dim-degree-arrays
    * \{
    */
    static std::vector<DimVec<double>*> baryDimDegree;
    static DimVec<int>* ndofDimDegree;
    static int nBasFctsDimDegree;
    static std::vector<BasFctType*> phifunc;
    static std::vector<GrdBasFctType*> grdPhifunc;
    static std::vector<D2BasFctType*> D2Phifunc;
    /** \} */

    /// List of all used BasisFunctions in the whole program. Avoids duplicate
    /// instantiation of identical BasisFunctions.
    static Bubble* Singleton;

  protected:
    /// Pointer to the used refineInter function
    void (*refineInter_fct)(DOFIndexed<double>*, RCNeighbourList*, int, BasisFunction*);

    static void  refineInter2_1d(DOFIndexed<double>*, RCNeighbourList*, int,
                                 BasisFunction*);
    static void  refineInter3_2d(DOFIndexed<double>*, RCNeighbourList*, int,
                                 BasisFunction*);
    static void  refineInter4_3d(DOFIndexed<double>*, RCNeighbourList*, int,
                                 BasisFunction*);

    /// Pointer to the used coarseRestr function
    void (*coarseRestr_fct)(DOFIndexed<double>*, RCNeighbourList*, int, BasisFunction*);

    static void  coarseRestr2_1d(DOFIndexed<double>*, RCNeighbourList*, int,
                                 BasisFunction*);
    static void  coarseRestr3_2d(DOFIndexed<double>*, RCNeighbourList*, int,
                                 BasisFunction*);
    static void  coarseRestr4_3d(DOFIndexed<double>*, RCNeighbourList*, int,
                                 BasisFunction*);

    /// Pointer to the used coarseInter function
    void (*coarseInter_fct)(DOFIndexed<double>*, RCNeighbourList*, int, BasisFunction*);

    static void  coarseInter2_1d(DOFIndexed<double>*, RCNeighbourList*, int,
                                 BasisFunction*);
    static void  coarseInter3_2d(DOFIndexed<double>*, RCNeighbourList*, int,
                                 BasisFunction*);
    static void  coarseInter4_3d(DOFIndexed<double>*, RCNeighbourList*, int,
                                 BasisFunction*);

    /// AbstractFunction which implements lagrange/bubble basis functions
    class Phi : public BasFctType
    {
    public:
      /// Constructs the local lagrange/bubble basis function for the given position,
      /// positionIndex and nodeIndex. owner_ is a pointer to the Bubble
      /// object this basis function belongs to.
      Phi(Bubble* owner, GeoIndex position, int positionIndex, int nodeIndex);

      /// Destructor
      virtual ~Phi();

    private:
      /// vertices needed for evaluation of this function
      int* vertices;

      /// Pointer to the evaluating function
      double (*func)(const DimVec<double>& lambda, int* vert);

      /// Returns \ref func(lambda, vertices)
      inline double operator()(const DimVec<double>& lambda) const override
      {
        return func(lambda, vertices);
      }

      // ====== Lagrange, degree = 1 =====================================
      // vertex
      inline static double phi1v(const DimVec<double>& lambda, int* vertices)
      {
        return lambda[vertices[0]];
      }

      // ====== Bubble ===================================================
      // 1d
      inline static double phi2c(const DimVec<double>& lambda, int* vertices)
      {
        return (4.0 * lambda[vertices[0]] * lambda[vertices[1]]);
      }

      // 2d
      inline static double phi3c(const DimVec<double>& lambda, int* vertices)
      {
        return 27.0 * lambda[vertices[0]] * lambda[vertices[1]] * lambda[vertices[2]];
      }

      // 3d
      inline static double phi4c(const DimVec<double>& lambda, int* vertices)
      {
        return 256.0 * lambda[vertices[0]] * lambda[vertices[1]] *
               lambda[vertices[2]] * lambda[vertices[3]];
      }
    };

    /// AbstractFunction which implements gradients of Lagrange/Bubble basis functions.
    /// See \ref Phi
    class GrdPhi : public GrdBasFctType
    {
    public:
      GrdPhi(Bubble* owner, GeoIndex position, int positionIndex, int nodeIndex);

      virtual ~GrdPhi();
    private:
      int* vertices;

      void (*func)(const DimVec<double>& lambda,
                   int* vertices_,
                   mtl::dense_vector<double>& result);

      inline void operator()(const DimVec<double>& lambda,
                             mtl::dense_vector<double>& result) const override
      {
        func(lambda, vertices, result);
      }

      // ====== Lagrange1 ================================================
      // vertex
      inline static void grdPhi1v(const DimVec<double>&,
                                  int* vertices,
                                  mtl::dense_vector<double>& result)
      {
        result = 0.0;
        result[vertices[0]] = 1.0;
      }

      // ======= Bubble ==================================================
      inline static void grdPhi2c(const DimVec<double>& lambda,
                                  int* vertices,
                                  mtl::dense_vector<double>& result)
      {
        result = 0.0;
        result[vertices[0]] = 4.0 * lambda[vertices[1]];
        result[vertices[1]] = 4.0 * lambda[vertices[0]];
      }

      inline static void grdPhi3c(const DimVec<double>& lambda,
                                  int* vertices,
                                  mtl::dense_vector<double>& result)
      {
        result = 0.0;
        result[vertices[0]] = 27.0 * lambda[vertices[1]] * lambda[vertices[2]];
        result[vertices[1]] = 27.0 * lambda[vertices[0]] * lambda[vertices[2]];
        result[vertices[2]] = 27.0 * lambda[vertices[0]] * lambda[vertices[1]];
      }

      inline static void grdPhi4c(const DimVec<double>& lambda,
                                  int* vertices,
                                  mtl::dense_vector<double>& result)
      {
        result = 0.0;
        result[0] =
          256.0 * lambda[vertices[1]] * lambda[vertices[2]] * lambda[vertices[3]];
        result[1] =
          256.0 * lambda[vertices[0]] * lambda[vertices[2]] * lambda[vertices[3]];
        result[2] =
          256.0 * lambda[vertices[0]] * lambda[vertices[1]] * lambda[vertices[3]];
        result[3] =
          256.0 * lambda[vertices[0]] * lambda[vertices[1]] * lambda[vertices[2]];
      }
    };

    /// AbstractFunction which implements second derivatives of Lagrange/Bubble basis
    /// functions. See \ref Phi
    class D2Phi : public D2BasFctType
    {
    public:
      D2Phi(Bubble* owner, GeoIndex position, int positionIndex, int nodeIndex);

      virtual ~D2Phi();

    private:
      int* vertices;

      void (*func)(const DimVec<double>& lambda, int* vertices_, DimMat<double>& result);

      inline void operator()(const DimVec<double>& lambda, DimMat<double>& result) const override
      {
        return func(lambda, vertices, result);
      }

      // ===== Lagrange1 ================================================
      // vertex
      inline static void D2Phi1v(const DimVec<double>&, int*, DimMat<double>& result)
      {
        result.set(0.0);
      }

      // ===== Bubble ===================================================
      inline static void D2Phi2c(const DimVec<double>&, int* vertices,
                                 DimMat<double>& result)
      {
        result.set(0.0);
        result[vertices[0]][vertices[1]] = 4.0;
        result[vertices[1]][vertices[0]] = 4.0;
      }

      inline static void D2Phi3c(const DimVec<double>& lambda, int* vertices,
                                 DimMat<double>& result)
      {
        result.set(0.0);
        result[vertices[0]][vertices[1]] =
          result[vertices[1]][vertices[0]] = 27.0 * lambda[vertices[2]];
        result[vertices[0]][vertices[2]] =
          result[vertices[2]][vertices[0]] = 27.0 * lambda[vertices[1]];
        result[vertices[1]][vertices[2]] =
          result[vertices[2]][vertices[1]] = 27.0 * lambda[vertices[0]];
      }

      inline static void D2Phi4c(const DimVec<double>& lambda, int* vertices,
                                 DimMat<double>& result)
      {
        result.set(0.0);
        result[vertices[0]][vertices[1]] =
          result[vertices[1]][vertices[0]] =
            256.0 * lambda[vertices[2]] * lambda[vertices[3]];
        result[vertices[0]][vertices[2]] =
          result[vertices[2]][vertices[0]] =
            256.0 * lambda[vertices[1]] * lambda[vertices[3]];
        result[vertices[0]][vertices[3]] =
          result[vertices[3]][vertices[0]] =
            256.0 * lambda[vertices[1]] * lambda[vertices[2]];
        result[vertices[1]][vertices[2]] =
          result[vertices[2]][vertices[1]] =
            256.0 * lambda[vertices[0]] * lambda[vertices[3]];
        result[vertices[1]][vertices[3]] =
          result[vertices[3]][vertices[1]] =
            256.0 * lambda[vertices[0]] * lambda[vertices[2]];
        result[vertices[2]][vertices[3]] =
          result[vertices[3]][vertices[2]] =
            256.0 * lambda[vertices[0]] * lambda[vertices[1]];
      }
    };
  };
}

#endif // AMDIS_Bubble_H


text:
// Software License for MTL
//
// Copyright (c) 2007 The Trustees of Indiana University.
//               2008 Dresden University of Technology and the Trustees of Indiana University.
//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.
// All rights reserved.
// Authors: Peter Gottschling and Andrew Lumsdaine
//
// This file is part of the Matrix Template Library
//
// See also license.mtl.txt in the distribution.

#include <iostream>
#include <typeinfo>

#include <boost/type_traits/is_same.hpp>
#include <boost/numeric/mtl/mtl.hpp>

int main(int, char**)
{
    using namespace mtl;
    using mtl::io::tout;

#if defined(MTL_WITH_VARIADIC_TEMPLATE) && defined(MTL_WITH_STATICASSERT) && defined(MTL_WITH_TEMPLATE_ALIAS)

    vector<double> v1;

    tout << "Type of v1 is " << typeid(v1).name() << '\n';
    static_assert(!traits::is_row_major<decltype(v1)>::value, "Vector must be column-major!");

    vector<double, column_major> v2;

    tout << "Type of v2 is " << typeid(v2).name() << '\n';
    static_assert(!traits::is_row_major<decltype(v2)>::value, "Vector must be column-major!");

    vector<double, row_major> v3;

    tout << "Type of v3 is " << typeid(v3).name() << '\n';
    static_assert(traits::is_row_major<decltype(v3)>::value, "Vector must be row-major!");

    vector<double, as_size_type<unsigned> > v4;

    tout << "Type of v4 is " << typeid(v4).name() << '\n';
    static_assert(boost::is_same<mtl::Collection<decltype(v4)>::size_type, unsigned>::value,
		  "Size type must be unsigned!");

    vector<double, dim<3> > v5;

    tout << "Type of v5 is " << typeid(v5).name() << '\n';
    static_assert(traits::is_static<decltype(v5)>::value, "Vector must have static size!");

    vector<double, sparse> v6;

    tout << "Type of v6 is " << typeid(v6).name() << '\n';
    static_assert(traits::is_sparse<decltype(v6)>::value, "Vector must be sparse!");

#else
    tout << "Test deactivated due to missing C++11 features.\n";
#endif

    return 0;
}

ext: cpp


text:
// This is an independent project of an individual developer. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
#include "str_utils.h"

#include <cstring>
#include <cctype>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <optional>

#ifdef __BCPLUSPLUS__
#include <ctype.h>
#else
  #ifdef USE_BOOST
  #include <boost/algorithm/string.hpp>
  #endif
#endif // NEW_COMPILER

using namespace std;

std::string trim(const std::string& s)
{
    auto b_it = s.begin();
    auto e_it = s.end();
    // find new first position in string
    for (;b_it < s.end() && *b_it == ' '; ++b_it) {}
    if (b_it == e_it) return "";
    // find new last position in string
    for (e_it = s.end()-1; e_it >= b_it; --e_it) {
        if (*e_it != ' ' && *e_it != '\n' && *e_it != '\r') {
            break;
        }
    }
    e_it = e_it + 1;
    // return trimmed string
    return string(b_it, e_it);
}

std::string trim_right(const std::string& s) {
    auto b_it = s.begin();
    auto e_it = s.end();
    if (b_it == e_it) return "";
    // find new last position in string
    for (e_it = s.end()-1; e_it >= b_it; --e_it) {
        if (*e_it != ' ' && *e_it != '\n' && *e_it != '\r') {
            break;
        }
    }
    e_it = e_it + 1;
    // return trimmed string
    return string(b_it, e_it);
}

std::string_view strip(std::string_view line) {
    while (!line.empty() && isspace(line.front())) {
        line.remove_prefix(1);
    }
    while (!line.empty() && isspace(line.back())) {
        line.remove_suffix(1);
    }
    return line;
}

void removeblanks(char* str)
{
  int n = int(strlen(str)) - 1;
  for(int i = n; i >= 0; --i)
    if(str[i] != ' ') {
      str[i+1] = 0;
      return;
    }
  str[0] = 0;
}

//std::string toLower(std::string s)
//{
//    for (size_t i = 0; i < s.size(); ++i) {
//        s[i] = tolower(s[i]);
//    }
//    return s;
//}

std::string str_tolower(std::string s) {
    std::transform(s.begin(), s.end(), s.begin(),
                // [](char c){ return std::tolower(c); }          // wrong
                   [](unsigned char c){ return std::tolower(c); } // correct
                  );
    return s;
}

std::string str_toupper(std::string s) {
    std::transform(s.begin(), s.end(), s.begin(),
                   [](unsigned char c){ return std::toupper(c); }
                  );
    return s;
}

bool startWith(const char* source, const char* signature)
{
  int n = int(strlen(signature));
  int i = 0;
  for(i = 0; i < n; i++)
    if(source[i] != signature[i]) break;
  return i == n;
}

bool startWith(const std::string& source, const std::string& signature) {
    if (signature.size() > source.size()) return false;
    return source.compare(0, signature.size(), signature) == 0;
}

int strToIntDef(const std::string& str, int defValue){
    try {
        int res = stol(str);
        return res;
    } catch (std::invalid_argument&) {
        return defValue;
    }
}

double strToFloatDef(const std::string& str, double defValue) {
    try {
        double res = stod(str);
        return res;
    } catch (std::invalid_argument&) {
        return defValue;
    }
}

bool tryStrToInt(const std::string& str, int& value) {
    try {
        value = stol(str);
        return true;
    } catch (std::invalid_argument&) {
        return false;
    }
}

bool tryStrToFloat(const std::string& str, double& value) {
    try {
        value = stod(str);
        return true;
    } catch (std::invalid_argument&) {
        return false;
    }
}

std::string intToStringF_need_to_test(int number, int digits) {
    stringstream ss;
    ss << setfill('0') << setw(digits);
    ss << number;
    return ss.str();
}

std::string intToStringF(int i, int width) {
    string res = to_string(i);
    if ((int)res.size() < width) {
        res = string(width - res.size(), '0') + res;
    }
    return res;
}

bool same_text(const std::string& s1, const std::string& s2)
{
#ifndef __BORLANDC__
    return str_tolower(s1) == str_tolower(s2);
#endif
}

void addSpacesToString(std::string& str, size_t new_length) {
  if (str.size() < new_length) {
    auto last_size = str.size();
    str.resize(new_length);
    for(size_t i = last_size; i < str.size(); i++) str[i] = ' ';
  }
}

std::vector<std::string> split_into_words(const std::string& str, char sep/*, bool is_grouped*/) {
    vector<string> result;
    string s = trim(str);
    auto str_begin = begin(s);
    const auto str_end = end(s);

    while (true) {
        auto it = find(str_begin, str_end, sep);
        result.emplace_back(str_begin, it);

        if (it == str_end) {
            break;
        } else {
            str_begin = next(it);
            while (str_begin != str_end && *str_begin == ' ') {
				++str_begin;
			}
			if (str_begin == str_end) {
                break;
			}
        }
    }
    return result;
}

std::pair<std::string_view, std::optional<std::string_view>> split_two_strict(std::string_view s, std::string_view delimiter) {
  const size_t pos = s.find(delimiter);
  if (pos == std::string_view::npos) {
    return {s, nullopt};
  } else {
    return {s.substr(0, pos), s.substr(pos + delimiter.length())};
  }
}

std::pair<std::string_view, std::string_view> split_two(std::string_view s, std::string_view delimiter) {
  const auto [lhs, rhs_opt] = split_two_strict(s, delimiter);
  return {lhs, rhs_opt.value_or("")};
}

std::string_view readToken(std::string_view& s, std::string_view delimiter) {
  const auto [lhs, rhs] = split_two(s, delimiter);
  s = rhs;
  return lhs;
}

std::string join_strings(const std::vector<std::string>& strings, char sep) {
    if (strings.empty()) return "";
    // calc final string size
    size_t full_size = accumulate(begin(strings), end(strings), size_t{0},
                              [](size_t b, const string& s) {return b + s.size();});
    full_size += strings.size() - 1;
    // make string
    string res;
    res.reserve(full_size);
    bool is_first = true;
    for (const auto& s : strings) {
        if (is_first) {
            is_first = false;
        } else {
            res += sep;
        }
        res += s;
    }
    return res;
}

std::string join_strings(const std::vector<std::string>& strings, std::string_view sep) {
    if (strings.empty()) return "";
    // calc final string size
    size_t full_size = accumulate(begin(strings), end(strings), 0u,
                                  [](size_t b, const string& s) {return b + s.size();});
    full_size += (strings.size() - 1) * sep.size();
    // make string
    string res;
    res.reserve(full_size);
    bool is_first = true;
    for (const auto& s : strings) {
        if (is_first) {
            is_first = false;
        } else {
            res += sep;
        }
        res += s;
    }
    return res;
}

void print_strings(std::ostream& out, const std::vector<std::string>& strings, char sep, char end_symbol) {
    bool is_first = true;
    for (const auto& s : strings) {
        if (is_first) {
            is_first = false;
        } else {
            out << sep;
        }
        out << s;
    }
    out << end_symbol;
}

//int word_count(const string& s, const set<char>& delimeters)
//{
//    size_t i(0);
//    int res(0);
//    while (i < s.size()) {
//        // delimeters before word
//        while (i < s.size() && delimeters.find(s[i]) != delimeters.end()) ++i;
//        // word
//        if (i < s.size()) ++res;
//        // word symbols
//        while (i < s.size() && delimeters.find(s[i]) == delimeters.end()) ++i;
//    }
//    return res;
//}
//
//int word_position(int n, const string& s, const set<char>& delimeters)
//{
//    int cnt(0);
//    size_t i(0);
//    while (i < s.size() && cnt != n) {
//        // skip over delimeters
//        while (i < s.size() && delimeters.find(s[i]) != delimeters.end()) ++i;
//        // if we're not beyond end of s, we're at the start of a word
//        if (i < s.size()) ++cnt;
//        // if not finished, find the end of the current word
//        if (cnt != n) {
//            while (i < s.size() && delimeters.find(s[i]) == delimeters.end()) ++i;
//        } else {
//            return i;
//        }
//    }
//    return -1;
//}
//
//std::string extract_word(int wordNum, const std::string& s, const std::set<char>& delimeters)
//{
//    int i = word_position(wordNum, s, delimeters);
//    unsigned int len(i);
//    if (i != -1) {
//        // find the end of current word
//        while (len < s.size() && delimeters.find(s[len]) == delimeters.end())
//            ++len;
//        return s.substr(i, len-i);
//    }
//    return "";
//}
//
//std::string extract_word(int wordNum, const std::string& s,
//                         const std::string& delimeters)
//{
//    #ifdef USE_BOOST
//    using namespace boost;
//    vector<string> words;
//    split(words, s, is_any_of(delimeters), token_compress_on);
//    if (static_cast<int>(words.size()) > wordNum)
//        return words[wordNum];
//    else
//    #endif // USE_BOOST
//        return "";
//}

max_stars_repo_name: gwlsrm/Units

max_issues_repo_name: gwlsrm/Units

max_forks_repo_name: gwlsrm/Units


text:
//  Copyright (c) 2001-2008 Hartmut Kaiser
//  Copyright (c) 2001-2007 Joel de Guzman
//
//  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)

#if !defined(SPIRIT_KARMA_ALTERNATIVE_MAR_01_2007_1117AM)
#define SPIRIT_KARMA_ALTERNATIVE_MAR_01_2007_1117AM

#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once      // MS compatible compilers support #pragma once
#endif

#include <boost/spirit/home/karma/operator/detail/alternative.hpp>
#include <boost/spirit/home/support/attribute_transform.hpp>
#include <boost/spirit/home/support/as_variant.hpp>
#include <boost/spirit/home/support/detail/what_function.hpp>
#include <boost/spirit/home/support/algorithm/any.hpp>
#include <boost/spirit/home/support/unused.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <boost/fusion/include/mpl.hpp>
#include <boost/fusion/include/transform.hpp>
#include <boost/variant.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/end.hpp>
#include <boost/mpl/insert_range.hpp>
#include <boost/mpl/transform_view.hpp>

namespace boost { namespace spirit { namespace karma
{
    struct alternative
    {
        template <typename T>
        struct transform_child : mpl::identity<T> {};

        template <typename All, typename Filtered>
        struct build_container
        {
            // Ok, now make a variant over the attribute_sequence. It's
            // a pity that make_variant_over does not support forward MPL
            // sequences. We use our own conversion metaprogram (as_variant).
            typedef typename
                as_variant<Filtered>::type
            type;
        };

        template <typename Component, typename Context, typename Iterator>
        struct attribute :
            build_fusion_sequence<alternative, Component, Iterator, Context>
        {
        };

        template <typename Component, typename OutputIterator,
            typename Context, typename Delimiter, typename Parameter>
        static bool
        generate(Component const& component, OutputIterator& sink,
            Context& ctx, Delimiter const& d, Parameter const& param)
        {
            typedef detail::alternative_generate_functor<
                OutputIterator, Context, Delimiter, Parameter
            > functor;

            // f return true if *any* of the parser succeeds
            functor f (sink, ctx, d, param);
            return fusion::any(component.elements, f);
        }

        template <typename Component>
        static std::string what(Component const& component)
        {
            std::string result = "alternatives[";
            fusion::for_each(component.elements,
                spirit::detail::what_function(result));
            result += "]";
            return result;
        }
    };
}}}

#endif

ext: hpp


text:
// Copyright 2020 Erik Teichmann <kontakt.teichmann@gmail.com>

#ifndef INCLUDE_SAM_ANALYSIS_SAVITZKY_GOLAY_HPP_
#define INCLUDE_SAM_ANALYSIS_SAVITZKY_GOLAY_HPP_

#include <Eigen/Dense>

#include <stdexcept>
#include <vector>

namespace sam {

template<typename state_type = std::vector<double>>
std::vector<std::vector<double>> SavitzkyGolayFilter(double stepsize,
                                                     state_type state,
                                                     unsigned int n_points,
                                                     unsigned int derivatives);

// Implementation

Eigen::MatrixXd CalculateConvolutionCoefficients(unsigned int n_points,
                                                 unsigned int derivatives) {
  unsigned int n_left = n_points/2;
  Eigen::MatrixXd J(n_points, derivatives);
  for (unsigned int i = 0; i < n_points; ++i) {
    double z = static_cast<int>(i) - static_cast<int>(n_left);
    for (unsigned int j = 0; j < derivatives; ++j) {
      J(i, j) = pow(z, j);
    }
  }
  return (J.transpose()*J).inverse()*J.transpose();
}

int factorial(unsigned int n) {
  int factorial = 1.;
  for (unsigned int i = 1; i < n+1; ++i) factorial *= i;
  return factorial;
}

template<typename state_type>
std::vector<std::vector<double>> SavitzkyGolayFilter(double stepsize,
                                                     state_type state,
                                                     unsigned int n_points,
                                                     unsigned int derivatives) {
  if (n_points%2 == 0) {
    throw std::invalid_argument("Number of points for Savitzky-Golay Filter "
        "has to be uneven.");
  }
  if (n_points < derivatives) {
    throw std::invalid_argument("Number of points has to be bigger than "
        "number of derivatives in Savitzky-Golay Filter.");
  }
  Eigen::MatrixXd coefficients = CalculateConvolutionCoefficients(n_points,
      derivatives);
  std::vector<std::vector<double>> a(derivatives);
  for (size_t point = n_points/2; point < state.size() - n_points/2; ++point) {
    for (size_t deriv = 0; deriv < derivatives; ++deriv) {
      double sum = 0.;
      for (int i = -static_cast<int>(n_points)/2;
           i <= static_cast<int>(n_points)/2; ++i) {
        sum += coefficients(deriv, i + n_points/2)*state[point + i];
      }
      sum *= factorial(deriv)/pow(stepsize, deriv);
      a[deriv].push_back(sum);
    }
  }
  return a;
}

}  // namespace sam

#endif  // INCLUDE_SAM_ANALYSIS_SAVITZKY_GOLAY_HPP_

max_stars_repo_name: boundter/SAM

max_issues_repo_name: boundter/SAM

max_forks_repo_name: boundter/SAM


text:
#include <boost/filesystem.hpp>
#include <sstream>
#include <yaml-cpp/yaml.h>

#include "core/Params.h"
#include "core/StatusPrinter.h"

Params::Params() {
}

Params::~Params() {
  clear();
}

Params::ParamValue& Params::getValueContainer(const std::string& key) const {
  ParamValue* valuePtr = NULL;

  ParamValueMap::const_iterator iter = params.find(key);

  if (iter != params.end()) {
    valuePtr = iter->second;
  }

  ABORT_IF(valuePtr == NULL, "Parameter '%s' is required, but its value "
           "has not been specified.", key.c_str());

  return *valuePtr;
}

bool Params::contains(const std::string& key) const {
  ParamValueMap::const_iterator mapIter = params.find(key);

  return mapIter != params.end();
}

bool Params::containsv(const char* format, ...) const {
  va_list ap;
  va_start(ap, format);
  char* key;
  ABORT_IF(vasprintf(&key, format, ap) == -1, "vasprintf() failed while "
           "running Params::containsv");
  va_end(ap);

  bool containsKey = contains(key);

  free(key);

  return containsKey;
}

void Params::parseFile(const char* filename) {
  TRITONSORT_ASSERT(fileExists(filename), "Can't find params file '%s'", filename);

  YAML::Node doc = YAML::LoadFile(filename);

  // Iterate over the resulting YAML node, adding all parameters to the
  // internal parameter map
  parseYAMLNode(doc);
}

void Params::parseYAMLNode(const YAML::Node& node) {
  std::list<std::string> keyStack;
  parseYAMLNode(node, keyStack);

  TRITONSORT_ASSERT(keyStack.empty());
}

void Params::parseYAMLNode(
  const YAML::Node& node, std::list<std::string>& keyStack) {

  // Since we may have arbitrarily nested key/value pairs
  std::stack<std::string> keyChunks;

  std::ostringstream keyConcatStream;

  // Join all previous parts of the key with '.' to form a "prefix" for all
  // keys under this node
  for (std::list<std::string>::iterator keyStackIter = keyStack.begin();
       keyStackIter != keyStack.end(); keyStackIter++) {
    keyConcatStream << *keyStackIter << '.';
  }

  std::string keyPrefix(keyConcatStream.str());

  for (YAML::const_iterator iter = node.begin(); iter != node.end(); iter++) {
    const YAML::Node& key = iter->first;
    const YAML::Node& value = iter->second;

    ABORT_IF(key.Type() != YAML::NodeType::Scalar,
             "YAML config files are expected to have scalar keys");

    std::string keyStr = key.as<std::string>();
    std::string valueStr;

    switch (value.Type()) {
    case YAML::NodeType::Null:
      ABORT("Params doesn't currently support null values (key %s)",
            keyStr.c_str());
      break;
    case YAML::NodeType::Scalar:
      valueStr = value.as<std::string>();

      if (keyPrefix.size() > 0) {
        add(keyPrefix + keyStr, valueStr);
      } else {
        add(keyStr, valueStr);
      }

      break;
    case YAML::NodeType::Sequence:
      ABORT("Params doesn't currently support null values");
      break;
    case YAML::NodeType::Map:
      // Append the current key to the stack and recursively evaluate the map
      keyStack.push_back(keyStr);
      parseYAMLNode(value, keyStack);

      // Done dealing with the map, so pop the current key from the stack
      keyStack.pop_back();
      break;
    case YAML::NodeType::Undefined:
      ABORT("Undefined node type");
      break;
    }
  }
}

void Params::clear() {
  for (ParamValueMap::iterator iter = params.begin(); iter != params.end();
       iter++) {
    delete iter->second;
  }

  params.clear();
}

void Params::parseCommandLineArguments(int argc, char** argv) {
  int startIndex = 1;

  if ((argc - startIndex) % 2 != 0) {
    std::cerr << "Invalid argument structure (expecting "
              << "'program-name [params file] -param1 val1 "
              << "-param2 val2 ...')" << std::endl;
    exit(3);
  }

  int i = argc - 1;
  char* key = NULL;
  char* value = NULL;

  while (i > 1) {
    key = argv[i - 1];
    value = argv[i];

    if (key[0] == '-') {
      // Strip the leading '-' from the key
      std::string keyStr(key, 1, strlen(key) - 1);

      // If the value starts with a '-', check to see if it's a number
      if (value[0] == '-') {
        try {
          double valueAsDouble = boost::lexical_cast<double>(value);
          // Add value here to avoid unused variable warning
          add(keyStr, valueAsDouble);
        } catch (boost::bad_lexical_cast& exception) {
          // This value is probably the key for some other parameter
          ABORT("Possibly malformed parameter list; non-numeric value '%s' for "
                "key '%s' starts with a '-'", value, key);
        }
      } else {
        std::string valStr(value);
        add(keyStr, valStr);
      }

      i -= 2;
    } else {
      ABORT("Malformed parameter list; expect all keys to begin with '-', but "
            "key '%s' does not", key);
    }
  }
}

void Params::parseCommandLine(int argc, char* argv[]) {
  if (argc == 2) {
    parseFile(argv[1]);
  } else if (argc >= 2) {
    parseCommandLineArguments(argc, argv);

    // Load default config file if available.
    if (contains("DEFAULT_CONFIG")) {
      std::ostringstream oss;
      oss << "Reading from default config file "
          << get<std::string>("DEFAULT_CONFIG");

      StatusPrinter::add(oss.str());
      parseFile(get<std::string>("DEFAULT_CONFIG").c_str());
    }

    // Load application config file if available.
    if (contains("CONFIG")) {
      std::ostringstream oss;
      oss << "Reading from config file "
          << get<std::string>("CONFIG");

      StatusPrinter::add(oss.str());
      parseFile(get<std::string>("CONFIG").c_str());
    }

    // This is a bit inelegant, but is necessary to override any config
    // file options with the command line.
    parseCommandLineArguments(argc, argv);
  }
}

void Params::dump(const std::string& filename) {
  std::ofstream ofs;
  ofs.open(filename.c_str());

  for (ParamValueMap::iterator iter = params.begin(); iter != params.end();
       iter++) {
    ofs << iter->first << ": ";
    iter->second->print(ofs);
    ofs << std::endl;
  }

  ofs.close();

  ABORT_IF(ofs.fail(), "Writing to params file %s failed", filename.c_str());
}

Params::ParamValue::ParamValue(const std::string& value)
  : strValue(value) {
}

Params::ParamValue::ParamValue(bool value) {
  setStringValue<bool>(value);
}

Params::ParamValue::ParamValue(int32_t value) {
  setStringValue<int32_t>(value);
}

Params::ParamValue::ParamValue(uint32_t value) {
  setStringValue<uint32_t>(value);
}

Params::ParamValue::ParamValue(int64_t value) {
  setStringValue<int64_t>(value);
}

Params::ParamValue::ParamValue(uint64_t value) {
  setStringValue<uint64_t>(value);
}

Params::ParamValue::ParamValue(double value) {
  setStringValue<double>(value);
}

Params::ParamValue::~ParamValue() {
}

bool Params::ParamValue::get(bool& value) const {
  if (strValue == "true" || strValue == "1") {
    value = true;
  } else if (strValue == "false" || strValue == "0") {
    value = false;
  } else {
    return false;
  }

  return true;
}

bool Params::ParamValue::get(int32_t& value) const {
  return getNumericValue<int32_t>(value);
}

bool Params::ParamValue::get(uint32_t& value) const {
  return getNumericValue<uint32_t>(value);
}

bool Params::ParamValue::get(int64_t& value) const {
  return getNumericValue<int64_t>(value);
}

bool Params::ParamValue::get(uint64_t& value) const {
  return getNumericValue<uint64_t>(value);
}

bool Params::ParamValue::get(double& value) const {
  return getNumericValue<double>(value);
}

bool Params::ParamValue::get(std::string& value) const {
  value.assign(strValue);
  return true;
}

bool Params::ParamValue::isNumeric() const {
  double doubleValue = 0;
  int64_t signedValue = 0;
  uint64_t unsignedValue = 0;

  return get(doubleValue) || get(unsignedValue) || get(signedValue);
}

void Params::ParamValue::print(std::ostream& stream) const {
  if (isNumeric()) {
    stream << strValue;
  } else {
    stream << "\"" << strValue << "\"";
  }
}

ext: cc


text:
// Copyright 2020-2022 The Defold Foundation
// Copyright 2014-2020 King
// Copyright 2009-2014 Ragnar Svensson, Christian Murray
// Licensed under the Defold License version 1.0 (the "License"); you may not use
// this file except in compliance with the License.
//
// You may obtain a copy of the License, together with FAQs at
// https://www.defold.com/license
//
// 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 <float.h>
#include <stdio.h>
#include <assert.h>

#include <dlib/hash.h>
#include <dlib/log.h>
#include <dlib/math.h>
#include <particle/particle.h>
#include <graphics/graphics.h>
#include <render/render.h>

#include "../gamesys.h"
#include <gamesys/gamesys_ddf.h>
#include "../gamesys_private.h"

#include "resources/res_particlefx.h"

#include "script_particlefx.h"

extern "C"
{
#include <lua/lauxlib.h>
#include <lua/lualib.h>
}

namespace dmGameSystem
{
    /*# Particle effects API documentation
     *
     * Functions for controlling particle effect component playback and
     * shader constants.
     *
     * @document
     * @name Particle effects
     * @namespace particlefx
     */

    /*# sleeping state
     * The emitter does not have any living particles and will not spawn any particles in this state.
     *
     * @name particlefx.EMITTER_STATE_SLEEPING
     * @variable
     */

    /*# prespawn state
     * The emitter will be in this state when it has been started but before spawning any particles. Normally the emitter is in this state for a short time, depending on if a start delay has been set for this emitter or not.
     *
     * @name particlefx.EMITTER_STATE_PRESPAWN
     * @variable
     */

    /*# spawning state
     * The emitter is spawning particles.
     *
     * @name particlefx.EMITTER_STATE_SPAWNING
     * @variable
     */

    /*# postspawn state
     * The emitter is not spawning any particles, but has particles that are still alive.
     *
     * @name particlefx.EMITTER_STATE_POSTSPAWN
     * @variable
     */

    void EmitterStateChangedCallback(uint32_t num_awake_emitters, dmhash_t emitter_id, dmParticle::EmitterState emitter_state, void* user_data)
    {

        EmitterStateChangedScriptData data = *(EmitterStateChangedScriptData*)(user_data);

        if (!dmScript::IsCallbackValid(data.m_CallbackInfo))
        {
            return;
        }

        lua_State* L = dmScript::GetCallbackLuaContext(data.m_CallbackInfo);

        DM_LUA_STACK_CHECK(L, 0);

        if (!dmScript::SetupCallback(data.m_CallbackInfo))
        {
            dmScript::DestroyCallback(data.m_CallbackInfo);
            data.m_CallbackInfo = 0x0;
            return;
        }

        dmScript::PushHash(L, data.m_ComponentId);
        dmScript::PushHash(L, emitter_id);
        lua_pushnumber(L, emitter_state);
        dmScript::PCall(L, 4, 0);

        dmScript::TeardownCallback(data.m_CallbackInfo);

        // Release the lua ref if the last emitter belonging to this particlefx har gone to sleep.
        if(num_awake_emitters == 0 && emitter_state == dmParticle::EMITTER_STATE_SLEEPING)
        {
            dmScript::DestroyCallback(data.m_CallbackInfo);
            data.m_CallbackInfo = 0x0;
        }
    }

    /*# start playing a particle FX
     * Starts playing a particle FX component.
     * Particle FX started this way need to be manually stopped through `particlefx.stop()`.
     * Which particle FX to play is identified by the URL.
     *
     * [icon:attention] A particle FX will continue to emit particles even if the game object the particle FX component belonged to is deleted. You can call `particlefx.stop()` to stop it from emitting more particles.
     *
     * @name particlefx.play
     * @param url [type:string|hash|url] the particle fx that should start playing.
     * @param [emitter_state_function] [type:function(self, id, emitter, state)] optional callback function that will be called when an emitter attached to this particlefx changes state.
     *
     * `self`
     * : [type:object] The current object
     *
     * `id`
     * : [type:hash] The id of the particle fx component
     *
     * `emitter`
     * : [type:hash] The id of the emitter
     *
     * `state`
     * : [type:constant] the new state of the emitter:
     *
     * - `particlefx.EMITTER_STATE_SLEEPING`
     * - `particlefx.EMITTER_STATE_PRESPAWN`
     * - `particlefx.EMITTER_STATE_SPAWNING`
     * - `particlefx.EMITTER_STATE_POSTSPAWN`
     *
     * @examples
     *
     * How to play a particle fx when a game object is created.
     * The callback receives the hash of the path to the particlefx, the hash of the id
     * of the emitter, and the new state of the emitter as particlefx.EMITTER_STATE_<STATE>.
     *
     * ```lua
     * local function emitter_state_change(self, id, emitter, state)
     *   if emitter == hash("exhaust") and state == particlefx.EMITTER_STATE_POSTSPAWN then
     *     -- exhaust is done spawning particles...
     *   end
     * end
     *
     * function init(self)
     *     particlefx.play("#particlefx", emitter_state_change)
     * end
     * ```
     */
    int ParticleFX_Play(lua_State* L)
    {
        dmGameObject::HInstance instance = CheckGoInstance(L);

        int top = lua_gettop(L);

        if (top < 1)
        {
            return luaL_error(L, "particlefx.play expects atleast URL as parameter");
        }

        DM_LUA_STACK_CHECK(L, 0);

        EmitterStateChangedScriptData data;
        char msg_buf[sizeof(dmParticle::EmitterStateChanged) + sizeof(EmitterStateChangedScriptData)];
        uint32_t msg_size = 0;

        dmMessage::URL receiver;
        dmMessage::URL sender;
        dmScript::ResolveURL(L, 1, &receiver, &sender);

        if (top > 1 && !lua_isnil(L, 2))
        {
            data.m_CallbackInfo = dmScript::CreateCallback(dmScript::GetMainThread(L), -1);
            if (data.m_CallbackInfo == 0x0)
            {
                return DM_LUA_ERROR("particlefx.play failed to create callback");
            }

            // path-only url (e.g. "/level/particlefx") has empty fragment, and relative path (e.g. "#particlefx") has non-empty fragment.
            if(receiver.m_Fragment == 0)
            {
                data.m_ComponentId = receiver.m_Path;
            }
            else
            {
                data.m_ComponentId = receiver.m_Fragment;
            }

            dmParticle::EmitterStateChanged fun;
            fun = EmitterStateChangedCallback;

            msg_size = sizeof(dmParticle::EmitterStateChanged) + sizeof(EmitterStateChangedScriptData);

            memcpy(msg_buf, &fun, sizeof(dmParticle::EmitterStateChanged));
            memcpy(msg_buf + sizeof(dmParticle::EmitterStateChanged), &data, sizeof(EmitterStateChangedScriptData));
        }

        dmMessage::Post(
            &sender,
            &receiver,
            dmGameSystemDDF::PlayParticleFX::m_DDFDescriptor->m_NameHash,
            (uintptr_t)instance,
            (uintptr_t)dmGameSystemDDF::PlayParticleFX::m_DDFDescriptor,
            (void*)msg_buf,
            msg_size,
            0);

        return 0;
    }

    /*# stop playing a particle fx
     * Stops a particle FX component from playing.
     * Stopping a particle FX does not remove already spawned particles.
     * Which particle FX to stop is identified by the URL.
     *
     * @name particlefx.stop
     * @param url [type:string|hash|url] the particle fx that should stop playing
     * @examples
     *
     * How to stop a particle fx when a game object is deleted:
     *
     * ```lua
     * function final(self)
     *     particlefx.stop("#particlefx")
     * end
     * ```
     */
    int ParticleFX_Stop(lua_State* L)
    {
        int top = lua_gettop(L);

        dmGameObject::HInstance instance = CheckGoInstance(L);

        if (top != 1)
        {
            return luaL_error(L, "particlefx.stop only takes a URL as parameter");
        }
        dmGameSystemDDF::StopParticleFX msg;
        uint32_t msg_size = sizeof(dmGameSystemDDF::StopParticleFX);

        dmMessage::URL receiver;
        dmMessage::URL sender;
        dmScript::ResolveURL(L, 1, &receiver, &sender);

        dmMessage::Post(&sender, &receiver, dmGameSystemDDF::StopParticleFX::m_DDFDescriptor->m_NameHash, (uintptr_t)instance, (uintptr_t)dmGameSystemDDF::StopParticleFX::m_DDFDescriptor, (void*)&msg, msg_size, 0);
        assert(top == lua_gettop(L));
        return 0;
    }

    /*# set a shader constant for a particle FX component emitter
     * Sets a shader constant for a particle FX component emitter.
     * The constant must be defined in the material assigned to the emitter.
     * Setting a constant through this function will override the value set for that constant in the material.
     * The value will be overridden until particlefx.reset_constant is called.
     * Which particle FX to set a constant for is identified by the URL.
     *
     * @name particlefx.set_constant
     * @param url [type:string|hash|url] the particle FX that should have a constant set
     * @param emitter [type:string|hash] the id of the emitter
     * @param constant [type:string|hash] the name of the constant
     * @param value [type:vector4] the value of the constant
     * @examples
     *
     * The following examples assumes that the particle FX has id "particlefx", it
     * contains an emitter with the id "emitter" and that the default-material in builtins is used, which defines the constant "tint".
     * If you assign a custom material to the sprite, you can reset the constants defined there in the same manner.
     *
     * How to tint particles from an emitter red:
     *
     * ```lua
     * function init(self)
     *     particlefx.set_constant("#particlefx", "emitter", "tint", vmath.vector4(1, 0, 0, 1))
     * end
     * ```
     */
    int ParticleFX_SetConstant(lua_State* L)
    {
        int top = lua_gettop(L);

        dmGameObject::HInstance instance = CheckGoInstance(L);

        dmhash_t emitter_id = dmScript::CheckHashOrString(L, 2);
        dmhash_t name_hash = dmScript::CheckHashOrString(L, 3);
        Vectormath::Aos::Vector4* value = dmScript::CheckVector4(L, 4);

        dmGameSystemDDF::SetConstantParticleFX msg;
        msg.m_EmitterId = emitter_id;
        msg.m_NameHash = name_hash;
        msg.m_Value = *value;

        dmMessage::URL receiver;
        dmMessage::URL sender;
        dmScript::ResolveURL(L, 1, &receiver, &sender);

        dmMessage::Post(&sender, &receiver, dmGameSystemDDF::SetConstantParticleFX::m_DDFDescriptor->m_NameHash, (uintptr_t)instance, (uintptr_t)dmGameSystemDDF::SetConstantParticleFX::m_DDFDescriptor, &msg, sizeof(msg), 0);
        assert(top == lua_gettop(L));
        return 0;
    }

    /*# reset a shader constant for a particle FX component emitter
     * Resets a shader constant for a particle FX component emitter.
     * The constant must be defined in the material assigned to the emitter.
     * Resetting a constant through this function implies that the value defined in the material will be used.
     * Which particle FX to reset a constant for is identified by the URL.
     *
     * @name particlefx.reset_constant
     * @param url [type:string|hash|url] the particle FX that should have a constant reset
     * @param emitter [type:string|hash] the id of the emitter
     * @param constant [type:string|hash] the name of the constant
     * @examples
     *
     * The following examples assumes that the particle FX has id "particlefx", it
     * contains an emitter with the id "emitter" and that the default-material in builtins is used, which defines the constant "tint".
     * If you assign a custom material to the sprite, you can reset the constants defined there in the same manner.
     *
     * How to reset the tinting of particles from an emitter:
     *
     * ```lua
     * function init(self)
     *     particlefx.reset_constant("#particlefx", "emitter", "tint")
     * end
     * ```
     */
    int ParticleFX_ResetConstant(lua_State* L)
    {
        int top = lua_gettop(L);

        dmGameObject::HInstance instance = CheckGoInstance(L);
        dmhash_t emitter_id = dmScript::CheckHashOrString(L, 2);
        dmhash_t name_hash = dmScript::CheckHashOrString(L, 3);

        dmGameSystemDDF::ResetConstantParticleFX msg;
        msg.m_EmitterId = emitter_id;
        msg.m_NameHash = name_hash;

        dmMessage::URL receiver;
        dmMessage::URL sender;
        dmScript::ResolveURL(L, 1, &receiver, &sender);

        dmMessage::Post(&sender, &receiver, dmGameSystemDDF::ResetConstantParticleFX::m_DDFDescriptor->m_NameHash, (uintptr_t)instance, (uintptr_t)dmGameSystemDDF::ResetConstantParticleFX::m_DDFDescriptor, &msg, sizeof(msg), 0);
        assert(top == lua_gettop(L));
        return 0;
    }

    static const luaL_reg PARTICLEFX_FUNCTIONS[] =
    {
        {"play",            ParticleFX_Play},
        {"stop",            ParticleFX_Stop},
        {"set_constant",    ParticleFX_SetConstant},
        {"reset_constant",  ParticleFX_ResetConstant},
        {0, 0}
    };

    void ScriptParticleFXRegister(const ScriptLibContext& context)
    {
        lua_State* L = context.m_LuaState;
        int top = lua_gettop(L);
        luaL_register(L, "particlefx", PARTICLEFX_FUNCTIONS);

        #define SETCONSTANT(name, val) \
            lua_pushnumber(L, (lua_Number) val); \
            lua_setfield(L, -2, #name);\

        SETCONSTANT(EMITTER_STATE_SLEEPING, dmParticle::EMITTER_STATE_SLEEPING);
        SETCONSTANT(EMITTER_STATE_PRESPAWN, dmParticle::EMITTER_STATE_PRESPAWN);
        SETCONSTANT(EMITTER_STATE_SPAWNING, dmParticle::EMITTER_STATE_SPAWNING);
        SETCONSTANT(EMITTER_STATE_POSTSPAWN, dmParticle::EMITTER_STATE_POSTSPAWN);

        #undef SETCONSTANT

        // pop table "particle_fx"
        lua_pop(L, 1);
        assert(top == lua_gettop(L));
    }
}

max_stars_repo_name: cmarincia/defold

max_issues_repo_name: cmarincia/defold

max_forks_repo_name: cmarincia/defold


text:
#include <string>
#include <sstream>
#include <iostream>
#include "php.h"
#include "exception.h"
#include "datasource_cache.h"
#include <boost/foreach.hpp>
#include <mapnik/datasource_cache.hpp>

zend_class_entry *datasource_cache_ce;

// Class methods

PHP_METHOD(DatasourceCache, registerDatasources)
{
    zend_string *path;

    ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 1, 1)
        Z_PARAM_STR(path)
    ZEND_PARSE_PARAMETERS_END();

    std::string path_str(ZSTR_VAL(path), ZSTR_LEN(path));
    mapnik::datasource_cache::instance().register_datasources(path_str);

    RETURN_TRUE;
}

PHP_METHOD(DatasourceCache, getPluginNames)
{
    std::vector<std::string> all_plugin_names = mapnik::datasource_cache::instance().plugin_names();
    array_init(return_value);

    BOOST_FOREACH (std::string plugin, all_plugin_names) {
        add_next_index_string(return_value, plugin.c_str());
    }
}

// Reflection info

ZEND_BEGIN_ARG_INFO_EX(argInfo_datasourceCache_registerDatasources, ZEND_SEND_BY_VAL, ZEND_RETURN_VALUE, 1)
    ZEND_ARG_INFO(0, path)
ZEND_END_ARG_INFO()

// Register methods

zend_function_entry datasource_cache_methods[] = {
    PHP_ME(DatasourceCache, registerDatasources, argInfo_datasourceCache_registerDatasources, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
    PHP_ME(DatasourceCache, getPluginNames, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
    { NULL, NULL, NULL }
};

// Extension class initializer

void init_datasource_cache(INIT_FUNC_ARGS)
{
    zend_class_entry ce;
    INIT_NS_CLASS_ENTRY(ce, "Mapnik", "DatasourceCache", datasource_cache_methods);
    datasource_cache_ce = zend_register_internal_class(&ce TSRMLS_CC);
}


text:
#define BOOST_TEST_MODULE tempfile
#include <boost/test/unit_test.hpp>

#include <bunsan/tempfile.hpp>

#include <boost/assert.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>

BOOST_AUTO_TEST_SUITE(tempfile)

using bunsan::tempfile;
using boost::filesystem::path;

const path &getpath(const tempfile &tmp) { return tmp.path(); }

const path &getpath(const path &path_) { return path_; }

template <typename T>
bool exists(const T &file) {
  return boost::filesystem::exists(getpath(file));
}

template <typename T>
void touch(const T &file) {
  boost::filesystem::ofstream tmp(getpath(file));
  tmp.close();
  BOOST_REQUIRE(tmp);
  BOOST_REQUIRE(exists(file));
}

BOOST_AUTO_TEST_CASE(auto_remove) {
  boost::filesystem::path tmppath;
  {
    tempfile tmp = tempfile::regular_file_in_tempdir();
    tmppath = tmp.path();
    BOOST_CHECK(tmp.auto_remove());
    BOOST_CHECK(exists(tmp));
  }
  BOOST_CHECK(!exists(tmppath));
}

BOOST_AUTO_TEST_CASE(swap_) {
  boost::filesystem::path tmppath;
  tempfile tmp = tempfile::regular_file_in_tempdir();
  tmppath = tmp.path();
  tempfile tmp2;
  BOOST_CHECK(tmp.auto_remove());
  BOOST_CHECK(!tmp2.auto_remove());
  swap(tmp, tmp2);
  BOOST_CHECK(!tmp.auto_remove());
  BOOST_CHECK(tmp2.auto_remove());
  BOOST_CHECK(tmp2.path() == tmppath);
}

BOOST_AUTO_TEST_CASE(model) {
  tempfile tmp = tempfile::regular_file_in_tempdir("%%%%-%%%%-%%%%-%%%%.tgz");
  BOOST_CHECK_EQUAL(tmp.path().extension(), ".tgz");
}

BOOST_AUTO_TEST_SUITE(create)

BOOST_AUTO_TEST_CASE(regular_file_fail) {
  BOOST_CHECK_THROW((tempfile::regular_file_in_tempdir("no-percent-string"),
                     tempfile::regular_file_in_tempdir("no-percent-string")),
                    bunsan::unable_to_create_unique_temp_regular_file);
}

BOOST_AUTO_TEST_CASE(regular_file) {
  const tempfile tmp =
      tempfile::regular_file_in_tempdir("%%%%-%%%%-%%%%-%%%%.suff");
  BOOST_CHECK(boost::filesystem::is_regular_file(tmp.path()));
  BOOST_CHECK_EQUAL(tmp.path().extension(), ".suff");
}

BOOST_AUTO_TEST_CASE(directory_file_fail) {
  BOOST_CHECK_THROW((tempfile::directory_in_tempdir("no-percent-string"),
                     tempfile::directory_in_tempdir("no-percent-string")),
                    bunsan::unable_to_create_unique_temp_directory);
}

BOOST_AUTO_TEST_CASE(directory) {
  const tempfile tmp =
      tempfile::directory_in_tempdir("%%%%%-%%%%%-%%%%-%%%%.suff");
  BOOST_CHECK(boost::filesystem::is_directory(tmp.path()));
  BOOST_CHECK_EQUAL(tmp.path().extension(), ".suff");
}

BOOST_AUTO_TEST_SUITE_END()  // create

BOOST_AUTO_TEST_SUITE_END()  // tempfile


text:
//------------------------------------------------------------------------------
/// \file ContinuationMonad_tests.cpp
/// \author Ernest Yeung
//------------------------------------------------------------------------------
//#include "Categories/Monads/ContinuationMonad.h"

#define BOOST_THREAD_PROVIDES_FUTURE
#define BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION

#include "Categories/Monads/ContinuationMonad.h"

#include <boost/test/unit_test.hpp>
#include <cmath>
#include <future>
#include <optional>
#include <string>
#include <utility>

using Categories::Monads::ContinuationMonad::AsLambdas::eval;
using Categories::Monads::ContinuationMonad::AsLambdas::return_;
using Categories::Monads::ContinuationMonad::AsLambdas::runContinuation;
using Categories::Monads::ContinuationMonad::apply_endomorphism;
using Categories::Monads::ContinuationMonad::evaluate;
using Categories::Monads::ContinuationMonad::unit;

using namespace Categories::Monads::ContinuationMonad;

BOOST_AUTO_TEST_SUITE(Categories)
BOOST_AUTO_TEST_SUITE(Monads)
BOOST_AUTO_TEST_SUITE(ContinuationMonad_tests)

// Test morphisms.

std::optional<std::string> user_full_name(const std::string name)
{
  if (name.empty() || name == "None")
  {
    return {};
  }
  else
  {
    return std::make_optional("Username: " + name);
  }
}

std::optional<std::string> to_html(const std::string name)
{
  if (name.empty() || name == "NA")
  {
    return {};
  }
  else
  {
    return std::make_optional("http://" + name);
  }
}

std::pair<bool, std::string> h(const std::optional<std::string> text)
{
  if (!text)
  {
    return std::make_pair(false, "");
  }
  if (text.value() == "What you want.")
  {
    return std::make_pair(true, text.value());
  }
  else
  {
    return std::make_pair(false, text.value());
  }
}

template <int Divisor>
std::pair<bool, int> integer_division(const int input)
{
  if (Divisor == 0)
  {
    return std::make_pair(false, input);
  }
  else
  {
    return std::make_pair(true, input / Divisor);
  }
}

BOOST_AUTO_TEST_SUITE(Endomorphisms)

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(ApplyEndomorphismAppliesInternalHomToInput)
{
  {
    const auto result = apply_endomorphism(user_full_name, "Sainte-Foy");
    BOOST_TEST(result.value() == "Username: Sainte-Foy");
  }
  {
    const auto result = apply_endomorphism(to_html, "Sainte-Foy");
    BOOST_TEST(result.value() == "http://Sainte-Foy");
  }
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RunContinuationAppliesInternalHomToInput)
{
  {
    const auto result = runContinuation(user_full_name, "Sainte-Foy");
    BOOST_TEST(result.value() == "Username: Sainte-Foy");
  }
  {
    const auto result = runContinuation(to_html, "Sainte-Foy");
    BOOST_TEST(result.value() == "http://Sainte-Foy");
  }
}

BOOST_AUTO_TEST_SUITE_END() // Endomorphisms

BOOST_AUTO_TEST_SUITE(Return)

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(TestMorphismsWork)
{
  {
    auto result = user_full_name("Sainte-Foy");
    BOOST_TEST(result.value() == "Username: Sainte-Foy");
  }
  {
    const auto result1 = integer_division<2>(5);
    BOOST_TEST(result1.first);
    BOOST_TEST(result1.second == 2);
  }
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(ReturnReturnsEndomorphismObject)
{
  auto returned_unit = return_("Sainte-Foy");
  {
    const auto result = returned_unit(user_full_name);
    BOOST_TEST(result.value() == "Username: Sainte-Foy");
  }
  {
    const auto result = returned_unit(to_html);
    BOOST_TEST(result.value() == "http://Sainte-Foy");
  }
  auto returned_unit1 = return_(10);
  {
  }
}

BOOST_AUTO_TEST_SUITE_END() // Return

// cf. https://github.com/dbrattli/OSlash/blob/master/tests/test_cont.py

BOOST_AUTO_TEST_SUITE(UnitComponent)

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(
  UnitComponentReturnsInternalHomMappingInternalHomToReturnType)
{
  auto returned_endomorphism = unit<std::string>("Helene Desportes");
  {
    const auto result = returned_endomorphism(user_full_name);
    BOOST_TEST(result.value() == "Username: Helene Desportes");
  }
  {
    const auto result = returned_endomorphism(to_html);
    BOOST_TEST(result.value() == "http://Helene Desportes");
  }
}

// cf. https://github.com/dbrattli/OSlash/blob/master/tests/test_cont.py
// The following reproduces the unit tests in the referenced link.

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(UnitComponentDelaysComputation)
{
  auto test_internal_hom = [](const int value)
  {
    return std::to_string(value);
  };
  {
    auto addition = [](const auto x, const auto y)
    {
      return unit(x + y);
    };
    auto square = [](const auto x)
    {
      return unit(x * x);
    };
    // Results is of type [[X, Y], Y]
    auto delay_addition = addition(25, 9);
    auto delay_square = square(5);

    const auto addition_result = delay_addition(test_internal_hom);
    const auto square_result = delay_square(test_internal_hom);

    BOOST_TEST_REQUIRE(addition_result == "34");
    BOOST_TEST_REQUIRE(square_result == "25");
    BOOST_TEST(addition(25, 9)(evaluate<int>) == 34);
    {
      auto create_add_x = [](const int x)
      {
        return [x](const auto y)
        {
          return (x + y);
        };
      };
      auto add_6 = create_add_x(6);
      auto add_7 = create_add_x(7);

      BOOST_TEST(delay_square(add_6) == 31);
      BOOST_TEST(delay_square(add_7) == 32);
      BOOST_TEST(square(5)(add_6) == 31);
      BOOST_TEST(square(5)(add_7) == 32);

      auto intermediate = square(5)(
        [addition](const int xx)
        {
          return addition(xx, 8);
        });

      BOOST_TEST_REQUIRE(intermediate(evaluate<int>) == 33);

      auto intermediate_f = [square, addition](const int x, const int y)
      {
        return square(x)(
          [addition, y](const int xx)
          {
            return addition(xx, y);
          });
      };

      auto intermediate_f_result = intermediate_f(3, 6)(evaluate<int>);
      BOOST_TEST(intermediate_f_result == 15);

      auto pythagoras_formula = [addition, square](const int x, const int y)
      {
        return square(x)(
          [addition, square, y](const int xx)
          {
            return square(y)(
              [addition, xx](const int yy)
              {
                return addition(xx, yy);
              });
          });
      };
      BOOST_TEST(pythagoras_formula(5, 6)(evaluate<int>) == 61);
      BOOST_TEST(pythagoras_formula(4, 4)(evaluate<int>) == 32);
    }
  }
  {
    auto addition = [](const auto x, const auto y)
    {
      return return_(x + y);
    };
    auto square = [](const auto x)
    {
      return return_(x * x);
    };
    auto delay_addition = addition(25, 9);
    auto delay_square = square(5);

    const auto addition_result = delay_addition(test_internal_hom);
    const auto square_result = delay_square(test_internal_hom);

    BOOST_TEST_REQUIRE(addition_result == "34");
    BOOST_TEST_REQUIRE(square_result == "25");

    {
      auto pythagoras_formula = [addition, square](const int x, const int y)
      {
        return square(x)(
          [addition, square, y](const int xx)
          {
            return square(y)(
              [addition, xx](const int yy)
              {
                return addition(xx, yy);
              });
          });
      };
      BOOST_TEST(pythagoras_formula(5, 6)(evaluate<int>) == 61);
      BOOST_TEST(pythagoras_formula(4, 4)(evaluate<int>) == 32);
    }
  }
}

int pair_add(const std::pair<int, int> inputs)
{
  return inputs.first + inputs.second;
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(UnitComponentTreatsFunctionsAsFirstClassValues)
{
  {
    auto pair_addition = unit(pair_add);
    BOOST_TEST_REQUIRE(pair_addition(eval)(std::make_pair<int, int>(40, 2)));
    BOOST_TEST(unit(pair_add)(eval)(std::make_pair<int, int>(40, 2)));
  }
  {
    auto pair_addition = return_(pair_add);
    BOOST_TEST_REQUIRE(pair_addition(eval)(std::make_pair<int, int>(40, 2)));
    BOOST_TEST(return_(pair_add)(eval)(std::make_pair<int, int>(40, 2)));
  }
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(SimpleUnitComponentExamples)
{
  auto morphism_c = [](const auto x) -> std::string
  {
    return "Done: " + std::to_string(x);
  };
  {
    auto f = [](const auto x)
    {
      return unit(std::pow(x, 3));
    };
    auto g = [](const auto x)
    {
      return unit(x - 2);
    };
    auto h = [f, g](const auto x)
    {
      return (x == 5) ? f(x) : g(x);
    };
    auto do_c = unit(4.0)(h);
    BOOST_TEST_REQUIRE(do_c(evaluate<float>) == 2.0);
    BOOST_TEST(do_c(morphism_c) == "Done: 2.000000");
  }
  {
    auto f = [](const auto x)
    {
      return return_(std::pow(x, 3));
    };
    auto g = [](const auto x)
    {
      return return_(x - 2);
    };
    auto h = [f, g](const auto x)
    {
      return (x == 5) ? f(x) : g(x);
    };
    auto do_c = return_(4.0)(h);
    BOOST_TEST_REQUIRE(do_c(evaluate<float>) == 2.0);
    BOOST_TEST(do_c(morphism_c) == "Done: 2.000000");
  }
}

BOOST_AUTO_TEST_SUITE_END() // UnitComponent

BOOST_AUTO_TEST_SUITE(Bind)

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(BindAsLambdas)
{
  auto composed_fg = AsLambdas::bind(to_html, user_full_name);
//  composed_fg(h);

}

BOOST_AUTO_TEST_SUITE_END() // Bind

BOOST_AUTO_TEST_SUITE_END() // ContinuationMonad_tests
BOOST_AUTO_TEST_SUITE_END() // Monads
BOOST_AUTO_TEST_SUITE_END() // Categories

max_stars_repo_name: ernestyalumni/HrdwCCppCUDA

max_issues_repo_name: ernestyalumni/HrdwCCppCUDA

max_forks_repo_name: ernestyalumni/HrdwCCppCUDA


text:
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/common/common.h>
#include <pcl/common/transforms.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/console/parse.h>
#include <pcl/console/print.h>
#include <pcl/io/pcd_io.h>
#include <iostream>
#include <flann/flann.h>
#include <flann/io/hdf5.h>
#include <boost/filesystem.hpp>

typedef std::pair<
    std::string,
    std::vector <float>
> VfhModel;

bool
loadHist (const boost::filesystem::path &path, VfhModel &vfh)
{
  int vfh_idx;
  // Load the file as a PCD
  try
  {
    pcl::PCLPointCloud2 cloud;
    int version;
    Eigen::Vector4f origin;
    Eigen::Quaternionf orientation;
    pcl::PCDReader r;
    int type; unsigned int idx;
    r.readHeader (path.string (), cloud, origin, orientation, version, type, idx);

    vfh_idx = pcl::getFieldIndex (cloud, "vfh");
    if (vfh_idx == -1)
      return (false);
    if ((int)cloud.width * cloud.height != 1)
      return (false);
  }
  catch (const pcl::InvalidConversionException&)
  {
    return (false);
  }

  // Treat the VFH signature as a single Point Cloud
  pcl::PointCloud <pcl::VFHSignature308> point;
  pcl::io::loadPCDFile (path.string (), point);
  vfh.second.resize (308);

  std::vector <pcl::PCLPointField> fields;
  pcl::getFieldIndex<pcl::VFHSignature308> ("vfh", fields);

  for (std::size_t i = 0; i < fields[vfh_idx].count; ++i)
  {
    vfh.second[i] = point[0].histogram[i];
  }
  vfh.first = path.string ();
  return (true);
}

inline void
nearestKSearch (flann::Index<flann::ChiSquareDistance<float> > &index, const VfhModel &model,
                int k, flann::Matrix<int> &indices, flann::Matrix<float> &distances)
{
  // Query point
  flann::Matrix<float> p = flann::Matrix<float>(new float[model.second.size ()], 1, model.second.size ());
  memcpy (&p.ptr ()[0], &model.second[0], p.cols * p.rows * sizeof (float));

  indices = flann::Matrix<int>(new int[k], 1, k);
  distances = flann::Matrix<float>(new float[k], 1, k);
  index.knnSearch (p, indices, distances, k, flann::SearchParams (512));
  delete[] p.ptr ();
}

int main(int argc, char** argv)
{   int k = 16;
    double thresh = DBL_MAX;

    std::string extension(".pcd");
    transform(extension.begin(), extension.end(), extension.begin(), (int(*)(int))tolower);

    //load the test histogram
    std::vector<int> pcdIndices = pcl::console::parse_file_extension_argument(argc, argv, ".pcd");
    VfhModel histogram;
    if(!loadHist(argv[pcdIndices.at(0)], histogram))
    {
        pcl::console::print_error("Cannot load test file %s\n", argv[pcdIndices.at(0)]);
        return -1;
    }

    std::string idxFile = "kdtree.idx";
    std::string h5File = "training_data.h5";
    std::string listFile = "training_data.list";

    std::vector<VfhModel> models;
    flann::Matrix<int> kIndices;
    flann::Matrix<float> kDistances;
    flann::Matrix<float> data;

    if(!boost::filesystem::exists(h5File) || !boost::filesystem::exists(listFile))
    {
        pcl::console::print_error("could not find kd-tree index in file %s!", idxFile.c_str());
        return -1;
    }else{
        flann::Index<flann::ChiSquareDistance<float>> index (data, flann::SavedIndexParams("kdtree.idx"));
        index.buildIndex();
        nearestKSearch(index, histogram, k, kIndices, kDistances);
    }

    //output the result on screen
    pcl::console::print_highlight("The closest %d neighbors for %s are : \n", k, argv[pcdIndices[0]]);
    for(int i = 0; i < k; i++)
    {
        pcl::console::print_info("%d - $s (%d) with a distance of : %f\n",
            i, models.at(kIndices[0][i]).first.c_str(), kIndices[0][i], kDistances[0][i]);
    }

    //load the result
    pcl::visualization::PCLVisualizer p (argc, argv, "VFH Cluster Classifier");
    int ys = (int )std::floor(sqrt((double)k));
    int xs = ys + (int) std::ceil((k/(double)ys) - ys);
    double xstep = (double)(1/(double)xs);
    double ystep = (double)(1/(double)ys);
    pcl::console::print_highlight ("Preparing to load ");
    pcl::console::print_value ("%d", k);
    pcl::console::print_info (" files (");
    pcl::console::print_value ("%d", xs);
    pcl::console::print_info ("x");
    pcl::console::print_value ("%d", ys);
    pcl::console::print_info (" / ");
    pcl::console::print_value ("%f", xstep);
    pcl::console::print_info ("x");
    pcl::console::print_value ("%f", ystep);
    pcl::console::print_info (")\n");

    int viewport = 0, l=0, m=0;
    for(int i =0; i<k; ++i)
    {
        std::string cloud_name = models.at(kIndices[0][i]).first;
        boost::replace_last(cloud_name, "_vfh", "");

        p.createViewPort(l*xstep, m*ystep, (l+1) * xstep, (m+1)* ystep, viewport);
        l++;
        if(l >= xs)
        {
            l=0;
            m++;
        }

        pcl::PCLPointCloud2 cloud;
        pcl::console::print_highlight(stderr, "Loading ");
        pcl::console::print_value(stderr, "%s ", cloud_name.c_str());
        if(pcl::io::loadPCDFile(cloud_name, cloud) == -1)
        {
            break;
        }

        //convert from blob to pointlcloud
        pcl::PointCloud<pcl::PointXYZ> cloud_xyz;
        pcl::fromPCLPointCloud2(cloud, cloud_xyz);

        if(cloud_xyz.size() == 0)
        {
            break;
        }

        pcl::console::print_info ("[done, ");
        pcl::console::print_value ("%zu", static_cast<std::size_t>(cloud_xyz.size ()));
        pcl::console::print_info (" points]\n");
        pcl::console::print_info ("Available dimensions: ");
        pcl::console::print_value ("%s\n", pcl::getFieldsList (cloud).c_str ());

    // Demean the cloud
    Eigen::Vector4f centroid;
    pcl::compute3DCentroid (cloud_xyz, centroid);
    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_xyz_demean (new pcl::PointCloud<pcl::PointXYZ>);
    pcl::demeanPointCloud<pcl::PointXYZ> (cloud_xyz, centroid, *cloud_xyz_demean);
    // Add to renderer*
    p.addPointCloud (cloud_xyz_demean, cloud_name, viewport);

    // Check if the model found is within our inlier tolerance
    std::stringstream ss;
    ss << kDistances[0][i];
    if (kDistances[0][i] > thresh)
    {
      p.addText (ss.str (), 20, 30, 1, 0, 0, ss.str (), viewport);  // display the text with red

      // Create a red line
      pcl::PointXYZ min_p, max_p;
      pcl::getMinMax3D (*cloud_xyz_demean, min_p, max_p);
      std::stringstream line_name;
      line_name << "line_" << i;
      p.addLine (min_p, max_p, 1, 0, 0, line_name.str (), viewport);
      p.setShapeRenderingProperties (pcl::visualization::PCL_VISUALIZER_LINE_WIDTH, 5, line_name.str (), viewport);
    }
    else
      p.addText (ss.str (), 20, 30, 0, 1, 0, ss.str (), viewport);

    // Increase the font size for the score*
    p.setShapeRenderingProperties (pcl::visualization::PCL_VISUALIZER_FONT_SIZE, 18, ss.str (), viewport);

    // Add the cluster name
    p.addText (cloud_name, 20, 10, cloud_name, viewport);
  }
  // Add coordianate systems to all viewports
  p.addCoordinateSystem (0.1, "global", 0);

  p.spin ();
  return (0);
}

max_stars_repo_name: Malikmal/Learning-Pointcloud

max_issues_repo_name: Malikmal/Learning-Pointcloud

max_forks_repo_name: Malikmal/Learning-Pointcloud


text:
//===-- bfeattacks/GraphFactory.cpp - Graphs from BloomFilters -*- C++ -*--===//
//
// Copyright 2017 Will Mitchell
//
// 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.
//
//===----------------------------------------------------------------------===//
//
// This file contains some implementations to construct a graph
//
//===----------------------------------------------------------------------===//

#include "bfeattacks/GraphFactory.h"

#include <iostream>
using std::cout;
using std::endl;
#include <string>
using std::string;
#include <utility>
using std::pair;
#include <vector>
using std::vector;

#include "graph/Graph.h"
using graph::Graph_t;
#include "util/Vector.h"

#include <boost/graph/adjacency_list.hpp>

Graph_t bfeattacks::constructGraph(vector<string> &vertices,
                                   const vector<pair<string, string> > &edges) {
  Graph_t g(vertices.size() + 2);

  // Sort the vertices lexicographically just to be sure since binary_search
  // below
  // assumes sorted
  std::sort(vertices.begin(), vertices.end());

  // Add labels to vertices
  g[0].name = "Source";
  g[1].name = "Sink";
  for (string::size_type i = 0; i < vertices.size(); ++i)
    g[i + 2].name = vertices[i];

  // Add the edges to the graph
  size_t edge_index = 0;
  for (const auto &i : edges) {
    auto tail_idx =
        (i.first == "Source") ? 0 : util::binary_search(vertices, i.first) + 2;
    auto head_idx =
        (i.second == "Sink") ? 1 : util::binary_search(vertices, i.second) + 2;

    boost::add_edge(tail_idx, head_idx, edge_index++, g);
  }

  return g;
}

string bfeattacks::simplify_path(const vector<string> &path,
                                 bool UseStartSentinel, char StartSentinel) {
  string simple = "";

  for (const auto &i : path) {
    if (i == "Source" || i == "Sink")
      continue;
    if (UseStartSentinel && i[0] == StartSentinel)
      continue;
    simple += i[0];
  }

  return simple;
}


text:
// slam3d - Frontend for graph-based SLAM
// Copyright (C) 2019 S. Kasperski
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "ScanSensor.hpp"
#include "Mapper.hpp"

#include <boost/format.hpp>
#include <boost/thread.hpp>

using namespace slam3d;

ScanSensor::ScanSensor(const std::string& n, Logger* l)
 : Sensor(n,l), mPatchSolver(NULL)
{
	mNeighborRadius = 1.0;
	mMaxNeighorLinks = 1;
	mMinLoopLength = 10;
	mLinkPrevious = true;
	mLastTransform = Transform::Identity();
}

ScanSensor::~ScanSensor()
{
}

bool ScanSensor::addMeasurement(const Measurement::Ptr& m)
{
	if(mLastVertex == 0)
	{
		mLastVertex = mMapper->addMeasurement(m);
		return true;
	}

	Measurement::Ptr source = mMapper->getGraph()->getVertex(mLastVertex).measurement;
	try
	{
		Constraint::Ptr c = createConstraint(source, m, mLastTransform, false);
		SE3Constraint::Ptr se3 = boost::dynamic_pointer_cast<SE3Constraint>(c);
		mLastTransform = se3->getRelativePose().transform;
		if(!se3 || checkMinDistance(mLastTransform))
		{
			IdType newVertex = mMapper->addMeasurement(m);
			if(se3)
			{
				Transform pose = mMapper->getCurrentPose() * mLastTransform;
				mMapper->getGraph()->setCorrectedPose(newVertex, pose);
			}
			mMapper->getGraph()->addConstraint(mLastVertex, newVertex, c);
			mLastVertex = newVertex;
			return true;
		}
	}catch(std::exception &e)
	{
		mLogger->message(WARNING, (boost::format("Could not add Measurement: %1%") % e.what()).str());
	}
	return false;
}

bool ScanSensor::addMeasurement(const Measurement::Ptr& m, const Transform& odom)
{
	if(mLastVertex == 0)
	{
		mLastVertex = mMapper->addMeasurement(m);
		mLastOdometry = odom;
		return true;
	}

	// Add measurement if sufficient movement is reported by the odometry
	Transform odom_delta = mLastOdometry.inverse() * odom;
	if(checkMinDistance(odom_delta))
	{
		IdType newVertex = mMapper->addMeasurement(m);
		Measurement::Ptr source = mMapper->getGraph()->getVertex(mLastVertex).measurement;
		if(mLinkPrevious)
		{
			try
			{
				Constraint::Ptr c = createConstraint(source, m, odom_delta, false);
				mMapper->getGraph()->addConstraint(mLastVertex, newVertex, c);
			}catch(std::exception &e)
			{
				mLogger->message(WARNING, (boost::format("Could not link Measurement to previous: %1%") % e.what()).str());
			}
		}
		mLastOdometry = odom;
		mLastVertex = newVertex;
		return true;
	}
	return false;
}

void ScanSensor::link(IdType source_id, IdType target_id)
{
	// We have no guess, so we use the current relative pose from the graph
	Transform guess = mMapper->getGraph()->getTransform(source_id, target_id).transform;
	link(source_id, target_id, guess);
}

void ScanSensor::link(IdType source_id, IdType target_id, const Transform& guess)
{
	// Add a placeholder before starting the computation
	mMapper->getGraph()->addTentativeConstraint(source_id, target_id, mName);

	// Build local patches around source and target
	Measurement::Ptr source_m = buildPatch(source_id);
	Measurement::Ptr target_m = buildPatch(target_id);

	// Create the relative pose constraint
	try
	{
		Constraint::Ptr se3 = createConstraint(source_m, target_m, guess, true);
		mMapper->getGraph()->replaceConstraint(source_id, target_id, se3);
	}catch(NoMatch &e)
	{
		mLogger->message(WARNING, (boost::format("Failed to link vertex %1% and %2%, because %3%.") % source_id % target_id % e.what()).str());
		// delete tentative constraint
		return;
	}

}

void ScanSensor::linkToNeighbors(IdType vertex)
{
	if(mMaxNeighorLinks == 0)
		return;

	mMapper->getGraph()->buildNeighborIndex(mName);
	VertexObject obj = mMapper->getGraph()->getVertex(vertex);
	VertexObjectList neighbors = mMapper->getGraph()->getNearbyVertices(obj.corrected_pose, mNeighborRadius);

	int count = 0;
	for(auto i = neighbors.rbegin(); i != neighbors.rend() && count < mMaxNeighorLinks; i++)
	{
		IdType index = i->index;
		if(index == vertex) continue;
		try
		{
			mMapper->getGraph()->getEdge(vertex, index, mName);
			continue;
		}
		catch(InvalidEdge &e){}
		catch(InvalidVertex &e)
		{
			mLogger->message(ERROR, e.what());
			return;
		}

		float dist = mMapper->getGraph()->calculateGraphDistance(index, vertex);
		mLogger->message(DEBUG, (boost::format("Distance(%2%,%3%) in Graph is: %1%") % dist % index % vertex).str());
		if(dist <= mPatchBuildingRange * 2 || dist < mMinLoopLength)
			continue;
		count++;
		link(index, vertex);
	}
}

void ScanSensor::linkLastToNeighbors(bool mt)
{
	if(mMaxNeighorLinks < 1)
		return;

	if(mt)
		boost::thread linkThread(&ScanSensor::linkToNeighbors, this, mLastVertex);
	else
		linkToNeighbors(mLastVertex);
}

Measurement::Ptr ScanSensor::buildPatch(IdType source)
{
	if(mPatchBuildingRange == 0)
	{
		return mMapper->getGraph()->getVertex(source).measurement;
	}

	VertexObjectList v_objects = mMapper->getGraph()->getVerticesInRange(source, mPatchBuildingRange);
	mLogger->message(DEBUG, (boost::format("Building pointcloud patch from %1% nodes.") % v_objects.size()).str());

	if(mPatchSolver)
	{
		std::lock_guard<std::mutex> guard(mPatchSolverMutex);
		mPatchSolver->clear();
		for(VertexObjectList::iterator v = v_objects.begin(); v < v_objects.end(); v++)
		{
			mPatchSolver->addVertex(v->index, v->corrected_pose);
		}

		EdgeObjectList e_objects = mMapper->getGraph()->getEdges(v_objects);
		for(EdgeObjectList::iterator e = e_objects.begin(); e < e_objects.end(); e++)
		{
			if(e->constraint->getType() != SE3)
				continue;
			try
			{
				mPatchSolver->addEdge(e->source, e->target, e->constraint);
			}catch(Solver::BadEdge &be)
			{
				mLogger->message(ERROR, be.what());
			}
		}

		mPatchSolver->setFixed(source);
		mPatchSolver->compute();
		IdPoseVector res = mPatchSolver->getCorrections();
		for(IdPoseVector::iterator it = res.begin(); it < res.end(); it++)
		{
			bool ok = false;
			for(VertexObjectList::iterator v = v_objects.begin(); v < v_objects.end(); v++)
			{
				if(v->index == it->first)
				{
					v->corrected_pose = it->second;
					ok = true;
					break;
				}
			}
			if(!ok)
			{
				mLogger->message(ERROR, (boost::format("Could not apply patch-solver result for vertex %1%!") % it->first).str());
			}
		}
	}
	return createCombinedMeasurement(v_objects, mMapper->getGraph()->getVertex(source).corrected_pose);
}

void ScanSensor::setNeighborRadius(float r, unsigned l)
{
	mLogger->message(INFO, (boost::format("neighbor_radius:        %1%") % r).str());
	mLogger->message(INFO, (boost::format("max_neighbor_links:     %1%") % l).str());
	mNeighborRadius = r;
	mMaxNeighorLinks = l;
}

void ScanSensor::setMinLoopLength(unsigned l)
{
	mLogger->message(INFO, (boost::format("min_loop_length:        %1%") % l).str());
	mMinLoopLength = l;
}

void ScanSensor::setLinkPrevious(bool l)
{
	mLogger->message(INFO, (boost::format("link_previous:          %1%") % l).str());
	mLinkPrevious = l;
}

void ScanSensor::setPatchBuildingRange(unsigned r)
{
	mLogger->message(INFO, (boost::format("patch_building_range:   %1%") % r).str());
	mPatchBuildingRange = r;
}


text:
#pragma once

#include <cstdint>

#include <boost/functional/hash.hpp>

namespace tcan_can {
    struct CanFrameIdentifier {
        explicit CanFrameIdentifier(uint32_t id, uint32_t msk = 0xffffffffu) : identifier(id), mask(msk) {};
        uint32_t identifier;
        uint32_t mask;

        bool operator==(const CanFrameIdentifier& rhs) const {
            return identifier == rhs.identifier && mask == rhs.mask;
        }
    };

    struct CanFrameIdentifierHasher {
        std::size_t operator()(const CanFrameIdentifier& matcher) const {
            std::size_t h = 0;
            boost::hash_combine(h, matcher.identifier);
            boost::hash_combine(h, matcher.mask);
            return h;
        };
    };
} // namespace tcan_can

max_stars_repo_name: mcx/tcan

max_issues_repo_name: mcx/tcan

max_forks_repo_name: mcx/tcan


text:
#include <algorithm>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/assert.hpp>
#include <deque>
#include <ranges>
#include <stdexcept>
#include <utility>

#include "command.hpp"
#include "utils.hpp"

class InvalidHandler : public Handler {
public:
  InvalidHandler() : Handler(Handler::do_not_register{}) {}
  void operator()(const arg_map_t &args,
                  const vararg_t &varargs) const override {
    invalid_argument();
  }
} invalid_handler;

Handler::Handler(Command &command,
                 const std::vector<std::shared_ptr<const Argument>> &arguments,
                 const std::string &description)
    : arguments(arguments), description(description) {
  command.handlers.push_back(this);
}

struct NextInfo {
  const Handler *handler = &invalid_handler;
  std::unordered_map<std::string, int64_t> keywords;
  std::unordered_map<std::string, std::string> alias;
  bool is_varargs = false;
  std::string variable = "";
  int64_t variable_next = -1;
  std::vector<Variable::suggester_t> suggesters;
};

const NextInfo invalid_next_info;

class StateMachine {
  int64_t id;
  std::unordered_map<std::string, std::string> args;
  std::vector<std::string> varargs;
  const std::unordered_map<int64_t, NextInfo> &next_;

  const NextInfo &next_info() const {
    if (next_.contains(id)) {
      return next_.at(id);
    }
    return invalid_next_info;
  };

public:
  StateMachine(const std::unordered_map<int64_t, NextInfo> &next)
      : id(0), next_(next) {}
  void feed(std::string text) {
    const NextInfo &next = next_info();
    if (next.keywords.contains(text)) {
      id = next.keywords.at(text);
    } else if (next.alias.contains(text)) {
      auto kwd = next.alias.at(text);
      id = next.keywords.at(kwd);
    } else if (next.variable.size() > 0) {
      if (next.is_varargs) {
        varargs.push_back(text);
      } else {
        args[next.variable] = text;
      }
      id = next.variable_next;
    } else {
      id = -1;
    }
  }

  void execute() const { (*next_info().handler)(args, varargs); }

  std::unordered_set<std::string> suggest(std::string prefix) {
    std::unordered_set<std::string> result;
    const NextInfo &next = next_info();
    auto match = [&](std::string str) {
      return str.size() >= prefix.size() &&
             str.substr(0, prefix.size()) == prefix;
    };
    for (auto &kv : next.keywords) {
      if (match(kv.first)) {
        result.insert(kv.first);
      }
    }
    for (auto &kv : next.alias) {
      if (match(kv.first) && !result.contains(kv.second)) {
        result.insert(kv.first);
      }
    }
    for (auto &s : next.suggesters) {
      auto new_suggestions = s(prefix);
      result.insert(new_suggestions.begin(), new_suggestions.end());
    }
    return result;
  }
};

class HandlerExecutor {
  bool compiled_ = false;
  std::unordered_map<int64_t, NextInfo> next;

public:
  void compile(const std::vector<const Handler *> &handlers);
  bool compiled() const { return compiled_; }
  StateMachine start() const { return {next}; }
};

void HandlerExecutor::compile(const std::vector<const Handler *> &handlers) {
  assert(!compiled_);
  compiled_ = true;
  struct Branch {
    std::vector<const Handler *> handlers = {};
    int64_t cursor;
    int64_t id;
    bool is_varargs;
    Branch(int64_t id, int64_t cursor, std::vector<const Handler *> handlers)
        : id(id), cursor(cursor), is_varargs(false), handlers(handlers) {}
  };

  // at the beginning, put all handlers in the same branch,
  // set cursor to 0, use id 0, and allocate a new NextInfo
  // to this id
  int64_t id = 0;
  std::deque<Branch> branches{Branch(id++, 0, handlers)};

  while (branches.size() > 0) {
    // pop the front of branches
    Branch branch = branches.front();
    branches.pop_front();
    NextInfo &next_info = next[branch.id];

    // varargs branch is handled separately, because it can
    // accept infinite number of arguments.
    if (branch.is_varargs) {
      BOOST_ASSERT_MSG(branch.handlers.size() == 1,
                       "BUG: varargs branch can only has 1 handler");
      auto handler = branch.handlers[0];
      auto &hargs = handler->arguments;
      BOOST_ASSERT_MSG(hargs.size() == branch.cursor,
                       "BUG: varargs must be the last argument");
      next_info.is_varargs = true;
      next_info.variable = hargs[branch.cursor - 1]->name;
      next_info.variable_next = branch.id;
    }

    // walk through all handlers in this branch, try
    // move cursor to the next, discover new branches
    int starting_id = id;
    for (auto h : branch.handlers) {
      auto &hargs = h->arguments;
      BOOST_ASSERT_MSG(hargs.size() >= branch.cursor,
                       "BUG: handlers shouldn't be in this branch");
      if (hargs.size() == branch.cursor) {
        // there can not be more than one handler ending
        // at the same branch, otherwise this language is not unique
        BOOST_ASSERT_MSG(next_info.handler == &invalid_handler,
                         "BUG: in one branch, only one handler can end here");
        next_info.handler = h;
      } else {
        std::shared_ptr<const Argument> harg = hargs[branch.cursor];

        // find if this handler fits an existing branch
        Branch *new_branch = nullptr;
        for (auto &b : std::ranges::views::reverse(branches)) {
          if (b.id < starting_id) {
            break;
          }
          BOOST_ASSERT_MSG(b.cursor == branch.cursor + 1,
                           "BUG: cursor for new branches not properly set.");
          BOOST_ASSERT_MSG(b.handlers.size() > 0,
                           "BUG: handlers for new branches not properly set.");
          std::shared_ptr<const Argument> barg =
              b.handlers[0]->arguments[branch.cursor];
          int compare_result = (*harg <=> *barg);
          BOOST_ASSERT_MSG(compare_result >= 0,
                           "BUG: Incompatible argument configuration.");
          if (compare_result == 0) {
            new_branch = &b;
            break;
          }
        }

        // if this handler fits to an existing branch, then add this handler to
        // this branch, otherwise, create a new branch
        if (new_branch != nullptr) {
          new_branch->handlers.push_back(h);
        } else {
          // create a new branch
          branches.emplace_back(id++, branch.cursor + 1,
                                std::vector<const Handler *>{h});
          new_branch = &branches.back();

          // update NextInfo of current branch to point to the new branch
          if (typeid(*harg) == typeid(Variable) ||
              typeid(*harg) == typeid(Varargs)) {
            bool is_varargs = (typeid(*harg) == typeid(Varargs));
            if (next_info.variable.size() == 0 &&
                next_info.variable_next == -1) {
              next_info.is_varargs = is_varargs;
              next_info.variable = harg->name;
              next_info.variable_next = new_branch->id;
            }
            new_branch->is_varargs = is_varargs;
            if (!is_varargs) {
              auto var = std::dynamic_pointer_cast<const Variable>(harg);
              if (var->suggest.has_value()) {
                next_info.suggesters.push_back(var->suggest.value());
              }
            }
            // At the same branch, different handlers can not have different
            // variables at the branching position. For example:
            //
            // legal:
            // tcg aaa, tcg aaa <bbb>, tcg aaa <bbb> <ccc>
            //
            // illegal:
            // tcg aaa <bbb>, tcg aaa <ccc>
            const char *msg = "BUG: different variables at the same position.";
            BOOST_ASSERT_MSG(next_info.is_varargs == is_varargs, msg);
            BOOST_ASSERT_MSG(next_info.variable == harg->name, msg);
            BOOST_ASSERT_MSG(next_info.variable_next == new_branch->id, msg);
          } else {
            BOOST_ASSERT_MSG(typeid(*harg) == typeid(Keyword),
                             "BUG: Unknown argument type.");
            auto check_conflict = [&](std::string k) {
              BOOST_ASSERT_MSG(!next_info.keywords.contains(k),
                               "BUG: keyword or alias conflict.");
              BOOST_ASSERT_MSG(!next_info.alias.contains(k),
                               "BUG: keyword or alias conflict.");
            };
            auto kwd = std::dynamic_pointer_cast<const Keyword>(harg);
            check_conflict(kwd->name);
            next_info.keywords[kwd->name] = new_branch->id;
            for (auto &alias : kwd->alias()) {
              check_conflict(alias);
              next_info.alias[alias] = kwd->name;
            }
          }
        }
      }
    }
  }
}

std::map<std::string, const Command *> Command::registry;

Command::Command(const std::string &name, const std::vector<std::string> &alias,
                 const std::string &short_description,
                 const std::string &additional_note, Flags flags)
    : executor(std::make_shared<HandlerExecutor>()), name(name), alias(alias),
      short_description(short_description), additional_note(additional_note),
      flags(flags) {
  if (registry.find(name) != registry.end()) {
    throw std::runtime_error(
        std::string("Conflicting name. Please report a bug at: ") + url);
  }
  registry[name] = this;
  for (auto &a : alias) {
    if (registry.find(a) != registry.end()) {
      throw std::runtime_error(
          std::string("Conflicting alias. Please report a bug at: ") + url);
    }
    registry[a] = this;
  }
}

class UndefinedCommand final : public Command {
public:
  UndefinedCommand() : Command({}, {}, {}, {}, {}) {}

  bool defined() const override { return false; }

  void execute(const char *args[]) const override { invalid_argument(); }

  std::unordered_set<std::string>
  suggest(const std::vector<std::string> &args) const override {
    return {};
  }
} undefined_command;

const Command *Command::get(const std::string &name) {
  auto i = registry.find(name);
  if (i == registry.end()) {
    return &undefined_command;
  }
  return registry[name];
}

void Command::execute(const char *args[]) const {
  if (!executor->compiled()) {
    executor->compile(handlers);
  }
  auto vm = executor->start();
  auto arg = args;
  while (*arg != nullptr) {
    vm.feed(*(arg++));
  }
  vm.execute();
}

std::unordered_set<std::string>
Command::suggest(const std::vector<std::string> &args) const {
  if (!executor->compiled()) {
    executor->compile(handlers);
  }
  auto vm = executor->start();
  for (int64_t i = 0; i < args.size() - 1; i++) {
    vm.feed(args[i]);
  }
  return vm.suggest(args[args.size() - 1]);
}

max_stars_repo_name: zasdfgbnm/autocgrouper

max_issues_repo_name: zasdfgbnm/tcg

max_forks_repo_name: zasdfgbnm/autocgrouper