text:
#include <ostream>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdio.h>
#include <utility>
#include <vector>
#include <iomanip>
#include <boost/algorithm/string.hpp>
#include <cmath>
#include <cstdlib>

using std::vector;
using std::string;
using std::stringstream;
using std::endl;
using std::pair;

vector<string> lookup_argument(const string& argument, const int& ind) {
  using boost::iequals;
  vector<string> args;
  if (iequals(argument, "int")) {
    args.push_back("int");
  } else if (iequals(argument, "ints")) {
    args.push_back("int");
    args.push_back("std::vector<int>");
    args.push_back("Eigen::Matrix<int, Eigen::Dynamic, 1>");
    args.push_back("Eigen::Matrix<int, 1, Eigen::Dynamic>");
  } else if (iequals(argument, "double")) {
    args.push_back("double");
    args.push_back("var");
  } else if (iequals(argument, "doubles")) {
    args.push_back("double");
    args.push_back("std::vector<double>");
    args.push_back("Eigen::Matrix<double, Eigen::Dynamic, 1>");
    args.push_back("Eigen::Matrix<double, 1, Eigen::Dynamic>");
    if (ind == 1) {
    args.push_back("var");
    args.push_back("std::vector<var>");
    args.push_back("Eigen::Matrix<var, Eigen::Dynamic, 1>");
    args.push_back("Eigen::Matrix<var, 1, Eigen::Dynamic>");
    }
    else if (ind == 2) {
    args.push_back("fvar<double>");
    args.push_back("std::vector<fvar<double> >");
    args.push_back("Eigen::Matrix<fvar<double>, Eigen::Dynamic, 1>");
    args.push_back("Eigen::Matrix<fvar<double>, 1, Eigen::Dynamic>");
    }
    else if (ind == 3) {
    args.push_back("fvar<var>");
    args.push_back("std::vector<fvar<var> >");
    args.push_back("Eigen::Matrix<fvar<var>, Eigen::Dynamic, 1>");
    args.push_back("Eigen::Matrix<fvar<var>, 1, Eigen::Dynamic>");
    }
    else if (ind == 4) {
    args.push_back("fvar<fvar<double> >");
    args.push_back("std::vector<fvar<fvar<double> > >");
    args.push_back("Eigen::Matrix<fvar<fvar<double> >, Eigen::Dynamic, 1>");
    args.push_back("Eigen::Matrix<fvar<fvar<double> >, 1, Eigen::Dynamic>");
    }
    else if (ind == 5) {
    args.push_back("fvar<fvar<var> >");
    args.push_back("std::vector<fvar<fvar<var> > >");
    args.push_back("Eigen::Matrix<fvar<fvar<var> >, Eigen::Dynamic, 1>");
    args.push_back("Eigen::Matrix<fvar<fvar<var> >, 1, Eigen::Dynamic>");
    }
  }
  return args;
}

std::ostream& operator<< (std::ostream& o, pair<string, string>& p) {
  o << "<" << p.first << ", " << p.second << ">" << endl;
  return o;
}

template <class T>
std::ostream& operator<< (std::ostream& o, vector<T>& vec) {
  o << "vector size: " << vec.size() << endl;
  for (size_t n = 0; n < vec.size(); n++) {
    o << "  \'" << vec[n] << "\'" << endl;
  }
  return o;
}

void write_includes(vector<std::ostream *>& outs, const string& include) {
  for (size_t n = 0; n < outs.size(); n++) {
    std::ostream* out = outs[n];
    *out << "#include <gtest/gtest.h>" << endl;
    *out << "#include <boost/mpl/vector.hpp>" << endl;
    *out << "#include <test/prob/test_fixture_distr.hpp>" << endl;
    *out << "#include <test/prob/test_fixture_cdf.hpp>" << endl;
    *out << "#include <test/prob/test_fixture_cdf_log.hpp>" << endl;
    *out << "#include <test/prob/test_fixture_ccdf_log.hpp>" << endl;
    *out << "#include <" << include << ">" << endl;
    *out << endl;
  }
}

vector<string> tokenize_arguments(const string& arguments) {
  vector<string> tokens;
  string delimiters = ", ";
  string args_only_string = arguments.substr(arguments.find(":") + 1);
  boost::algorithm::trim(args_only_string);
  boost::algorithm::split(tokens, args_only_string,
        boost::is_any_of(delimiters),
        boost::token_compress_on);
  return tokens;
}

size_t size(const vector<vector<string> >& sequences) {
  if (sequences.size() == 0)
    return 0;
  size_t N = 1;
  for (size_t n = 0; n < sequences.size(); n++)
    N *= sequences[n].size();
  return N;
}

bool is_argument_list(const string& line) {
  size_t comment = line.find("//");
  if (comment == string::npos)
    return false;
  size_t keyword = line.find("Arguments:", comment+1);
  if (keyword == string::npos)
    return false;
  return true;
}

string read_file(const string& in_name) {
  std::ifstream in(in_name.c_str());

  string file;
  in.seekg(0, std::ios::end);
  file.resize(in.tellg());
  in.seekg(0, std::ios::beg);
  in.read(&file[0], file.size());
  in.close();

  return file;
}

string read_arguments_from_file(const string& file) {
  string arguments;
  std::istringstream in(file);
  if (!in.eof()) {
    std::getline (in, arguments);
    while (in.good() && !is_argument_list(arguments)) {
      std::getline (in, arguments);
    }
  }
  if (!is_argument_list(arguments))
    arguments = "";
  return arguments;
}

pair<string, string> read_test_name_from_file(const string& file) {
  pair<string, string> name;

  size_t pos = 0;
  string class_keyword = "class ";
  string public_keyword = "public ";
  pos = file.find(class_keyword, pos);
  if (pos < file.size()) {
    pos += class_keyword.size();
    size_t pos2 = file.find(":", pos);
    string test_name = file.substr(pos, pos2-pos);
    pos = file.find(public_keyword, pos) + public_keyword.size();
    pos2 = file.find("{", pos);
    string fixture_name = file.substr(pos, pos2-pos);
    pos = file.find("};", pos) + 2;
    boost::algorithm::trim(test_name);
    boost::algorithm::trim(fixture_name);

    if (fixture_name.find("Test") != string::npos) {
      fixture_name += "Fixture";
      name = pair<string, string>(test_name, fixture_name);
    }
  }
  return name;
}

vector<vector<string> > build_argument_sequence(const string& arguments,
                                                const int& ind) {
  vector<string> argument_list = tokenize_arguments(arguments);
  vector<vector<string> > argument_sequence;
  for (size_t n = 0; n < argument_list.size(); n++)
    argument_sequence.push_back(lookup_argument(argument_list[n],ind));
  return argument_sequence;
}

bool check_all_double(string base, string arg) {
  string arguments = base + arg;
  bool result = true;
  bool temp;

  vector<string> tokens;
  string delimiters = ", ";
  boost::algorithm::trim(arguments);
  boost::algorithm::split(tokens, arguments,
        boost::is_any_of(delimiters),
        boost::token_compress_on);

  for (size_t i = 0; i < tokens.size(); i++) {
    if (tokens[i] == "1" || tokens[i] == "Eigen::Dynamic>"
        || tokens[i] == "1>" || tokens[i] == "Eigen::Dynamic")
      result = result && true;
    else {
      temp = (tokens[i] == "double") || (tokens[i] == "std::vector<double>")
        || (tokens[i] == "Eigen::Matrix<double") || (tokens[i] == "int")
        || (tokens[i] == "std::vector<int>") || (tokens[i] == "Eigen::Matrix<int");
      result = result && temp;
    }
  }
  return result;
}

int num_doubles(string arguments) {
  vector<string> tokens;
  string delimiters = ", ";
  boost::algorithm::trim(arguments);
  boost::algorithm::split(tokens, arguments,
        boost::is_any_of(delimiters),
        boost::token_compress_on);

  int num = 0;
  for (size_t i = 0; i < tokens.size(); i++) {
    if (tokens[i] == "Doubles")
      ++num;
  }
  return num;
}
int num_ints(string arguments) {
  vector<string> tokens;
  string delimiters = ", ";
  boost::algorithm::trim(arguments);
  boost::algorithm::split(tokens, arguments,
        boost::is_any_of(delimiters),
        boost::token_compress_on);

  int num = 0;
  for (size_t i = 0; i < tokens.size(); i++) {
    if (tokens[i] == "Ints")
      ++num;
  }
  return num;
}

void write_types_typedef(vector<std::ostream *>& outs, string base, size_t& N,
                         vector<vector<string> > argument_sequence,
                         const size_t depth, const int& index, const int& N_TESTS) {
  vector<string> args = argument_sequence.front();
  argument_sequence.erase(argument_sequence.begin());
  if (argument_sequence.size() > 0) {
    for (size_t n = 0; n < args.size(); n++)
      write_types_typedef(outs, base + args[n] + ", ", N, argument_sequence,
                          depth, index, N_TESTS);
  } else {
    string extra_args;
    for (size_t n = depth; n < 6; n++) {
      extra_args += ", empty";
    }
    for (size_t n = 0; n < args.size(); n++) {
      std::ostream* out = outs[int(N / N_TESTS)];
      if (index == 1) {
        *out << "typedef boost::mpl::vector<" << base << args[n] << extra_args;
        if (extra_args.size() == 0)
          *out << " ";
        *out << "> type_v_" << N << ";" << endl;
        N++;
      } else {
        if (check_all_double(base,args[n]) == false) {
          *out << "typedef boost::mpl::vector<" << base << args[n] << extra_args;
          if (extra_args.size() == 0)
            *out << " ";
          else if (index == 2)
            *out << "> type_fd_" << N << ";" << endl;
          else if (index == 3)
            *out << "> type_fv_" << N << ";" << endl;
          else if (index == 4)
            *out << "> type_ffd_" << N << ";" << endl;
          else if (index == 5)
            *out << "> type_ffv_" << N << ";" << endl;
          N++;
        }
      }
    }
  }
}

size_t write_types(vector<std::ostream *>& outs,
                 const vector<vector<string> >& argument_sequence,
                 const int& index, const int& N_TESTS) {
  size_t N = 0;
  write_types_typedef(outs, "", N, argument_sequence,
                      argument_sequence.size(),index,N_TESTS);
  for (size_t n = 0; n < outs.size(); n++)
    *outs[n] << endl;
  return N;
}

void write_test(vector<std::ostream *>& outs, const string& test_name,
                const string& fixture_name, const size_t N, const int& index,
                const int& N_TESTS) {
  for (size_t n = 0; n < N; n++) {
    std::ostream *out = outs[int(n / N_TESTS)];
    if (index == 1)
      *out << "typedef boost::mpl::vector<" << test_name << ", type_v_" << n << "> " << test_name << "_v_" << n << ";" << endl;
    else if (index == 2)
      *out << "typedef boost::mpl::vector<" << test_name << ", type_fd_" << n << "> " << test_name << "_fd_" << n << ";" << endl;
    else if (index == 3)
      *out << "typedef boost::mpl::vector<" << test_name << ", type_fv_" << n << "> " << test_name << "_fv_" << n << ";" << endl;
    else if (index == 4)
      *out << "typedef boost::mpl::vector<" << test_name << ", type_ffd_" << n << "> " << test_name << "_ffd_" << n << ";" << endl;
    else if (index == 5)
      *out << "typedef boost::mpl::vector<" << test_name << ", type_ffv_" << n << "> " << test_name << "_ffv_" << n << ";" << endl;
  }
  for (size_t i = 0; i < outs.size(); i++) {
    *outs[i] << endl;
  }
  for (size_t n = 0; n < N; n++) {
    std::ostream *out = outs[int(n / N_TESTS)];
    if (index == 1)
      *out << "INSTANTIATE_TYPED_TEST_CASE_P(" << test_name << "_v_" << n << ", " << fixture_name << ", " <<  test_name << "_v_" << n << ");" << endl;
    else if (index == 2)
      *out << "INSTANTIATE_TYPED_TEST_CASE_P(" << test_name << "_fd_" << n << ", " << fixture_name << ", " <<  test_name << "_fd_" << n << ");" << endl;
    else if (index == 3)
      *out << "INSTANTIATE_TYPED_TEST_CASE_P(" << test_name << "_fv_" << n << ", " << fixture_name << ", " <<  test_name << "_fv_" << n << ");" << endl;
    else if (index == 4)
      *out << "INSTANTIATE_TYPED_TEST_CASE_P(" << test_name << "_ffd_" << n << ", " << fixture_name << ", " <<  test_name << "_ffd_" << n << ");" << endl;
    else if (index == 5)
      *out << "INSTANTIATE_TYPED_TEST_CASE_P(" << test_name << "_ffv_" << n << ", " << fixture_name << ", " <<  test_name << "_ffv_" << n << ");" << endl;
  }
  for (size_t i = 0; i < outs.size(); i++) {
    *outs[i] << endl;
  }
}

void write_test_cases(vector<std::ostream *>& outs, const string& file,
                      const vector<vector<string> >& argument_sequence,
                      const int& index, const int& N_TESTS) {
  pair<string, string> name = read_test_name_from_file(file);
  string test_name = name.first;
  string fixture_name = name.second;

  size_t num_tests = write_types(outs, argument_sequence,index,N_TESTS);
  write_test(outs, test_name, fixture_name, num_tests,index,N_TESTS);
}

int create_files(const int& argc, const char* argv[],const int& index,
                 const int& start, const int& N_TESTS) {
  if (argc != 3)
    return -1;
  string in_suffix = "_test.hpp";

  string in_name = argv[1];

  size_t last_in_suffix = in_name.find_last_of(in_suffix) + 1 - in_suffix.length();
  string out_name_base = in_name.substr(0, last_in_suffix);

  string file = read_file(in_name);

  string arguments = read_arguments_from_file(file);
  vector<vector<string> > argument_sequence = build_argument_sequence(arguments,index);

  int num_tests;
  if (index == 1)
    num_tests = size(argument_sequence);
  else
    num_tests = size(argument_sequence) - std::pow(4,num_ints(arguments))
      * std::pow(4, num_doubles(arguments));

  vector<std::ostream *> outs;
  const double BATCHES = N_TESTS > 0 ? num_tests / N_TESTS : -N_TESTS;
  for (int n = start+1; n < start+1+BATCHES+1; n++) {
    stringstream out_name;
    out_name << out_name_base;
    out_name << "_" << std::setw(5) << std::setfill('0') << n;
    if (index == 1)
      out_name << "_generated_v_test.cpp";
    else if (index == 2)
      out_name << "_generated_fd_test.cpp";
    else if (index == 3)
      out_name << "_generated_fv_test.cpp";
    else if (index == 4)
      out_name << "_generated_ffd_test.cpp";
    else if (index == 5)
      out_name << "_generated_ffv_test.cpp";
    std::string tmp(out_name.str());
    outs.push_back(new std::ofstream(tmp.c_str()));
  }

  write_includes(outs, in_name);
  if(N_TESTS > 0)
    write_test_cases(outs, file, argument_sequence,index,N_TESTS);
  else if(num_tests > 0)
    write_test_cases(outs, file, argument_sequence,index,ceil(num_tests / BATCHES));

  for (size_t n = 0; n < outs.size(); n++) {
    static_cast<std::ofstream*>(outs[n])->close();
    delete(outs[n]);
  }
  outs.clear();

  return start+BATCHES;
}

/**
 * Generate test cases.
 *
 * @param argc Number of arguments
 * @param argv Arguments. Should contain one argument with a filename and
 * the number of tests per file or if non-positive, the number of files - 1
 *
 * @return 0 for success, negative number otherwise.
 */
int main(int argc, const char* argv[]) {
  int N_TESTS = atoi(argv[2]);
  create_files(argc,argv,1,-1,N_TESTS);  // create var tests
  create_files(argc,argv,2,-1,N_TESTS);  // create fd tests
  create_files(argc,argv,3,-1,N_TESTS);  // create fv tests
  create_files(argc,argv,4,-1,N_TESTS);  // create ffd tests
  create_files(argc,argv,5,-1,N_TESTS);  // create ffv tests

  return 0;
}

max_stars_repo_name: yizhang-cae/torsten

max_issues_repo_name: yizhang-cae/torsten

max_forks_repo_name: yizhang-cae/torsten


text:
// Copyright 2014, D. E. Shaw Research.
// 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 )

// Example code demonstrating how to set up and use a
// counter_based_engine in a threaded program.  Usage:
//
//   counter_based_example [Nthread [Natoms]]
//
// Random numbers are generated in the functions 'assignmasses' and
// 'thermalize'.  By using a counter_based_engine, these functions can
// easily be called in multipe threads with the program's final result
// independent of the number of threads or the assignment of atoms to
// threads.

#include <boost/random/counter_based_engine.hpp>
#include <boost/random/threefry.hpp>
#include <boost/random/normal_distribution.hpp>
#include <boost/random/bernoulli_distribution.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/thread.hpp>
#include <vector>
#include <iostream>
#include <sstream>
#include <cmath>

using namespace boost::random;

// First, provide a tiny bit of illustrative "molecular dynamics" boilerplate.
struct atom{
    float vx, vy, vz; // m/s
    float mass;  // kg/mol
    unsigned id;
};
float kT = 8.314 * 300; // J/mol
float amu = 1.e-3;      // 1 amu = 1e-3 kg/mol

// Choose a pseudo-random function:
typedef threefry<2, uint64_t> Prf;
typedef counter_based_engine<uint32_t, Prf, 32> engine_t;

// An enum to distinguish the different contexts in which we generate
// randoms:
enum { THERMALIZE_CTXT, MASS_ASSIGN_CTXT };

// assignmasses - assigns masses, randomly with equal probability
// of m1 or m2.  Use a bernoulli distribution
void assignmasses(atom* atoms, size_t Natoms, float m1, float m2, const Prf::key_type& key){
    bernoulli_distribution<float> bd;
    engine_t cbeng(key);
    for(size_t i=0; i<Natoms; ++i){
#if __cplusplus>=201103L && defined(BOOST_NO_CXX11_HDR_INITIALIZER_LIST)
        cbeng.restart({atoms[i].id, 0, MASS_ASSIGN_CTXT});
#else
        uint32_t base32[3] = {atoms[i].id, 0, MASS_ASSIGN_CTXT};
        Prf::domain_type start = engine_t::domain_traits::make_counter(&base32[0], &base32[3]);
        cbeng.restart(start);
#endif
        bd.reset();
        atoms[i].mass = bd(cbeng)  ? m1 : m2;
    }
}

// thermalize - assign the velocities according to the
// Maxwell-Boltzmann distribution, i.e., a normal distribution with
// zero mean and 'sigma' that depends on the temperature and the
// atomic mass.
void thermalize(atom* atoms, size_t Natoms, uint32_t timestep, const Prf::key_type& key){
    engine_t cbeng(key);
    for(size_t i=0; i<Natoms; ++i){
        float rmsvelocity = sqrt(kT/atoms[i].mass);
        normal_distribution<float> mbd(0., rmsvelocity);
#if __cplusplus>=201103L && defined(BOOST_NO_CXX11_HDR_INITIALIZER_LIST)
        cbeng.restart({atoms[i].id, timestep, THERMALIZE_CTXT});
#else
        uint32_t base32[3] = {atoms[i].id, timestep, THERMALIZE_CTXT};
        Prf::domain_type start = engine_t::domain_traits::make_counter(&base32[0], &base32[3]);
        //Prf::domain_type start = {atoms[i].id, timestep, THERMALIZE_CTXT};
        cbeng.restart(start);
#endif
        atoms[i].vx = mbd(cbeng);
        atoms[i].vy = mbd(cbeng);
        atoms[i].vz = mbd(cbeng);
    }
}

// mt_assign_masses - launch Nthr threads calling assign_masses in each:
void mt_assignmasses(size_t Nthr, std::vector<atom>& atoms, float m1, float m2, const Prf::key_type& key){
    // Assign atoms to threads in blocks:
    //  thread i updates a block starting at i* (Natoms/Nthr) (rounded appopriately).
    boost::thread_group threads;
    size_t atoms_left = atoms.size();
    atom *start = &atoms[0];
    for(size_t t=0; t<Nthr; ++t){
        size_t atoms_per_thread = atoms_left/(Nthr - t);
        threads.add_thread(new boost::thread(assignmasses, start, atoms_per_thread, m1, m2, key));
        atoms_left -= atoms_per_thread;
        start += atoms_per_thread;
    }
    threads.join_all();
}

// mt_thermalize - launch Nthr threads calling thermalize in each.
void mt_thermalize(size_t Nthr, std::vector<atom>& atoms, uint32_t timestep, const Prf::key_type& key){
    // Assign atoms to threads in blocks:
    //  thread i updates a block starting at i* (Natoms/Nthr) (rounded appopriately).
    boost::thread_group threads;
    size_t atoms_left = atoms.size();
    atom *start = &atoms[0];
    for(size_t t=0; t<Nthr; ++t){
        size_t atoms_per_thread = atoms_left/(Nthr - t);
        threads.add_thread(new boost::thread(thermalize, start, atoms_per_thread, timestep, key));
        atoms_left -= atoms_per_thread;
        start += atoms_per_thread;
    }
    threads.join_all();
}

void out(const std::vector<atom>& atoms, long timestep){
    std::cout << "id mass vx vy vz thermalized at timestep=" << timestep << "\n";
    for(size_t i=0; i<atoms.size(); ++i){
        std::cout << i << " " << atoms[i].mass << " " << atoms[i].vx << " " << atoms[i].vy << " " << atoms[i].vz << "\n";
    }
}

int main(int argc, char **argv){
    size_t nthread = 4;
    if( argc > 1 ){
        nthread = boost::lexical_cast<size_t>(argv[1]);
    }
    uint32_t seed = 1;
    if( argc > 2 ){
        seed = boost::lexical_cast<uint32_t>(argv[2]);
    }

    std::vector<atom> atoms(10);
    for(size_t i=0; i<atoms.size(); ++i){
        atoms[i].id = i;
    }
    Prf::key_type key = {{seed}};
    std::cout << "running with " << nthread << " threads\n";
    long timestep = 1;
    // Pick random masses uniformly between Hydrogen (1amu) and Oxygen (16amu).
    mt_assignmasses(nthread, atoms, 1.*amu, 16.*amu, key);
    // Thermalize the velocities according to the Boltzmann distribution.
    mt_thermalize(nthread, atoms, timestep, key);
    out(atoms, timestep);

    // Advance the timestep and rethermalize.
    timestep++;
    mt_thermalize(nthread, atoms, timestep, key);
    out(atoms, timestep);

    return 0;
}

ext: cpp


text:
// Copyright (c) 2005 - 2014 Marc de Kamps
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation
//      and/or other materials provided with the distribution.
//    * 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 OWNER 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.
//
//      If you use this software in work leading to a scientific publication, you should include a reference there to
//      the 'currently valid reference', which can be found at http://miind.sourceforge.net
#define BOOST_TEST_DYN_LINK
#include <iostream>
#include <boost/test/unit_test.hpp>
#include <boost/test/execution_monitor.hpp>
#include <GeomLib.hpp>

using namespace GeomLib;

BOOST_AUTO_TEST_CASE(OdeParameterTest )
{
	// start with OdeParameter
	Number n_plus = 10;

	Time t_mem        =  10e-3;
	Time t_ref        =  0.0;
	Potential V_min   = -0.1;
	Potential V_peak  =  20e-3;
	Potential V_reset =  0.0;
	Potential V_rev   =  0.0;

	NeuronParameter par_neuron(V_peak, V_rev, V_reset, t_ref, t_mem);

	OdeParameter
		par_ode
		(
		 n_plus,
		 V_min,
		 par_neuron,
		 InitialDensityParameter(V_reset,0.0)
		);

	double lambda = 0.01;

	LifNeuralDynamics dyn(par_ode,lambda);
	LeakingOdeSystem syst(dyn);

	// then create an OdeDtParameter and see if we achieve the same effect
	MPILib::Time dt = syst.TStep();

}

max_stars_repo_name: dekamps/miind

max_issues_repo_name: dekamps/miind

max_forks_repo_name: dekamps/miind


text:
#pragma once

#include <string>

#include <boost/core/demangle.hpp>

template <class T>
class UniquelyNamedObject
{
 public:
  UniquelyNamedObject()
      : name_(boost::core::demangle(typeid(T).name()) + "_" + std::to_string(nextID_++))
  {
  }

  const std::string& objectName() const { return name_; }

 private:
  std::string name_;
  static int        nextID_;
};

template <class T>
int UniquelyNamedObject<T>::nextID_ = 0;

ext: hpp

max_stars_repo_name: mlohry/maDGiCart-CH

max_issues_repo_name: mlohry/maDGiCart-CH

max_forks_repo_name: mlohry/maDGiCart-CH


text:
#pragma once

#include <memory>
#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include "../../general_store.hpp"
#include "../beast_internals.hpp"
#include "../request_handler.hpp"

// Handles an HTTP1 server connection
class Session : public std::enable_shared_from_this<Session> {
    // This is the C++11 equivalent of a generic lambda.
    // The function object is used to send an HTTP message.
    struct SendLambda {
        Session& self_;

        explicit SendLambda(Session& self) : self_(self) {}

        template <bool isRequest, class Body, class Fields> void operator()(boost::beast::http::message<isRequest, Body, Fields>&& msg) const {
            // The lifetime of the message has to extend
            // for the duration of the async operation so
            // we use a shared_ptr to manage it.
            auto sp = std::make_shared<boost::beast::http::message<isRequest, Body, Fields>>(std::move(msg));

            // Store a type-erased version of the shared
            // pointer in the class to keep it alive.
            self_.res_ = sp;

            // Write the response
            boost::beast::http::async_write(
                self_.socket_, *sp,
                boost::asio::bind_executor(self_.strand_, std::bind(&Session::on_write, self_.shared_from_this(), std::placeholders::_1,
                                                                          std::placeholders::_2, sp->need_eof())));
        }
    };

    boost::asio::ip::tcp::socket socket_;
    boost::asio::strand<boost::asio::ip::tcp::socket::executor_type> strand_;
    boost::beast::flat_buffer buffer_;
    std::reference_wrapper<GeneralStore> m_gstore;
    boost::beast::http::request<boost::beast::http::string_body> req_;
    std::shared_ptr<void> res_;
    SendLambda lambda_;

  public:
    // Take ownership of the socket
    explicit Session(boost::asio::ip::tcp::socket socket, GeneralStore& gstore)
        : socket_(std::move(socket)), strand_(socket_.get_executor()), m_gstore(gstore), lambda_(*this) {}

    // Start the asynchronous operation
    void run() { do_read(); }

    void do_read() {
        // Make the request empty before reading,
        // otherwise the operation behavior is undefined.
        req_ = {};

        // Read a request
        boost::beast::http::async_read(socket_, buffer_, req_,
                                       boost::asio::bind_executor(
                                           strand_, std::bind(&Session::on_read, shared_from_this(), std::placeholders::_1, std::placeholders::_2)));
    }

    void on_read(boost::beast::error_code ec, std::size_t bytes_transferred) {
        boost::ignore_unused(bytes_transferred);

        // This means they closed the connection
        if (ec == boost::beast::http::error::end_of_stream)
            return do_close();

        if (ec)
            return fail(ec, "read");

        // Send the response
        handle_request(m_gstore, std::move(req_), lambda_);
    }

    void on_write(boost::beast::error_code ec, std::size_t bytes_transferred, bool close) {
        boost::ignore_unused(bytes_transferred);

        if (ec)
            return fail(ec, "write");

        if (close) {
            // This means we should close the connection, usually because
            // the response indicated the "Connection: close" semantic.
            return do_close();
        }

        // We're done with the response so delete it
        res_ = nullptr;

        // Read another request
        do_read();
    }

    void do_close() {
        // Send a TCP shutdown
        boost::beast::error_code ec;
        socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_send, ec);

        // At this point the connection is closed gracefully
    }
};

max_stars_repo_name: AeroStun/virthttp

max_issues_repo_name: AeroStun/virthttp

max_forks_repo_name: AeroStun/virthttp


text:
// make_shared_move_emulation_test.cpp - a test of make_shared
//   semi-perfect forwarding of constructor arguments when using a C++03
//   compiler with move emulation.
//   Note the "semi": it means moving temporaries (real r-values) doesn't work.
//
// Copyright 2016 Giel van Schijndel
//
// 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 <boost/detail/lightweight_test.hpp>
#include <boost/make_shared.hpp>
#include <boost/move/core.hpp>
#include <boost/move/utility_core.hpp>
#include <boost/shared_ptr.hpp>

class movearg
{
private:
    BOOST_MOVABLE_BUT_NOT_COPYABLE(movearg)
public:
    movearg()
    {}
    movearg(BOOST_RV_REF(movearg))
    {}
    movearg& operator=(BOOST_RV_REF(movearg))
    {
        return *this;
    }
};

class ByVal
{
public:
    ByVal(movearg) {}
};

class ByRef
{
public:
    enum constructor_id
    {
        move_constructor,
        const_ref_constructor
    };

    ByRef(BOOST_RV_REF(movearg)): constructed_by_(move_constructor)
    {}
    ByRef(const movearg &arg): constructed_by_(const_ref_constructor)
    {}

    constructor_id constructed_by_;
};

int main()
{
    {
        movearg a;
        boost::shared_ptr< ByVal > x = boost::make_shared< ByVal >(boost::move(a));
    }
    {
        movearg a;
        boost::shared_ptr< ByRef > x = boost::make_shared< ByRef >(boost::move(a));
        BOOST_TEST( x->constructed_by_ == ByRef::move_constructor);
    }
#if !defined( BOOST_NO_CXX11_RVALUE_REFERENCES )
    {
        boost::shared_ptr< ByVal > x = boost::make_shared< ByVal >(movearg());
        boost::shared_ptr< ByRef > y = boost::make_shared< ByRef >(movearg());
        BOOST_TEST( y->constructed_by_ == ByRef::move_constructor);
    }
#endif // !defined( BOOST_NO_CXX11_RVALUE_REFERENCES )
    {
        const movearg ca;
        boost::shared_ptr< ByRef > x = boost::make_shared< ByRef >(ca);
        BOOST_TEST( x->constructed_by_ == ByRef::const_ref_constructor);
    }

    return boost::report_errors();
}


text: #include <boost/graph/stoer_wagner_min_cut.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include <boost/test/unit_test.hpp>
#include <stdlib.h>
#include <iostream>
#include <am/succinct/dag_vector/dag_vector.hpp>

using namespace std;

using namespace boost::unit_test;

BOOST_AUTO_TEST_SUITE(dag_vector_test)

BOOST_AUTO_TEST_CASE(dag_vector)
{
    int n = 10000;
    int vmax = 100;

    cout << "n=" << n << " vmax=" << vmax << endl;
    izenelib::am::succinct::dag_vector dagv;
    vector<uint64_t> vals;
    vector<uint64_t> sums;
    uint64_t sum = 0;
    for (int i = 0; i < n; ++i)
    {
        uint64_t val = rand() % vmax;
        dagv.push_back(val);
        vals.push_back(val);
        sums.push_back(sum);
        sum += val;
    }

    cout<<"get_alloc_byte_num "<<dagv.get_alloc_byte_num()<<endl;
    BOOST_CHECK(dagv.size() == (size_t)n);

    for (uint64_t i = 0; i < vals.size(); ++i)
    {
        if (dagv[i] != vals[i])
        {
            cout << "Error [] i=" << i << " dagv[i]=" << dagv[i] << " vals[i]=" << vals[i] << endl;
        }
        if (dagv.prefix_sum(i) != sums[i])
        {
            cout << "Error prefix_sum i=" << i << " dagv.prefix_sum(i)=" << dagv.prefix_sum(i) << " prefix_sums[i]=" << sums[i] << endl;
        }
    }

    size_t pos = 0;
    for (izenelib::am::succinct::dag_vector::const_iterator it = dagv.begin(); it != dagv.end(); ++it, ++pos)
    {
        if (*it != vals[pos])
        {
            cout << "Error Iter i=" << pos << " dagv[i]=" << *it << " vals[i]=" << vals[pos] << endl;
        }
    }

    cout << "test passed." << endl;

}

BOOST_AUTO_TEST_SUITE_END() // dag_vector_test

max_stars_repo_name: izenecloud/izenelib

max_issues_repo_name: izenecloud/izenelib

max_forks_repo_name: izenecloud/izenelib


text:
#include <vector>
#include <iostream>
#include <fstream>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/predicate.hpp>

#include "BaseTypes.h"
#include "GraphIO.h"

UndirectedGraph read_graph(std::istream& stream)
{
    UndirectedGraph graph;
    std::vector<VIndex> vertices;
    for (std::string line; std::getline(stream, line);)
    {
        if (boost::starts_with(line, "c"))
            continue;

        if (boost::starts_with(line, "p"))
        {
            // // save node and edge number
            std::vector<std::string> strs;
            boost::split(strs, line, boost::is_any_of(" "));

            int numNodes = std::stoi(strs[2]);
            for(int i = 0; i < numNodes; i++)
            {
                vertices.push_back(boost::add_vertex(Vertex{i}, graph));
            }
            // nEdges = std::stoi(strs[3]);
        }
        else {
            // split string
            std::vector<std::string> strs;
            boost::split(strs, line, boost::is_any_of(" "));
            std::vector<int> edge(strs.size());
            // add new edge
            int fromNode = std::stoi(strs[0]) - 1;
            int toNode = std::stoi(strs[1]) - 1;

            boost::add_edge(vertices[fromNode], vertices[toNode], graph);
        }
    }

    return graph;
}

void write_file(std::string input_path, const Tree& solution){
    std::string output_path = input_path.substr(0, input_path.length()-2) + "tree";
    std::ofstream out;
    out.open(output_path);
    out << solution.Depth << std::endl;
    for (int i = 0; i < solution.ParentLookup.size(); ++i){
        out << solution.ParentLookup[i] + 1 << std::endl;
    }
    out.close();
}

void write_stdout(const Tree& solution){
    std::cout << solution.Depth << std::endl;
    int solution_size = solution.ParentLookup.size();
    for (int i = 0; i < solution_size; ++i){
        std::cout << solution.ParentLookup[i] + 1;
        if (i != solution_size-1){
           std::cout << std::endl;
        }
    }
}