text:
// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:

// Copyright (c) 2007 Aristid Breitkreuz, Ruediger Sonderfeld, Christian Uhrhan
//
// Distributed under the Boost Software License, Version 1.0 and under the MIT
// License.
//
// See accompanying LICENSES.txt or
// <http://fragments.sourceforge.net/LICENSES.txt> or, for the Boost Software
// License, <http://www.boost.org/LICENSE_1_0.txt>.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

#ifndef FRAGMENTS_DETAIL_ITERATE_FRAGMENTS_HPP
#define FRAGMENTS_DETAIL_ITERATE_FRAGMENTS_HPP

#include <fragments/detail/create_vector.hpp>
#include <boost/mpl/front.hpp>
#include <boost/mpl/pop_front.hpp>

namespace fragments { namespace detail {
  template<typename Sequence, typename Before>
  struct iterate_fragments {
    typedef Sequence sequence;
    typedef typename boost::mpl::front<sequence>::type first;
    typedef typename boost::mpl::pop_front<sequence>::type next_sequence;
    typedef typename first::template fragment<Before> second;
  };
}}

#endif

max_stars_repo_name: aristidb/fragments

max_issues_repo_name: aristidb/fragments

max_forks_repo_name: aristidb/fragments


text:
#ifdef PARSER_TESTS

#include <boost/test/unit_test.hpp>
#include "../PlcParser.h"

class PlcParserMock : public PlcParser<2, 3>
{
public:

  PlcParserMock(Parser<2, 3>& parser, PlcAst& plcAst) : PlcParser(parser, plcAst) {}

  void parseTermMock(plc::Term& term)
  {
    parseTerm(term);
  }

  static plc::Expression::Operator toOperatorMock(ParserResult& parserResult)
  {
    return toOperator(parserResult);
  }

  void parseExpressionMock(std::unique_ptr<plc::Expression>& expression)
  {
    parseExpression(expression);
  }

  void parseEquationMock(const std::string& left)
  {
    parseEquation(left);
  }

  void parseVariablesMock(Variable::Type type)
  {
    parseVariables(type);
  }

};

BOOST_AUTO_TEST_CASE(PlcParser_toOperator)
{
  std::string dummy;
  ParserResult parseResultInt(4711ull, dummy);

  BOOST_CHECK_THROW(PlcParserMock::toOperatorMock(parseResultInt), ParserException);

  ParserResult parserResult;
  BOOST_CHECK_THROW(PlcParserMock::toOperatorMock(parserResult), ParserException);

  parserResult = "text";
  BOOST_CHECK_THROW(PlcParserMock::toOperatorMock(parserResult), ParserException);

  parserResult = 'a';
  BOOST_CHECK_THROW(PlcParserMock::toOperatorMock(parserResult), ParserException);

  parserResult = '&';
  BOOST_CHECK(PlcParserMock::toOperatorMock(parserResult) == plc::Expression::Operator::And);
  parserResult = '|';
  BOOST_CHECK(PlcParserMock::toOperatorMock(parserResult) == plc::Expression::Operator::Or);
}

BOOST_AUTO_TEST_CASE(PlcParser_Term)
{
  std::istringstream in("abc !xyz 123");
  ParserInput<2> parserInput(in);
  Parser<2, 3> parser(parserInput);
  PlcAst plcAst;
  PlcParserMock plcParser(parser, plcAst);

  plcAst.addVariable(Variable("abc", Variable::Type::Input, 0));
  plcAst.addVariable(Variable("xyz", Variable::Type::Input, 1));

  plc::Term term;
  BOOST_CHECK(!term);

  plcParser.parseTermMock(term);
  BOOST_CHECK(term.type() == plc::Term::Type::Identifier);
  BOOST_CHECK_EQUAL(term.variable()->name(), "abc");
  BOOST_CHECK(term.unary() == plc::Term::Unary::None);

  plcParser.parseTermMock(term);
  BOOST_CHECK(term.type() == plc::Term::Type::Identifier);
  BOOST_CHECK_EQUAL(term.variable()->name(), "xyz");
  BOOST_CHECK(term.unary() == plc::Term::Unary::Not);

  BOOST_CHECK_THROW(plcParser.parseTermMock(term), ParserException);
}

BOOST_AUTO_TEST_CASE(PlcParser_Vars)
{
  std::istringstream in(": abc=0, xyz=1, min=2, no=3;");

  ParserInput<2> parserInput(in);
  Parser<2, 3> parser(parserInput);
  PlcAst plcAst;
  PlcParserMock plcParser(parser, plcAst);
  ParserResult pr;

  plcParser.parseVariablesMock(Variable::Type::Input);

  BOOST_CHECK(parser.next(pr).type() == ParserResult::Type::Empty);
  BOOST_CHECK_EQUAL(plcAst.getVariable("abc").time(), 0);
  BOOST_CHECK_EQUAL(plcAst.getVariable("xyz").time(), 0);
  BOOST_CHECK_EQUAL(plcAst.getVariable("min").time(), 0);
  BOOST_CHECK_EQUAL(plcAst.getVariable("no").time(), 0);
}

BOOST_AUTO_TEST_CASE(PlcParser_Timer_Arg)
{
  std::istringstream in(": abc(10s)=0, xyz(1h)=1, min(10 min)=2, no=3;");

  ParserInput<2> parserInput(in);
  Parser<2, 3> parser(parserInput);
  PlcAst plcAst;
  PlcParserMock plcParser(parser, plcAst);
  ParserResult pr;

  plcParser.parseVariablesMock(Variable::Type::Monoflop);

  BOOST_CHECK(parser.next(pr).type() == ParserResult::Type::Empty);
  BOOST_CHECK_EQUAL(plcAst.getVariable("abc").time(), 5);
  BOOST_CHECK_EQUAL(plcAst.getVariable("xyz").time(), 1800);
  BOOST_CHECK_EQUAL(plcAst.getVariable("min").time(), 300);
  BOOST_CHECK_EQUAL(plcAst.getVariable("no").time(), 30);
}

BOOST_AUTO_TEST_CASE(PlcParser_Expression_Precedence1)
{
  std::istringstream in("a | b & c;");
  ParserInput<2> parserInput(in);
  Parser<2, 3> parser(parserInput);
  PlcAst plcAst;
  PlcParserMock plcParser(parser, plcAst);

  plcAst.addVariable(Variable("a", Variable::Type::Input, 0));
  plcAst.addVariable(Variable("b", Variable::Type::Input, 1));
  plcAst.addVariable(Variable("c", Variable::Type::Input, 2));

  std::unique_ptr<plc::Expression> expression(new plc::Expression());

  BOOST_CHECK(!*expression);

  plcParser.parseExpressionMock(expression);
  BOOST_CHECK(*expression);

  BOOST_CHECK_EQUAL(expression->terms().size(), 2);
  BOOST_CHECK(expression->terms()[0]);
  BOOST_CHECK(expression->terms()[0].type() == plc::Term::Type::Identifier);
  BOOST_CHECK_EQUAL(expression->terms()[0].variable()->name(), "a");
  BOOST_CHECK(expression->op() == plc::Expression::Operator::Or);
  BOOST_CHECK(expression->terms()[1]);
  BOOST_CHECK(expression->terms()[1].expression());
  BOOST_CHECK(*expression->terms()[1].expression());
  BOOST_CHECK_EQUAL(expression->terms()[1].expression()->terms().size(),2);
  BOOST_CHECK(expression->terms()[1].expression()->terms()[0]);
  BOOST_CHECK(expression->terms()[1].expression()->terms()[0].type() == plc::Term::Type::Identifier);
  BOOST_CHECK_EQUAL(expression->terms()[1].expression()->terms()[0].variable()->name(), "b");
  BOOST_CHECK(expression->terms()[1].expression()->op() == plc::Expression::Operator::And);
  BOOST_CHECK(expression->terms()[1].expression()->terms()[1].type() == plc::Term::Type::Identifier);
  BOOST_CHECK_EQUAL(expression->terms()[1].expression()->terms()[1].variable()->name(), "c");
}

BOOST_AUTO_TEST_CASE(PlcParser_Expression_Precedence2)
{
  std::istringstream in("(a | b) & c;");
  ParserInput<2> parserInput(in);
  Parser<2, 3> parser(parserInput);
  PlcAst plcAst;
  PlcParserMock plcParser(parser, plcAst);

  plcAst.addVariable(Variable("a", Variable::Type::Input, 0));
  plcAst.addVariable(Variable("b", Variable::Type::Input, 1));
  plcAst.addVariable(Variable("c", Variable::Type::Input, 2));

  std::unique_ptr<plc::Expression> expression(new plc::Expression());

  BOOST_CHECK(!*expression);

  plcParser.parseExpressionMock(expression);
  BOOST_CHECK(*expression);

  BOOST_CHECK_EQUAL(expression->terms().size(), 2);
  BOOST_CHECK(expression->terms()[0]);
  BOOST_CHECK(expression->terms()[0].type() == plc::Term::Type::Expression);
  BOOST_CHECK(expression->terms()[0]);
  BOOST_CHECK(expression->terms()[0].expression());
  BOOST_CHECK(*expression->terms()[0].expression());
  BOOST_CHECK_EQUAL(expression->terms()[0].expression()->terms().size(), 2);
  BOOST_CHECK(expression->terms()[0].expression()->terms()[0]);
  BOOST_CHECK(expression->terms()[0].expression()->terms()[0].type() == plc::Term::Type::Identifier);
  BOOST_CHECK_EQUAL(expression->terms()[0].expression()->terms()[0].variable()->name(), "a");
  BOOST_CHECK(expression->terms()[0].expression()->op() == plc::Expression::Operator::Or);
  BOOST_CHECK(expression->terms()[0].expression()->terms()[1].type() == plc::Term::Type::Identifier);
  BOOST_CHECK_EQUAL(expression->terms()[0].expression()->terms()[1].variable()->name(), "b");
  BOOST_CHECK(expression->op() == plc::Expression::Operator::And);
  BOOST_CHECK(expression->terms()[1].type() == plc::Term::Type::Identifier);
  BOOST_CHECK_EQUAL(expression->terms()[1].variable()->name(), "c");
}

BOOST_AUTO_TEST_CASE(PlcParser_Expression_Precedence3)
{
  std::istringstream in("a & b | c;");
  ParserInput<2> parserInput(in);
  Parser<2, 3> parser(parserInput);
  PlcAst plcAst;
  PlcParserMock plcParser(parser, plcAst);

  plcAst.addVariable(Variable("a", Variable::Type::Input, 0));
  plcAst.addVariable(Variable("b", Variable::Type::Input, 1));
  plcAst.addVariable(Variable("c", Variable::Type::Input, 2));

  std::unique_ptr<plc::Expression> expression(new plc::Expression());

  BOOST_CHECK(!*expression);

  plcParser.parseExpressionMock(expression);
  BOOST_CHECK(*expression);

  BOOST_CHECK_EQUAL(expression->terms().size(), 2);
  BOOST_CHECK(expression->terms()[0]);
  BOOST_CHECK(expression->terms()[0].type() == plc::Term::Type::Expression);
  BOOST_CHECK(expression->terms()[0].expression());
  BOOST_CHECK(*expression->terms()[0].expression());
  BOOST_CHECK_EQUAL(expression->terms()[0].expression()->terms().size(), 2);
  BOOST_CHECK(expression->terms()[0].expression()->terms()[0]);
  BOOST_CHECK(expression->terms()[0].expression()->terms()[0].type() == plc::Term::Type::Identifier);
  BOOST_CHECK_EQUAL(expression->terms()[0].expression()->terms()[0].variable()->name(), "a");
  BOOST_CHECK(expression->terms()[0].expression()->op() == plc::Expression::Operator::And);
  BOOST_CHECK(expression->terms()[0].expression()->terms()[1].type() == plc::Term::Type::Identifier);
  BOOST_CHECK_EQUAL(expression->terms()[0].expression()->terms()[1].variable()->name(), "b");
  BOOST_CHECK(expression->op() == plc::Expression::Operator::Or);
  BOOST_CHECK(expression->terms()[1].type() == plc::Term::Type::Identifier);
  BOOST_CHECK_EQUAL(expression->terms()[1].variable()->name(), "c");
}

BOOST_AUTO_TEST_CASE(PlcParser_Expression_Precedence4)
{
  std::istringstream in("a | (b & c);");
  ParserInput<2> parserInput(in);
  Parser<2, 3> parser(parserInput);
  PlcAst plcAst;
  PlcParserMock plcParser(parser, plcAst);

  plcAst.addVariable(Variable("a", Variable::Type::Input, 0));
  plcAst.addVariable(Variable("b", Variable::Type::Input, 1));
  plcAst.addVariable(Variable("c", Variable::Type::Input, 2));

  std::unique_ptr<plc::Expression> expression(new plc::Expression());

  BOOST_CHECK(!*expression);

  plcParser.parseExpressionMock(expression);
  BOOST_CHECK(*expression);

  BOOST_CHECK_EQUAL(expression->terms().size(), 2);
  BOOST_CHECK(expression->terms()[0]);
  BOOST_CHECK(expression->terms()[0].type() == plc::Term::Type::Identifier);
  BOOST_CHECK_EQUAL(expression->terms()[0].variable()->name(), "a");
  BOOST_CHECK(expression->op() == plc::Expression::Operator::Or);
  BOOST_CHECK(expression->terms()[1]);
  BOOST_CHECK(expression->terms()[1].expression());
  BOOST_CHECK(*expression->terms()[1].expression());
  BOOST_CHECK_EQUAL(expression->terms()[1].expression()->terms().size(), 2);
  BOOST_CHECK(expression->terms()[1].expression()->terms()[0]);
  BOOST_CHECK(expression->terms()[1].expression()->terms()[0].type() == plc::Term::Type::Identifier);
  BOOST_CHECK_EQUAL(expression->terms()[1].expression()->terms()[0].variable()->name(), "b");
  BOOST_CHECK(expression->terms()[1].expression()->op() == plc::Expression::Operator::And);
  BOOST_CHECK(expression->terms()[1].expression()->terms()[1].type() == plc::Term::Type::Identifier);
  BOOST_CHECK_EQUAL(expression->terms()[1].expression()->terms()[1].variable()->name(), "c");
}

BOOST_AUTO_TEST_CASE(PlcParser_Expression_Precedence5)
{
  std::istringstream in("a | b & c & d;");
  ParserInput<2> parserInput(in);
  Parser<2, 3> parser(parserInput);
  PlcAst plcAst;
  PlcParserMock plcParser(parser, plcAst);

  plcAst.addVariable(Variable("a", Variable::Type::Input, 0));
  plcAst.addVariable(Variable("b", Variable::Type::Input, 1));
  plcAst.addVariable(Variable("c", Variable::Type::Input, 2));
  plcAst.addVariable(Variable("d", Variable::Type::Input, 3));

  std::unique_ptr<plc::Expression> expression(new plc::Expression());

  BOOST_CHECK(!*expression);

  plcParser.parseExpressionMock(expression);
  BOOST_CHECK(*expression);

  BOOST_CHECK_EQUAL(expression->terms().size(), 2);
  BOOST_CHECK(expression->terms()[0]);
  BOOST_CHECK(expression->terms()[0].type() == plc::Term::Type::Identifier);
  BOOST_CHECK_EQUAL(expression->terms()[0].variable()->name(), "a");
  BOOST_CHECK(expression->op() == plc::Expression::Operator::Or);
  BOOST_CHECK(expression->terms()[1]);
  BOOST_CHECK(expression->terms()[1].expression());
  BOOST_CHECK(*expression->terms()[1].expression());
  BOOST_CHECK_EQUAL(expression->terms()[1].expression()->terms().size(), 3);
  BOOST_CHECK(expression->terms()[1].expression()->terms()[0]);
  BOOST_CHECK(expression->terms()[1].expression()->terms()[0].type() == plc::Term::Type::Identifier);
  BOOST_CHECK_EQUAL(expression->terms()[1].expression()->terms()[0].variable()->name(), "b");
  BOOST_CHECK(expression->terms()[1].expression()->op() == plc::Expression::Operator::And);
  BOOST_CHECK(expression->terms()[1].expression()->terms()[1].type() == plc::Term::Type::Identifier);
  BOOST_CHECK_EQUAL(expression->terms()[1].expression()->terms()[1].variable()->name(), "c");
  BOOST_CHECK(expression->terms()[1].expression()->terms()[2].type() == plc::Term::Type::Identifier);
  BOOST_CHECK_EQUAL(expression->terms()[1].expression()->terms()[2].variable()->name(), "d");
}

BOOST_AUTO_TEST_CASE(PlcParser_Expression_Precedence6)
{
  std::istringstream in("a | b & c | d;");
  ParserInput<2> parserInput(in);
  Parser<2, 3> parser(parserInput);
  PlcAst plcAst;
  PlcParserMock plcParser(parser, plcAst);

  plcAst.addVariable(Variable("a", Variable::Type::Input, 0));
  plcAst.addVariable(Variable("b", Variable::Type::Input, 1));
  plcAst.addVariable(Variable("c", Variable::Type::Input, 2));
  plcAst.addVariable(Variable("d", Variable::Type::Input, 3));

  std::unique_ptr<plc::Expression> expression(new plc::Expression());

  BOOST_CHECK(!*expression);

  plcParser.parseExpressionMock(expression);
  BOOST_CHECK(*expression);

  BOOST_CHECK_EQUAL(expression->terms().size(), 2);
  BOOST_CHECK(expression->terms()[0]);
  BOOST_CHECK(expression->terms()[0].type() == plc::Term::Type::Identifier);
  BOOST_CHECK_EQUAL(expression->terms()[0].variable()->name(), "a");
  BOOST_CHECK(expression->op() == plc::Expression::Operator::Or);
  BOOST_CHECK(expression->terms()[1]);
  BOOST_CHECK(expression->terms()[1].expression());
  BOOST_CHECK(*expression->terms()[1].expression());
  BOOST_CHECK_EQUAL(expression->terms()[1].expression()->terms().size(), 2);

  BOOST_CHECK(expression->terms()[1].expression()->terms()[0]);
  BOOST_CHECK(expression->terms()[1].expression()->terms()[0].type() == plc::Term::Type::Expression);
  BOOST_CHECK(expression->terms()[1].expression()->terms()[0].expression());
  BOOST_CHECK(*expression->terms()[1].expression()->terms()[0].expression());
  BOOST_CHECK_EQUAL(expression->terms()[1].expression()->terms()[0].expression()->terms().size(),2);
  BOOST_CHECK_EQUAL(expression->terms()[1].expression()->terms()[0].expression()->terms()[0].variable()->name(), "b");
  BOOST_CHECK(expression->terms()[1].expression()->terms()[0].expression()->op() == plc::Expression::Operator::And);
  BOOST_CHECK(expression->terms()[1].expression()->terms()[0].expression()->terms()[1].type() == plc::Term::Type::Identifier);
  BOOST_CHECK_EQUAL(expression->terms()[1].expression()->terms()[0].expression()->terms()[1].variable()->name(), "c");

  BOOST_CHECK(expression->terms()[1].expression()->terms()[1]);
  BOOST_CHECK(expression->terms()[1].expression()->terms()[1].type() == plc::Term::Type::Identifier);
  BOOST_CHECK_EQUAL(expression->terms()[1].expression()->terms()[1].variable()->name(), "d");
}

BOOST_AUTO_TEST_CASE(PlcParser_Expression_Levels1)
{
  std::istringstream in("a;");
  ParserInput<2> parserInput(in);
  Parser<2, 3> parser(parserInput);
  PlcAst plcAst;
  PlcParserMock plcParser(parser, plcAst);

  plcAst.addVariable(Variable("a", Variable::Type::Input, 0));

  std::unique_ptr<plc::Expression> expression(new plc::Expression());

  plcParser.parseExpressionMock(expression);
  BOOST_CHECK(*expression);
  BOOST_CHECK_EQUAL(expression->countLevels(), 1u);
}

BOOST_AUTO_TEST_CASE(PlcParser_Expression_Levels2)
{
  std::istringstream in("a | b | c;");
  ParserInput<2> parserInput(in);
  Parser<2, 3> parser(parserInput);
  PlcAst plcAst;
  PlcParserMock plcParser(parser, plcAst);

  plcAst.addVariable(Variable("a", Variable::Type::Input, 0));
  plcAst.addVariable(Variable("b", Variable::Type::Input, 1));
  plcAst.addVariable(Variable("c", Variable::Type::Input, 2));

  std::unique_ptr<plc::Expression> expression(new plc::Expression());

  BOOST_CHECK(!*expression);

  plcParser.parseExpressionMock(expression);
  BOOST_CHECK(*expression);
  BOOST_CHECK_EQUAL(expression->countLevels(), 1u);
}

BOOST_AUTO_TEST_CASE(PlcParser_Expression_Levels3)
{
  std::istringstream in("a | b & c;");
  ParserInput<2> parserInput(in);
  Parser<2, 3> parser(parserInput);
  PlcAst plcAst;
  PlcParserMock plcParser(parser, plcAst);

  plcAst.addVariable(Variable("a", Variable::Type::Input, 0));
  plcAst.addVariable(Variable("b", Variable::Type::Input, 1));
  plcAst.addVariable(Variable("c", Variable::Type::Input, 2));

  std::unique_ptr<plc::Expression> expression(new plc::Expression());

  BOOST_CHECK(!*expression);

  plcParser.parseExpressionMock(expression);
  BOOST_CHECK(*expression);
  BOOST_CHECK_EQUAL(expression->countLevels(), 2u);
}

BOOST_AUTO_TEST_CASE(PlcParser_Expression_Levels4)
{
  std::istringstream in("a | b & c | d;");
  ParserInput<2> parserInput(in);
  Parser<2, 3> parser(parserInput);
  PlcAst plcAst;
  PlcParserMock plcParser(parser, plcAst);

  plcAst.addVariable(Variable("a", Variable::Type::Input, 0));
  plcAst.addVariable(Variable("b", Variable::Type::Input, 1));
  plcAst.addVariable(Variable("c", Variable::Type::Input, 2));
  plcAst.addVariable(Variable("d", Variable::Type::Input, 3));

  std::unique_ptr<plc::Expression> expression(new plc::Expression());

  BOOST_CHECK(!*expression);

  plcParser.parseExpressionMock(expression);
  BOOST_CHECK(*expression);
  BOOST_CHECK_EQUAL(expression->countLevels(), 3u);
}

BOOST_AUTO_TEST_CASE(PlcParser_Expression_Levels5)
{
  std::istringstream in("(a | b) & (c | d) & (e | f);");
  ParserInput<2> parserInput(in);
  Parser<2, 3> parser(parserInput);
  PlcAst plcAst;
  PlcParserMock plcParser(parser, plcAst);

  plcAst.addVariable(Variable("a", Variable::Type::Input, 0));
  plcAst.addVariable(Variable("b", Variable::Type::Input, 1));
  plcAst.addVariable(Variable("c", Variable::Type::Input, 2));
  plcAst.addVariable(Variable("d", Variable::Type::Input, 3));
  plcAst.addVariable(Variable("e", Variable::Type::Input, 4));
  plcAst.addVariable(Variable("f", Variable::Type::Input, 5));

  std::unique_ptr<plc::Expression> expression(new plc::Expression());

  BOOST_CHECK(!*expression);

  plcParser.parseExpressionMock(expression);
  BOOST_CHECK(*expression);
  BOOST_CHECK_EQUAL(expression->countLevels(), 2u);
}

#endif

ext: cpp

max_stars_repo_name: saarbastler/plc

max_issues_repo_name: saarbastler/plc

max_forks_repo_name: saarbastler/plc


text:
   #include <boost/circular_buffer.hpp>
   #include <numeric>
   #include <assert.h>
   #include <iostream>
using namespace std;

   int main(int /*argc*/, char* /*argv*/[])
   {
      // create a circular buffer of capacity 3
      boost::circular_buffer<int> cb(20);
      boost::circular_buffer<int>::iterator it;

      // Here the reserve and capacity have the same result
      cout << "Available slots? " << cb.reserve() << endl;
      cout << "Container capacity? " << cb.capacity() << endl;

      // insert some other elements
      cb.push_back(121);
      cb.push_back(123);
      cb.push_back(1223);
      cb.push_back(1223);
      cb.push_back(1223);
      cb.push_back(1223);
      cb.push_back(1223);
      cb.push_back(1223);
      cb.push_back(123123);
      cb.push_back(1223);
      cb.push_back(123123);
      cb.push_back(123);
      cb.push_back(123123);
      cb.push_back(12);
      cb.push_back(123123);
      cb.push_back(1233);
      cb.push_back(123);
      cb.push_back(12);

      // The capacity is always the same, but reserve returns only 1
      cout << "Available slots? " << cb.reserve() << endl;
      cout << "Container capacity? " << cb.capacity() << endl;

      cb.push_back(1);

      cout << "Available slots? " << cb.reserve() << endl;

      // pop everything (and more?)
//    cb.pop_front(); //would abort code

      for(it=cb.begin(); it < cb.end(); it++)
		std::cout << *it;

      return 0;
   }

max_stars_repo_name: PFigs/portfolio

max_issues_repo_name: PFigs/portfolio

max_forks_repo_name: PFigs/portfolio


text:
/*
   Copyright 2021 The Silkworm Authors

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

#include <iomanip>
#include <iostream>
#include <string>
#include <unordered_map>

#include <CLI/CLI.hpp>
#include <boost/endian/conversion.hpp>
#include <boost/filesystem.hpp>

#include <silkworm/common/log.hpp>
#include <silkworm/db/access_layer.hpp>
#include <silkworm/db/bitmap.hpp>
#include <silkworm/db/stages.hpp>
#include <silkworm/db/tables.hpp>
#include <silkworm/etl/collector.hpp>

using namespace silkworm;

constexpr size_t kBitmapBufferSizeLimit = 256 * kMebi;

int main(int argc, char *argv[]) {
    namespace fs = boost::filesystem;

    CLI::App app{"Generates History Indexes"};

    std::string db_path{db::default_path()};
    bool full, storage;
    app.add_option("--chaindata", db_path, "Path to a database populated by Turbo-Geth", true)
        ->check(CLI::ExistingDirectory);

    app.add_flag("--full", full, "Start making history indexes from block 0");
    app.add_flag("--storage", storage, "Do history of storages");

    CLI11_PARSE(app, argc, argv);

    // Check data.mdb exists in provided directory
    fs::path db_file{fs::path(db_path) / fs::path("data.mdb")};
    if (!fs::exists(db_file)) {
        SILKWORM_LOG(LogError) << "Can't find a valid TG data file in " << db_path << std::endl;
        return -1;
    }
    fs::path datadir(db_path);
    fs::path etl_path(datadir.parent_path() / fs::path("etl-temp"));
    fs::create_directories(etl_path);
    etl::Collector collector(etl_path.string().c_str(), /* flush size */ 512 * kMebi);

    lmdb::DatabaseConfig db_config{db_path};
    db_config.set_readonly(false);
    std::shared_ptr<lmdb::Environment> env{lmdb::get_env(db_config)};
    std::unique_ptr<lmdb::Transaction> txn{env->begin_rw_transaction()};
    // We take data from header table and transform it and put it in blockhashes table
    lmdb::TableConfig changeset_config =
        storage ? db::table::kPlainStorageChangeSet : db::table::kPlainAccountChangeSet;
    lmdb::TableConfig index_config = storage ? db::table::kStorageHistory : db::table::kAccountHistory;
    const char *stage_key = storage ? db::stages::kStorageHistoryIndexKey : db::stages::kAccountHistoryKey;
    auto changeset_table{txn->open(changeset_config)};
    std::unordered_map<std::string, roaring::Roaring64Map> bitmaps;

    try {
        auto last_processed_block_number{db::stages::get_stage_progress(*txn, stage_key)};

        if (full) {
            last_processed_block_number = 0;
            txn->open(index_config, MDB_CREATE)->clear();
        }

        // Extract
        Bytes start(8, '\0');
        boost::endian::store_big_u64(&start[0], last_processed_block_number);
        MDB_val mdb_key{db::to_mdb_val(start)};
        MDB_val mdb_data;

        SILKWORM_LOG(LogInfo) << "Started " << (storage ? "Storage" : "Account") << " Index Extraction" << std::endl;

        size_t allocated_space{0};
        uint64_t block_number{0};
        int rc{changeset_table->seek(&mdb_key, &mdb_data)};  // Sets cursor to nearest key greater equal than this
        while (!rc) {                                        /* Loop as long as we have no errors*/
            std::string composite_key;
            if (storage) {
                char composite_key_array[kHashLength + kAddressLength];
                std::memcpy(&composite_key_array[0], &static_cast<uint8_t *>(mdb_key.mv_data)[8], kAddressLength);
                std::memcpy(&composite_key_array[kAddressLength], mdb_data.mv_data, kHashLength);
                composite_key = std::string(composite_key_array);
            } else {
                composite_key = std::string(static_cast<char *>(mdb_data.mv_data), kAddressLength);
            }

            if (bitmaps.find(composite_key) == bitmaps.end()) {
                bitmaps.emplace(composite_key, roaring::Roaring64Map());
            }
            block_number = boost::endian::load_big_u64(static_cast<uint8_t *>(mdb_key.mv_data));
            bitmaps.at(composite_key).add(block_number);
            allocated_space += 8;
            if (64 * bitmaps.size() + allocated_space > kBitmapBufferSizeLimit) {
                for (const auto &[key, bm] : bitmaps) {
                    Bytes bitmap_bytes(bm.getSizeInBytes(), '\0');
                    bm.write(byte_ptr_cast(bitmap_bytes.data()));
                    etl::Entry entry{Bytes(byte_ptr_cast(key.c_str()), key.size()), bitmap_bytes};
                    collector.collect(entry);
                }
                SILKWORM_LOG(LogInfo) << "Current Block: " << block_number << std::endl;
                bitmaps.clear();
                allocated_space = 0;
            }
            rc = changeset_table->get_next(&mdb_key, &mdb_data);
        }

        if (rc && rc != MDB_NOTFOUND) { /* MDB_NOTFOUND is not actually an error rather eof */
            lmdb::err_handler(rc);
        }

        for (const auto &[key, bm] : bitmaps) {
            Bytes bitmap_bytes(bm.getSizeInBytes(), '\0');
            bm.write(byte_ptr_cast(bitmap_bytes.data()));
            etl::Entry entry{Bytes(byte_ptr_cast(key.c_str()), key.size()), bitmap_bytes};
            collector.collect(entry);
        }
        bitmaps.clear();

        SILKWORM_LOG(LogInfo) << "Latest Block: " << block_number << std::endl;
        // Proceed only if we've done something
        if (collector.size()) {
            SILKWORM_LOG(LogInfo) << "Started Loading" << std::endl;

            auto target_table{txn->open(index_config, MDB_CREATE)};
            size_t target_table_rcount{0};
            lmdb::err_handler(target_table->get_rcount(&target_table_rcount));
            unsigned int db_flags{target_table_rcount ? 0u : MDB_APPEND};

            // Eventually load collected items WITH transform (may throw)
            collector.load(
                target_table.get(),
                [](etl::Entry entry, lmdb::Table *history_index_table, unsigned int db_flags) {
                    auto bm{roaring::Roaring64Map::readSafe(byte_ptr_cast(entry.value.data()), entry.value.size())};
                    Bytes last_chunk_index(entry.key.size() + 8, '\0');
                    std::memcpy(&last_chunk_index[0], &entry.key[0], entry.key.size());
                    boost::endian::store_big_u64(&last_chunk_index[entry.key.size()], UINT64_MAX);
                    auto previous_bitmap_bytes{history_index_table->get(last_chunk_index)};
                    if (previous_bitmap_bytes.has_value()) {
                        bm |= roaring::Roaring64Map::readSafe(byte_ptr_cast(previous_bitmap_bytes->data()),
                                                              previous_bitmap_bytes->size());
                        db_flags = 0;
                    }
                    while (bm.cardinality() > 0) {
                        auto current_chunk{db::bitmap::cut_left(bm, db::bitmap::kBitmapChunkLimit)};
                        // make chunk index
                        Bytes chunk_index(entry.key.size() + 8, '\0');
                        std::memcpy(&chunk_index[0], &entry.key[0], entry.key.size());
                        uint64_t suffix{bm.cardinality() == 0 ? UINT64_MAX : current_chunk.maximum()};
                        boost::endian::store_big_u64(&chunk_index[entry.key.size()], suffix);
                        Bytes current_chunk_bytes(current_chunk.getSizeInBytes(), '\0');
                        current_chunk.write(byte_ptr_cast(&current_chunk_bytes[0]));
                        history_index_table->put(chunk_index, current_chunk_bytes, db_flags);
                    }
                },
                db_flags, /* log_every_percent = */ 20);

            // Update progress height with last processed block
            db::stages::set_stage_progress(*txn, stage_key, block_number);
            lmdb::err_handler(txn->commit());

        } else {
            SILKWORM_LOG(LogInfo) << "Nothing to process" << std::endl;
        }

        SILKWORM_LOG(LogInfo) << "All Done" << std::endl;
    } catch (const std::exception &ex) {
        SILKWORM_LOG(LogError) << ex.what() << std::endl;
        return -5;
    }
    return 0;
}

max_stars_repo_name: MarcoGuarducci/silkworm

max_issues_repo_name: MarcoGuarducci/silkworm

max_forks_repo_name: MarcoGuarducci/silkworm


text:
// Copyright 2021 Yu-Kai Lin. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

#pragma once

#include <Eigen/Dense>

#include <vector>

/**
 * @brief Namespace for the KCP library.
 *
 */
namespace kcp {

/**
 * @brief Data structure for point correspondences.
 *
 */
struct Correspondences {
  /**
   * @brief Correspondences in terms of position, where the first and the second
   * parts correspond to the source and the target clouds respectively.
   *
   */
  std::pair<Eigen::Matrix3Xd, Eigen::Matrix3Xd> points;

  /**
   * @brief Correspondences in terms of point indices, where the first and the
   * second parts correspond to the source and the target clouds respectively.
   *
   */
  std::pair<std::vector<int>, std::vector<int>> indices;
};

};  // namespace kcp

ext: hpp

max_stars_repo_name: StephLin/KCP

max_issues_repo_name: StephLin/KCP

max_forks_repo_name: StephLin/KCP


text:
// Copyright 2018 dit authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <stdio.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <fstream>
#include <iostream>

#include <boost/any.hpp>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <snappy.h>

#include "dit_server_impl.h"
#include "proto/dit.pb.h"
#include "utils/common_util.h"

DECLARE_int32(server_thread_num);

namespace baidu {
namespace dit {

DitServerImpl::DitServerImpl() : pool_(FLAGS_server_thread_num) {}

DitServerImpl::~DitServerImpl() {}

template<class T, class M>
void travel_files(T it, T end_dir_it, M* message, bool opt_a) {
    for (; it != end_dir_it; ++it) {
        try {
            // skip hidden file or dir
            if (!opt_a && it->path().filename().string()[0] == '.') {
                continue;
            }

            if (boost::filesystem::is_directory(*it)) {
                proto::DitFileMeta* dit_file = message->add_files();
                dit_file->set_type(proto::kDitDirectory);
                dit_file->set_path(it->path().string() + "/");
                dit_file->set_size(4096);
                dit_file->set_perms(boost::filesystem::status(it->path()).permissions());
            }

            if (boost::filesystem::is_regular_file(*it)) {
                proto::DitFileMeta* dit_file = message->add_files();
                dit_file->set_type(proto::kDitFile);
                dit_file->set_path(it->path().string());
                dit_file->set_size(boost::filesystem::file_size(*it));
                dit_file->set_perms(boost::filesystem::status(it->path()).permissions());
            }
        } catch (const std::exception& ex ) {
            LOG(WARNING) << ex.what();
            continue;
        }
    }
}

void DitServerImpl::GetFileMeta(::google::protobuf::RpcController* controller,
                                const proto::GetFileMetaRequest* request,
                                proto::GetFileMetaResponse* response,
                                ::google::protobuf::Closure* done) {
    LOG(INFO) << "get file meta, path: " << request->path();
    if (!request->has_path()) {
        response->mutable_ret()->set_status(proto::kError);
        response->mutable_ret()->set_message("invalid param, path is required");
        done->Run();
        return;
    }

    boost::filesystem::path path(request->path());
    if (!boost::filesystem::exists(path)) {
        response->mutable_ret()->set_status(proto::kError);
        response->mutable_ret()->set_message("path: " + path.string() + " does not exist");
        done->Run();
        return;
    }

    // file
    if (boost::filesystem::is_regular_file(path)) {
        proto::DitFileMeta* dit_file = response->add_files();
        dit_file->set_perms(boost::filesystem::status(path).permissions());
        dit_file->set_path(path.string());
        dit_file->set_type(proto::kDitFile);
        dit_file->set_size(boost::filesystem::file_size(path));
        done->Run();
        return;
    }

    // symblink
    if (boost::filesystem::is_symlink(path)) {
        proto::DitFileMeta* dit_file = response->add_files();
        dit_file->set_type(proto::kDitSymlink);
        dit_file->set_path(path.string());
        dit_file->set_canonical(boost::filesystem::canonical(path).string());
        dit_file->set_size(1);
        dit_file->set_perms(boost::filesystem::status(path).permissions());
        if (!boost::algorithm::ends_with(path.string(), "/")) {
            done->Run();
            return;
        }
    }

    // directory
    if (boost::filesystem::is_directory(path)) {
        std::string dir_path = request->path();
        if (!boost::algorithm::ends_with(dir_path, "/")) {
            dir_path += "/";
        }
        // add dir self
        proto::DitFileMeta* dit_file = response->add_files();
        dit_file->set_type(proto::kDitDirectory);
        dit_file->set_path(dir_path);
        dit_file->set_size(4096);
        dit_file->set_perms(boost::filesystem::status(path).permissions());

        // parse options
        bool opt_r = false;
        bool opt_a = false;
        for (int i = 0; i < request->options_size(); i++) {
            if (proto::kOptionAll == request->options(i)) {
                opt_a = true;
            }
            if (proto::kOptionRecursive == request->options(i)) {
                opt_r = true;
            }
        }

        if (opt_r) {
            try {
                boost::filesystem::recursive_directory_iterator end_dir_it(path), it;
                travel_files(end_dir_it, it, response, opt_a);
            } catch (const std::exception& e) {
                response->mutable_ret()->set_status(proto::kError);
                response->mutable_ret()->set_message(e.what());
            }
        } else {
            try {
                boost::filesystem::directory_iterator end_dir_it(path), it;
                travel_files(end_dir_it, it, response, opt_a);
            } catch (const std::exception& e) {
                response->mutable_ret()->set_status(proto::kError);
                response->mutable_ret()->set_message(e.what());
            }
        }
    }

    done->Run();
    return;
}

void DitServerImpl::GetFileBlock(::google::protobuf::RpcController* controller,
                                 const proto::GetFileBlockRequest* request,
                                 proto::GetFileBlockResponse* response,
                                 ::google::protobuf::Closure* done) {
    // add to pool
    boost::function<void(void)> handler = boost::bind(
        &DitServerImpl::HandleGetFileBlock,
        this, controller, request, response, done);
    pool_.AddTask(handler);
    return;
}

void DitServerImpl::HandleGetFileBlock(::google::protobuf::RpcController* controller,
                                       const proto::GetFileBlockRequest* request,
                                       proto::GetFileBlockResponse* response,
                                       ::google::protobuf::Closure* done) {
    std::string path = request->block().path();
    int64_t offset = request->block().offset();
    int64_t length = request->block().length();
    VLOG(20)
       << "+++ FileBlock, file: [" << path
       << "], offset: [" << offset
       << "], length: [" << length
       << "]";

    int fd = open(path.c_str(), O_RDONLY);
    if (fd > 0) {
        char* ptr = reinterpret_cast<char*>(mmap(NULL, length, PROT_READ, MAP_SHARED, fd, offset));
        close(fd);
        std::string z_content;
        snappy::Compress(ptr, length, &z_content);
        proto::DitFileBlock* block = response->mutable_block();
        block->set_path(path);
        block->set_offset(offset);
        block->set_length(z_content.length());
        block->set_content(z_content);
        response->mutable_ret()->set_status(proto::kOk);
        VLOG(20)
            << "--- FileBlock, file: [" << path
            << "], offset: [" << offset
            << "], length: [" << length
            << "]";
        munmap(ptr, length);
    } else {
        LOG(WARNING)
           << "open file failed, file: " << path
           << ", error: " << strerror(errno);
        response->mutable_ret()->set_status(proto::kError);
        response->mutable_ret()->set_message("open file failed");
    }

    done->Run();
}

void DitServerImpl::PutFileMeta(::google::protobuf::RpcController* controller,
                                const proto::PutFileMetaRequest* request,
                                proto::PutFileMetaResponse* response,
                                ::google::protobuf::Closure* done) {
    LOG(INFO) << "put file meta, files: " << request->files_size();
    for (int i = 0; i < request->files_size(); i++) {
        const proto::DitFileMeta& file = request->files(i);
        if (proto::kDitDirectory == file.type()) {
            // create_directory
            std::string file_path = file.path();
            if (!boost::filesystem::exists(file_path)) {
                boost::filesystem::create_directory(file_path);
            }
        } else {
            std::string file_path = file.path();
            int fd = open(file_path.c_str(), O_RDWR | O_CREAT, file.perms());
            if (fd == -1) {
                fprintf(stderr, "-file open failed, file: %s, err: %s\n",
                        file_path.c_str(), strerror(errno));
                response->mutable_ret()->set_status(proto::kError);
                done->Run();
                return;
            }

            if (ftruncate(fd, file.size()) < 0) {
                close(fd);
                response->mutable_ret()->set_status(proto::kError);
                return;
            }

            if (0 == file.size()) {
                close(fd);
                response->mutable_ret()->set_status(proto::kError);
                return;
            }
        }
    }

    response->mutable_ret()->set_status(proto::kOk);
    done->Run();
}

void DitServerImpl::PutFileBlock(::google::protobuf::RpcController* controller,
                                 const proto::PutFileBlockRequest* request,
                                 proto::PutFileBlockResponse* response,
                                 ::google::protobuf::Closure* done) {
    // add to pool
    boost::function<void(void)> handler = boost::bind(
        &DitServerImpl::HandlePutFileBlock,
        this, controller, request, response, done);
    pool_.AddTask(handler);
    return;
}

void DitServerImpl::HandlePutFileBlock(::google::protobuf::RpcController* controller,
                                       const proto::PutFileBlockRequest* request,
                                       proto::PutFileBlockResponse* response,
                                       ::google::protobuf::Closure* done) {
    std::string path = request->block().path();
    int64_t offset = request->block().offset();
    int64_t length = request->block().length();
    char* ptr = NULL;
    if (file_ptrs_.find(path) != file_ptrs_.end()) {
        ptr = file_ptrs_[path];
    } else {
        int fd = open(path.c_str(), O_RDWR);
        struct stat st;
        if(stat(path.c_str(), &st) != 0) {
            close(fd);
            return;
        }

        if (fd > 0) {
            ptr = reinterpret_cast<char*>(mmap(NULL, st.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0));
            file_ptrs_[path] = ptr;
            close(fd);
        }
    }

    std::string content;
    snappy::Uncompress(request->block().content().c_str(), length, &content);
    memcpy(ptr + offset, content.c_str(), content.size());
    VLOG(20)
       << "+++ FileBlock, file: [" << path
       << "], offset: [" << offset
       << "], length: [" << content.size()
       << "]";

    response->mutable_ret()->set_status(proto::kOk);
    done->Run();
}

}  // namespace dit
}  // namespace baidu

ext: cc

max_stars_repo_name: taotaowill/dit

max_issues_repo_name: taotaowill/dit

max_forks_repo_name: taotaowill/dit


text:
#include <LIEF/PE.hpp>
#include <LIEF/logging.hpp>
#include <boost/filesystem.hpp>
#include <osquery/core/system.h>
#include <osquery/filesystem/filesystem.h>
#include <osquery/logger/logger.h>
#include <osquery/sdk/sdk.h>
#include <osquery/sql/dynamic_table_row.h>

#include <sstream>
class PeSigTable : public osquery::TablePlugin {
 private:
  osquery::TableColumns columns() const {
    return {
        std::make_tuple(
            "path", osquery::TEXT_TYPE, osquery::ColumnOptions::REQUIRED),
        std::make_tuple(
            "filename", osquery::TEXT_TYPE, osquery::ColumnOptions::DEFAULT),
        std::make_tuple("certificate_valid_from",
                        osquery::TEXT_TYPE,
                        osquery::ColumnOptions::DEFAULT),
        std::make_tuple("certificate_valid_to",
                        osquery::TEXT_TYPE,
                        osquery::ColumnOptions::DEFAULT),
        std::make_tuple("certificate_issuer",
                        osquery::TEXT_TYPE,
                        osquery::ColumnOptions::DEFAULT),
        std::make_tuple("certificate_subject",
                        osquery::TEXT_TYPE,
                        osquery::ColumnOptions::DEFAULT),
        std::make_tuple("certificate_version",
                        osquery::INTEGER_TYPE,
                        osquery::ColumnOptions::DEFAULT),
        std::make_tuple("certificate_serial_number",
                        osquery::TEXT_TYPE,
                        osquery::ColumnOptions::DEFAULT),
    };
  }

  osquery::TableRows generate(osquery::QueryContext& context) {
    auto paths = context.constraints["path"].getAll(osquery::EQUALS);

    // Expand contstraints
    context.expandConstraints(
        "path",
        osquery::LIKE,
        paths,
        ([&](const std::string& pattern, std::set<std::string>& out) {
          std::vector<std::string> patterns;
          auto status = resolveFilePattern(
              pattern, patterns, osquery::GLOB_ALL | osquery::GLOB_NO_CANON);
          if (status.ok()) {
            for (const auto& resolved : patterns) {
              out.insert(resolved);
            }
          }
          return status;
        }));
    boost::system::error_code ec;
    osquery::TableRows results;
    for (const auto& path_string : paths) {
      boost::filesystem::path path = path_string;
      if (!boost::filesystem::is_regular_file(path, ec)) {
        continue;
      }
      try {
        // Skip non-pe files
        if (!LIEF::PE::is_pe(path_string)) {
          continue;
        }
        std::unique_ptr<LIEF::PE::Binary> pe_binary =
            LIEF::PE::Parser::parse(path_string);
        if (!pe_binary->has_signatures()) {
          continue;
        }

        auto sig = pe_binary->signatures();

        // Get Signature info from PE file
        for (const auto& certs : sig->certificates()) {
          auto r = osquery::make_table_row();
          r["path"] = path_string;
          r["filename"] = path.filename().string();
          r["certificate_issuer"] = certs.issuer();
          r["certificate_subject"] = certs.subject();
          std::string valid_from = "";
          for (int dates = 0; dates < certs.valid_from().size(); dates++) {
            if (dates > 2) {
              valid_from += std::to_string(certs.valid_from()[dates]) + ":";
              continue;
            }
            if (dates == 2) {
              valid_from += std::to_string(certs.valid_from()[dates]) + " ";
              continue;
            }
            valid_from += std::to_string(certs.valid_from()[dates]) + "-";
          }
          valid_from.pop_back();
          r["certificate_valid_from"] = valid_from;
          std::string valid_to = "";
          for (int dates = 0; dates < certs.valid_to().size(); dates++) {
            if (dates > 2) {
              valid_to += std::to_string(certs.valid_to()[dates]) + ":";
              continue;
            }
            if (dates == 2) {
              valid_to += std::to_string(certs.valid_to()[dates]) + " ";
              continue;
            }
            valid_to += std::to_string(certs.valid_to()[dates]) + "-";
          }
          valid_to.pop_back();
          r["certificate_valid_to"] = valid_to;
          r["certificate_version"] = osquery::INTEGER(certs.version());
          std::string serial = "";
          for (const auto& serial_num : certs.serial_number()) {
            std::ostringstream stream;
            stream << std::hex << (int)serial_num;
            serial += stream.str() + ":";
          }
          serial.pop_back();
          r["certificate_serial_number"] = serial;
          results.push_back(std::move(r));
        }
      } catch (std::exception& error) {
        LOG(WARNING) << "Failed to parse PE file: " << error.what();
      }
    }
    return results;
  }
};

REGISTER_EXTERNAL(PeSigTable, "table", "pe_sig");

max_stars_repo_name: puffyCid/lief-osquery

max_issues_repo_name: puffyCid/lief-osquery

max_forks_repo_name: puffyCid/lief-osquery


text:
////////////////////////////////////////////////////////////////////////////////
// Name:      link.cpp
// Purpose:   Implementation of class wex::link
// Author:    Anton van Wezenbeek
// Copyright: (c) 2021-2022 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////

#include <boost/algorithm/string.hpp>
#include <wex/core/config.h>
#include <wex/core/core.h>
#include <wex/core/path.h>
#include <wex/core/regex.h>
#include <wex/factory/lexer.h>
#include <wex/factory/link.h>
#include <wex/factory/stc.h>

#include <algorithm>

namespace wex::factory
{
class paths
{
public:
  paths()
    : m_paths(config(_("stc.link.Include directory")).get(config::strings_t()))
  {
    ;
  };

  bool add_path(const path& p)
  {
    if (p.dir_exists() && !find(p))
    {
      m_paths.emplace_back(p.string());
      return true;
    }

    return false;
  }

  path find(const std::string& path) const
  {
    for (const auto& it : m_paths)
    {
      if (const wex::path valid(wex::path(it), path); valid.file_exists())
      {
        return valid;
      }
    }

    return wex::path();
  };

  bool find(const path& p) const
  {
    return std::any_of(
      m_paths.begin(),
      m_paths.end(),
      [p](const auto& it)
      {
        return p.string() == it;
      });
  };

private:
  config::strings_t m_paths;
};
}; // namespace wex::factory

wex::factory::link::link()
  : m_paths(std::make_unique<paths>())
{
}

wex::factory::link::~link() {}

bool wex::factory::link::add_path(const path& p)
{
  return m_paths->add_path(p);
}

void wex::factory::link::config_get()
{
  m_paths.reset();
  m_paths = std::make_unique<paths>();
}

const wex::path wex::factory::link::find_between(
  const std::string& text,
  factory::stc*      stc) const
{
  if (text.empty())
  {
    return path();
  }

  // Path in po files.
  if (regex v("#: "); stc != nullptr &&
                      stc->get_lexer().scintilla_lexer() == "po" &&
                      v.search(text) > 0)
  {
    return path(v[0]);
  }

  // Path in bash files.
  if (regex v("^source (.*)"); stc != nullptr &&
                               stc->get_lexer().scintilla_lexer() == "bash" &&
                               v.search(text) > 0)
  {
    return path(v[0]);
  }

  // Path in git status.
  if (regex v(": +(.*)"); stc != nullptr &&
                          stc->get_lexer().scintilla_lexer().empty() &&
                          v.search(text) > 0)
  {
    return path(v[0]);
  }

  if (const auto& lp = get_link_pairs(text); !lp.empty())
  {
    return path(lp);
  }

  return path(boost::algorithm::trim_copy(text));
}

const wex::path wex::factory::link::find_filename(
  const std::string& text,
  line_data&         data) const
{
  if (text.empty())
  {
    return path();
  }

  std::string text_filter(text);

  // The harddrive letter is filtered, it does not work
  // when adding it to match.
  std::string prefix;

#ifdef __WXMSW__
  if (
    text_filter.size() > 1 && isalpha(text_filter[0]) && text_filter[1] == ':')
  {
    prefix      = text_filter.substr(0, 1);
    text_filter = text_filter.substr(2);
  }
#endif

  // file[:line[:column]]
  // the first is to match file names without spaces,
  // to match xx ./vnc.env.sh yy
  const regex::regex_v_t t(
    {"(\\.[\\0-9A-Za-z_/.-]+) .*",
     "^([\\0-9A-Za-z _/.-]+):([0-9]*):?([0-9]*)"});

  if (regex v(t); v.search(text_filter) > 0)
  {
    const auto& link(v.which_no() == 0 ? find_before(v[0], " ") : v[0]);

    data.reset();

    if (v.size() > 1 && !v[1].empty())
    {
      data.line(std::stoi(v[1]));

      if (v.size() > 2 && !v[2].empty())
      {
        data.col(std::stoi(v[2]));
      }
    }

    path p(boost::algorithm::trim_copy(prefix + link));

    if (const path q(find_before(p.string(), ":")); q.file_exists())
    {
      return p.make_absolute();
    }
    else if (const path r(m_paths->find(q.string())); !r.empty())
    {
      return r;
    }
  }

  return path();
}

const wex::path wex::factory::link::find_url_or_mime(
  const std::string& text,
  const line_data&   data,
  factory::stc*      stc) const
{
  if (!text.empty())
  {
    // hypertext link
    if (regex v({{"(https?:.*)"}, {"(www.*)"}});
        data.line() == LINE_OPEN_URL && v.search(text) > 0)
    {
      // with a possible delimiter
      const auto        match(v[0]);
      const std::string delimiters("\")]");

      for (const auto& c : delimiters)
      {
        if (const auto pos = match.find(c); pos != std::string::npos)
        {
          return path(match.substr(0, pos));
        }
      }

      // without delimiter
      return path(match);
    }
  }

  // previewable (MIME) file
  return (stc != nullptr && stc->get_lexer().is_previewable()) ? stc->path() :
                                                                 path();
}

// text contains selected text, or current line
const wex::path wex::factory::link::get_path(
  const std::string& text,
  line_data&         data,
  factory::stc*      stc)
{
  // mime or url
  if (data.line() == LINE_OPEN_MIME || data.line() == LINE_OPEN_URL)
  {
    return find_url_or_mime(text, data, stc);
  }

  // if text starts with file:[line[:col]]
  if (const auto& p(find_filename(text, data)); !p.empty())
  {
    return p;
  }

  // if we have something in between
  const auto& between(find_between(text, stc));

  // if between text now starts with file:line:no
  if (const auto& p(find_filename(between.string(), data)); !p.empty())
  {
    return p;
  }

  // if text is a file somewhere on the search paths
  if (const auto& p(m_paths->find(between.string())); !p.empty())
  {
    return p;
  }

  // if text now exists, or exists in the stc directory
  if (wex::path file(between); file.file_exists())
  {
    return file.make_absolute();
  }
  else if (file.is_relative() && stc != nullptr && stc->path().file_exists())
  {
    if (wex::path path(stc->path().parent_path());
        path.append(file).file_exists())
    {
      return path.make_absolute();
    }
  }

  // if last word is a file
  const auto pos = between.string().find_last_of(' ');

  if (wex::path word(boost::algorithm::trim_copy(
        (pos != std::string::npos ? between.string().substr(pos) :
                                    std::string())));
      !word.empty())
  {
    if (word.file_exists())
    {
      data.reset();
      return word.make_absolute();
    }

    if (const auto& p(find_filename(word.string(), data)); !p.empty())
    {
      return p;
    }
  }

  return path();
}

max_stars_repo_name: antonvw/wxExtension

max_issues_repo_name: antonvw/wxExtension

max_forks_repo_name: antonvw/wxExtension


text:
// Copyright 2015-2021 Tier IV, Inc. All rights reserved.
//
// 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.
//
// Co-developed by Tier IV, Inc. and Robotec.AI sp. z o.o.

#ifndef RANDOM_TEST_RUNNER__GOAL_REACHED_METRIC_H
#define RANDOM_TEST_RUNNER__GOAL_REACHED_METRIC_H

#include <boost/optional.hpp>
#include <iostream>

#include "geometry_msgs/msg/pose.hpp"
#include "random_test_runner/data_types.hpp"
#include "traffic_simulator_msgs/msg/entity_status.hpp"

class GoalReachedMetric
{
public:
  bool isGoalReached(const traffic_simulator_msgs::msg::EntityStatus & status)
  {
    if (!goal_pose_) {
      return false;
    }

    geometry_msgs::msg::Point current_position = status.pose.position;
    geometry_msgs::msg::Point goal_position = goal_pose_->position;

    if (distance(current_position, goal_position) < goal_reaching_accuracy_threshold_) {
      return true;
    }

    return false;
  }

  void setGoal(const geometry_msgs::msg::Pose & goal_pose) { goal_pose_ = goal_pose; }

private:
  const double goal_reaching_accuracy_threshold_ = 3.0;

  boost::optional<geometry_msgs::msg::Pose> goal_pose_;

  static double distance(
    const geometry_msgs::msg::Point & lhs, const geometry_msgs::msg::Point & rhs)
  {
    geometry_msgs::msg::Point diff;
    diff.x = lhs.x - rhs.x;
    diff.y = lhs.y - rhs.y;
    diff.z = lhs.z - rhs.z;
    return std::sqrt(diff.x * diff.x + diff.y * diff.y + diff.z * diff.z);
  }
};

#endif  // RANDOM_TEST_RUNNER__GOAL_REACHED_METRIC_H


text:
/*

Copyright (c) 2018, Brian Bingham
All rights reserved

This file is part of the usv_gazebo_dynamics_plugin package, known as this Package.

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

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

You should have received a copy of the GNU General Public License
along with this package.  If not, see <http://www.gnu.org/licenses/>.

*/

#ifndef USV_GAZEBO_WIND_H
#define USV_GAZEBO_WIND_H

// Gazebo
#include <gazebo/common/common.hh>
#include <gazebo/physics/physics.hh>
//#include <gazebo_plugins/gazebo_ros_utils.h>

//ROS
#include <nav_msgs/Odometry.h>
#include <geometry_msgs/TwistWithCovariance.h>
#include <geometry_msgs/PoseWithCovariance.h>

#include <Eigen/Core>
				    //#include <tf/transform_broadcaster.h>
#include <ros/ros.h>

// Custom Callback Queue
#include <ros/callback_queue.h>
#include <ros/advertise_options.h>

namespace gazebo
{
  class UsvWindPlugin : public ModelPlugin
  {
  public:
    UsvWindPlugin();
    virtual ~UsvWindPlugin();
    /*! Loads the model in gets dynamic parameters from SDF. */
    virtual void Load(physics::ModelPtr _parent, sdf::ElementPtr _sdf);
  protected:
    /*! Callback for Gazebo simulation engine */
    virtual void UpdateChild();
    virtual void FiniChild();
  private:

    double getSdfParamDouble(sdf::ElementPtr sdfPtr, const std::string &param_name, double default_val);

    /*! ROS spin once */
    void spin();

    /// Parameters
    std::string node_namespace_;
    std::string link_name_;

    ros::NodeHandle *rosnode_;

    //GazeboRosPtr gazebo_ros_;
    //physics::ModelPtr parent;
    event::ConnectionPtr update_connection_;

    /*! Pointer to the Gazebo world, retrieved when the model is loaded */
    physics::WorldPtr world_;
    /*! Pointer to Gazebo parent model, retrieved when the model is loaded */
    physics::ModelPtr model_;
    /*! Pointer to model link in gazebo,
      optionally specified by the bodyName parameter,
      The states are taken from this link and forces applied to this link.*/
    physics::LinkPtr link_;

    /*! Wind velocity in Gazebo coordinates [m/s] */
    math::Vector3 param_wind_velocity_vector_;

    /*! Wind force coefficients */
    math::Vector3 param_wind_coeff_vector_;

    boost::thread *spinner_thread_;

    event::ConnectionPtr contact_event_;

    // Pointer to the update event connection
    event::ConnectionPtr updateConnection;

  };  // class UsvWindPlugin
} // namespace gazebo

#endif //USV_GAZEBO_WIND_H

ext: hh


text:
#include "crypt/base64.h"
#include "crypt/hmac.h"
#include "crypt/sha1.h"
#include <alibabacloud/open_api_util.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/any.hpp>
#include <darabonba/core.hpp>
#include <darabonba/util.hpp>
#include <iostream>
#include <map>

using namespace std;
using namespace Alibabacloud_OpenApiUtil;

void Alibabacloud_OpenApiUtil::Client::convert(
    shared_ptr<Darabonba::Model> body, shared_ptr<Darabonba::Model> content) {
  map<string, boost::any> props;
  map<std::string, boost::any> properties = body->toMap();
  for (const auto &it : properties) {
    if (typeid(Darabonba::Stream) != it.second.type()) {
      props[it.first] = it.second;
    }
  }
  content->fromMap(props);
}

string get_canonicalized_headers(map<string, string> headers) {
  string canon_header;
  for (const auto &i : headers) {
    if (boost::starts_with(i.first, "x-acs-")) {
      canon_header.append(i.first).append(":").append(i.second).append("\n");
    }
  }
  return canon_header;
}

string get_canonicalized_resource(string pathname, map<string, string> query) {
  if (query.empty()) {
    return pathname;
  }
  string resource = pathname + "?";
  for (const auto &i : query) {
    if (i.second.empty()) {
      resource.append(i.first).append("&");
    } else {
      resource.append(i.first).append("=").append(i.second).append("&");
    }
  }
  return resource.substr(0, resource.size() - 1);
}

string Alibabacloud_OpenApiUtil::Client::getStringToSign(
    shared_ptr<Darabonba::Request> request) {
  if (!request) {
    return "";
  }
  string method = request->method;
  string pathname = request->pathname;
  map<string, string> headers = request->headers;
  map<string, string> query = request->query;
  string accept = headers["accept"];
  string content_md5 = headers["content-md5"];
  string content_type = headers["content-type"];
  string date = headers["date"];

  string sign_str;
  sign_str.append(method)
      .append("\n")
      .append(accept)
      .append("\n")
      .append(content_md5)
      .append("\n")
      .append(content_type)
      .append("\n")
      .append(date)
      .append("\n");

  return sign_str.append(get_canonicalized_headers(headers))
      .append(get_canonicalized_resource(pathname, query));
}

string Alibabacloud_OpenApiUtil::Client::getROASignature(
    shared_ptr<string> stringToSign, shared_ptr<string> secret) {
  boost::uint8_t hash_val[sha1::HASH_SIZE];
  hmac<sha1>::calc(*stringToSign, *secret, hash_val);
  return base64::encode_from_array(hash_val, sha1::HASH_SIZE);
}

void flatten(map<string, string> &res, std::string prefix, boost::any curr) {
  if (typeid(map<string, boost::any>) == curr.type()) {
    map<string, boost::any> m = boost::any_cast<map<string, boost::any>>(curr);
    for (const auto &it : m) {
      std::string p;
      if (prefix.empty()) {
        p = prefix + it.first;
      } else {
        p = prefix + "." + it.first;
      }
      flatten(res, p, it.second);
    }
  } else if (typeid(vector<boost::any>) == curr.type()) {
    vector<boost::any> v = boost::any_cast<vector<boost::any>>(curr);
    int n = 0;
    for (const auto &it : v) {
      std::string p;
      if (prefix.empty()) {
        p = prefix + to_string(n + 1);
      } else {
        p = prefix + "." + to_string(n + 1);
      }
      flatten(res, p, it);
      n++;
    }
  } else {
    if (typeid(string) == curr.type()) {
      std::string v = boost::any_cast<string>(curr);
      res.insert(pair<string, string>(prefix, v));
    } else if (typeid(int) == curr.type()) {
      string v = std::to_string(boost::any_cast<int>(curr));
      res.insert(pair<string, string>(prefix, v));
    } else if (typeid(long) == curr.type()) {
      string v = std::to_string(boost::any_cast<long>(curr));
      res.insert(pair<string, string>(prefix, v));
    } else if (typeid(double) == curr.type()) {
      string v = std::to_string(boost::any_cast<double>(curr));
      res.insert(pair<string, string>(prefix, v));
    } else if (typeid(float) == curr.type()) {
      string v = std::to_string(boost::any_cast<float>(curr));
      res.insert(pair<string, string>(prefix, v));
    } else if (typeid(bool) == curr.type()) {
      auto b = boost::any_cast<bool>(curr);
      string v = b ? "true" : "false";
      res.insert(pair<string, string>(prefix, v));
    } else if (typeid(const char *) == curr.type()) {
      const char *v = boost::any_cast<const char *>(curr);
      res.insert(pair<string, string>(prefix, v));
    } else if (typeid(char *) == curr.type()) {
      char *v = boost::any_cast<char *>(curr);
      res.insert(pair<string, string>(prefix, v));
    }
  }
}

string Alibabacloud_OpenApiUtil::Client::toForm(
    shared_ptr<map<string, boost::any>> filter) {
  if (!filter) {
    return "";
  }
  map<string, string> flat;
  flatten(flat, string(""), boost::any(*filter));
  map<string, string> res;
  for (auto it : flat) {
    res.insert(pair<string, string>(it.first, it.second));
  }

  return Darabonba_Util::Client::toFormString(
      make_shared<map<string, boost::any>>(
          Darabonba_Util::Client::anyifyMapValue(
              make_shared<map<string, string>>(res))));
}

string Alibabacloud_OpenApiUtil::Client::getTimestamp() {
  char buf[80];
  time_t t = time(nullptr);
  std::strftime(buf, sizeof buf, "%Y-%m-%dT%H:%M:%SZ", gmtime(&t));
  return buf;
}

map<string, string> Alibabacloud_OpenApiUtil::Client::query(
    shared_ptr<map<string, boost::any>> filter) {
  if (!filter) {
    return map<string, string>();
  }
  map<string, string> flat;
  flatten(flat, string(""), boost::any(*filter));
  map<string, string> res;
  for (auto it : flat) {
    res.insert(pair<string, string>(it.first, it.second));
  }

  return res;
}

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

string url_encode(const std::string &str) {
  std::stringstream escaped;
  escaped.fill('0');
  escaped << hex;

  for (char c : str) {
    if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
      escaped << c;
      continue;
    }
    escaped << std::uppercase;
    escaped << '%' << std::setw(2) << int((unsigned char)c);
    escaped << nouppercase;
  }

  return escaped.str();
}

std::string implode(const std::vector<std::string> &vec,
                    const std::string &glue) {
  string res;
  int n = 0;
  for (const auto &str : vec) {
    if (n == 0) {
      res = str;
    } else {
      res += glue + str;
    }
    n++;
  }
  return res;
}

std::string strToSign(std::string method, const map<string, string> &query) {
  std::vector<string> tmp;
  for (const auto &it : query) {
    std::string s;
    s = s.append(url_encode(it.first))
            .append("=")
            .append(url_encode(it.second));
    tmp.push_back(s);
  }
  std::string str = implode(tmp, "&");
  std::string res;
  return res.append(uppercase(std::move(method)))
      .append("&%2F&")
      .append(url_encode(str));
}

string Alibabacloud_OpenApiUtil::Client::getRPCSignature(
    shared_ptr<map<string, string>> signedParams, shared_ptr<string> method,
    shared_ptr<string> secret) {
  map<string, string> sp;
  if (!signedParams) {
    sp = map<string, string>();
  } else {
    sp = *signedParams;
  }
  string m = !method ? "" : *method;
  string s = !secret ? "" : *secret;

  std::string str = strToSign(std::move(m), sp);
  s = s + "&";
  boost::uint8_t hash_val[sha1::HASH_SIZE];
  hmac<sha1>::calc(str, s, hash_val);
  return base64::encode_from_array(hash_val, sha1::HASH_SIZE);
}

string flat_repeat_vec(vector<boost::any> arr, string prefix) {
  map<string, string> flat;
  map<string, boost::any> m = {{prefix, arr}};
  flatten(flat, string(""), boost::any(m));

  vector<string> vec;
  for (const auto &i : flat) {
    vec.push_back(url_encode(i.first) + "=" + url_encode(i.second));
  }
  return boost::join(vec, "&&");
}

string flat_vec(vector<boost::any> arr, string sep) {
  vector<string> str_arr;
  for (auto i : arr) {
    if (typeid(int) == i.type()) {
      str_arr.push_back(to_string(boost::any_cast<int>(i)));
    } else if (typeid(long) == i.type()) {
      str_arr.push_back(to_string(boost::any_cast<long>(i)));
    } else if (typeid(string) == i.type()) {
      str_arr.push_back(boost::any_cast<string>(i));
    } else if (typeid(double) == i.type()) {
      str_arr.push_back(to_string(boost::any_cast<double>(i)));
    } else if (typeid(bool) == i.type()) {
      auto b = boost::any_cast<bool>(i);
      string v = b ? "true" : "false";
      str_arr.push_back(v);
    } else if (typeid(const char *) == i.type()) {
      str_arr.push_back(boost::any_cast<const char *>(i));
    } else if (typeid(char *) == i.type()) {
      str_arr.push_back(boost::any_cast<char *>(i));
    }
  }
  return boost::join(str_arr, sep);
}

string Alibabacloud_OpenApiUtil::Client::arrayToStringWithSpecifiedStyle(
    const boost::any &array, shared_ptr<string> prefix,
    shared_ptr<string> style) {
  string result;
  if (typeid(shared_ptr<vector<boost::any>>) == array.type()) {
    shared_ptr<vector<boost::any>> vec_ptr =
        boost::any_cast<shared_ptr<vector<boost::any>>>(array);
    if (!style || !vec_ptr) {
      return result;
    }

    if (*style == "repeatList") {
      return result = flat_repeat_vec(*vec_ptr, *prefix);
    } else if (*style == "simple") {
      return result = flat_vec(*vec_ptr, ",");
    } else if (*style == "spaceDelimited") {
      return result = flat_vec(*vec_ptr, " ");
      ;
    } else if (*style == "pipeDelimited") {
      return result = flat_vec(*vec_ptr, "|");
      ;
    } else if (*style == "json") {
      return result = Darabonba_Util::Client::toJSONString(array);
    }
    return result;
  }
  return "";
}

std::vector<std::string> explode(const std::string &str,
                                 const std::string &delimiter) {
  int pos = str.find(delimiter, 0);
  int pos_start = 0;
  int split_n = pos;
  string line_text(delimiter);

  std::vector<std::string> dest;

  while (pos > -1) {
    line_text = str.substr(pos_start, split_n);
    pos_start = pos + 1;
    pos = str.find(delimiter, pos + 1);
    split_n = pos - pos_start;
    dest.push_back(line_text);
  }
  line_text = str.substr(pos_start, str.length() - pos_start);
  dest.push_back(line_text);
  return dest;
}

string
Alibabacloud_OpenApiUtil::Client::getEndpoint(shared_ptr<string> endpoint,
                                              shared_ptr<bool> serverUse,
                                              shared_ptr<string> endpointType) {
  string e = !endpoint ? "" : *endpoint;
  bool s;
  if (!serverUse) {
    s = false;
  } else {
    s = *serverUse;
  }
  string et = !endpointType ? "" : *endpointType;
  if (et == string("internal")) {
    std::vector<std::string> tmp = explode(e, ".");
    tmp.at(0) = tmp.at(0).append("-internal");
    e = implode(tmp, ".");
  }
  if (s && et == string("accelerate")) {
    e = "oss-accelerate.aliyuncs.com";
  }
  return e;
}

max_stars_repo_name: vicsdf/darabonba-openapi-util

max_issues_repo_name: vicsdf/darabonba-openapi-util

max_forks_repo_name: vicsdf/darabonba-openapi-util


text:
#include "sigen/toolbox/toolbox.h"
#include "sigen/common/disjoint_set.h"
#include "sigen/common/math.h"
#include <algorithm>
#include <boost/foreach.hpp>
#include <boost/scoped_array.hpp>
#include <cmath>
#include <functional>
#include <iostream>
#include <kdtree/kdtree.h>
#include <limits>
#include <map>
#include <queue>
#include <set>
#include <utility>
#include <vector>
namespace sigen {
static double norm2(
    const NeuronNodePtr &a,
    const NeuronNodePtr &b) {
  const double dx = std::abs(a->gx_ - b->gx_);
  const double dy = std::abs(a->gy_ - b->gy_);
  const double dz = std::abs(a->gz_ - b->gz_);
  return std::sqrt(dx * dx + dy * dy + dz * dz);
}

// N = left.NumNodes()
// M = right.NumNodes()
// O(N*M)
static std::pair<double, std::pair<int, int> > normNeuronFastPath(const Neuron &left, const Neuron &right) {
  int l, r;
  double minimum = std::numeric_limits<double>::max();
  for (int i = 0; i < (int)left.NumNodes(); ++i) {
    for (int j = 0; j < (int)right.NumNodes(); ++j) {
      double d = norm2(left.storage_[i], right.storage_[j]);
      if (minimum > d) {
        minimum = d;
        l = i;
        r = j;
      }
    }
  }
  return std::make_pair(minimum, std::make_pair(l, r));
}

// N = left.NumNodes()
// M = right.NumNodes()
// O((N + M) log N)
// Use https://github.com/jtsiomb/kdtree
static std::pair<double, std::pair<int, int> > normNeuronSlowPath(const Neuron &left, const Neuron &right) {
  kdtree *tree = kd_create(3);

  boost::scoped_array<int> indexes(new int[left.NumNodes()]);
  for (int i = 0; i < (int)left.NumNodes(); ++i) {
    indexes[i] = i;
    kd_insert3(
        tree,
        left.storage_[i]->gx_,
        left.storage_[i]->gy_,
        left.storage_[i]->gz_,
        &indexes[i]);
  }

  int l, r;
  double minimum = std::numeric_limits<double>::max();
  for (int j = 0; j < (int)right.NumNodes(); ++j) {
    kdres *set = kd_nearest3(
        tree,
        right.storage_[j]->gx_,
        right.storage_[j]->gy_,
        right.storage_[j]->gz_);
    int i = *(int *)kd_res_item_data(set);
    kd_res_free(set);
    double d = norm2(left.storage_[i], right.storage_[j]);
    if (minimum > d) {
      minimum = d;
      l = i;
      r = j;
    }
  }

  kd_free(tree);
  return std::make_pair(minimum, std::make_pair(l, r));
}

static std::pair<double, std::pair<int, int> > normNeuron(const Neuron &left, const Neuron &right) {
  assert(!left.IsEmpty());
  assert(!right.IsEmpty());
  if (std::min(left.NumNodes(), right.NumNodes()) >= 300) {
    return normNeuronSlowPath(left, right);
  } else {
    return normNeuronFastPath(left, right);
  }
}

std::vector<Neuron> Interpolate(const std::vector<Neuron> &input, const double dt, const int vt) {
  const int N = input.size();
  std::vector<Neuron> forest;
  for (int i = 0; i < N; ++i) {
    forest.push_back(input[i].Clone());
  }
  DisjointSet<int> set;
  std::vector<bool> is_not_small(forest.size(), false);
  for (int i = 0; i < N; ++i) {
    if (forest[i].NumNodes() >= vt) {
      set.Add(i);
      is_not_small[i] = true;
    }
  }
  set.SetUp();

  typedef std::pair<double, std::pair<int, int> > priorityQueueNode;
  std::priority_queue<
      priorityQueueNode,
      std::vector<priorityQueueNode>,
      std::greater<priorityQueueNode> >
      pq;

  std::vector<std::map<int, double> > distance(N);

  for (int i = 0; i < N; ++i) {
    if (is_not_small[i]) {
      for (int j = i + 1; j < N; ++j) {
        if (is_not_small[j]) {
          assert(i != j);
          double d = normNeuron(forest[i], forest[j]).first;
          if (d <= dt) {
            pq.push(std::make_pair(d, std::make_pair(i, j)));
            distance[i][j] = d;
            distance[j][i] = d;
          }
        }
      }
    }
  }
  while (!pq.empty()) {
    priorityQueueNode node = pq.top();
    pq.pop();
    int l = node.second.first;
    int r = node.second.second;
    if (forest[l].IsEmpty())
      continue;
    if (forest[r].IsEmpty())
      continue;
    if (set.IsSame(l, r))
      continue;
    std::pair<double, std::pair<int, int> > dist = normNeuron(forest[l], forest[r]);
    set.Merge(l, r);
    forest[l].ConnectToOtherNeuron(dist.second.first, forest[r], dist.second.second);
    forest[r].ConnectToOtherNeuron(dist.second.second, forest[l], dist.second.first);
    forest[l].Extend(forest[r]);
    forest[r].Clear();

    for (std::map<int, double>::iterator it = distance[r].begin(); it != distance[r].end(); ++it) {
      int i = it->first;
      double d = it->second;
      assert(is_not_small[i]);
      if (set.IsSame(l, i) == false && forest[i].IsEmpty() == false) {
        if (distance[l].count(i)) {
          distance[l][i] = std::min(distance[l][i], d);
        } else {
          distance[l][i] = d;
        }

        if (distance[i].count(l)) {
          distance[i][l] = std::min(distance[i][l], d);
        } else {
          distance[i][l] = d;
        }

        pq.push(std::make_pair(d, std::make_pair(l, i)));
      }
    }
  }
  for (int i = 0; i < (int)forest.size(); ++i) {
    if (forest[i].IsEmpty()) {
      forest.erase(forest.begin() + i);
      i--;
    }
  }
  return forest;
}

struct PointAndRadius {
  double gx_, gy_, gz_, radius_;
  void setCoord(const double gx, const double gy, const double gz) {
    gx_ = gx;
    gy_ = gy;
    gz_ = gz;
  }
};

std::vector<Neuron> Smoothing(const std::vector<Neuron> &input, const int n_iter) {
  std::vector<Neuron> forest;
  for (int i = 0; i < (int)input.size(); ++i) {
    forest.push_back(input[i].Clone());
  }
  for (int iter = 0; iter < n_iter; ++iter) {
    std::map<int, PointAndRadius> next_value;
    for (int i = 0; i < (int)forest.size(); ++i) {
      BOOST_FOREACH (NeuronNodePtr node, forest[i].storage_) {
        std::vector<double> gx, gy, gz, radius;
        gx.push_back(node->gx_);
        gy.push_back(node->gy_);
        gz.push_back(node->gz_);
        radius.push_back(node->radius_);
        BOOST_FOREACH (NeuronNode *adj, node->adjacent_) {
          gx.push_back(adj->gx_);
          gy.push_back(adj->gy_);
          gz.push_back(adj->gz_);
          radius.push_back(adj->radius_);
        }
        PointAndRadius next_node;
        next_node.setCoord(Mean(gx), Mean(gy), Mean(gz));
        next_node.radius_ = Mean(radius);
        next_value[node->id_] = next_node;
      }
    }
    for (int i = 0; i < (int)forest.size(); ++i) {
      BOOST_FOREACH (NeuronNodePtr node, forest[i].storage_) {
        PointAndRadius next_node = next_value[node->id_];
        node->setCoord(next_node.gx_, next_node.gy_, next_node.gz_);
        node->radius_ = next_node.radius_;
      }
    }
  }
  return forest;
}

// return max_height
static int clippingDfs(
    NeuronNode *node,
    NeuronNode *parent,
    const int level,
    std::set<int> &will_remove,
    std::map<NeuronNode *, int> &memo) {
  if (memo.count(node))
    return memo[node];
  if (node->CountNumChild(parent) < 2) {
    // If count_num_child == 1
    BOOST_FOREACH (NeuronNode *next, node->adjacent_) {
      if (next != parent) {
        return memo[node] = clippingDfs(next, node, level, will_remove, memo) + 1;
      }
    }
    // If count_num_child == 0
    return 1;
  }
  int has_longpath = 0;
  BOOST_FOREACH (NeuronNode *next, node->adjacent_) {
    if (next != parent) {
      int depth = clippingDfs(next, node, level, will_remove, memo);
      if (depth > level)
        has_longpath = true;
    }
  }
  if (has_longpath) {
    int maxdepth = 0;
    BOOST_FOREACH (NeuronNode *next, node->adjacent_) {
      if (next != parent) {
        int depth = clippingDfs(next, node, level, will_remove, memo);
        if (depth <= level) {
          will_remove.insert(next->id_);
        }
        maxdepth = std::max(maxdepth, depth);
      }
    }
    return memo[node] = maxdepth + 1;
  } else {
    int maxdepth = 0;
    NeuronNode *longest_child = NULL;
    BOOST_FOREACH (NeuronNode *next, node->adjacent_) {
      if (next != parent) {
        int depth = clippingDfs(next, node, level, will_remove, memo);
        if (maxdepth < depth) {
          maxdepth = depth;
          longest_child = next;
        }
      }
    }
    if (maxdepth > 0) {
      BOOST_FOREACH (NeuronNode *next, node->adjacent_) {
        if (next != parent && next != longest_child) {
          will_remove.insert(next->id_);
        }
      }
    }
    return memo[node] = maxdepth + 1;
  }
}

std::vector<Neuron> Clipping(const std::vector<Neuron> &input, const int level) {
  std::set<int> will_remove;
  std::vector<Neuron> forest;
  std::map<NeuronNode *, int> memo;
  for (int i = 0; i < (int)input.size(); ++i) {
    forest.push_back(input[i].Clone());
    clippingDfs(forest[i].get_root(), NULL, level, will_remove, memo);
  }
  for (int i = 0; i < (int)forest.size(); ++i) {
    forest[i].RemoveConnections(will_remove);
  }
  return forest;
}
} // namespace sigen


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 <utility>
#include <cmath>
// #include <boost/test/minimal.hpp>

#include <boost/numeric/mtl/mtl.hpp>
#include <boost/numeric/itl/itl.hpp>

using namespace std;

template <typename Vector>
struct f_test
{
    f_test() : s(3)
    {
	mtl::vec::inserter<Vector> ins(s);
	ins[0] << 1; ins[1] << 2; ins[2] << 2;
    }

    typename mtl::Collection<Vector>::value_type
    operator() (const Vector& x) const
    {
	return dot(s, Vector(ele_prod(x, x)));
    }
    Vector s;
};

template <typename Vector>
struct grad_f_test
{
    grad_f_test() : s(3)
    {
	mtl::vec::inserter<Vector> ins(s);
	ins[0] << 2; ins[1] << 4; ins[2] << 4;
    }

    Vector operator() (const Vector& x) const {  return Vector(ele_prod(s, x)); }
    Vector s;
};

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

    mtl::dense_vector<double>       x(3, 8);
    tout << "x= " << x << "\n";

    grad_f_test<mtl::dense_vector<double> > grad_f;
    f_test<mtl::dense_vector<double> >      f;

    itl::cyclic_iteration<double>  iter(grad_f(x), 1000, 0, 1e-4, 100);
    itl::cyclic_iteration<double> iter1(grad_f(x), 1000, 0, 1e-4, 100);
    itl::cyclic_iteration<double> iter2(grad_f(x), 1000, 0, 1e-4, 100);
    itl::cyclic_iteration<double> iter3(grad_f(x), 1000, 0, 1e-4, 100);
    itl::cyclic_iteration<double> iter4(grad_f(x), 1000, 0, 1e-4, 100);

    quasi_newton(x, f, grad_f, itl::wolf<>(), itl::bfgs(), iter);
    iter.error_code();

   // tout << "x= " << x << "\n";
    tout << "grad_f(x)= " << grad_f(x) << "\n\n";
    if (two_norm(x) > 10 * iter.atol()) throw "x should be 0.";
    x= 8;
    quasi_newton(x, f, grad_f, itl::wolf<>(), itl::dfp(), iter1);
    iter1.error_code();

   // tout << "dfp x= " << x << "\n";
    tout << "grad_f(x)= " << grad_f(x) << "\n\n";
    if (two_norm(x) > 10 * iter1.atol()) throw "x should be 0.";

    x= 8;
    quasi_newton(x, f, grad_f, itl::wolf<>(), itl::broyden(), iter2);
    iter2.error_code();

    tout << "broyden x= " << x << "\n";
    tout << "grad_f(x)= " << grad_f(x) << "\n\n";
    if (two_norm(x) > 10 * iter2.atol()) throw "x should be 0.";

 #if 0  //bad condition on some compiler
    x= 8;
    quasi_newton(x, f, grad_f, itl::wolf<>(), itl::sr1(), iter3);
    iter3.error_code();

    tout << "sr1 x= " << x << "\n";
    tout << "grad_f(x)= " << grad_f(x) << "\n";
    if (two_norm(x) > 10 * iter3.atol())
	throw "x should be 0.";
#endif

    x= 8;
    quasi_newton(x, f, grad_f, itl::wolf<>(), itl::psb(), iter4);
    iter4.error_code();

    tout << "psb x= " << x << "\n";
    tout << "grad_f(x)= " << grad_f(x) << "\n\n";
    if (two_norm(x) > 10 * iter4.atol()) throw "x should be 0.";

    return 0;
}


text:
// ===================================================================
//
// Description
//		Contains the implementation of Vec3D
//
// Revision history
//		Date			Description
//		30-Nov-2013		First version
//
// ===================================================================
#include "Vec3D.h"

#include <boost/system/error_code.hpp>

namespace Sfs2X {
namespace Entities {
namespace Data {

// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------
Vec3D::Vec3D (long int px, long int py, long int pz)
{
	ix = px; iy = py; iz = pz;
	useFloat = false;
}

Vec3D::Vec3D (long int px, long int py)
{
	ix = px; iy = py; iz = 0;
	useFloat = false;
}

Vec3D::Vec3D (float px, float py, float pz)
{
	fx = px; fy = py; fz = pz;
	useFloat = true;
}

Vec3D::Vec3D (float px, float py)
{
	fx = px; fy = py; fz = 0;
	useFloat = true;
}

// -------------------------------------------------------------------
// Destructor
// -------------------------------------------------------------------
Vec3D::~Vec3D()
{
}

// -------------------------------------------------------------------
// IsFloat
// -------------------------------------------------------------------
bool Vec3D::IsFloat()
{
	return useFloat;
}

// -------------------------------------------------------------------
// FloatX
// -------------------------------------------------------------------
float Vec3D::FloatX()
{
	return fx;
}

// -------------------------------------------------------------------
// FloatY
// -------------------------------------------------------------------
float Vec3D::FloatY()
{
	return fy;
}

// -------------------------------------------------------------------
// FloatZ
// -------------------------------------------------------------------
float Vec3D::FloatZ()
{
	return fz;
}

// -------------------------------------------------------------------
// IntX
// -------------------------------------------------------------------
long int Vec3D::IntX()
{
	return ix;
}

// -------------------------------------------------------------------
// IntY
// -------------------------------------------------------------------
long int Vec3D::IntY()
{
	return iy;
}

// -------------------------------------------------------------------
// IntZ
// -------------------------------------------------------------------
long int Vec3D::IntZ()
{
	return iz;
}

// -------------------------------------------------------------------
// fromIntArray
// -------------------------------------------------------------------
boost::shared_ptr<Vec3D> Vec3D::fromIntArray(boost::shared_ptr<vector<long int> > array)
{
	if (array->size() != 3)
		boost::throw_exception(boost::enable_error_info (std::runtime_error("Wrong array size. Vec3D requires an array with 3 parameters (x,y,z)")));

	return boost::shared_ptr<Vec3D>(new Vec3D(array->at(0), array->at(1), array->at(2)));
}

// -------------------------------------------------------------------
// fromFloatArray
// -------------------------------------------------------------------
boost::shared_ptr<Vec3D> Vec3D::fromFloatArray(boost::shared_ptr<vector<float> > array)
{
	if (array->size() != 3)
		boost::throw_exception(boost::enable_error_info (std::runtime_error("Wrong array size. Vec3D requires an array with 3 parameters (x,y,z)")));

	return boost::shared_ptr<Vec3D>(new Vec3D(array->at(0), array->at(1), array->at(2)));
}

// -------------------------------------------------------------------
// ToIntArray
// -------------------------------------------------------------------
boost::shared_ptr<vector<long int> > Vec3D::ToIntArray()
{
	boost::shared_ptr<vector<long int> > returned (new vector<long int>());
	returned->push_back(ix);
	returned->push_back(iy);
	returned->push_back(iz);

	return returned;
}

// -------------------------------------------------------------------
// ToFloatArray
// -------------------------------------------------------------------
boost::shared_ptr<vector<float> > Vec3D::ToFloatArray()
{
	boost::shared_ptr<vector<float> > returned (new vector<float>());
	returned->push_back(fx);
	returned->push_back(fy);
	returned->push_back(fz);

	return returned;
}

// -------------------------------------------------------------------
// ToString
// -------------------------------------------------------------------
boost::shared_ptr<string> Vec3D::ToString()
{
	char buffer[512];

	if (IsFloat())
		sprintf (buffer, "(%f,%f,%f)\n", fx, fy, fz);
	else
		sprintf (buffer, "(%ld,%ld,%ld)\n", ix, iy, iz);

	boost::shared_ptr<string> str (new string(buffer));

	return str;
}

// -------------------------------------------------------------------
// fromArray
// -------------------------------------------------------------------
boost::shared_ptr<Vec3D> Vec3D::fromArray(long int tp, boost::shared_ptr<void> array)
{
	if (tp == SFSDATATYPE_INT_ARRAY)
	{
		return fromIntArray((boost::static_pointer_cast<vector<long int> >)(array));
	}
	else if (tp == SFSDATATYPE_FLOAT_ARRAY)
	{
		return fromFloatArray((boost::static_pointer_cast<vector<float> >)(array));
	}
	else
		boost::throw_exception(boost::enable_error_info (std::runtime_error("Invalid Array Type, cannot convert to Vec3D!")));
}

}	// namespace Data
}	// namespace Entities
}	// namespace Sfs2X


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2007-2011 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2011 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2011 Mateusz Loskot, London, UK.

// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_GEOMETRY_ALGORITHMS_CONVEX_HULL_HPP
#define BOOST_GEOMETRY_ALGORITHMS_CONVEX_HULL_HPP

#include <boost/geometry/core/cs.hpp>
#include <boost/geometry/core/point_order.hpp>
#include <boost/geometry/core/exterior_ring.hpp>

#include <boost/geometry/geometries/concepts/check.hpp>

#include <boost/geometry/strategies/convex_hull.hpp>
#include <boost/geometry/strategies/concepts/convex_hull_concept.hpp>

#include <boost/geometry/views/detail/range_type.hpp>

#include <boost/geometry/algorithms/detail/as_range.hpp>

namespace boost { namespace geometry
{

#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace convex_hull
{

template
<
    typename Geometry,
    order_selector Order,
    typename Strategy
>
struct hull_insert
{

    // Member template function (to avoid inconvenient declaration
    // of output-iterator-type, from hull_to_geometry)
    template <typename OutputIterator>
    static inline OutputIterator apply(Geometry const& geometry,
            OutputIterator out, Strategy const& strategy)
    {
        typename Strategy::state_type state;

        strategy.apply(geometry, state);
        strategy.result(state, out, Order == clockwise);
        return out;
    }
};

template
<
    typename Geometry,
    typename OutputGeometry,
    typename Strategy
>
struct hull_to_geometry
{
    static inline void apply(Geometry const& geometry, OutputGeometry& out,
            Strategy const& strategy)
    {
        hull_insert
            <
                Geometry,
                geometry::point_order<OutputGeometry>::value,
                Strategy
            >::apply(geometry,
                std::back_inserter(
                    // Handle linestring, ring and polygon the same:
                    detail::as_range
                        <
                            typename range_type<OutputGeometry>::type
                        >(out)), strategy);
    }
};

}} // namespace detail::convex_hull
#endif // DOXYGEN_NO_DETAIL

#ifndef DOXYGEN_NO_DISPATCH
namespace dispatch
{

template
<
    typename Tag1,
    typename Geometry,
    typename Output,
    typename Strategy
>
struct convex_hull
    : detail::convex_hull::hull_to_geometry<Geometry, Output, Strategy>
{};

template
<
    typename GeometryTag,
    order_selector Order,
    typename GeometryIn, typename Strategy
 >
struct convex_hull_insert
    : detail::convex_hull::hull_insert<GeometryIn, Order, Strategy>
{};

} // namespace dispatch
#endif // DOXYGEN_NO_DISPATCH

template<typename Geometry1, typename Geometry2, typename Strategy>
inline void convex_hull(Geometry1 const& geometry,
            Geometry2& out, Strategy const& strategy)
{
    concept::check_concepts_and_equal_dimensions
        <
            const Geometry1,
            Geometry2
        >();

    BOOST_CONCEPT_ASSERT( (geometry::concept::ConvexHullStrategy<Strategy>) );

    dispatch::convex_hull
        <
            typename tag<Geometry1>::type,
            Geometry1,
            Geometry2,
            Strategy
        >::apply(geometry, out, strategy);
}

/*!
\brief \brief_calc{convex hull}
\ingroup convex_hull
\details \details_calc{convex_hull,convex hull}.
\tparam Geometry1 \tparam_geometry
\tparam Geometry2 \tparam_geometry
\param geometry \param_geometry,  input geometry
\param hull \param_geometry \param_set{convex hull}

\qbk{[include reference/algorithms/convex_hull.qbk]}
 */
template<typename Geometry1, typename Geometry2>
inline void convex_hull(Geometry1 const& geometry,
            Geometry2& hull)
{
    concept::check_concepts_and_equal_dimensions
        <
            const Geometry1,
            Geometry2
        >();

    typedef typename point_type<Geometry2>::type point_type;

    typedef typename strategy_convex_hull
        <
            typename cs_tag<point_type>::type,
            Geometry1,
            point_type
        >::type strategy_type;

    convex_hull(geometry, hull, strategy_type());
}

#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace convex_hull
{

template<typename Geometry, typename OutputIterator, typename Strategy>
inline OutputIterator convex_hull_insert(Geometry const& geometry,
            OutputIterator out, Strategy const& strategy)
{
    // Concept: output point type = point type of input geometry
    concept::check<Geometry const>();
    concept::check<typename point_type<Geometry>::type>();

    BOOST_CONCEPT_ASSERT( (geometry::concept::ConvexHullStrategy<Strategy>) );

    return dispatch::convex_hull_insert
        <
            typename tag<Geometry>::type,
            geometry::point_order<Geometry>::value,
            Geometry, Strategy
        >::apply(geometry, out, strategy);
}

/*!
\brief Calculate the convex hull of a geometry, output-iterator version
\ingroup convex_hull
\tparam Geometry the input geometry type
\tparam OutputIterator: an output-iterator
\param geometry the geometry to calculate convex hull from
\param out an output iterator outputing points of the convex hull
\note This overloaded version outputs to an output iterator.
In this case, nothing is known about its point-type or
    about its clockwise order. Therefore, the input point-type
    and order are copied

 */
template<typename Geometry, typename OutputIterator>
inline OutputIterator convex_hull_insert(Geometry const& geometry,
            OutputIterator out)
{
    // Concept: output point type = point type of input geometry
    concept::check<Geometry const>();
    concept::check<typename point_type<Geometry>::type>();

    typedef typename point_type<Geometry>::type point_type;

    typedef typename strategy_convex_hull
        <
            typename cs_tag<point_type>::type,
            Geometry,
            point_type
        >::type strategy_type;

    return convex_hull_insert(geometry, out, strategy_type());
}

}} // namespace detail::convex_hull
#endif // DOXYGEN_NO_DETAIL

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_ALGORITHMS_CONVEX_HULL_HPP

max_stars_repo_name: bobzabcik/OpenStudio

max_issues_repo_name: bobzabcik/OpenStudio

max_forks_repo_name: bobzabcik/OpenStudio


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

    @copyright 2016 NumScale SAS

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

#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{

  /*!
    @ingroup group-trigonometric
    This function object returns the inverse tangent in \f$\pi\f$ multiples.

    @par Header <boost/simd/function/atanpi.hpp>

    @par Note

      For every parameter of floating type `atanpi(x)`
      returns the arc @c r in the interval  \f$[-0.5, 0.5[\f$
      such that <tt>tanpi(r) == x</tt>.

    @see atan2, atan2d, atand, atan, tanpi

    @par Example:

      @snippet atanpi.cpp atanpi

    @par Possible output:

      @snippet atanpi.txt atanpi

  **/
  IEEEValue atanpi(IEEEValue const& x);
} }
#endif

#include <boost/simd/function/scalar/atanpi.hpp>
#include <boost/simd/function/simd/atanpi.hpp>

#endif

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran