text:
// All content Copyright (C) 2018 Genomics plc
#include "io/bamFile.hpp"

#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>

#include "ioFixture.hpp"

using wecall::caller::Region;
using wecall::caller::regions_t;

using namespace wecall::test;

BOOST_FIXTURE_TEST_CASE( shouldReadBedWithSingleThreeColumnLine, BedFileFixture )
{
    regions_t expectedRegions = {Region( "chr1", 1, 2 )};
    auto regions = bedFiles.at( 0 )->getRegions();
    BOOST_CHECK_EQUAL( regions.size(), expectedRegions.size() );
    BOOST_CHECK_EQUAL_COLLECTIONS( regions.begin(), regions.end(), expectedRegions.begin(), expectedRegions.end() );
}

BOOST_FIXTURE_TEST_CASE( shouldReadBedWithMultipleThreeColumnLines, BedFileFixture )
{
    regions_t expectedRegions = {Region( "chr1", 2, 3 ), Region( "chr2", 5, 7 )};
    auto regions = bedFiles.at( 1 )->getRegions();
    BOOST_CHECK_EQUAL( regions.size(), expectedRegions.size() );
    BOOST_CHECK_EQUAL_COLLECTIONS( regions.begin(), regions.end(), expectedRegions.begin(), expectedRegions.end() );
}

BOOST_FIXTURE_TEST_CASE( shouldReadRealExampleWithoutHeader, BedFileFixture )
{
    // example take from https://genome.ucsc.edu/FAQ/FAQformat.html#format1
    regions_t expectedRegions = {Region( "chr7", 0, 10 ), Region( "chr7", 20, 25 ), Region( "chr7", 30, 50 )};
    auto regions = bedFiles.at( 2 )->getRegions();
    BOOST_CHECK_EQUAL( regions.size(), expectedRegions.size() );
    BOOST_CHECK_EQUAL_COLLECTIONS( regions.begin(), regions.end(), expectedRegions.begin(), expectedRegions.end() );
}

BOOST_FIXTURE_TEST_CASE( shouldReadRealExampleWithHeader, BedFileFixture )
{
    // example take from https://genome.ucsc.edu/FAQ/FAQformat.html#format1
    regions_t expectedRegions = {
        Region( "chr7", 0, 10 ), Region( "chr7", 20, 25 ), Region( "gi|734691289|gb|KN707645.1|", 30, 50 )};
    auto regions = bedFiles.at( 3 )->getRegions();
    BOOST_CHECK_EQUAL( regions.size(), expectedRegions.size() );
    BOOST_CHECK_EQUAL_COLLECTIONS( regions.begin(), regions.end(), expectedRegions.begin(), expectedRegions.end() );
}

ext: cpp

max_stars_repo_name: dylex/wecall

max_issues_repo_name: dylex/wecall

max_forks_repo_name: dylex/wecall


text:
// Copyright (c) 2006, 2007 Julio M. Merino Vidal
// Copyright (c) 2008 Ilya Sokolov, Boris Schaeling
// Copyright (c) 2009 Boris Schaeling
// Copyright (c) 2010 Felipe Tanus, Boris Schaeling
// Copyright (c) 2011, 2012 Jeff Flinn, Boris Schaeling
//
// 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)

#define BOOST_TEST_MAIN
#define BOOST_TEST_IGNORE_SIGCHLD

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

#include <boost/process/exe.hpp>
#include <boost/process/args.hpp>
#include <boost/process/cmd.hpp>
#include <boost/process/io.hpp>
#include <boost/process/error.hpp>
#include <boost/process/child.hpp>

#include <boost/algorithm/string/predicate.hpp>

namespace bp = boost::process;

BOOST_AUTO_TEST_CASE(args, *boost::unit_test::timeout(2))
{
    using boost::unit_test::framework::master_test_suite;

    bp::ipstream is;

    std::error_code ec;
    bp::child c(
        master_test_suite().argv[1],
        L"test", "--echo-argv", L"hello thingy", "\"stuff\"", static_cast<const wchar_t*>(L"  spa ce  "),
        bp::std_out>is,
        ec
    );
    if (ec)
        std::cout << "EC: " << ec.message() << std::endl;
    BOOST_REQUIRE(!ec);

    std::string s;

    std::getline(is, s);
    s.resize(4);
    BOOST_CHECK_EQUAL(s, "test");

    std::getline(is, s);
    s.resize(11);
    BOOST_CHECK_EQUAL(s, "--echo-argv");

    std::getline(is, s);
    s.resize(12);

    BOOST_CHECK_EQUAL(s, "hello thingy");

    std::getline(is, s);
    s.resize(7);

    BOOST_CHECK_EQUAL(s, "\"stuff\"");

    std::getline(is, s);
    s.resize(10);

    BOOST_CHECK_EQUAL(s, "  spa ce  ");

}

BOOST_AUTO_TEST_CASE(cmd, *boost::unit_test::timeout(2))
{
    using boost::unit_test::framework::master_test_suite;

    bp::ipstream is;

    std::error_code ec;

    std::wstring cmd =
            bp::detail::convert(master_test_suite().argv[1]);
    cmd+= L" test --echo-argv \"hello thingy\" \\\"stuff\\\" \"  spa ce  \"";

    bp::child c(cmd,
        bp::std_out>is,
        ec
    );
    BOOST_REQUIRE(!ec);

    std::string s;

    std::getline(is, s);
    s.resize(4);
    BOOST_CHECK_EQUAL(s, "test");

    std::getline(is, s);
    s.resize(11);
    BOOST_CHECK_EQUAL(s, "--echo-argv");

    std::getline(is, s);
    s.resize(12);

    BOOST_CHECK_EQUAL(s, "hello thingy");

    std::getline(is, s);
    s.resize(7);

    BOOST_CHECK_EQUAL(s, "\"stuff\"");

    std::getline(is, s);
    s.resize(10);

    BOOST_CHECK_EQUAL(s, "  spa ce  ");
}

max_stars_repo_name: alexhenrie/poedit

max_issues_repo_name: alexhenrie/poedit

max_forks_repo_name: alexhenrie/poedit


text:
#include <locale.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <thread>
#include <unistd.h>

#include "IOWrapper/ImageDisplay.h"
#include "IOWrapper/Output3DWrapper.h"

#include "util/DatasetReader.h"
#include "util/globalCalib.h"
#include "util/globalFuncs.h"
#include "util/settings.h"
#include <boost/thread.hpp>

#include "FullSystem/PixelSelector2.h"
#include "OptimizationBackend/MatrixAccumulators.h"
#include "util/NumType.h"

#include "SODSOSystem.h"

#include "IOWrapper/Pangolin/PangolinDSOViewer.h"

#include <Eigen/Core>
#include <boost/thread.hpp>
#include <cv_bridge/cv_bridge.h>
#include <image_transport/image_transport.h>
#include <message_filters/subscriber.h>
#include <message_filters/sync_policies/approximate_time.h>
#include <message_filters/synchronizer.h>
#include <opencv2/core/eigen.hpp>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/Imu.h>
#include <std_msgs/String.h>

#include "output_wrappers/OutputWrapperSODSO.h"

using namespace dso;

sig_atomic_t stopFlag = 0; // sigint flag

class SODSONode {
private:
  std::string cam0_topic;
  std::string cam1_topic;
  std::string calib0;
  std::string calib1;
  std::string vignette0 = "";
  std::string vignette1 = "";
  std::string gamma0 = "";
  std::string gamma1 = "";

  float init_scale;
  float scale_accept_th;
  SE3 T_stereo_;

  SODSOSystem *so_dso_System;
  Undistort *undistorter0;
  Undistort *undistorter1;
  int frameID;

  IOWrap::OutputWrapperSODSO *outputWrapperSODSO;

  float playbackSpeed =
      0; // 0 for linearize (play as fast as possible, while sequentializing
         // tracking & mapping). otherwise, factor on timestamps.
  void settingsDefault(int preset);

public:
  SODSONode();
  ~SODSONode();
  void imageMessageCallback(const sensor_msgs::ImageConstPtr &msg0,
                            const sensor_msgs::ImageConstPtr &msg1);
  void finish();
};

void SODSONode::settingsDefault(int preset) {
  printf("\n=============== PRESET Settings: ===============\n");
  if (preset == 0 || preset == 1) {
    printf("DEFAULT settings:\n"
           "- %s real-time enforcing\n"
           "- 2000 active points\n"
           "- 5-7 active frames\n"
           "- 1-6 LM iteration each KF\n"
           "- original image resolution\n",
           preset == 0 ? "no " : "1x");

    playbackSpeed = (preset == 0 ? 0 : 1);
    setting_desiredImmatureDensity = 1500;
    setting_desiredPointDensity = 2000;
    setting_minFrames = 5;
    setting_maxFrames = 7;
    setting_maxOptIterations = 6;
    setting_minOptIterations = 1;

    setting_logStuff = false;
  }

  if (preset == 2 || preset == 3) {
    printf("FAST settings:\n"
           "- %s real-time enforcing\n"
           "- 800 active points\n"
           "- 4-6 active frames\n"
           "- 1-4 LM iteration each KF\n"
           "- 424 x 320 image resolution\n",
           preset == 2 ? "no " : "5x");

    playbackSpeed = (preset == 2 ? 0 : 1);
    setting_desiredImmatureDensity = 600;
    setting_desiredPointDensity = 800;
    setting_minFrames = 4;
    setting_maxFrames = 6;
    setting_maxOptIterations = 4;
    setting_minOptIterations = 1;

    benchmarkSetting_width = 424;
    benchmarkSetting_height = 320;

    setting_logStuff = false;
  }

  printf("==============================================\n");
}

SODSONode::SODSONode() {
  ros::NodeHandle nhPriv("~");
  // stereo camera model
  std::vector<double> T_stereo_vec;
  if (!nhPriv.getParam("cam0_topic", cam0_topic) ||
      !nhPriv.getParam("cam1_topic", cam1_topic) ||
      !nhPriv.getParam("calib0", calib0) ||
      !nhPriv.getParam("calib1", calib1) ||
      !nhPriv.getParam("T_stereo/data", T_stereo_vec)) {
    ROS_INFO("Fail to get sensor topics/params, exit.");
    return;
  }

  // stereo pose
  cv::Mat T_stereo_cv = cv::Mat(T_stereo_vec);
  T_stereo_cv = T_stereo_cv.reshape(0, 4);
  Eigen::Matrix<double, 4, 4> T_stereo_eigen;
  cv::cv2eigen(T_stereo_cv, T_stereo_eigen);
  T_stereo_ = SE3(T_stereo_eigen);

  nhPriv.param("init_scale", init_scale, 1.0f);
  nhPriv.param("scale_accept_th", scale_accept_th, 15.0f);

  bool nomt;
  int preset, mode;
  setting_onlyLogKFPoses = false;
  nhPriv.param("preset", preset, 0);
  nhPriv.param("mode", mode, 0);
  nhPriv.param<std::string>("vignette0", vignette0, "");
  nhPriv.param<std::string>("vignette1", vignette1, "");
  nhPriv.param<std::string>("gamma0", gamma0, "");
  nhPriv.param<std::string>("gamma1", gamma1, "");
  nhPriv.param("quiet", setting_debugout_runquiet, true);
  nhPriv.param("nolog", setting_logStuff, true);
  nhPriv.param("nogui", disableAllDisplay, false);
  nhPriv.param("nomt", nomt, false);
  multiThreading = !nomt;
  settingsDefault(preset);
  if (mode == 0) {
    printf("PHOTOMETRIC MODE WITH CALIBRATION!\n");
  }
  if (mode == 1) {
    printf("PHOTOMETRIC MODE WITHOUT CALIBRATION!\n");
    setting_photometricCalibration = 0;
    setting_affineOptModeA = 0; //-1: fix. >=0: optimize (with prior, if > 0).
    setting_affineOptModeB = 0; //-1: fix. >=0: optimize (with prior, if > 0).
  }
  if (mode == 2) {
    printf("PHOTOMETRIC MODE WITH PERFECT IMAGES!\n");
    setting_photometricCalibration = 0;
    setting_affineOptModeA = -1; //-1: fix. >=0: optimize (with prior, if > 0).
    setting_affineOptModeB = -1; //-1: fix. >=0: optimize (with prior, if > 0).
    setting_minGradHistAdd = 3;
  }

  undistorter0 = Undistort::getUndistorterForFile(calib0, gamma0, vignette0);
  undistorter1 = Undistort::getUndistorterForFile(calib1, gamma1, vignette1);

  setGlobalCalib((int)undistorter0->getSize()[0],
                 (int)undistorter0->getSize()[1],
                 undistorter0->getK().cast<float>());

  so_dso_System = new SODSOSystem((int)undistorter1->getSize()[0],
                                  (int)undistorter1->getSize()[1],
                                  undistorter1->getK().cast<float>(), T_stereo_,
                                  undistorter1, init_scale, scale_accept_th);
  so_dso_System->linearizeOperation = (playbackSpeed == 0);

  if (!disableAllDisplay)
    so_dso_System->outputWrapper.push_back(new IOWrap::PangolinDSOViewer(
        (int)undistorter0->getSize()[0], (int)undistorter0->getSize()[1]));

  outputWrapperSODSO = new IOWrap::OutputWrapperSODSO();
  so_dso_System->outputWrapper.push_back(outputWrapperSODSO);

  ros::NodeHandle nh;
  typedef message_filters::sync_policies::ApproximateTime<sensor_msgs::Image,
                                                          sensor_msgs::Image>
      StereoSyncPolicy;
  message_filters::Subscriber<sensor_msgs::Image> *cam0_sub;
  message_filters::Subscriber<sensor_msgs::Image> *cam1_sub;
  message_filters::Synchronizer<StereoSyncPolicy> *sync;
  cam0_sub = new message_filters::Subscriber<sensor_msgs::Image>(nh, cam0_topic,
                                                                 10000);
  cam1_sub = new message_filters::Subscriber<sensor_msgs::Image>(nh, cam1_topic,
                                                                 10000);
  sync = new message_filters::Synchronizer<StereoSyncPolicy>(
      StereoSyncPolicy(10), *cam0_sub, *cam1_sub);
  sync->registerCallback(
      boost::bind(&SODSONode::imageMessageCallback, this, _1, _2));

  frameID = 0;
}

SODSONode::~SODSONode() {
  delete so_dso_System;
  delete undistorter0;
  delete undistorter1;
  delete outputWrapperSODSO;
}

void SODSONode::finish() {
  so_dso_System->blockUntilMappingIsFinished();
  clock_t ended = clock();
  struct timeval tv_end;
  gettimeofday(&tv_end, NULL);

  so_dso_System->printResult("poses.txt", "ba_time.txt", "scale_time.txt",
                             "fps_time.txt");

  // int numFramesProcessed = abs(idsToPlay[0]-idsToPlay.back());
  // double numSecondsProcessed =
  // fabs(reader->getTimestamp(idsToPlay[0])-reader->getTimestamp(idsToPlay.back()));
  // double MilliSecondsTakenSingle =
  // 1000.0f*(ended-started)/(float)(CLOCKS_PER_SEC); double MilliSecondsTakenMT
  // = sInitializerOffset + ((tv_end.tv_sec-tv_start.tv_sec)*1000.0f +
  // (tv_end.tv_usec-tv_start.tv_usec)/1000.0f);
  // printf("\n======================"
  //         "\n%d Frames (%.1f fps)"
  //         "\n%.2fms per frame (single core); "
  //         "\n%.2fms per frame (multi core); "
  //         "\n%.3fx (single core); "
  //         "\n%.3fx (multi core); "
  //         "\n======================\n\n",
  //         numFramesProcessed, numFramesProcessed/numSecondsProcessed,
  //         MilliSecondsTakenSingle/numFramesProcessed,
  //         MilliSecondsTakenMT / (float)numFramesProcessed,
  //         1000 / (MilliSecondsTakenSingle/numSecondsProcessed),
  //         1000 / (MilliSecondsTakenMT / numSecondsProcessed));
  // //so_dso_System->printFrameLifetimes();
  // if(setting_logStuff)
  // {
  //     std::ofstream tmlog;
  //     tmlog.open("logs/time.txt", std::ios::trunc | std::ios::out);
  //     tmlog <<
  //     1000.0f*(ended-started)/(float)(CLOCKS_PER_SEC*reader->getNumImages())
  //     << " "
  //           << ((tv_end.tv_sec-tv_start.tv_sec)*1000.0f +
  //           (tv_end.tv_usec-tv_start.tv_usec)/1000.0f) /
  //           (float)reader->getNumImages() << "\n";
  //     tmlog.flush();
  //     tmlog.close();
  // }
}

void SODSONode::imageMessageCallback(const sensor_msgs::ImageConstPtr &msg0,
                                     const sensor_msgs::ImageConstPtr &msg1) {
  cv::Mat img, stereo_img, conc;
  try {
    img = cv_bridge::toCvShare(msg0, "mono8")->image;
    stereo_img = cv_bridge::toCvShare(msg1, "mono8")->image;
  } catch (cv_bridge::Exception &e) {
    ROS_ERROR("cv_bridge exception: %s", e.what());
  }

  if (so_dso_System->isLost) {
    printf("Reinitializing\n");
    std::vector<IOWrap::Output3DWrapper *> wraps = so_dso_System->outputWrapper;
    delete so_dso_System;
    for (IOWrap::Output3DWrapper *ow : wraps)
      ow->reset();
    so_dso_System = new SODSOSystem(
        (int)undistorter1->getSize()[0], (int)undistorter1->getSize()[1],
        undistorter1->getK().cast<float>(), T_stereo_, undistorter1, init_scale,
        scale_accept_th);
    so_dso_System->linearizeOperation = (playbackSpeed == 0);
    so_dso_System->outputWrapper = wraps;
    if (undistorter0->photometricUndist != 0)
      so_dso_System->setGammaFunction(undistorter0->photometricUndist->getG());
    // setting_fullResetRequested=false;
  }

  if (undistorter0->photometricUndist != 0)
    so_dso_System->setGammaFunction(undistorter0->photometricUndist->getG());

  MinimalImageB minImg((int)img.cols, (int)img.rows, (unsigned char *)img.data);
  ImageAndExposure *undistImg =
      undistorter0->undistort<unsigned char>(&minImg, 1, 0, 1.0f);
  undistImg->timestamp = msg0->header.stamp.toSec();
  so_dso_System->addStereoImg(stereo_img, frameID);
  so_dso_System->addActiveFrame(undistImg, frameID);
  frameID++;
  delete undistImg;
}

void finishHandler(int sig) { stopFlag = 1; }

int main(int argc, char **argv) {
  ros::init(argc, argv, "so_dso_");
  SODSONode vo_node;

  signal(SIGINT, finishHandler);

  ros::Rate r(10); // 10 hz
  while (stopFlag == 0) {
    ros::spinOnce();
    r.sleep();
  }

  printf("Finishing up\n");
  vo_node.finish();

  return 0;
}


text:
//
// Created by Amir Masoud Abdol on 2019-05-07.
//

#define BOOST_TEST_DYN_LINK

#define BOOST_TEST_MODULE Researcher Tests

#include <boost/test/unit_test.hpp>

#include <armadillo>
#include <iostream>
#include <fstream>

#include "ExperimentSetup.h"
#include "Experiment.h"
#include "Researcher.h"
#include "HackingStrategy.h"
#include "Journal.h"
#include "ResearchStrategy.h"

#include "sam.h"

#include "test_fixtures.h"

using namespace arma;
using namespace sam;
using namespace std;

using json = nlohmann::json;

bool FLAGS::VERBOSE = false;
bool FLAGS::PROGRESS = false;
bool FLAGS::DEBUG = false;
bool FLAGS::UPDATECONFIG = false;

BOOST_AUTO_TEST_CASE ( default_constructor )
{
    Researcher researcher;
}

BOOST_FIXTURE_TEST_SUITE ( researcher, SampleResearch )

BOOST_AUTO_TEST_CASE( researcher_builder )
{

    initResearch();

    Researcher new_researcher = Researcher::create("John")
                                        .createExperiment(setup)
                                        .createResearchStrategy(de_s_conf)
                                        .createJournal(j_conf)
                                        .addNewHackingStrategy(hs)
                                        .build();

    // Aha! This is where the open-close principle shows itself. I cannot access
    // alpha here because ReviewStrategy abstract class doesn't have a `params`
    // instance, and even if it had, it would not be the same as the one that I
    // created via the factory.
//    BOOST_TEST((new_researcher.journal->review_strategy->params.alpha == 0.05));

        // The same here as well, I've removed the params from the Abstract class and this is the result.
        // BOOST_TEST((new_researcher.research_strategy->params.preference == DecisionPreference::PreRegisteredOutcome));
}

BOOST_AUTO_TEST_SUITE_END()


text:
#ifndef SHIFT_SERVICE_SERVICEHOSTIMPL_HPP
#define SHIFT_SERVICE_SERVICEHOSTIMPL_HPP

#include <cstdint>
#include <chrono>
#include <vector>
#include <set>
#include <mutex>
#include <shift/core/boost_disable_warnings.hpp>
#include <boost/asio/ip/udp.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <shift/core/boost_restore_warnings.hpp>
#include <shift/core/singleton.hpp>
#include <shift/network/network.hpp>
#include <shift/serialization/types.hpp>
#include "shift/service/types.hpp"
#include "shift/service/basic_service.hpp"
#include "shift/service/service_host.hpp"

namespace shift::service
{
///
struct remote_service_provider
{
  guid_t host_guid;
  guid_t service_guid;
  service_uid_t service_uid;
  interface_uids_t interface_uids;
  std::uint16_t service_tag;
  boost::asio::ip::address local_address;
  boost::asio::ip::address remote_address;
  std::uint16_t remote_port;

  // std::chrono::system_clock::time_point lastSeen;
};

struct service_guid_tag
{
};

using remote_service_provider_set = boost::multi_index_container<
  remote_service_provider,
  boost::multi_index::indexed_by<boost::multi_index::ordered_unique<
    boost::multi_index::tag<service_guid_tag>,
    BOOST_MULTI_INDEX_MEMBER(remote_service_provider, guid_t, service_guid)>>>;

class service_host::impl
{
public:
  /// Constructor.
  impl(service_host& host);

  /// Destructor.
  ~impl();

  /// @see service_host::start.
  bool start(serialization::protocol_version_t new_protocol_version,
             serialization::protocol_version_t new_required_version);

  /// @see service_host::publish.
  void publish();

  /// Event handler for receiving multicast messages send by other service
  /// hosts.
  void on_receive_multicast(network::udp_socket& socket,
                            boost::asio::ip::udp::endpoint sender,
                            std::vector<char> buffer);

public:
  service_host& host;
  std::mutex start_mutex;
  bool running = false;

  std::vector<boost::asio::ip::address> bind_addresses;
  guid_t host_guid;
  std::uint16_t multicast_port = 0x700;
  boost::asio::ip::address_v4 multicast_address4 =
    boost::asio::ip::address_v4::from_string("239.255.255.1");
  boost::asio::ip::address_v6 multicast_address6 =
    boost::asio::ip::address_v6::from_string("FF05::1337:1");
  serialization::protocol_version_t protocol_version;
  serialization::protocol_version_t required_version;

  std::vector<std::shared_ptr<network::udp_socket>> multicast_sockets;

  std::mutex service_client_mutex;
  std::set<basic_service*> service_clients;
  std::mutex service_provider_mutex;
  std::set<basic_service*> service_providers;

  std::mutex known_remote_services_mutex;
  remote_service_provider_set known_remote_services;
};
}

#endif

ext: hpp

max_stars_repo_name: cspanier/shift

max_issues_repo_name: cspanier/shift

max_forks_repo_name: cspanier/shift


text:
/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
 *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
 *    Author(s):       Vincent Rouvreau
 *
 *    Copyright (C) 2014 Inria
 *
 *    Modification(s):
 *      - YYYY/MM Author: Description of the modification
 */

#include <iostream>

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE "simplex_tree_remove"
#include <boost/test/unit_test.hpp>

//  ^
// /!\ Nothing else from Simplex_tree shall be included to test includes are well defined.
#include "gudhi/Simplex_tree.h"

using namespace Gudhi;

struct MyOptions : Simplex_tree_options_full_featured {
  // Not doing persistence, so we don't need those
  static const bool store_key = false;
  static const bool store_filtration = false;
  // I have few vertices
  typedef short Vertex_handle;
};

using Mini_stree = Simplex_tree<MyOptions>;
using Stree = Simplex_tree<>;

BOOST_AUTO_TEST_CASE(remove_maximal_simplex) {
  std::clog << "********************************************************************" << std::endl;
  std::clog << "REMOVE MAXIMAL SIMPLEX" << std::endl;

  Mini_stree st;

  st.insert_simplex_and_subfaces({0, 1, 6, 7});
  st.insert_simplex_and_subfaces({3, 4, 5});

  // Constructs a copy at this state for further test purpose
  Mini_stree st_pruned = st;

  st.insert_simplex_and_subfaces({3, 0});
  st.insert_simplex_and_subfaces({2, 1, 0});

  // Constructs a copy at this state for further test purpose
  Mini_stree st_complete = st;
  // st_complete and st:
  //    1   6
  //    o---o
  //   /X\7/
  //  o---o---o---o
  //  2   0   3\X/4
  //            o
  //            5
  // st_pruned:
  //    1   6
  //    o---o
  //     \7/
  //      o   o---o
  //      0   3\X/4
  //            o
  //            5

#ifdef GUDHI_DEBUG
  std::clog << "Check exception throw in debug mode" << std::endl;
  // throw excpt because sh has children
  BOOST_CHECK_THROW (st.remove_maximal_simplex(st.find({0, 1, 6})), std::invalid_argument);
  BOOST_CHECK_THROW (st.remove_maximal_simplex(st.find({3})), std::invalid_argument);
  BOOST_CHECK(st == st_complete);
#endif
  std::clog << "st.remove_maximal_simplex({0, 2})" << std::endl;
  st.remove_maximal_simplex(st.find({0, 2}));
  std::clog << "st.remove_maximal_simplex({0, 1, 2})" << std::endl;
  st.remove_maximal_simplex(st.find({0, 1, 2}));
  std::clog << "st.remove_maximal_simplex({1, 2})" << std::endl;
  st.remove_maximal_simplex(st.find({1, 2}));
  std::clog << "st.remove_maximal_simplex({2})" << std::endl;
  st.remove_maximal_simplex(st.find({2}));
  std::clog << "st.remove_maximal_simplex({3})" << std::endl;
  st.remove_maximal_simplex(st.find({0, 3}));

  BOOST_CHECK(st == st_pruned);
  // Remove all, but as the simplex tree is not storing filtration, there is no modification
  st.prune_above_filtration(0.0);
  BOOST_CHECK(st == st_pruned);

  Mini_stree st_wo_seven;

  st_wo_seven.insert_simplex_and_subfaces({0, 1, 6});
  st_wo_seven.insert_simplex_and_subfaces({3, 4, 5});
  // st_wo_seven:
  //    1   6
  //    o---o
  //     \X/
  //      o   o---o
  //      0   3\X/4
  //            o
  //            5

  // Remove all 7 to test the both remove_maximal_simplex cases (when _members is empty or not)
  std::clog << "st.remove_maximal_simplex({0, 1, 6, 7})" << std::endl;
  st.remove_maximal_simplex(st.find({0, 1, 6, 7}));
  std::clog << "st.remove_maximal_simplex({0, 1, 7})" << std::endl;
  st.remove_maximal_simplex(st.find({0, 1, 7}));
  std::clog << "st.remove_maximal_simplex({0, 6, 7})" << std::endl;
  st.remove_maximal_simplex(st.find({0, 6, 7}));
  std::clog << "st.remove_maximal_simplex({0, 7})" << std::endl;
  st.remove_maximal_simplex(st.find({0, 7}));
  std::clog << "st.remove_maximal_simplex({1, 6, 7})" << std::endl;
  st.remove_maximal_simplex(st.find({1, 6, 7}));
  std::clog << "st.remove_maximal_simplex({1, 7})" << std::endl;
  st.remove_maximal_simplex(st.find({1, 7}));
  std::clog << "st.remove_maximal_simplex({6, 7})" << std::endl;
  st.remove_maximal_simplex(st.find({6, 7}));
  std::clog << "st.remove_maximal_simplex({7})" << std::endl;
  st.remove_maximal_simplex(st.find({7}));

  std::clog << "st.upper_bound_dimension()=" << st.upper_bound_dimension() << std::endl;
  BOOST_CHECK(st.upper_bound_dimension() == 3);

  // Check dimension calls lower_upper_bound_dimension to recompute dimension
  BOOST_CHECK(st.dimension() == 2);
  BOOST_CHECK(st.upper_bound_dimension() == 2);

  std::clog << "st.upper_bound_dimension()=" << st.upper_bound_dimension()
            << " | st_wo_seven.upper_bound_dimension()=" << st_wo_seven.upper_bound_dimension() << std::endl;
  std::clog << "st.dimension()=" << st.dimension() << " | st_wo_seven.dimension()=" << st_wo_seven.dimension() << std::endl;
  BOOST_CHECK(st == st_wo_seven);
}

BOOST_AUTO_TEST_CASE(auto_dimension_set) {
  std::clog << "********************************************************************" << std::endl;
  std::clog << "DIMENSION ON REMOVE MAXIMAL SIMPLEX" << std::endl;

  Mini_stree st;

  st.insert_simplex_and_subfaces({0, 1, 2});
  st.insert_simplex_and_subfaces({0, 1, 3});
  st.insert_simplex_and_subfaces({1, 2, 3, 4});
  st.insert_simplex_and_subfaces({1, 2, 3, 5});
  st.insert_simplex_and_subfaces({6, 7, 8, 9});
  st.insert_simplex_and_subfaces({6, 7, 8, 10});

  BOOST_CHECK(st.upper_bound_dimension() == 3);
  BOOST_CHECK(st.dimension() == 3);

  std::clog << "st.remove_maximal_simplex({6, 7, 8, 10})" << std::endl;
  st.remove_maximal_simplex(st.find({6, 7, 8, 10}));
  std::clog << "st.upper_bound_dimension()=" << st.upper_bound_dimension() << std::endl;
  BOOST_CHECK(st.upper_bound_dimension() == 3);
  BOOST_CHECK(st.dimension() == 3);

  std::clog << "st.remove_maximal_simplex({6, 7, 8, 9})" << std::endl;
  st.remove_maximal_simplex(st.find({6, 7, 8, 9}));
  std::clog << "st.upper_bound_dimension()=" << st.upper_bound_dimension() << std::endl;
  BOOST_CHECK(st.upper_bound_dimension() == 3);
  BOOST_CHECK(st.dimension() == 3);

  std::clog << "st.remove_maximal_simplex({1, 2, 3, 4})" << std::endl;
  st.remove_maximal_simplex(st.find({1, 2, 3, 4}));
  std::clog << "st.upper_bound_dimension()=" << st.upper_bound_dimension() << std::endl;
  BOOST_CHECK(st.upper_bound_dimension() == 3);
  BOOST_CHECK(st.dimension() == 3);

  std::clog << "st.remove_maximal_simplex({1, 2, 3, 5})" << std::endl;
  st.remove_maximal_simplex(st.find({1, 2, 3, 5}));
  std::clog << "st.upper_bound_dimension()=" << st.upper_bound_dimension() << std::endl;
  BOOST_CHECK(st.upper_bound_dimension() == 3);
  BOOST_CHECK(st.dimension() == 2);
  std::clog << "st.dimension()=" << st.dimension() << std::endl;

  std::clog << "st.insert_simplex_and_subfaces({1, 2, 3, 5})" << std::endl;
  st.insert_simplex_and_subfaces({1, 2, 3, 5});
  std::clog << "st.upper_bound_dimension()=" << st.upper_bound_dimension() << std::endl;
  BOOST_CHECK(st.upper_bound_dimension() == 3);
  BOOST_CHECK(st.dimension() == 3);

  std::clog << "st.insert_simplex_and_subfaces({1, 2, 3, 4})" << std::endl;
  st.insert_simplex_and_subfaces({1, 2, 3, 4});
  std::clog << "st.upper_bound_dimension()=" << st.upper_bound_dimension() << std::endl;
  BOOST_CHECK(st.upper_bound_dimension() == 3);
  BOOST_CHECK(st.dimension() == 3);

  std::clog << "st.remove_maximal_simplex({1, 2, 3, 5})" << std::endl;
  st.remove_maximal_simplex(st.find({1, 2, 3, 5}));
  std::clog << "st.upper_bound_dimension()=" << st.upper_bound_dimension() << std::endl;
  BOOST_CHECK(st.upper_bound_dimension() == 3);
  BOOST_CHECK(st.dimension() == 3);

  std::clog << "st.remove_maximal_simplex({1, 2, 3, 4})" << std::endl;
  st.remove_maximal_simplex(st.find({1, 2, 3, 4}));
  std::clog << "st.upper_bound_dimension()=" << st.upper_bound_dimension() << std::endl;
  BOOST_CHECK(st.upper_bound_dimension() == 3);
  BOOST_CHECK(st.dimension() == 2);
  std::clog << "st.dimension()=" << st.dimension() << std::endl;

  std::clog << "st.insert_simplex_and_subfaces({0, 1, 3, 4})" << std::endl;
  st.insert_simplex_and_subfaces({0, 1, 3, 4});
  std::clog << "st.upper_bound_dimension()=" << st.upper_bound_dimension() << std::endl;
  BOOST_CHECK(st.upper_bound_dimension() == 3);
  BOOST_CHECK(st.dimension() == 3);

  std::clog << "st.remove_maximal_simplex({0, 1, 3, 4})" << std::endl;
  st.remove_maximal_simplex(st.find({0, 1, 3, 4}));
  std::clog << "st.upper_bound_dimension()=" << st.upper_bound_dimension() << std::endl;
  BOOST_CHECK(st.upper_bound_dimension() == 3);
  BOOST_CHECK(st.dimension() == 2);
  std::clog << "st.dimension()=" << st.dimension() << std::endl;

  std::clog << "st.insert_simplex_and_subfaces({1, 2, 3, 5})" << std::endl;
  st.insert_simplex_and_subfaces({1, 2, 3, 5});
  std::clog << "st.upper_bound_dimension()=" << st.upper_bound_dimension() << std::endl;
  BOOST_CHECK(st.upper_bound_dimension() == 3);
  BOOST_CHECK(st.dimension() == 3);

  std::clog << "st.insert_simplex_and_subfaces({1, 2, 3, 4})" << std::endl;
  st.insert_simplex_and_subfaces({1, 2, 3, 4});
  std::clog << "st.upper_bound_dimension()=" << st.upper_bound_dimension() << std::endl;
  BOOST_CHECK(st.upper_bound_dimension() == 3);
  BOOST_CHECK(st.dimension() == 3);

  // Check you can override the dimension
  // This is a limit test case - shall not happen
  st.set_dimension(1);
  std::clog << "st.upper_bound_dimension()=" << st.upper_bound_dimension() << std::endl;
  BOOST_CHECK(st.upper_bound_dimension() == 1);
  // check dimension() and lower_upper_bound_dimension() is not giving the right answer because dimension is too low
  BOOST_CHECK(st.dimension() == 1);

  // Check you can override the dimension
  // This is a limit test case - shall not happen
  st.set_dimension(6);
  std::clog << "st.upper_bound_dimension()=" << st.upper_bound_dimension() << std::endl;
  BOOST_CHECK(st.upper_bound_dimension() == 6);
  // check dimension() do not launch lower_upper_bound_dimension()
  BOOST_CHECK(st.dimension() == 6);

  // Reset with the correct value
  st.set_dimension(3);
  std::clog << "st.upper_bound_dimension()=" << st.upper_bound_dimension() << std::endl;
  BOOST_CHECK(st.upper_bound_dimension() == 3);
  BOOST_CHECK(st.dimension() == 3);

  std::clog << "st.insert_simplex_and_subfaces({0, 1, 2, 3, 4, 5, 6})" << std::endl;
  st.insert_simplex_and_subfaces({0, 1, 2, 3, 4, 5, 6});
  std::clog << "st.upper_bound_dimension()=" << st.upper_bound_dimension() << std::endl;
  BOOST_CHECK(st.upper_bound_dimension() == 6);
  BOOST_CHECK(st.dimension() == 6);

  std::clog << "st.remove_maximal_simplex({0, 1, 2, 3, 4, 5, 6})" << std::endl;
  st.remove_maximal_simplex(st.find({0, 1, 2, 3, 4, 5, 6}));
  std::clog << "st.upper_bound_dimension()=" << st.upper_bound_dimension() << std::endl;
  BOOST_CHECK(st.upper_bound_dimension() == 6);
  BOOST_CHECK(st.dimension() == 5);

}

BOOST_AUTO_TEST_CASE(prune_above_filtration) {
  std::clog << "********************************************************************" << std::endl;
  std::clog << "PRUNE ABOVE FILTRATION" << std::endl;

  Stree st;

  st.insert_simplex_and_subfaces({0, 1, 6, 7}, 1.0);
  st.insert_simplex_and_subfaces({3, 4, 5}, 2.0);

  // Constructs a copy at this state for further test purpose
  Stree st_pruned = st;
  st_pruned.initialize_filtration();  // reset

  st.insert_simplex_and_subfaces({3, 0}, 3.0);
  st.insert_simplex_and_subfaces({2, 1, 0}, 4.0);

  // Constructs a copy at this state for further test purpose
  Stree st_complete = st;
  // st_complete and st:
  //    1   6
  //    o---o
  //   /X\7/
  //  o---o---o---o
  //  2   0   3\X/4
  //            o
  //            5
  // st_pruned:
  //    1   6
  //    o---o
  //     \7/
  //      o   o---o
  //      0   3\X/4
  //            o
  //            5

  bool simplex_is_changed = false;
  // Check the no action cases
  // greater than initial filtration value
  simplex_is_changed = st.prune_above_filtration(10.0);
  if (simplex_is_changed)
    st.initialize_filtration();
  BOOST_CHECK(st == st_complete);
  BOOST_CHECK(!simplex_is_changed);
  // equal to initial filtration value
  simplex_is_changed = st.prune_above_filtration(6.0);
  if (simplex_is_changed)
    st.initialize_filtration();
  BOOST_CHECK(st == st_complete);
  BOOST_CHECK(!simplex_is_changed);
  // lower than initial filtration value, but still greater than the maximum filtration value
  simplex_is_changed = st.prune_above_filtration(5.0);
  if (simplex_is_changed)
    st.initialize_filtration();
  BOOST_CHECK(st == st_complete);
  BOOST_CHECK(!simplex_is_changed);

  // Display the Simplex_tree
  std::clog << "The complex contains " << st.num_simplices() << " simplices";
  std::clog << " - dimension " << st.dimension() << std::endl;
  std::clog << "Iterator on Simplices in the filtration, with [filtration value]:" << std::endl;
  for (auto f_simplex : st.filtration_simplex_range()) {
    std::clog << "   " << "[" << st.filtration(f_simplex) << "] ";
    for (auto vertex : st.simplex_vertex_range(f_simplex)) {
      std::clog << (int) vertex << " ";
    }
    std::clog << std::endl;
  }

  // Check the pruned cases
  simplex_is_changed = st.prune_above_filtration(2.5);
  if (simplex_is_changed)
    st.initialize_filtration();
  BOOST_CHECK(st == st_pruned);
  BOOST_CHECK(simplex_is_changed);

  // Display the Simplex_tree
  std::clog << "The complex pruned at 2.5 contains " << st.num_simplices() << " simplices";
  std::clog << " - dimension " << st.dimension() << std::endl;

  simplex_is_changed = st.prune_above_filtration(2.0);
  if (simplex_is_changed)
    st.initialize_filtration();

  std::clog << "The complex pruned at 2.0 contains " << st.num_simplices() << " simplices";
  std::clog << " - dimension " << st.dimension() << std::endl;

  BOOST_CHECK(st == st_pruned);
  BOOST_CHECK(!simplex_is_changed);

  Stree st_empty;
  simplex_is_changed = st.prune_above_filtration(0.0);
  BOOST_CHECK(simplex_is_changed == true);
  if (simplex_is_changed)
    st.initialize_filtration();

  // Display the Simplex_tree
  std::clog << "The complex pruned at 0.0 contains " << st.num_simplices() << " simplices";
  std::clog << " - upper_bound_dimension " << st.upper_bound_dimension() << std::endl;
  BOOST_CHECK(st.upper_bound_dimension() == 3);

  BOOST_CHECK(st.dimension() == -1);
  std::clog << "upper_bound_dimension=" << st.upper_bound_dimension() << std::endl;
  BOOST_CHECK(st.upper_bound_dimension() == -1);

  BOOST_CHECK(st == st_empty);
  BOOST_CHECK(simplex_is_changed);

  // Test case to the limit
  simplex_is_changed = st.prune_above_filtration(-1.0);
  if (simplex_is_changed)
    st.initialize_filtration();
  BOOST_CHECK(st == st_empty);
  BOOST_CHECK(!simplex_is_changed);
}

BOOST_AUTO_TEST_CASE(mini_prune_above_filtration) {
  std::clog << "********************************************************************" << std::endl;
  std::clog << "MINI PRUNE ABOVE FILTRATION" << std::endl;

  Mini_stree st;

  st.insert_simplex_and_subfaces({0, 1, 6, 7});
  st.insert_simplex_and_subfaces({3, 4, 5});
  st.insert_simplex_and_subfaces({3, 0});
  st.insert_simplex_and_subfaces({2, 1, 0});

  // st:
  //    1   6
  //    o---o
  //   /X\7/
  //  o---o---o---o
  //  2   0   3\X/4
  //            o
  //            5

  st.initialize_filtration();

  // Display the Simplex_tree
  std::clog << "The complex contains " << st.num_simplices() << " simplices" << std::endl;
  BOOST_CHECK(st.num_simplices() == 27);

  // Test case to the limit - With these options, there is no filtration, which means filtration is 0
  bool simplex_is_changed = st.prune_above_filtration(1.0);
  if (simplex_is_changed)
    st.initialize_filtration();
  // Display the Simplex_tree
  std::clog << "The complex pruned at 1.0 contains " << st.num_simplices() << " simplices" << std::endl;
  BOOST_CHECK(!simplex_is_changed);
  BOOST_CHECK(st.num_simplices() == 27);

  simplex_is_changed = st.prune_above_filtration(0.0);
  if (simplex_is_changed)
    st.initialize_filtration();
  // Display the Simplex_tree
  std::clog << "The complex pruned at 0.0 contains " << st.num_simplices() << " simplices" << std::endl;
  BOOST_CHECK(!simplex_is_changed);
  BOOST_CHECK(st.num_simplices() == 27);

  // Test case to the limit
  simplex_is_changed = st.prune_above_filtration(-1.0);
  if (simplex_is_changed)
    st.initialize_filtration();
  // Display the Simplex_tree
  std::clog << "The complex pruned at -1.0 contains " << st.num_simplices() << " simplices" << std::endl;
  BOOST_CHECK(simplex_is_changed);
  BOOST_CHECK(st.num_simplices() == 0);

  // Display the Simplex_tree
  std::clog << "The complex contains " << st.num_simplices() << " simplices" << std::endl;

}


text:
// Copyright (c) 2014-2017 Jae-jun Kang
// See the file LICENSE for details.

#ifndef X2BOOST_THREADLESS_FLOW_HPP_
#define X2BOOST_THREADLESS_FLOW_HPP_

#ifndef X2BOOST_PRE_HPP_
#include "x2boost/pre.hpp"
#endif

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

#include "x2boost/flows/event_based_flow.hpp"

namespace x2boost
{
    template<class Q = synchronized_event_queue>
    class X2BOOST_API threadless_flow : public event_based_flow<Q>
    {
    public:
        threadless_flow() : running_(false) {}

        virtual ~threadless_flow() {}

        virtual void startup()
        {
            boost::mutex::scoped_lock lock(flow::mutex_);
            if (running_) { return; }

            this->setup();
            flow::case_stack_.setup(boost::enable_shared_from_this<flow>::shared_from_this());

            running_ = true;
        }

        virtual void shutdown()
        {
            boost::mutex::scoped_lock lock(flow::mutex_);
            if (!running_) { return; }

            // enqueue flow_stop
            event_based_flow<Q>::queue_.close();

            running_ = false;

            flow::case_stack_.teardown(boost::enable_shared_from_this<flow>::shared_from_this());
            this->teardown();
        }

        event_ptr try_dispatch()
        {
            event_ptr e;

            if (queue_.try_dequeue(&e))
            {
                dispatch(e);
            }
            return e;
        }

        size_t try_dispatch_all()
        {
            event_ptr e;

            deququed_.clear();
            while (queue_.try_dequeue(&e))
            {
                deqeueud_.add(e);
            }
            size_t count = dequeued_.size();
            if (count != 0)
            {
                for (int i = 0; i < count; ++i)
                {
                    dispatch(dequeued_[i]);
                }
                dequeued_.clear();
            }
            return count;
        }

    protected:
        bool running_;
        std::vector<event_ptr> dequeued_;
    };
}

#endif  // X2BOOST_THREADLESS_FLOW_HPP_