text:
/* Copyright © 2017 Apple Inc. All rights reserved.
 *
 * Use of this source code is governed by a BSD-3-clause license that can
 * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
 */
#include <unity/lib/extensions/option_info.hpp>

#include <boost/lexical_cast.hpp>

namespace turi { namespace option_handling {

flexible_type option_info::to_dictionary() const {

  flex_dict n;
  n.push_back({"description", description});
  n.push_back({"default_value", default_value});
  switch(parameter_type) {
    case REAL: {
      n.push_back({"parameter_type", "REAL"});
      n.push_back({"lower_bound", lower_bound});
      n.push_back({"upper_bound", upper_bound});
      break;
    }
    case INTEGER: {
      n.push_back({"parameter_type", "INTEGER"});
      n.push_back({"lower_bound", lower_bound});
      n.push_back({"upper_bound", upper_bound});
      break;
    }
    case BOOL: {
      n.push_back({"parameter_type", "BOOL"});
      break;
    }
    case CATEGORICAL: {
      n.push_back({"parameter_type", "CATEGORICAL"});
      flex_list a;
      for (const flexible_type& v : allowed_values) {
        a.push_back(v);
      }
      n.push_back({"possible_values", a});
      break;
    }
    case STRING: {
      n.push_back({"parameter_type", "STRING"});
      break;
    }
    case FLEXIBLE_TYPE: {
      n.push_back({"parameter_type", "DYNAMIC"});
      break;
    }
  }
  return n;
}

flexible_type option_info::interpret_value(const flexible_type& value) const {

  std::string sep_char = (value.get_type() == flex_type_enum::STRING) ? "'" : "";

  flexible_type ret_v;

  switch(parameter_type) {
    case option_info::REAL:
      {
        bool value_type_okay = false;

        switch(value.get_type()) {
          case flex_type_enum::INTEGER:
            ret_v = double(value);
            value_type_okay = true;
            break;
          case flex_type_enum::FLOAT:
            ret_v = value;
            value_type_okay = true;
            break;
          case flex_type_enum::STRING:
            {
              try {
                ret_v = boost::lexical_cast<double>(value.get<flex_string>());
                value_type_okay = true;
              } catch(const boost::bad_lexical_cast&) {
                value_type_okay = false;
              }

              break;
            }
          case flex_type_enum::UNDEFINED:
            ret_v = default_value;
            value_type_okay = true;
            break;
          default:
            value_type_okay = false;
            break;
        }

        if(!value_type_okay) {
          std::ostringstream msg;
          msg << "Expected numeric value for option '" << name
              << "'. Cannot cast " << sep_char << value << sep_char
              << " to a numeric value.";
          log_and_throw(msg.str());
        }

        if( (!(double(ret_v) >= lower_bound)) || (!(double(ret_v) <= upper_bound))) {
          std::ostringstream msg;
          msg << "Option '" << name << "' must be in the range ["
              << lower_bound << ", " << upper_bound << "].";
          log_and_throw(msg.str());
        }

        break;
      }
    case option_info::INTEGER:
      {
        bool value_type_okay = false;

        switch(value.get_type()) {
          case flex_type_enum::INTEGER:
            ret_v = value;
            value_type_okay = true;
            break;
          case flex_type_enum::FLOAT:
            ret_v = int64_t(value.get<double>());
            if(double(ret_v) != value.get<double>())
              value_type_okay = false;
            else
              value_type_okay = true;
            break;
          case flex_type_enum::STRING:
            {
              try {
                ret_v = boost::lexical_cast<int64_t>(value.get<flex_string>());
                value_type_okay = true;
              } catch(const boost::bad_lexical_cast&) {
                value_type_okay = false;
              }

              break;
            }
          case flex_type_enum::UNDEFINED:
            ret_v = default_value;
            value_type_okay = true;
            break;
          default:
            value_type_okay = false;
            break;
        }

        if(!value_type_okay) {
          std::ostringstream msg;
          msg << "Expected integer value for option '" << name
              << "'. Cannot cast " << sep_char << value << sep_char
              << " to an integer value.";
          log_and_throw(msg.str());
        }

        if( (!(flex_int(ret_v) >= lower_bound)) || (!(flex_int(ret_v) <= upper_bound))) {
          std::ostringstream msg;
          msg << "Option '" << name << "' must be in the range ["
              << lower_bound << ", " << upper_bound << "].";
          log_and_throw(msg.str());
        }

        break;
      }
    case option_info::BOOL:
      {
        bool value_type_okay = false;

        switch(value.get_type()) {
          case flex_type_enum::INTEGER:
            if(value.get<flex_int>() == 0) {
              ret_v = false;
              value_type_okay = true;
            } else if (value.get<flex_int>() == 1) {
              ret_v = true;
              value_type_okay = true;
            } else {
              value_type_okay = false;
            }
            break;
          case flex_type_enum::FLOAT:
            if(value.get<flex_float>() == 0.0) {
              ret_v = false;
              value_type_okay = true;
            } else if (value.get<flex_float>() == 1.0) {
              ret_v = true;
              value_type_okay = true;
            } else {
              value_type_okay = false;
            }
            break;

          case flex_type_enum::STRING:
            {
              static const std::map<std::string, bool> okay_values =
                  { {"1",      true},
                    {"True",   true},
                    {"T",      true},
                    {"true",   true},
                    {"Y",      true},
                    {"y",      true},
                    {"yes",    true},
                    {"0",      false},
                    {"False",  false},
                    {"F",      false},
                    {"false",  false},
                    {"N",      false},
                    {"n",      false},
                    {"no",     false} };

              auto it = okay_values.find(value.get<flex_string>());

              if(it != okay_values.end()) {
                ret_v = it->second;
                value_type_okay = true;
              } else {
                value_type_okay = false;
              }
            }

          case flex_type_enum::UNDEFINED:
            ret_v = default_value;
            value_type_okay = true;
            break;

          default:
            value_type_okay = false;
            break;
        }

        if(!value_type_okay) {

          std::ostringstream msg;
          msg << "Expected boolean value for option '" << name << sep_char
              << "'. Cannot interpret " << sep_char << value << sep_char
              << " as True or False.";

          log_and_throw(msg.str());
        }

        break;
      }
    case option_info::CATEGORICAL:
      {
        DASSERT_EQ(std::set<flexible_type>(allowed_values.begin(),
                                           allowed_values.end()).count(default_value), 1);

        bool is_okay = false;
        for(const auto& okay_v : allowed_values) {
          if(value == okay_v) {
            is_okay = true;
            break;
          }
        }
        if(!is_okay){
          std::ostringstream msg;
          msg << "Option '" << name << "' must be one of (";
          for(size_t i = 0; i < allowed_values.size()-1; i++){
            msg << sep_char << allowed_values[i] << sep_char << ", ";
          }
          msg << "or " << sep_char << allowed_values[allowed_values.size()-1]
              << sep_char << ").";
          log_and_throw(msg.str());
        }
        ret_v = value;
        break;
      }
    case option_info::STRING:
      ret_v = value;

      // Maybe more on this later?
      break;

    case option_info::FLEXIBLE_TYPE:
      ret_v = value;
      break;

    default:
      log_and_throw("Internal error. Option type un-implemented");
      break;

  }

  return ret_v;
}

/**
 * Check to make sure that the options satisfy the requirements.
*/
void option_info::check_value(const flexible_type& value) const {
  interpret_value(value);
}

/**
 * Save
*/
void option_info::save(turi::oarchive& oarc) const {
  oarc << name << description << default_value << parameter_type
       << lower_bound << upper_bound << allowed_values;
}

/**
 * Load
*/
void option_info::load(turi::iarchive& iarc) {
  iarc >> name >> description >> default_value >> parameter_type
       >> lower_bound >> upper_bound >> allowed_values;
}

}}

max_stars_repo_name: LeeCenY/turicreate

max_issues_repo_name: LeeCenY/turicreate

max_forks_repo_name: ZeroInfinite/turicreate


text:
/*!
 * @file
 * This file contains unit tests for `boost::mpl::matches`.
 */

#include <boost/mpl/matches.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/type_traits/is_same.hpp>

using namespace boost;
using namespace mpl;

struct Leaf;
template <typename ...> struct Node;

// Pattern matching with non-template types
BOOST_MPL_ASSERT_MATCHES((Leaf, Leaf));
BOOST_MPL_ASSERT_MATCHES_NOT((Leaf, struct some_other_type));

// Pattern matching with template types
BOOST_MPL_ASSERT_MATCHES((Node<Leaf>, Node<Leaf>));
BOOST_MPL_ASSERT_MATCHES_NOT((Node<Leaf>, Node<struct other>));
BOOST_MPL_ASSERT_MATCHES((
    Node<Node<Leaf>, struct X>,
    Node<Node<Leaf>, struct X>
));
BOOST_MPL_ASSERT_MATCHES_NOT((
    Node<Node<Leaf>, struct X>,
    Node<Node<Leaf>, struct Y>
));
BOOST_MPL_ASSERT_MATCHES_NOT((
    Node<Node<>, Node<>>,
    Node<Node<Leaf>, Node<>>
));

// `match::any`
BOOST_MPL_ASSERT_MATCHES((Leaf, match::any));
BOOST_MPL_ASSERT_MATCHES((Node<>, match::any));
BOOST_MPL_ASSERT_MATCHES((Node<Leaf>, match::any));
// note: the `match::any` on the left should not be considered as a keyword.
BOOST_MPL_ASSERT_MATCHES((Node<match::any>, match::any));
BOOST_MPL_ASSERT_MATCHES((Node<Leaf>, Node<match::any>));
BOOST_MPL_ASSERT_MATCHES_NOT((Node<>, Node<match::any>));
BOOST_MPL_ASSERT_MATCHES((
    Node<Node<Leaf>, Node<>, Node<Leaf>>,
    Node<Node<match::any>, Node<>, Node<Leaf>>
));

// `match::if_`
BOOST_MPL_ASSERT_MATCHES((Leaf, match::if_<is_same<Leaf, _1>>));
BOOST_MPL_ASSERT_MATCHES_NOT((struct X, match::if_<is_same<Leaf, _1>>));

// `match::unless`
BOOST_MPL_ASSERT_MATCHES_NOT((Leaf, match::unless<is_same<Leaf, _1>>));
BOOST_MPL_ASSERT_MATCHES((struct X, match::unless<is_same<Leaf, _1>>));

int main() { }

ext: cpp


text:
#include "Function.hpp"

#include <boost/lexical_cast.hpp>

std::ostream& operator<<(std::ostream& os, const Function& fn)
{
    os << reverse_parse(fn.getNode());
    return os;
}

std::istream& operator>>(std::istream& in, Function& fn)
{
    std::string buffer;
    std::getline(in, buffer);

    try
    {
        fn = parse(buffer).statement;
    }
    catch(boost::bad_lexical_cast& e)
    {
        in.setstate(std::istream::failbit);
    }

    return in;
}


text:
// Copyright (C) 2006  Tiago de Paula Peixoto <tiago@forked.de>
//
// Boost Software License - Version 1.0 - August 17th, 2003
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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.

//  Authors: Tiago de Paula Peixoto

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graphml.hpp>
#include <boost/test/minimal.hpp>
#include <cmath>
#include <fstream>
#include <string>

using namespace std;
using namespace boost;

int test_main(int argc, char** argv)
{
    typedef adjacency_list<vecS,vecS,directedS,
                           property<vertex_color_t,int,
                             property<vertex_name_t,string> >,
                           property<edge_weight_t,double>,
                           property<graph_name_t, string> > graph_t;
    graph_t g;
    dynamic_properties dp;
    dp.property("foo",get(vertex_color_t(),g));
    dp.property("weight",get(edge_weight_t(),g));
    dp.property("name",get(vertex_name_t(),g));
    boost::ref_property_map<graph_t*,std::string>
        gname(get_property(g, graph_name));
    dp.property("description",gname);

    ifstream ifile(argv[1]);
    read_graphml(ifile, g, dp);
    ifile.close();

    BOOST_CHECK(num_vertices(g) == 9);
    BOOST_CHECK(num_edges(g) == 9);
    BOOST_CHECK(get(vertex_color_t(), g, vertex(2,g)) == 100);
    BOOST_CHECK(get(vertex_color_t(), g, vertex(3,g)) == 42);
    BOOST_CHECK(std::abs(get(edge_weight_t(), g, edge(vertex(0,g),vertex(1,g),g).first) - 0.0) < 0.00001);
    BOOST_CHECK(std::abs(get(edge_weight_t(), g, edge(vertex(1,g),vertex(2,g),g).first) - 0.8) < 0.00001);
    BOOST_CHECK(get("description", dp, &g) == "Root graph.");

    ofstream ofile("graphml_test_out.xml");
    write_graphml(ofile, g, dp);
    ofile.close();

    graph_t g2;
    dynamic_properties dp2;
    dp2.property("foo",get(vertex_color_t(),g2));
    dp2.property("weight",get(edge_weight_t(),g2));
    dp2.property("name",get(vertex_name_t(),g2));
    boost::ref_property_map<graph_t*,std::string>
        gname2(get_property(g2, graph_name));
    dp2.property("description",gname2);
    ifile.open("graphml_test_out.xml");
    read_graphml(ifile, g2, dp2);
    ifile.close();

    BOOST_CHECK(num_vertices(g) == num_vertices(g2));
    BOOST_CHECK(num_edges(g) == num_edges(g2));
    BOOST_CHECK(get("description", dp, &g) == get("description", dp2, &g2));

    graph_traits<graph_t>::vertex_iterator v, v_end;
    for (boost::tie(v,v_end) = vertices(g); v != v_end; ++v)
      BOOST_CHECK(get(vertex_color_t(), g, *v) == get(vertex_color_t(), g2, *v));

    graph_traits<graph_t>::edge_iterator e, e_end;
    for (boost::tie(e,e_end) = edges(g); e != e_end; ++e)
      BOOST_CHECK(std::abs(get(edge_weight_t(), g, *e) - get(edge_weight_t(), g2, *e)) < 0.00001);

    return 0;
}


text:
#ifndef SCHNACKENBERGODESYSTEM_HPP_
#define SCHNACKENBERGODESYSTEM_HPP_

#include "ChasteSerialization.hpp"
#include <boost/serialization/base_object.hpp>

#include <cmath>
#include <iostream>

#include "AbstractOdeSystem.hpp"

class SchnackenbergOdeSystem : public AbstractOdeSystem
{

public:

    /**
     * Default constructor.
     *
     * @param stateVariables optional initial conditions for state variables (only used in archiving)
     */
    SchnackenbergOdeSystem(std::vector<double> stateVariables=std::vector<double>());

    /**
     * Destructor.
     */
    ~SchnackenbergOdeSystem();

    /**
     * Compute the RHS of the  Collier et al. system of ODEs.
     *
     * Returns a vector representing the RHS of the ODEs at each time step, y' = [y1' ... yn'].
     * An ODE solver will call this function repeatedly to solve for y = [y1 ... yn].
     *
     * @param time used to evaluate the RHS.
     * @param rY value of the solution vector used to evaluate the RHS.
     * @param rDY filled in with the resulting derivatives (using  Collier et al. system of equations).
     */
    void EvaluateYDerivatives(double time, const std::vector<double>& rY, std::vector<double>& rDY);
};

#endif

ext: hpp

max_stars_repo_name: OSS-Lab/ChemChaste

max_issues_repo_name: OSS-Lab/ChemChaste

max_forks_repo_name: OSS-Lab/ChemChaste


text:
#include <gtest/gtest.h>

#include <chrono>
#include <exception>
#include <memory>
#include <thread>
#include <vector>

#include <boost/asynchronous/servant_proxy.hpp>
#include <boost/asynchronous/trackable_servant.hpp>
#include <boost/asynchronous/queue/lockfree_queue.hpp>
#include <boost/asynchronous/scheduler_shared_proxy.hpp>
#include <boost/asynchronous/scheduler/multiqueue_threadpool_scheduler.hpp>
#include <boost/asynchronous/scheduler/single_thread_scheduler.hpp>

#include <libcvpg/core/histogram.hpp>
#include <libcvpg/core/image.hpp>
#include <libcvpg/imageproc/algorithms/hog.hpp>

template<class image_type>
struct test_servant : boost::asynchronous::trackable_servant<>
{
    test_servant(boost::asynchronous::any_weak_scheduler<> scheduler, boost::asynchronous::any_shared_scheduler_proxy<> pool)
        : boost::asynchronous::trackable_servant<>(scheduler, pool)
    {}

    std::future<std::vector<cvpg::histogram<double> > > hog(image_type image)
    {
        auto promise_alg = std::make_shared<std::promise<std::vector<cvpg::histogram<double> > > >();
        auto future_alg = promise_alg->get_future();

        post_callback(
            [img = std::move(image)]() mutable
            {
                return cvpg::imageproc::algorithms::hog(std::move(img));
            },
            [promise_alg](auto cont_res)
            {
                try
                {
                    promise_alg->set_value(std::move(cont_res.get()));
                }
                catch (...)
                {
                    promise_alg->set_exception(std::current_exception());
                }
            }
        );

        return future_alg;
    }

    std::future<cvpg::image_gray_8bit> hog_image(std::vector<cvpg::histogram<double> > histograms, std::size_t cells_per_row, std::size_t cell_dimension)
    {
        auto promise_alg = std::make_shared<std::promise<cvpg::image_gray_8bit> >();
        auto future_alg = promise_alg->get_future();

        post_callback(
            [histograms = std::move(histograms), cells_per_row, cell_dimension]() mutable
            {
                return cvpg::imageproc::algorithms::hog_image(std::move(histograms), cells_per_row, cell_dimension);
            },
            [promise_alg](auto cont_res)
            {
                try
                {
                    promise_alg->set_value(std::move(cont_res.get()));
                }
                catch (...)
                {
                    promise_alg->set_exception(std::current_exception());
                }
            }
        );

        return future_alg;
    }
};

template<class image_type>
struct test_servant_proxy : public boost::asynchronous::servant_proxy<test_servant_proxy<image_type>, test_servant<image_type> >
{
   template<typename... Args>
   test_servant_proxy(Args... args)
       : boost::asynchronous::servant_proxy<test_servant_proxy<image_type>, test_servant<image_type> >(std::forward<Args>(args)...)
   {}

   BOOST_ASYNC_FUTURE_MEMBER(hog)
   BOOST_ASYNC_FUTURE_MEMBER(hog_image)
};

TEST(test_algorithms, hog_gray_8bit)
{
    // create a thread pool for a single thread
    auto pool = boost::asynchronous::make_shared_scheduler_proxy<
                    boost::asynchronous::multiqueue_threadpool_scheduler<
                        boost::asynchronous::lockfree_queue<> > >(1);

    // create a scheduler
    auto scheduler = boost::asynchronous::make_shared_scheduler_proxy<
                        boost::asynchronous::single_thread_scheduler<
                            boost::asynchronous::lockfree_queue<> > >();

    // create test image
    cvpg::image_gray_8bit image(128, 128);

    test_servant_proxy<decltype(image)> tester(scheduler, pool);

    try
    {
        auto f = tester.hog(std::move(image));

        auto status = f.wait_for(std::chrono::seconds(3));

        ASSERT_TRUE(status != std::future_status::deferred && status != std::future_status::timeout);

        auto histograms = std::move(f.get().get());

        // test for the correct amount of histogram feature vectors
        ASSERT_EQ(histograms.size(), (image.width() / 8) * (image.height() / 8));
    }
    catch (std::exception const & e)
    {
        std::cerr << e.what() << std::endl << std::flush;

        ASSERT_TRUE(false);
    }
    catch(...)
    {
        ASSERT_TRUE(false);
    }
}

max_stars_repo_name: franz-alt/cv-playground

max_issues_repo_name: franz-alt/cv-playground

max_forks_repo_name: franz-alt/cv-playground


text:
#include "Config.h"
#include <string.h>
#include <iostream>
#include <boost/property_tree/ini_parser.hpp>
namespace QuasDB
{
  namespace Config
  {
    Conf::Conf(std::string path)
    {
      conf_path = path;

      try
      {
        boost::property_tree::ini_parser::read_ini(conf_path, conf);
      }
      catch (const std::exception &e)
      {
        std::cerr << e.what() << std::endl;
        std::cout << "QAQ" << std::endl;
      }
    }
  } // namespace Config
} // namespace QuasDB

max_stars_repo_name: Quasrain/QuasDB

max_issues_repo_name: Quasrain/QuasDB

max_forks_repo_name: Quasrain/QuasDB


text:
/***************************************************************************
 *   Software License Agreement (BSD License)                              *
 *   Copyright (C) 2012 by Markus Bader <markus.bader@tuwien.ac.at>        *
 *                                                                         *
 *   Redistribution and use in source and binary forms, with or without    *
 *   modification, are permitted provided that the following conditions    *
 *   are met:                                                              *
 *                                                                         *
 *   1. Redistributions of source code must retain the above copyright     *
 *      notice, this list of conditions and the following disclaimer.      *
 *   2. Redistributions in binary form must reproduce the above copyright  *
 *      notice, this list of conditions and the following disclaimer in    *
 *      the documentation and/or other materials provided with the         *
 *      distribution.                                                      *
 *   3. Neither the name of the copyright holder nor the names of its      *
 *      contributors may be used to endorse or promote products derived    *
 *      from this software without specific prior written permission.      *
 *                                                                         *
 *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   *
 *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     *
 *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS     *
 *   FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE        *
 *   COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,  *
 *   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,  *
 *   BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;      *
 *   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER      *
 *   CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT    *
 *   LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY *
 *   WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE           *
 *   POSSIBILITY OF SUCH DAMAGE.                                           *
 ***************************************************************************/

#include <iostream>
#include <stdlib.h>
#include "shmfw/header.h"
#include "shmfw/gerneralization/handler_variable.h"

#include <boost/program_options.hpp>

namespace bi = boost::interprocess;
namespace po = boost::program_options;

struct Prarmeters {
    bool clear;
    std::string shm_memory_name;
    unsigned int shm_memory_size;
    std::string variable_name;
    bool show_hidden;
    bool show_container;
    bool show_lock;
    bool show_timestamp;
    bool show_type;
    bool show_context;
};

Prarmeters readArgs ( int argc, char **argv ) {
    Prarmeters params;
    po::options_description desc ( "Allowed Parameters" );
    desc.add_options()
    ( "help", "get this help message" )
    ( "clear,c", "clears the shared memory" )
    ( "timestamp,t", "show variable timestamp" )
    ( "context", "show variable context" )
    ( "type", "show variable type" )
    ( "lock,l", "toggel variable lock" )
    ( "hidden", "show hidden variables" )
    ( "container", "toggel variable container type" )
    ( "shm_memory_name,m", po::value<std::string> ( &params.shm_memory_name )->default_value ( ShmFw::DEFAULT_SEGMENT_NAME() ), "shared memory segment name" )
    ( "shm_memory_size,s", po::value<unsigned int> ( &params.shm_memory_size )->default_value ( ShmFw::DEFAULT_SEGMENT_SIZE() ), "shared memory segment size" )
    ( "variable_name,v", po::value<std::string> ( &params.variable_name ), "shared variable name" );

    po::variables_map vm;
    try {
        po::store ( po::parse_command_line ( argc, argv, desc ), vm );
    } catch ( const std::exception &ex ) {
        std::cout << desc << std::endl;;
        exit ( 1 );
    }
    po::notify ( vm );

    if ( vm.count ( "help" ) )  {
        std::cout << desc << std::endl;
        exit ( 1 );
    }
    params.clear = ( vm.count ( "clear" ) > 0 );
    params.show_context = ( vm.count ( "context" ) > 0 );
    params.show_type = ( vm.count ( "type" ) > 0 );
    params.show_timestamp = ( vm.count ( "timestamp" ) > 0 );
    params.show_lock = !( vm.count ( "lock" ) > 0 );
    params.show_container = !( vm.count ( "container" ) > 0 );
    params.show_hidden = vm.count ( "hidden" ) > 0;

    return params;
}

int main ( int argc, char **argv ) {
    Prarmeters params = readArgs ( argc, argv );
    if ( params.clear ) {
        ShmFw::Handler::removeSegment ( params.shm_memory_name );
        std::cout << "Shared Memory " << params.shm_memory_name << " cleared" << std::endl;
	exit(0);
    }
    std::vector<std::string> varNames;
    std::vector < ShmFw::HandlerObjectPtr > objects;
    ShmFw::HandlerPtr shmHdl = ShmFw::Handler::create ( params.shm_memory_name, params.shm_memory_size );
    bi::managed_shared_memory::segment_manager *seg_manager = shmHdl->getShm()->get_segment_manager();
    std::cout << std::endl;
    std::cout << "Segment name                    : " << std::setw(10) << params.shm_memory_name << std::endl;
    std::cout << "Wegment size                    : " << std::setw(10) << seg_manager->get_size()        << " bytes = " << seg_manager->get_size()/(1024.*1024.) << " MByte" << std::endl;
    std::cout << "Free memory                     : " << std::setw(10) << seg_manager->get_free_memory() << " bytes = " << seg_manager->get_free_memory()/(1024.*1024.) << " MByte = " << seg_manager->get_free_memory()*100/seg_manager->get_size() <<  " %" << std::endl;
    std::cout << "All memory has been deallocated : " << std::setw(10) << (seg_manager->all_memory_deallocated()?"ture":"false") <<  std::endl;
    std::cout << "Internal structures             : " << std::setw(10) << (seg_manager->check_sanity()?"OK":"errors") <<  std::endl;
    std::cout << "Number of named objects         : " << std::setw(10) << seg_manager->get_num_named_objects() <<  std::endl;
    std::cout << "Number of unique objects        : " << std::setw(10) << seg_manager->get_num_unique_objects() <<  std::endl;
    std::cout << std::endl;
    shmHdl->listNames ( varNames, params.show_hidden);
    for ( unsigned int i = 0; i < varNames.size(); i++ ) {
        ShmFw::Header shmHeader ( shmHdl, varNames[i] );
        std::cout << std::setw ( 3 ) << i << ": " << std::setw ( 30 ) << varNames[i];
        std::cout << ( shmHeader.locked() ? ", x" : ", o" );
        if ( params.show_container ) {
            std::cout << ", " << std::setw ( 12 ) << shmHeader.containerName();
        }
        if ( params.show_context ) {
            if ( ( shmHeader.container() == ShmFw::Header::CONTAINER_VARIABLE ) ||
                    ( shmHeader.container() == ShmFw::Header::CONTAINER_VECTOR ) ) {
                ShmFw::HandlerObjectPtr objects = ShmFw::HandlerObject::open ( varNames[i], shmHdl );
                if ( objects ) {
                    std::cout << " = " << objects->value();
                } else {
                    std::cout << "?";
                }
            } else {
                std::cout << " = unsupported container";
            }
        }
        if ( params.show_type ) {
            std::cout << ", " << std::setw ( 8 )  << shmHeader.type_hash_code() << " : ";
            std::cout << shmHeader.type_name();
        }
        if ( params.show_timestamp ) {
            std::cout << ", " << shmHeader.timestampShm() ;
        }
        std::cout << std::endl;
    }
    exit ( 0 );
}

max_stars_repo_name: ShmFw/shmfw

max_issues_repo_name: ShmFw/shmfw

max_forks_repo_name: ShmFw/shmfw


text: #include <boost/mpl/unique.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text: #include <boost/locale/boundary/boundary_point.hpp>


text:
#define BOOST_TEST_MODULE reduce

#include <boost/test/included/unit_test.hpp>
#include <mpl/mpl.hpp>

template<typename T>
class add {
public:
  T operator()(const T &a, const T &b) { return a + b; }
};

template<typename T>
bool reduce_func_test() {
  const mpl::communicator &comm_world = mpl::environment::comm_world();
  int N = comm_world.size();
  T x{T(comm_world.rank() + 1)};
  if (comm_world.rank() == 0) {
    T y{};
    comm_world.reduce(add<T>(), 0, x, y);
    return y == T((N * N + N) / 2);
  } else {
    comm_world.reduce(add<T>(), 0, x);
  }
  return true;
}

template<typename T>
bool reduce_op_test() {
  const mpl::communicator &comm_world = mpl::environment::comm_world();
  int N = comm_world.size();
  T x{T(comm_world.rank() + 1)};
  if (comm_world.rank() == 0) {
    T y{};
    comm_world.reduce(mpl::plus<T>(), 0, x, y);
    return y == T((N * N + N) / 2);
  } else {
    comm_world.reduce(mpl::plus<T>(), 0, x);
  }
  return true;
}

template<typename T>
bool reduce_lambda_test() {
  const mpl::communicator &comm_world = mpl::environment::comm_world();
  int N = comm_world.size();
  T x{T(comm_world.rank() + 1)};
  if (comm_world.rank() == 0) {
    T y{};
    comm_world.reduce([](T a, T b) { return a + b; }, 0, x, y);
    return y == T((N * N + N) / 2);
  } else {
    comm_world.reduce([](T a, T b) { return a + b; }, 0, x);
  }
  return true;
}

template<typename T>
bool reduce_inplace_func_test() {
  const mpl::communicator &comm_world = mpl::environment::comm_world();
  int N = comm_world.size();
  T x{T(comm_world.rank() + 1)};
  comm_world.reduce(add<T>{}, 0, x);
  return x == T((N * N + N) / 2) or comm_world.rank() > 0;
}

template<typename T>
bool reduce_inplace_op_test() {
  const mpl::communicator &comm_world = mpl::environment::comm_world();
  int N = comm_world.size();
  T x{T(comm_world.rank() + 1)};
  comm_world.reduce(mpl::plus<T>(), 0, x);
  return x == T((N * N + N) / 2) or comm_world.rank() > 0;
}

template<typename T>
bool reduce_inplace_lambda_test() {
  const mpl::communicator &comm_world = mpl::environment::comm_world();
  int N = comm_world.size();
  T x{T(comm_world.rank() + 1)};
  comm_world.reduce([](T a, T b) { return a + b; }, 0, x);
  return x == T((N * N + N) / 2) or comm_world.rank() > 0;
}

template<typename T>
bool allreduce_func_test() {
  const mpl::communicator &comm_world = mpl::environment::comm_world();
  int N = comm_world.size();
  T x{T(comm_world.rank() + 1)}, y{};
  comm_world.allreduce(add<T>(), x, y);
  return y == T((N * N + N) / 2);
}

template<typename T>
bool allreduce_op_test() {
  const mpl::communicator &comm_world = mpl::environment::comm_world();
  int N = comm_world.size();
  T x{T(comm_world.rank() + 1)}, y{};
  comm_world.allreduce(mpl::plus<T>(), x, y);
  return y == T((N * N + N) / 2);
}

template<typename T>
bool allreduce_lambda_test() {
  const mpl::communicator &comm_world = mpl::environment::comm_world();
  int N = comm_world.size();
  T x{T(comm_world.rank() + 1)}, y{};
  comm_world.allreduce([](T a, T b) { return a + b; }, x, y);
  return y == T((N * N + N) / 2);
}

template<typename T>
bool allreduce_inplace_func_test() {
  const mpl::communicator &comm_world = mpl::environment::comm_world();
  int N = comm_world.size();
  T x{T(comm_world.rank() + 1)};
  comm_world.allreduce(add<T>(), x);
  return x == T((N * N + N) / 2);
}

template<typename T>
bool allreduce_inplace_op_test() {
  const mpl::communicator &comm_world = mpl::environment::comm_world();
  int N = comm_world.size();
  T x{T(comm_world.rank() + 1)};
  comm_world.allreduce(mpl::plus<T>(), x);
  return x == T((N * N + N) / 2);
}

template<typename T>
bool allreduce_inplace_lambda_test() {
  const mpl::communicator &comm_world = mpl::environment::comm_world();
  int N = comm_world.size();
  T x{T(comm_world.rank() + 1)};
  comm_world.allreduce([](T a, T b) { return a + b; }, x);
  return x == T((N * N + N) / 2);
}

BOOST_AUTO_TEST_CASE(reduce) {
  BOOST_TEST(reduce_func_test<double>());
  BOOST_TEST(reduce_op_test<double>());
  BOOST_TEST(reduce_lambda_test<double>());
  BOOST_TEST(reduce_inplace_func_test<double>());
  BOOST_TEST(reduce_inplace_op_test<double>());
  BOOST_TEST(reduce_inplace_lambda_test<double>());
  BOOST_TEST(allreduce_func_test<double>());
  BOOST_TEST(allreduce_op_test<double>());
  BOOST_TEST(allreduce_lambda_test<double>());
  BOOST_TEST(allreduce_inplace_func_test<double>());
  BOOST_TEST(allreduce_inplace_op_test<double>());
  BOOST_TEST(allreduce_inplace_lambda_test<double>());
}

ext: cc

max_stars_repo_name: mpi-advance/Exhanced-MPL-tiny-

max_issues_repo_name: mpi-advance/mpl-subset

max_forks_repo_name: mpi-advance/mpl-subset


text:
#include "IntegratorRect.hh"

#include <Eigen/Dense>
#include <iterator>

#include "TypesFunctions.hh"

using namespace Eigen;
using namespace std;

IntegratorRect::IntegratorRect(int order, const std::string& mode) : IntegratorBase(order)
{
  init(mode);
}

IntegratorRect::IntegratorRect(size_t bins, int orders, double* edges, const std::string& mode) : IntegratorBase(bins, orders, edges)
{
  init(mode);
}

IntegratorRect::IntegratorRect(size_t bins, int* orders, double* edges, const std::string& mode) : IntegratorBase(bins, orders, edges)
{
  init(mode);
}

void IntegratorRect::init(const std::string& mode) {
  m_mode = mode;

  if(m_mode=="left"){
    m_rect_offset=-1;
  }
  else if(m_mode=="center"){
    m_rect_offset=0;
  }
  else if(m_mode=="right"){
    m_rect_offset=1;
  }
  else{
    throw std::runtime_error("invalid rectangular integration mode");
  }

  init_sampler();
}

void IntegratorRect::sample(FunctionArgs& fargs){
  auto& rets=fargs.rets;
  rets[1].x = m_edges.cast<double>();
  rets[2].x = 0.0;
  auto npoints=m_edges.size()-1;
  rets[3].x = 0.5*(m_edges.tail(npoints)+m_edges.head(npoints));

  auto& abscissa=rets[0].x;

  auto nbins=m_edges.size()-1;
  auto& binwidths=m_edges.tail(nbins) - m_edges.head(nbins);
  ArrayXd samplewidths=binwidths/m_orders.cast<double>();

  ArrayXd low, high;
  switch(m_rect_offset){
    case -1: {
      low=m_edges.head(nbins);
      high=m_edges.tail(nbins)-samplewidths;
      break;
      }
    case 0: {
      ArrayXd offsetwidth=samplewidths*0.5;
      low=m_edges.head(nbins)+offsetwidth;
      high=m_edges.tail(nbins)-offsetwidth;
      break;
      }
    case 1: {
      samplewidths=binwidths/m_orders.cast<double>();
      low=m_edges.head(nbins)+samplewidths;
      high=m_edges.tail(nbins);
      break;
      }
  }

  size_t offset=0;
  for (size_t i = 0; i < static_cast<size_t>(m_orders.size()); ++i) {
    auto n=m_orders[i];
    if(n>1){
      abscissa.segment(offset, n)=ArrayXd::LinSpaced(n, low[i], high[i]);
      m_weights.segment(offset, n)=samplewidths[i];
    }
    else{
      abscissa[i]=low[i];
      m_weights[i]=binwidths[i];
    }
    offset+=n;
  }
  rets.untaint();
  rets.freeze();
}

max_stars_repo_name: gnafit/gna

max_issues_repo_name: gnafit/gna

max_forks_repo_name: gnafit/gna


text:
/*=============================================================================
    Copyright (c) 2001-2011 Joel de Guzman

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#if !defined(FUSION_SET_09162005_1104)
#define FUSION_SET_09162005_1104

#include <boost/fusion/support/config.hpp>
#include <boost/fusion/support/sequence_base.hpp>
#include <boost/fusion/support/category_of.hpp>
#include <boost/fusion/support/detail/access.hpp>
#include <boost/fusion/container/set/set_fwd.hpp>
#include <boost/fusion/container/set/detail/begin_impl.hpp>
#include <boost/fusion/container/set/detail/end_impl.hpp>
#include <boost/fusion/container/set/detail/value_of_impl.hpp>
#include <boost/fusion/container/set/detail/deref_data_impl.hpp>
#include <boost/fusion/container/set/detail/deref_impl.hpp>
#include <boost/fusion/container/set/detail/key_of_impl.hpp>
#include <boost/fusion/container/set/detail/value_of_data_impl.hpp>
#include <boost/fusion/container/vector/vector.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/mpl/bool.hpp>

#if !defined(BOOST_FUSION_DONT_USE_PREPROCESSED_FILES)
#include <boost/fusion/container/set/detail/preprocessed/set.hpp>
#else
#if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES)
#pragma wave option(preserve: 2, line: 0, output: "detail/preprocessed/set" FUSION_MAX_SET_SIZE_STR ".hpp")
#endif

/*=============================================================================
    Copyright (c) 2001-2011 Joel de Guzman

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

    This is an auto-generated file. Do not edit!
==============================================================================*/

#if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES)
#pragma wave option(preserve: 1)
#endif

namespace boost { namespace fusion
{
    struct void_;
    struct fusion_sequence_tag;

    template <BOOST_PP_ENUM_PARAMS(FUSION_MAX_SET_SIZE, typename T)>
    struct set : sequence_base<set<BOOST_PP_ENUM_PARAMS(FUSION_MAX_SET_SIZE, T)> >
    {
        struct category : forward_traversal_tag, associative_tag {};

        typedef set_tag fusion_tag;
        typedef fusion_sequence_tag tag; // this gets picked up by MPL
        typedef mpl::false_ is_view;

        typedef vector<
            BOOST_PP_ENUM_PARAMS(FUSION_MAX_SET_SIZE, T)>
        storage_type;

        typedef typename storage_type::size size;

        BOOST_FUSION_GPU_ENABLED
        set()
            : data() {}

        template <typename Sequence>
        BOOST_FUSION_GPU_ENABLED
        set(Sequence const& rhs)
            : data(rhs) {}

        #include <boost/fusion/container/set/detail/set_forward_ctor.hpp>

        template <typename T>
        BOOST_FUSION_GPU_ENABLED
        set&
        operator=(T const& rhs)
        {
            data = rhs;
            return *this;
        }

        BOOST_FUSION_GPU_ENABLED
        storage_type& get_data() { return data; }
        BOOST_FUSION_GPU_ENABLED
        storage_type const& get_data() const { return data; }

    private:

        storage_type data;
    };
}}

#if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES)
#pragma wave option(output: null)
#endif

#endif // BOOST_FUSION_DONT_USE_PREPROCESSED_FILES

#endif


text:
//#define ARMA_NO_DEBUG

#include <iostream>
#include <armadillo>
#include <float.h>
#include <ctime>

using namespace std;
using namespace arma;

typedef double (*callback_type)(int, double[]);
typedef bool (*is_terminate_type)(long, int, double); // runid, iter, value -> isTerminate

static uvec inverse(const uvec& indices) {
    uvec inverse = uvec(indices.size());
    for (int i = 0; i < indices.size(); i++)
        inverse(indices(i)) = i;
    return inverse;
}

static vec sequence(double start, double end, double step) {
    int size = (int) ((end - start) / step + 1);
    vec d(size);
    double value = start;
    for (int r = 0; r < size; r++) {
        d(r) = value;
        value += step;
    }
    return d;
}

// wrapper around the fittness function, scales according to boundaries

class Fittness {

public:

    Fittness(callback_type pfunc, const vec &lower_limit,
            const vec &upper_limit) {
        func = pfunc;
        lower = lower_limit;
        upper = upper_limit;
        evaluationCounter = 0;
        if (lower.size() > 0) { // bounds defined
            scale = 0.5 * (upper - lower);
            typx = 0.5 * (upper + lower);
        }
    }

    void closestFeasible(vec &X) const { // in place
        if (lower.size() > 0)
            X.for_each([](double &val) {
                val = max(min(val, 1.0), -1.0);
            });
    }

    vec getClosestFeasible(const vec &col) const {
        if (lower.size() > 0) {
            vec X(col);
            X.for_each([](double &val) {
                val = max(min(val, 1.0), -1.0);
            });
            return X;
        }
        return col;
    }

    double eval(const vec &X) {
        int n = X.size();
        double parg[n];
        for (int i = 0; i < n; i++)
            parg[i] = X(i);
        double res = func(n, parg);
        evaluationCounter++;
        return res;
    }

    double value(const vec &X) {
        double value;
        if (lower.size() > 0) {
            return eval(decode(getClosestFeasible(X)));
        } else
            return eval(X);
    }

    vec encode(const vec &X) const {
        if (lower.size() > 0)
            return (X - typx) / scale;
        else
            return X;
    }

    vec decode(const vec &X) const {
        if (lower.size() > 0)
            return (X % scale) + typx;
        else
            return X;
    }

    int getEvaluations() {
        return evaluationCounter;
    }

private:
   callback_type func;
   vec lower;
   vec upper;
   long evaluationCounter;
   vec scale;
   vec typx;
};

class AcmaesOptimizer {

public:

    AcmaesOptimizer(long runid_, Fittness* fitfun_, int popsize_, int mu_, const vec &guess_, const vec &inputSigma_,
            int maxIterations_, int maxEvaluations_, double accuracy_, double stopfitness_, is_terminate_type isTerminate_) {
// runid used in isTerminate callback to identify a specific run at different iteration
        runid = runid_;
// fitness function to minimize
        fitfun = fitfun_;
// initial guess for the arguments of the fitness function
        guess = guess_;
// accuracy = 1.0 is default, > 1.0 reduces accuracy
        accuracy = accuracy_;
// callback to check if to terminate
        isTerminate = isTerminate_;
// Number of objective variables/problem dimension
        dim = guess_.size();
//     Population size, offspring number. The primary strategy parameter to play
//     with, which can be increased from its default value. Increasing the
//     population size improves global search properties in exchange to speed.
//     Speed decreases, as a rule, at most linearly with increasing population
//     size. It is advisable to begin with the default small population size.
        if (popsize_ > 0)
            popsize = popsize_;
        else
            popsize = 4 + int(3. * log(dim));
//     Individual sigma values - initial search volume. inputSigma determines
//     the initial coordinate wise standard deviations for the search. Setting
//     SIGMA one third of the initial search region is appropriate.
        if (inputSigma_.size() == 1)
            inputSigma = vec(dim).fill(inputSigma_(0));
        else
            inputSigma = inputSigma_;
// Overall standard deviation - search volume.
        sigma = max(inputSigma);
// termination criteria
// maximal number of evaluations allowed.
        maxEvaluations = maxEvaluations_;
// maximal number of iterations allowed.
        maxIterations = maxIterations_;
// Limit for fitness value.
        stopfitness = stopfitness_;
// Stop if x-changes larger stopTolUpX.
        stopTolUpX = 1e3 * sigma;
// Stop if x-change smaller stopTolX.
        stopTolX = 1e-11 * sigma * accuracy;
// Stop if fun-changes smaller stopTolFun.
        stopTolFun = 1e-12 * accuracy;
// Stop if back fun-changes smaller stopTolHistFun.
        stopTolHistFun = 1e-13 * accuracy;
// selection strategy parameters
// Number of parents/points for recombination.
        mu = mu_ > 0 ? mu_ : popsize / 2;
// Array for weighted recombination.
        weights = (log(sequence(1, mu, 1)) * -1.) + log(mu + 0.5);
        double sumw = sum(weights);
        double sumwq = sum(weights % weights);
        weights *= 1. / sumw;
// Variance-effectiveness of sum w_i x_i.
        mueff = sumw * sumw / sumwq;

// dynamic strategy parameters and constants
// Cumulation constant.
        cc = (4. + mueff / dim) / (dim + 4. + 2. * mueff / dim);
// Cumulation constant for step-size.
        cs = (mueff + 2.) / (dim + mueff + 3.);
// Damping for step-size.
           damps = (1. + 2. * ::max(0., ::sqrt((mueff - 1.)
                    / (dim + 1.)) - 1.))
                    * max(0.3, 1.
                            - // modification for short runs
                            dim / (1e-6 + min(maxIterations, maxEvaluations
                                    / popsize))) + cs; // minor increment
// Learning rate for rank-one update.
        ccov1 = 2. / ((dim + 1.3) * (dim + 1.3) + mueff);
// Learning rate for rank-mu update'
        ccovmu = min(1. - ccov1,
                2. * (mueff - 2. + 1. / mueff)
                        / ((dim + 2.) * (dim + 2.) + mueff));
// Expectation of ||N(0,I)|| == norm(randn(N,1)).
        chiN = sqrt(dim) * (1. - 1. / (4. * dim) + 1 / (21. * dim * dim));
        ccov1Sep = min(1., ccov1 * (dim + 1.5) / 3.);
        ccovmuSep = min(1. - ccov1, ccovmu * (dim + 1.5) / 3.);

// CMA internal values - updated each generation
// Objective variables.
        xmean = fitfun->encode(guess);
// Evolution path.
        pc = zeros<vec>(dim);
// Evolution path for sigma.
        ps = zeros<vec>(dim);
// Norm of ps, stored for efficiency.
        normps = norm(ps);
// Coordinate system.
        B = mat(dim,dim).eye();
// Diagonal of sqrt(D), stored for efficiency.
        diagD = inputSigma / sigma;
        diagC = square(diagD);
// B*D, stored for efficiency.
        BD = B % repmat(diagD.t(), dim, 1);
// Covariance matrix.
        C = B * (mat(dim,dim).eye() * B.t());
// Number of iterations already performed.
        iterations = 0;
// Size of history queue of best values.
        historySize = 10 + int(3. * 10. * dim / popsize);
// stop criteria
        stop = 0;
// best value so far
        bestValue = fitfun->value(xmean);
// best parameters so far
        bestX = guess;
// History queue of best values.
        fitnessHistory = vec(historySize).fill(DBL_MAX);
        fitnessHistory(0) = bestValue;
    }

    // param zmean weighted row matrix of the gaussian random numbers generating the current offspring
    // param xold xmean matrix of the previous generation
    // return hsig flag indicating a small correction

    bool updateEvolutionPaths(const vec& zmean, const vec& xold) {
        ps = ps * (1. - cs) + ((B * zmean) * sqrt(cs * (2. - cs) * mueff));
        normps = norm(ps);
        bool hsig = normps / sqrt(1. - pow(1. - cs, 2. * iterations)) / chiN < 1.4 + 2. / (dim + 1.);
        pc *= (1. - cc);
        if (hsig)
            pc += (xmean - xold) * (sqrt(cc * (2. - cc) * mueff) / sigma);
        return hsig;
    }

    // param hsig flag indicating a small correction
    // param bestArx fitness-sorted matrix of the argument vectors producing the current offspring
    // param arz unsorted matrix containing the gaussian random values of the current offspring
    // param arindex indices indicating the fitness-order of the current offspring
    // param xold xmean matrix of the previous generation

    double updateCovariance(bool hsig, const mat& bestArx, const mat& arz,
            const uvec& arindex, const mat& xold) {
        double negccov = 0;
        if (ccov1 + ccovmu > 0) {
            mat arpos = (bestArx - repmat(xold, 1, mu)) * (1. / sigma); // mu difference vectors
            mat roneu = pc * pc.t() * ccov1;
            // minor correction if hsig==false
            double oldFac = hsig ? 0 : ccov1 * cc * (2. - cc);
            oldFac += 1. - ccov1 - ccovmu;
            // Adapt covariance matrix C active CMA
            negccov = (1. - ccovmu) * 0.25 * mueff
                    / (pow(dim + 2., 1.5) + 2. * mueff);
            double negminresidualvariance = 0.66;
            // keep at least 0.66 in all directions, small popsize are most critical
            double negalphaold = 0.5; // where to make up for the variance loss,
            // prepare vectors, compute negative updating matrix Cneg
            uvec arReverseIndex = reverse(arindex);
            mat arzneg = arz.cols(arReverseIndex.head(mu));
            vec arnorms = sqrt(sum(square(arzneg.t()), 1)); // rowsum
            uvec idxnorms = sort_index(arnorms);
            vec arnormsSorted = arnorms(idxnorms);
            uvec idxReverse = reverse(idxnorms);
            vec arnormsReverse = arnorms(idxReverse);
            arnorms = arnormsReverse / arnormsSorted;
            vec arnormsInv = arnorms(inverse(idxnorms));
            mat sqarnw = square(arnormsInv).t() * weights;
            double negcovMax = (1. - negminresidualvariance) / sqarnw(0);
            if (negccov > negcovMax)
                negccov = negcovMax;
            arzneg = arzneg % repmat(arnormsInv.t(), dim, 1);
            mat artmp = BD * arzneg;
            mat Cneg = artmp * diagmat(weights) * artmp.t();
            oldFac += negalphaold * negccov;
            C = (C * oldFac) + roneu
                    + ( arpos * (ccovmu + (1. - negalphaold) * negccov) *
                               (repmat(weights, 1, dim) % arpos.t()))
                    - (Cneg * negccov);
        }
        return negccov;
    }

    // Update B and diagD from C
    // param negccov Negative covariance factor.

    void updateBD(double negccov) {

        if (ccov1 + ccovmu + negccov > 0
                && (std::fmod(iterations, 1. / (ccov1 + ccovmu + negccov) / dim / 10.)) < 1.) {
            // to achieve O(N^2) enforce symmetry to prevent complex numbers
            C = trimatu(C) + trimatu(C, 1).t();
            // diagD defines the scaling
            vec eigval;
            mat eigvec;
            eig_sym(eigval, eigvec, C);

            diagD = reverse(eigval); // descending order of eigenvalues
            for (int i = 0; i < dim; i++)
                B.col(i) = eigvec.col(dim - 1 - i);

            if (diagD.min() <= 0) {
                for (int i = 0; i < dim; i++)
                    if (diagD(i, 0) < 0)
                        diagD(i, 0) = 0.;
                double tfac = diagD.max() / 1e14;
                C += mat(dim,dim).eye() * tfac;
                diagD += ones(dim, 1) * tfac;
            }
            if (diagD.max() > 1e14 * diagD.min()) {
                double tfac = diagD.max() / 1e14 - diagD.min();
                C += mat(dim,dim).eye() * tfac;
                diagD += ones(dim, 1) * tfac;
            }
            diagC = C.diag();
            diagD = sqrt(diagD); // D contains standard deviations now
            BD = B % repmat(diagD.t(), dim, 1);
        }
    }

    void doOptimize() {

        // -------------------- Generation Loop --------------------------------

        for (iterations = 1; iterations <= maxIterations &&
                    fitfun->getEvaluations() < maxEvaluations; iterations++) {
            // Generate and evaluate popsize offspring
            mat arz = mat(dim, popsize).randn();
            mat arx = mat(dim, popsize);
            vec fitness = vec(popsize).fill(DBL_MAX);
            // generate random offspring
            fitfun->closestFeasible(xmean);
            for (int k = 0; k < popsize; k++) {
                vec delta = (BD * arz.col(k)) * sigma;
                arx.col(k) = fitfun->getClosestFeasible(xmean + delta);
                fitness[k] = fitfun->value(arx.col(k)); // compute fitness
                if (!isfinite(fitness[k])) {
                    stop = -1;
                    break;
                }
            }
            if (stop != 0)
                break;
            // Sort by fitness and compute weighted mean into xmean
            uvec arindex = sort_index(fitness);

            // Calculate new xmean, this is selection and recombination
            vec xold = xmean; // for speed up of Eq. (2) and (3)
            uvec bestIndex = arindex.head(mu);
            mat bestArx = arx.cols(bestIndex);
            xmean = bestArx * weights;
            mat bestArz = arz.cols(bestIndex);
            mat zmean = bestArz * weights;

            bool hsig = updateEvolutionPaths(zmean, xold);
            double negccov = updateCovariance(hsig, bestArx, arz, arindex, xold);
            updateBD(negccov);
            // Adapt step size sigma - Eq. (5)
            sigma *= exp(min(1.0, (normps / chiN - 1.) * cs / damps));
            double bestFitness = fitness(arindex(0));
            double worstFitness = fitness(arindex(arindex.size()-1));
            if (bestValue > bestFitness) {
                bestValue = bestFitness;
                bestX = fitfun->decode(bestArx.col(0));
            }

            // handle termination criteria
            if (isfinite(stopfitness) && bestFitness < stopfitness) {
                stop = 1;
                break;
            }
            vec sqrtDiagC = sqrt(diagC);
            vec pcCol = pc;

            for (int i = 0; i < dim; i++) {
                if (sigma * (max(abs(pcCol[i]), sqrtDiagC[i])) > stopTolX)
                    break;
                if (i >= dim - 1)
                    stop = 2;
            }
            for (int i = 0; i < dim; i++)
                if (sigma * sqrtDiagC[i] > stopTolUpX)
                    stop = 3;
            if (stop > 0)
                break;
            double historyBest = min(fitnessHistory);
            double historyWorst = max(fitnessHistory);
            if (iterations > 2
                    && max(historyWorst, worstFitness)
                            - min(historyBest, bestFitness) < stopTolFun) {
                stop = 4;
                break;
            }
            if (iterations > fitnessHistory.size()
                    && historyWorst - historyBest < stopTolHistFun) {
                stop = 5;
                break;
            }
            // condition number of the covariance matrix exceeds 1e14
            if ( diagD.max() / diagD.min() > 1e7 * 1.0 / sqrt(accuracy)) {
                stop = 6;
                break;
            }
            if (isTerminate != NULL && isTerminate(runid, iterations, bestValue)) {
                stop = 7;
                break;
            }
            // Adjust step size in case of equal function values (flat fitness)
            if (bestValue == fitness[arindex[(int) (0.1 + popsize / 4.)]]) {
                sigma *= exp(0.2 + cs / damps);
            }
            if (iterations > 2
                    && max(historyWorst, bestFitness)
                            - ::min(historyBest, bestFitness) == 0) {
                sigma *= ::exp(0.2 + cs / damps);
            }
            // store best in history
            for (int i = 1; i < fitnessHistory.size(); i++)
                fitnessHistory[i] = fitnessHistory[i - 1];
            fitnessHistory[0] = bestFitness;
        }
    }

    vec getBestX() {
        return bestX;
    }

    double getBestValue() {
        return bestValue;
    }

    double getIterations() {
        return iterations;
    }

    double getStop() {
        return stop;
    }

private:
      long runid;
      Fittness* fitfun;
      vec guess;
      double accuracy;
      is_terminate_type isTerminate;
      int popsize; // population size
      vec inputSigma;
      int dim;
      int maxIterations;
      int maxEvaluations;
      double stopfitness;
      double stopTolUpX;
      double stopTolX;
      double stopTolFun;
      double stopTolHistFun;
      int mu; //
      vec weights;
      double mueff; //
      double sigma;
      double cc;
      double cs;
      double damps;
      double ccov1;
      double ccovmu;
      double chiN;
      double ccov1Sep;
      double ccovmuSep;
      vec xmean;
      vec pc;
      vec ps;
      double normps;
      mat B;
      mat BD;
      mat diagD;
      mat C;
      vec diagC;
      int iterations;
      vec fitnessHistory;
      int historySize;
      double bestValue;
      vec bestX;
      int stop;
};

// see https://cvstuff.wordpress.com/2014/11/27/wraping-c-code-with-python-ctypes-memory-and-pointers/

extern "C" {
    void seed(int s) {
        arma_rng::set_seed(s);
    }
}

extern "C" {
    void seedRandom() {
        arma_rng::set_seed_random();
    }
}

extern "C" {
    void free_mem(double* a) {
        delete[] a;
    }
}

extern "C" {
    double* optimizeACMA_C(long runid, callback_type func, int dim, double *init,
            double *lower, double *upper, double *sigma, int maxIter, int maxEvals,
            double stopfitness, int mu, int popsize, double accuracy,
            bool useTerminate, is_terminate_type isTerminate) {
        int n = dim;
        double *res = new double[n + 4];
        vec guess(n), lower_limit(n), upper_limit(n), inputSigma(n);
        bool useLimit = false;
        for (int i = 0; i < n; i++) {
            guess[i] = init[i];
            inputSigma[i] = sigma[i];
            lower_limit[i] = lower[i];
            upper_limit[i] = upper[i];
            useLimit |= (lower[i] != 0);
            useLimit |= (upper[i] != 0);
        }
        if (useLimit == false) {
            lower_limit.resize(0);
            upper_limit.resize(0);
        }
        Fittness fitfun(func, lower_limit, upper_limit);
        AcmaesOptimizer opt(
            runid,
            &fitfun,
            popsize,
            mu,
            guess,
            inputSigma,
            maxIter,
            maxEvals,
            accuracy,
            stopfitness,
            useTerminate ? isTerminate : NULL);
        try {
            opt.doOptimize();
            vec bestX = opt.getBestX();
            double bestY = opt.getBestValue();
            for (int i = 0; i < n; i++)
                res[i] = bestX[i];
            res[n] = bestY;
            res[n+1] = fitfun.getEvaluations();
            res[n+2] = opt.getIterations();
            res[n+3] = opt.getStop();
            return res;
        } catch (std::exception& e) {
            cout << e.what() << endl;
            return res;
        }
    }
}

max_stars_repo_name: juliendehos/fast-cma-es

max_issues_repo_name: juliendehos/fast-cma-es

max_forks_repo_name: juliendehos/fast-cma-es


text:
#include <algorithm>

#include <iostream>
#include <vector>

#include <boost/sort/common/time_measure.hpp>

uint64_t llcnt_partitionings=0;
uint64_t llcnt_partitions=0;

extern "C" {
  #include "introsort.h"
}

size_t NELEM = 32;

namespace bsc = boost::sort::common;

using bsc::time_point;
using bsc::now;
using bsc::subtract_time;

template <typename A> void print_range(A begin, A end) {

  uint64_t last=0;
  bool dots=false;
  for (auto i=begin;i<end;++i) {
      bool print = i==begin || last+1 != *i;

      if (!print && !dots) {std::cout<<"..."; dots=true; }

      if (print && dots) {std::cout<<last; dots=false; }

      if (print && i!=begin) std::cout<<" ";
      if (print) {std::cout<<*i; dots=false; }

      last=*i;
  }

  if (dots) {std::cout<<last; dots=false; }

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

void prn(int x) {
  if (x<10) std::cout<<" "; std::cout<<x;
}

template <typename A> void print_range2(A l0, A begin, A end) {

  size_t n = end-begin;
  size_t base = begin-l0;

  for (size_t i=0;i<n;++i) {prn(base+i); std::cout<<" ";}
  std::cout<<std::endl;
  for (size_t i=0;i<n;++i) {prn(*(begin+i)); std::cout<<" ";}
  std::cout<<std::endl;
}

/*
template <typename A> void print_range(A begin, A end) {
  for (auto i=begin;i<end;++i) std::cout<<*i<<" ";
  std::cout<<std::endl;
}
*/

extern "C" {
  void incr_partitionings() {++llcnt_partitionings;}
  void incr_partitions() {++llcnt_partitions;}

  void print_partition(uint64_t *a, int64_t l, int64_t h) {
    print_range(a+l,a+h);
  }

}

template<typename RandomAccessIterator>
  inline void
  std_heapsort(RandomAccessIterator first, RandomAccessIterator last)
  {
    std::make_heap(first,last);
    std::sort_heap(first,last);
  }

namespace annot {

  uint64_t cnt_dlimit=0;
  uint64_t cnt_intro_loops=0;
  uint64_t cnt_partitionings=0;
  uint64_t cnt_partitions=0;

  void print_stats() {
    std::cout<<"**** STL ***"<<std::endl;
    std::cout<<"hit depth limit: "<<cnt_dlimit<<std::endl;
    std::cout<<"intro loops: "<<cnt_intro_loops<<std::endl;
    std::cout<<"partitionings: "<<cnt_partitionings<<std::endl;
    std::cout<<"partitions: "<<cnt_partitions<<std::endl;
    std::cout<<std::endl;
    std::cout<<"**** Isabelle-LLVM ***"<<std::endl;
    std::cout<<"partitionings: "<<llcnt_partitionings<<std::endl;
    std::cout<<"partitions: "<<llcnt_partitions<<std::endl;

  }

  /// This is a helper function for the sort routine.
  template<typename _RandomAccessIterator, typename _Size, typename _Compare>
    void
    __introsort_loop(_RandomAccessIterator __first,
		     _RandomAccessIterator __last,
		     _Size __depth_limit, _Compare __comp)
    {
      while (__last - __first > int(std::_S_threshold))
	{
          ++cnt_intro_loops;
	  if (__depth_limit == 0)
	    {
              ++cnt_dlimit;
	      std::__partial_sort(__first, __last, __last, __comp);
	      return;
	    }
	  --__depth_limit;
          print_range(__first,__last);
	  _RandomAccessIterator __cut =
	    std::__unguarded_partition_pivot(__first, __last, __comp);
          print_range(__first,__last);
          ++cnt_partitionings;
	  annot::__introsort_loop(__cut, __last, __depth_limit, __comp);
	  __last = __cut;
	}

      ++cnt_partitions;
    }

  // sort

  template<typename _RandomAccessIterator, typename _Compare>
    inline void
    __sort(_RandomAccessIterator __first, _RandomAccessIterator __last,
	   _Compare __comp)
    {
      if (__first != __last)
	{
	  annot::__introsort_loop(__first, __last,
				std::__lg(__last - __first) * 2,
				__comp);
	  std::__final_insertion_sort(__first, __last, __comp);
	}
    }

  template<typename _RandomAccessIterator>
    inline void
    sort(_RandomAccessIterator __first, _RandomAccessIterator __last)
    {
      // concept requirements
      __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept<
	    _RandomAccessIterator>)
      __glibcxx_function_requires(_LessThanComparableConcept<
	    typename iterator_traits<_RandomAccessIterator>::value_type>)
      __glibcxx_requires_valid_range(__first, __last);
      __glibcxx_requires_irreflexive(__first, __last);

      annot::__sort(__first, __last, __gnu_cxx::__ops::__iter_less_iter());
    }

}

namespace test2 {

  std::vector<uint64_t>::iterator l0;

  /// This is a helper function...
  template<typename _RandomAccessIterator, typename _Compare>
    _RandomAccessIterator
    __unguarded_partition(_RandomAccessIterator __first,
			  _RandomAccessIterator __last,
			  _RandomAccessIterator __pivot, _Compare __comp)
    {
      while (true)
	{
	  while (__first!=__last && __comp(__first, __pivot))
	    ++__first;
	  --__last;
	  while (__first!=__last && __comp(__pivot, __last))
	    --__last;
	  if (!(__first < __last))
	    return __first;
	  std::iter_swap(__first, __last);
	  ++__first;
	}
    }

  /// This is a helper function...
  template<typename _RandomAccessIterator, typename _Compare>
    inline _RandomAccessIterator
    __unguarded_partition_pivot(_RandomAccessIterator __first,
				_RandomAccessIterator __last, _Compare __comp)
    {
      _RandomAccessIterator __mid = __first + (__last - __first) / 2;

      std::cout<<"mid = "<<__mid-l0<<std::endl;

      std::__move_median_to_first(__first, __first + 1, __mid, __last - 1,
				  __comp);
      return test2::__unguarded_partition(__first + 1, __last, __first, __comp);
    }

  /// This is a helper function for the sort routine.
  template<typename _RandomAccessIterator, typename _Size, typename _Compare>
    void
    __introsort_loop(_RandomAccessIterator __first,
		     _RandomAccessIterator __last,
		     _Size __depth_limit, _Compare __comp)
    {
      while (__last - __first > int(std::_S_threshold))
	{
          std::cout<<"Sorting ["<<(__first-l0)<<"..."<<(__last-l0)<<"]"<<std::endl;

	  if (__depth_limit == 0)
	    {
              std::cout<<"HIT DEPTH LIMIT"<<std::endl;
	      std::__partial_sort(__first, __last, __last, __comp);
	      return;
	    }
	  --__depth_limit;
	  _RandomAccessIterator __cut =
	    test2::__unguarded_partition_pivot(__first, __last, __comp);

          std::cout<<"cut at "<<(__cut-l0)<<std::endl;
          print_range2(l0,__first,__last);

	  test2::__introsort_loop(__cut, __last, __depth_limit, __comp);
	  __last = __cut;
	}
    }

  template<typename _RandomAccessIterator, typename _Compare>
    inline void
    __sort(_RandomAccessIterator __first, _RandomAccessIterator __last,
	   _Compare __comp)
    {
      if (__first != __last)
	{
	  test2::__introsort_loop(__first, __last,
				std::__lg(__last - __first) * 2,
				__comp);

          std::cout<<"partially sorted array"<<std::endl;
          print_range2(l0,__first,__last);

	  std::__final_insertion_sort(__first, __last, __comp);

          std::cout<<"RESULT"<<std::endl;
          print_range2(l0,__first,__last);

	}
    }

  template<typename _RandomAccessIterator>
    inline void
    sort(_RandomAccessIterator __first, _RandomAccessIterator __last)
    {
      // concept requirements
      __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept<
	    _RandomAccessIterator>)
      __glibcxx_function_requires(_LessThanComparableConcept<
	    typename iterator_traits<_RandomAccessIterator>::value_type>)
      __glibcxx_requires_valid_range(__first, __last);
      __glibcxx_requires_irreflexive(__first, __last);

      test2::__sort(__first, __last, __gnu_cxx::__ops::__iter_less_iter());
    }

}

template<typename A> void time_op(std::string name, A op) {
  auto start = now ();
  op();
  auto finish = now ();
  auto duration = subtract_time (finish, start);

  std::cout<<name<<": "<<duration<<std::endl;
}

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

  std::cout<<sizeof(llstring)<<std::endl;
  std::cout<<sizeof(std::vector<char>)<<std::endl;
  std::cout<<sizeof(std::string)<<std::endl;

  return 1;

  std::vector<uint64_t> A,B;

  A.reserve (NELEM);
  A.clear ();
  for (size_t i = 0; i < NELEM; ++i)
      A.push_back (i);

  A[0]=9;
  A[15]=10;

  B=A;

  test2::l0=B.begin();

  time_op("test2::sort", [&B]{test2::sort(B.begin(),B.end());});

//   B=A;
//   time_op("std::sort", [&B]{std::sort(B.begin(),B.end());});

//   B=A;
//   time_op("std::heapsort", [&B]{std_heapsort(B.begin(),B.end());});
//
//   B=A;
//   time_op("isabelle-llvm::heapsort", [&B]{heapsort(B.data(),0,NELEM);});

//   annot::print_stats();

/*
  B=A;
  time_op("std::heapsort", [&B]{std::make_heap(B.begin(),B.end()); std::sort_heap(B.begin(),B.end()); });*/

//   xxx, ctd here: try to confirm influence of insertion-sort (measure time with omitted final-sort)
//   try to tune threshold factor?

}


text:
// Boost.Geometry

// Copyright (c) 2021, Oracle and/or its affiliates.
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle

// Licensed under the Boost Software License version 1.0.
// http://www.boost.org/users/license.html

#ifndef BOOST_GEOMETRY_STRATEGIES_LINE_INTERPOLATE_GEOGRAPHIC_HPP
#define BOOST_GEOMETRY_STRATEGIES_LINE_INTERPOLATE_GEOGRAPHIC_HPP

#include <boost/geometry/strategies/detail.hpp>

#include <boost/geometry/strategies/distance/detail.hpp>

#include <boost/geometry/strategies/geographic/distance.hpp>
#include <boost/geometry/strategies/geographic/line_interpolate.hpp>

#include <boost/geometry/strategies/line_interpolate/services.hpp>

namespace boost { namespace geometry
{

namespace strategies { namespace line_interpolate
{

template
<
    typename FormulaPolicy = strategy::andoyer,
    typename Spheroid = srs::spheroid<double>,
    typename CalculationType = void
>
class geographic
    : public strategies::detail::geographic_base<Spheroid>
{
    using base_t = strategies::detail::geographic_base<Spheroid>;

public:
    geographic() = default;

    explicit geographic(Spheroid const& spheroid)
        : base_t(spheroid)
    {}

    template <typename Geometry1, typename Geometry2>
    auto distance(Geometry1 const&, Geometry2 const&,
                  distance::detail::enable_if_pp_t<Geometry1, Geometry2> * = nullptr) const
    {
        return strategy::distance::geographic
                <
                    FormulaPolicy, Spheroid, CalculationType
                >(base_t::m_spheroid);
    }

    template <typename Geometry>
    auto line_interpolate(Geometry const&) const
    {
        return strategy::line_interpolate::geographic
                <
                    FormulaPolicy, Spheroid, CalculationType
                >(base_t::m_spheroid);
    }
};

namespace services
{

template <typename Geometry>
struct default_strategy<Geometry, geographic_tag>
{
    using type = strategies::line_interpolate::geographic<>;
};

template <typename FP, typename S, typename CT>
struct strategy_converter<strategy::line_interpolate::geographic<FP, S, CT> >
{
    static auto get(strategy::line_interpolate::geographic<FP, S, CT> const& s)
    {
        return strategies::line_interpolate::geographic<FP, S, CT>(s.model());
    }
};

} // namespace services

}} // namespace strategies::line_interpolate

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_STRATEGIES_LINE_INTERPOLATE_GEOGRAPHIC_HPP


text:
#include <functional>
#include <future>
#include <thread>
#include <map>
#include <wiertlo/lambda_visitor.hpp>
#include <gdbplz/utility/blocking_queue.hpp>
#include <gdbplz/utility/counter.hpp>
#include <gdbplz/gdb_raw.hpp>
#include <gdbplz/gdb_version.hpp>
#include <gdbplz/function_id.hpp>
#include <gdbplz/source_location.hpp>
#include <gdbplz/session.hpp>
#include <gdbplz/internal/parsing.hpp>
#include <iostream>
#include <boost/log/trivial.hpp>
#include <boost/signals2.hpp>

namespace gdbplz
{
	struct user_token_compare
	{
		bool operator()(const user_token& lhs, const user_token& rhs)
		{
			return lhs.get() < rhs.get();
		}
	};

	struct session::impl : wiertlo::pimpl_implementation_mixin<session::pimpl_handle_type, session::impl>
	{
		utility::Counter<unsigned> token_counter; // access from the class
		std::unique_ptr<abstract_connection> connection_; // (thread-safe)
		boost::signals2::signal<void(std::string)> signal_program_output;
		boost::signals2::signal<void(std::string)> signal_cli_responses;
		boost::signals2::signal<void(std::string)> signal_gdb_logs;
		std::thread event_thread; // access from the class
		wiertlo::blocking_queue<std::pair<user_token, std::promise<result_record>>> promises_queue;

		impl(std::unique_ptr<abstract_connection> connection_) :
			token_counter(),
			connection_(std::move(connection_))
		{

		}

		std::future<result_record> send(mi_command mi)
		{
			mi.token = std::to_string(token_counter());
			std::promise<result_record> promise;
			auto future = promise.get_future();
			promises_queue.push(std::make_pair(mi.token, std::move(promise)));
			connection_->send(mi);
			return future;
		}
	};

	std::future<result_record> session::send(mi_command mi)
	{
		auto& i = impl::get(pi);
		return i.send(mi);
	}

	session::~session()
	{
		auto& i = impl::get(pi);
		i.event_thread.detach();
	}

	session::session(session&&) = default;
	session& session::operator=(session&&) = default;

	boost::signals2::signal<void(std::string)>& session::signal_program_output()
	{
		auto& i = impl::get(pi);
		return i.signal_program_output;
	}

	boost::signals2::signal<void(std::string)>& session::signal_cli_responses()
	{
		auto& i = impl::get(pi);
		return i.signal_cli_responses;
	}

	boost::signals2::signal<void(std::string)>& session::signal_gdb_logs()
	{
		auto& i = impl::get(pi);
		return i.signal_gdb_logs;
	}

	session::session(std::unique_ptr<abstract_connection> conn) :
		pi(impl::create_pimpl_handle(std::unique_ptr<impl>(new impl(std::move(conn)))))
	{
		auto& i = impl::get(pi);
		// set up thread now, when everything's initialized
		i.event_thread = std::thread([&i]()
		{
			std::map<user_token, std::promise<result_record>, user_token_compare> promises;
			bool quit = false;
			do
			{
				auto resopt = i.connection_->wait();
				if(!resopt)
					throw "FUCK"; // TODO: suitable exception type
				boost::apply_visitor(wiertlo::make_lambda_visitor<void>(
					[&](const output& out)
					{
						boost::apply_visitor(wiertlo::make_lambda_visitor<void>(
						[&](const result_record& res)
						{
							auto it = promises.find(res.token);
							if(it != promises.end())
							{
								it->second.set_value(res);
							}
							promises.erase(it);
						},
						[&](const async_record& as)
						{

						},
						[&](const stream_record& str)
						{
							boost::apply_visitor(wiertlo::make_lambda_visitor<void>(
							[&](const console_stream_output& output)
							{
								i.signal_cli_responses(output.get());
							},
							[&](const target_stream_output& output)
							{
								std::string s = output.get();
								i.signal_program_output(s);
							},
							[&](const log_stream_output& output)
							{
								i.signal_gdb_logs(output.get());
							}), str);
						},
						[&](end_of_output_tag)
						{

						}), out);
					},
					[&](const input& in)
					{
						boost::apply_visitor(wiertlo::make_lambda_visitor<void>(
						[&](const mi_command& comm)
						{
							promises.insert(i.promises_queue.pop());
						},
						[&](const cli_command& comm)
						{
							// TODO:
						},
						[&](end_work)
						{
							quit = true;
						}), in);
					}), *resopt);
			} while(!quit);
		});
	}

	void fill_in_defaults(local_params& params)
	{
		if(!params.arguments)
			params.arguments = std::vector<boost::string_ref>();
		if(!params.symbol_file)
			params.symbol_file = params.debugged_executable;
		// TODO: handle in another way
		if(!params.working_directory)
			params.symbol_file = params.debugged_executable.parent_path();
	}

	std::shared_ptr<inferior> session::launch(local_params params)
	{
		auto& i = impl::get(pi);
		fill_in_defaults(params);

		std::future<result_record> result;
		std::vector<nonempty<std::string>> cmdline_args(params.arguments->begin(), params.arguments->end());
		result = i.send(mi_command{ "", "exec-arguments", {}, cmdline_args });
		if(result.get().state != result_class::done)
			throw "FUCK";
		result = i.send(mi_command{ "", "file-symbol-file", {}, { params.symbol_file->string() } });
		if(result.get().state != result_class::done)
			throw "FUCK";
		/*result = i.send(mi_command{ "", "environment-directory", {}, { params.working_directory->string() } });
		if(result.get().state != result_class::done)
			throw "FUCK";*/
		result = i.send(mi_command{ "", "file-exec-file", {}, { params.debugged_executable.string() } });
		if(result.get().state != result_class::done)
			throw "FUCK";
		result = i.send(mi_command{ "", "exec-run", {}, {} });
		if(result.get().state != result_class::done)
			throw "FUCK";
		//params.arguments;
		return nullptr;
	}

	gdb_version session::version() const
	{
		//auto& i = impl::get(pi);
		// TODO: implement
		return gdb_version(0, 0, 0, "");
	}

	const auto tied_version = [](const gdb_version& v)
	{
		return std::tie(v.major, v.minor, v.patch, v.others);
	};

	bool gdb_version::operator<(const gdb_version& other) const
	{
		return tied_version(*this) < tied_version(other);
	}

	bool gdb_version::operator==(const gdb_version& other) const
	{
		return tied_version(*this) == tied_version(other);
	}

// Remove the "helpful" macros defined by glibc.
// Friendly reminder: I'm using `-std=c++11 -Wall -Wextra -pedantic`, these shouldn't be there.
// I thought only <windows.h> was retarded as fuck.
#ifdef major
#undef major
#endif
#ifdef minor
#undef minor
#endif

	gdb_version::gdb_version(unsigned major, unsigned minor) :
		major(major),
		minor(minor),
		patch(0)
	{

	}

	gdb_version::gdb_version(unsigned major, unsigned minor, unsigned patch) :
		major(major),
		minor(minor),
		patch(patch)
	{

	}

	gdb_version::gdb_version(unsigned major, unsigned minor, unsigned patch, std::string others) :
		major(major),
		minor(minor),
		patch(patch),
		others(others)
	{

	}

	struct function_id::impl : wiertlo::pimpl_implementation_mixin<function_id::pimpl_handle_type, void*, std::string>
	{

	};

	function_id::function_id(const function_id&) = default;
	function_id& function_id::operator=(const function_id&) = default;
	function_id::function_id(function_id&&) = default;
	function_id& function_id::operator=(function_id&&) = default;
	function_id::~function_id() = default;

	bool function_id::operator<(const function_id& other) const
	{
		return impl::get_handle(this->pi) < impl::get_handle(other.pi);
	}

	bool function_id::operator==(const function_id& other) const
	{
		return impl::get_handle(this->pi) == impl::get_handle(other.pi);
	}

	std::string function_id::to_string() const
	{
		return impl::get_handle(this->pi);
	}

	source_location::source_location(boost::filesystem::path source, unsigned long long line) :
		source(source),
		line(line)
	{

	}
}

namespace std
{
	std::size_t hash<::gdbplz::function_id>::operator()(const ::gdbplz::function_id& id) const
	{
		return std::hash<std::string>()(::gdbplz::function_id::impl::get_handle(id.pi));
	}
}

max_stars_repo_name: milleniumbug/gdbplz

max_issues_repo_name: milleniumbug/gdbplz

max_forks_repo_name: milleniumbug/gdbplz


text:
//          Copyright Rein Halbersma 2010-2020.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#include <core/ui/dxp/parser.hpp>
#include <dctl/core/ui/dxp/message.hpp> // factory
//#include <dctl/core.hpp>
#include <boost/test/unit_test.hpp>     // BOOST_AUTO_TEST_SUITE, BOOST_AUTO_TEST_CASE, BOOST_CHECK_EQUAL_COLLECTIONS, BOOST_AUTO_TEST_SUITE_END
#include <stdexcept>                    // invalid_argument
#include <string>                       // string
#include <vector>                       // vector
#include <variant>                      // visit

using namespace dctl::core;

BOOST_AUTO_TEST_SUITE(DXPParser)

        BOOST_FIXTURE_TEST_CASE(MesanderMessageExamples, Fixture)
        {
                // Examples of DXP messages (Layer 2 protocol description)
                // http://www.mesander.nl/damexchange/edxplg2.htm

                std::vector<std::string> messages =
                {
                        "R01Tornado voor Windows 4.0        W060065A",
                        "ATornado voor Windows 4.0        0",
                        "M0012061100",
                        "M001205250422122320",
                        "E00",
                        "CWhat do you think about move 35?",
                        "B005Z",
                        "K1"
                };

                for (auto const& m : messages) {
                        auto value = parse(m);
                        BOOST_CHECK_EQUAL(std::visit([](auto const& v){ return v.str(); }, value), m);
                }
                BOOST_CHECK_THROW(parse("This is not a valid DXP message"), std::invalid_argument);
/*
                auto const initial = basic_state<international, basic_board<international>>::initial();
                auto gamereq = parse(messages[0]);
                BOOST_CHECK_EQUAL(std::visit(to_state, gamereq), initial);
                for (auto it = std::next(messages.begin()); it != messages.end(); ++it) {
                        auto value = parse(*it);
                        BOOST_CHECK_THROW(std::visit(to_state, value), std::invalid_argument);
                }
*/
        }

BOOST_AUTO_TEST_SUITE_END()


text:
#include <math.h>
#include <iostream>
#include <vector>
#include <boost/math/common_factor.hpp>
#include <gecode/gist.hh>

using namespace std;

class ModelExec{
public:
	template <class T>
	void ExecModel (T a, int mode)
	{
		Gist::Print<T> p("Print solution");
		Gist::Options o;
		o.inspect.click(&p);
		Gist::bab(model,o);
		delete model;
		break;
		return;
	}

};

max_stars_repo_name: forsyde/DeSyDe

max_issues_repo_name: forsyde/DeSyDe

max_forks_repo_name: forsyde/DeSyDe


text:
//
// Copyright © 2020 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include "ActivateTimelineReportingCommandHandler.hpp"
#include "TimelineUtilityMethods.hpp"

#include <armnn/Exceptions.hpp>
#include <boost/format.hpp>

namespace armnn
{

namespace profiling
{

void ActivateTimelineReportingCommandHandler::operator()(const arm::pipe::Packet& packet)
{
    ProfilingState currentState = m_StateMachine.GetCurrentState();

    if (!m_ReportStructure.has_value())
    {
            throw armnn::Exception(std::string("Profiling Service constructor must be initialised with an "
                                               "IReportStructure argument in order to run timeline reporting"));
    }

    switch ( currentState )
    {
        case ProfilingState::Uninitialised:
        case ProfilingState::NotConnected:
        case ProfilingState::WaitingForAck:
            throw RuntimeException(boost::str(
                boost::format("Activate Timeline Reporting Command Handler invoked while in a wrong state: %1%")
                    % GetProfilingStateName(currentState)));
        case ProfilingState::Active:
            if ( !( packet.GetPacketFamily() == 0u && packet.GetPacketId() == 6u ))
            {
                throw armnn::Exception(std::string("Expected Packet family = 0, id = 6 but received family =")
                                           + std::to_string(packet.GetPacketFamily())
                                           + " id = " + std::to_string(packet.GetPacketId()));
            }

            if(!m_TimelineReporting)
            {
                m_SendTimelinePacket.SendTimelineMessageDirectoryPackage();

                TimelineUtilityMethods::SendWellKnownLabelsAndEventClasses(m_SendTimelinePacket);

                m_TimelineReporting = true;

                m_ReportStructure.value().ReportStructure();

                m_BackendNotifier.NotifyBackendsForTimelineReporting();
            }

            break;
        default:
            throw RuntimeException(boost::str(boost::format("Unknown profiling service state: %1%")
                                                  % static_cast<int>(currentState)));
    }
}

} // namespace profiling

} // namespace armnn

max_stars_repo_name: UberLambda/armnn

max_issues_repo_name: UberLambda/armnn

max_forks_repo_name: UberLambda/armnn


text:
#include "subsystems/TurretFeederSubsystem.h"

#include <Eigen/Core>
#include <frc/smartdashboard/SmartDashboard.h>
#include <frc2/command/button/JoystickButton.h>

#include "ctre/Phoenix.h"

TurretFeederSubsystem::TurretFeederSubsystem()
{
    // Disable Talon FX velocity filtering so that our Kalman filter can do the
    // work

    m_feeder.SetNeutralMode(Brake);
    m_feeder.ConfigFactoryDefault();
    // m_feeder.ConfigVoltageMeasurementFilter(true);
    // m_feeder.ConfigVoltageCompSaturation(9);
    //  Set Feeder to coast and config Default
    //  frc::SmartDashboard::PutNumber("Flywheel.Setpoint", 0);
}

void TurretFeederSubsystem::StartFeeder(double FeedRpm)
{
    m_feeder.Set(ControlMode::PercentOutput, FeedRpm);
}

/*
frc2::SequentialCommandGroup FlywheelSubsystem::HoodShot(rad_per_s_t HoodRPM,  double FeedRPM) {
        [this](rad_per_s_t HoodRPM, double FeedRPM) {
            FlywheelSubsystem::StartFeeder(FeedRPM);
            FlywheelSubsystem::SetSetpoint(HoodRPM);
        }

        m_feeder.Set(ControlMode::PercentOutput, FeedRPm),
        FlywheelSubsystem::SetSetpoint(HoodRPM)
}
*/


text:
/*
@copyright Louis Dionne 2015
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_HANA_TEST_TEST_AUTO_LOGICAL_HPP
#define BOOST_HANA_TEST_TEST_AUTO_LOGICAL_HPP

#include <boost/hana/assert.hpp>
#include <boost/hana/bool.hpp>
#include <boost/hana/core/models.hpp>
#include <boost/hana/logical.hpp>

#include <test/auto/base.hpp>

namespace boost { namespace hana { namespace test {
    template <typename L>
    auto laws<Logical, L> = [] {
        static_assert(_models<Logical, L>{}, "");

        // laws
        {
            auto is_true_valued = [](auto x) { return if_(x, true_, false_); };
            auto is_false_valued = [](auto x) { return if_(x, false_, true_); };
            auto for_each_such_that = [](auto xs, auto pred, auto f) {
                for_each(xs, [=](auto x) {
                    eval_if(pred(x),
                        [=](auto _) { _(f)(x); },
                        [](auto _) { }
                    );
                });
            };

            for_each_such_that(objects<L>, is_true_valued, [=](auto t) {
            for_each_such_that(objects<L>, is_false_valued, [=](auto f) {
            for_each(objects<L>, [=](auto a) {
            for_each(objects<L>, [=](auto b) {
            for_each(objects<L>, [=](auto c) {
                // associativity
                BOOST_HANA_CHECK(equal(
                    or_(a, or_(b, c)), or_(or_(a, b), c)
                ));
                BOOST_HANA_CHECK(equal(
                    and_(a, and_(b, c)), and_(and_(a, b), c)
                ));

                // equivalence through commutativity
                BOOST_HANA_CHECK(
                    or_(a, b) ^iff^ or_(b, a)
                );
                BOOST_HANA_CHECK(
                    and_(a, b) ^iff^ and_(b, a)
                );

                // absorption
                BOOST_HANA_CHECK(equal(
                    or_(a, and_(a, b)), a
                ));
                BOOST_HANA_CHECK(equal(
                    and_(a, or_(a, b)), a
                ));

                // left identity
                BOOST_HANA_CHECK(equal(
                    or_(f, a), a
                ));
                BOOST_HANA_CHECK(equal(
                    and_(t, a), a
                ));

                // distributivity
                BOOST_HANA_CHECK(equal(
                    or_(a, and_(b, c)), and_(or_(a, b), or_(a, c))
                ));
                BOOST_HANA_CHECK(equal(
                    and_(a, or_(b, c)), or_(and_(a, b), and_(a, c))
                ));

                // complements
                BOOST_HANA_CHECK(is_true_valued(or_(a, not_(a))));
                BOOST_HANA_CHECK(is_false_valued(and_(a, not_(a))));
            });});});});});
        }
    };
}}} // end namespace boost::hana::test

#endif // !BOOST_HANA_TEST_TEST_AUTO_LOGICAL_HPP

max_stars_repo_name: josephwinston/hana

max_issues_repo_name: josephwinston/hana

max_forks_repo_name: josephwinston/hana


text:
/* Program to verify compilation against the unit test framework */

#define BOOST_TEST_MODULE EmptyTest
#include <boost/test/unit_test.hpp>

namespace {
BOOST_AUTO_TEST_CASE(Empty) {}
} // namespace

max_issues_repo_name: Pangeamt/nectm

max_forks_repo_name: Pangeamt/nectm


text:
/*=============================================================================
    Copyright (c) 2001-2003 Joel de Guzman
    Copyright (c) 2001-2003 Daniel Nuffer
    http://spirit.sourceforge.net/

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

///////////////////////////////////////////////////////////////////////////////
#include <boost/shared_ptr.hpp>
#include <boost/spirit/home/classic/namespace.hpp>
#include <boost/spirit/home/classic/core/primitives/primitives.hpp>
#include <boost/spirit/home/classic/utility/impl/chset/basic_chset.hpp>

///////////////////////////////////////////////////////////////////////////////
namespace lslboost { namespace spirit {

BOOST_SPIRIT_CLASSIC_NAMESPACE_BEGIN

namespace utility { namespace impl {

    // This is here because some compilers choke on out-of-line member
    // template functions.  And we don't want to put the whole algorithm
    // in the chset constructor in the class definition.
    template <typename CharT, typename CharT2>
    void construct_chset(lslboost::shared_ptr<basic_chset<CharT> >& ptr,
            CharT2 const* definition);

}} // namespace utility::impl

///////////////////////////////////////////////////////////////////////////////
//
//  chset class
//
///////////////////////////////////////////////////////////////////////////////
template <typename CharT = char>
class chset: public char_parser<chset<CharT> > {

public:
                    chset();
                    chset(chset const& arg_);
    explicit        chset(CharT arg_);
    explicit        chset(anychar_parser arg_);
    explicit        chset(nothing_parser arg_);
    explicit        chset(chlit<CharT> const& arg_);
    explicit        chset(range<CharT> const& arg_);
    explicit        chset(negated_char_parser<chlit<CharT> > const& arg_);
    explicit        chset(negated_char_parser<range<CharT> > const& arg_);

                    template <typename CharT2>
    explicit        chset(CharT2 const* definition)
                    : ptr(new basic_chset<CharT>())
                    {
                        utility::impl::construct_chset(ptr, definition);
                    }
                    ~chset();

    chset&          operator=(chset const& rhs);
    chset&          operator=(CharT rhs);
    chset&          operator=(anychar_parser rhs);
    chset&          operator=(nothing_parser rhs);
    chset&          operator=(chlit<CharT> const& rhs);
    chset&          operator=(range<CharT> const& rhs);
    chset&          operator=(negated_char_parser<chlit<CharT> > const& rhs);
    chset&          operator=(negated_char_parser<range<CharT> > const& rhs);

    void            set(range<CharT> const& arg_);
    void            set(negated_char_parser<chlit<CharT> > const& arg_);
    void            set(negated_char_parser<range<CharT> > const& arg_);

    void            clear(range<CharT> const& arg_);
    void            clear(negated_char_parser<range<CharT> > const& arg_);
    bool            test(CharT ch) const;
    chset&          inverse();
    void            swap(chset& x);

    chset&          operator|=(chset const& x);
    chset&          operator&=(chset const& x);
    chset&          operator-=(chset const& x);
    chset&          operator^=(chset const& x);

private:

    lslboost::shared_ptr<basic_chset<CharT> > ptr;
};

///////////////////////////////////////////////////////////////////////////////
//
//  Generator functions
//
///////////////////////////////////////////////////////////////////////////////
template <typename CharT>
inline chset<CharT>
chset_p(chlit<CharT> const& arg_)
{ return chset<CharT>(arg_); }

//////////////////////////////////
template <typename CharT>
inline chset<CharT>
chset_p(range<CharT> const& arg_)
{ return chset<CharT>(arg_); }

template <typename CharT>
inline chset<CharT>
chset_p(negated_char_parser<chlit<CharT> > const& arg_)
{ return chset<CharT>(arg_); }

template <typename CharT>
inline chset<CharT>
chset_p(negated_char_parser<range<CharT> > const& arg_)
{ return chset<CharT>(arg_); }

//////////////////////////////////
inline chset<char>
chset_p(char const* init)
{ return chset<char>(init); }

//////////////////////////////////
inline chset<wchar_t>
chset_p(wchar_t const* init)
{ return chset<wchar_t>(init); }

//////////////////////////////////
inline chset<char>
chset_p(char ch)
{ return chset<char>(ch); }

//////////////////////////////////
inline chset<wchar_t>
chset_p(wchar_t ch)
{ return chset<wchar_t>(ch); }

//////////////////////////////////
inline chset<int>
chset_p(int ch)
{ return chset<int>(ch); }

//////////////////////////////////
inline chset<unsigned int>
chset_p(unsigned int ch)
{ return chset<unsigned int>(ch); }

//////////////////////////////////
inline chset<short>
chset_p(short ch)
{ return chset<short>(ch); }

#if !defined(BOOST_NO_INTRINSIC_WCHAR_T)
//////////////////////////////////
inline chset<unsigned short>
chset_p(unsigned short ch)
{ return chset<unsigned short>(ch); }
#endif
//////////////////////////////////
inline chset<long>
chset_p(long ch)
{ return chset<long>(ch); }

//////////////////////////////////
inline chset<unsigned long>
chset_p(unsigned long ch)
{ return chset<unsigned long>(ch); }

#ifdef BOOST_HAS_LONG_LONG
//////////////////////////////////
inline chset< ::lslboost::long_long_type>
chset_p( ::lslboost::long_long_type ch)
{ return chset< ::lslboost::long_long_type>(ch); }

//////////////////////////////////
inline chset< ::lslboost::ulong_long_type>
chset_p( ::lslboost::ulong_long_type ch)
{ return chset< ::lslboost::ulong_long_type>(ch); }
#endif

///////////////////////////////////////////////////////////////////////////////
BOOST_SPIRIT_CLASSIC_NAMESPACE_END

}} // namespace BOOST_SPIRIT_CLASSIC_NS

#endif

#include <boost/spirit/home/classic/utility/impl/chset.ipp>
#include <boost/spirit/home/classic/utility/chset_operators.hpp>