text:
#include "test_file_rm_guard.hpp"

#include "asioext/open_flags.hpp"
#include "asioext/basic_file.hpp"
#include "asioext/thread_pool_file_service.hpp"

#if defined(ASIOEXT_USE_BOOST_ASIO)
# include <boost/asio/write.hpp>
# include <boost/asio/write_at.hpp>
# include <boost/asio/read.hpp>
# include <boost/asio/read_at.hpp>
# include <boost/asio/post.hpp>
#else
# include <asio/write.hpp>
# include <asio/write_at.hpp>
# include <asio/read.hpp>
# include <asio/read_at.hpp>
# include <asio/post.hpp>
#endif

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

ASIOEXT_NS_BEGIN

BOOST_AUTO_TEST_SUITE(asioext_basic_file)

// BOOST_AUTO_TEST_SUITE() gives us a unique NS, so we don't need to
// prefix our variables.

static const char empty_filename[] = "asioext_basicfile_empty";
static const wchar_t empty_filenamew[] = L"asioext_basicfile_empty2";

static const char test_filename[] = "asioext_basicfile_test";
static const wchar_t test_filenamew[] = L"asioext_basicfile_test";
static const char test_data[] = "hello world!";
static const std::size_t test_data_size = sizeof(test_data) - 1;

typedef boost::mpl::list<asioext::thread_pool_file_service> service_types;

BOOST_AUTO_TEST_CASE_TEMPLATE(empty, FileService, service_types)
{
  asio::io_context io_context;
  asioext::basic_file<FileService> file(io_context);
  BOOST_CHECK(!file.is_open());
  BOOST_CHECK_NO_THROW(file.close());
}

BOOST_AUTO_TEST_CASE_TEMPLATE(constructor, FileService, service_types)
{
  test_file_rm_guard rguard1(empty_filename);

  asio::io_context io_context;
  asioext::error_code ec;
  asioext::basic_file<FileService> f1(io_context, "nosuchfile",
                                      asioext::open_flags::access_read |
                                      asioext::open_flags::open_existing, ec);
  BOOST_REQUIRE(ec);
  asioext::basic_file<FileService> f2(io_context, empty_filename,
                                      asioext::open_flags::access_write |
                                      asioext::open_flags::open_always, ec);
  BOOST_REQUIRE_MESSAGE(!ec, "ec: " << ec);
#if defined(ASIOEXT_WINDOWS)
  test_file_rm_guard rguard2(empty_filenamew);
  asioext::basic_file<FileService> f3(io_context, L"nosuchfile",
                                      asioext::open_flags::access_read |
                                      asioext::open_flags::open_existing, ec);
  BOOST_REQUIRE(ec);
  asioext::basic_file<FileService> f4(io_context, empty_filenamew,
                                      asioext::open_flags::access_write |
                                      asioext::open_flags::open_always, ec);
  BOOST_REQUIRE_MESSAGE(!ec, "ec: " << ec);
#endif
}

BOOST_AUTO_TEST_CASE_TEMPLATE(open, FileService, service_types)
{
  test_file_rm_guard rguard1(empty_filename);
#if defined(ASIOEXT_WINDOWS)
  test_file_rm_guard rguard2(empty_filenamew);
#endif

  asio::io_context io_context;
  asioext::basic_file<FileService> file(io_context);

  asioext::error_code ec;
  file.open("nosuchfile",
            open_flags::access_read | open_flags::open_existing, ec);

  BOOST_REQUIRE(ec);
  BOOST_CHECK(!file.is_open());
  BOOST_CHECK_NO_THROW(file.close());

#if defined(ASIOEXT_WINDOWS)
  file.open(L"nosuchfile",
            open_flags::access_read | open_flags::open_existing, ec);

  BOOST_REQUIRE(ec);
  BOOST_CHECK(!file.is_open());
  BOOST_CHECK_NO_THROW(file.close());
#endif

  file.open(empty_filename,
            open_flags::access_write | open_flags::open_always, ec);

  BOOST_REQUIRE_MESSAGE(!ec, "ec: " << ec);
  BOOST_CHECK(file.is_open());

  BOOST_CHECK_NO_THROW(file.close());
  BOOST_CHECK(!file.is_open());

#if defined(ASIOEXT_WINDOWS)
  file.open(empty_filenamew,
            open_flags::access_write | open_flags::open_always, ec);
  BOOST_REQUIRE_MESSAGE(!ec, "ec: " << ec);
  BOOST_CHECK(file.is_open());
#endif
}

BOOST_AUTO_TEST_CASE_TEMPLATE(read_write, FileService, service_types)
{
  test_file_rm_guard rguard1(test_filename);

  asio::io_context io_context;
  asioext::basic_file<FileService> file(io_context);

  asioext::error_code ec;
  file.open(test_filename,
            open_flags::access_write | open_flags::create_always, ec);
  BOOST_REQUIRE_MESSAGE(!ec, "ec: " << ec);

  BOOST_REQUIRE_EQUAL(0, asio::write(file, asio::buffer(test_data, 0)));
  BOOST_REQUIRE_EQUAL(test_data_size,
                      asio::write(file, asio::buffer(test_data,
                                                     test_data_size)));

  BOOST_REQUIRE_NO_THROW(file.close());

  file.open(test_filename,
            open_flags::access_read | open_flags::open_existing, ec);
  BOOST_REQUIRE_MESSAGE(!ec, "ec: " << ec);

  char buffer[128];
  BOOST_REQUIRE_EQUAL(test_data_size,
                      asio::read(file, asio::buffer(buffer, test_data_size)));
  BOOST_REQUIRE_EQUAL(0, std::memcmp(test_data, buffer, test_data_size));
}

BOOST_AUTO_TEST_CASE_TEMPLATE(position_and_size, FileService, service_types)
{
  test_file_rm_guard rguard1(test_filename);

  asio::io_context io_context;
  asioext::basic_file<FileService> file(io_context);

  asioext::error_code ec;
  file.open(test_filename,
            open_flags::access_write | open_flags::create_always, ec);
  BOOST_REQUIRE_MESSAGE(!ec, "ec: " << ec);

  BOOST_REQUIRE_EQUAL(0, file.position());
  BOOST_REQUIRE_EQUAL(test_data_size,
                      asio::write(file, asio::buffer(test_data,
                                                     test_data_size)));
  BOOST_REQUIRE_EQUAL(test_data_size, file.position());
  BOOST_REQUIRE_EQUAL(test_data_size, file.size());
}

BOOST_AUTO_TEST_CASE_TEMPLATE(seek, FileService, service_types)
{
  test_file_rm_guard rguard1(test_filename);

  asio::io_context io_context;
  asioext::basic_file<FileService> file(io_context);

  asioext::error_code ec;
  file.open(test_filename,
            open_flags::access_write | open_flags::create_always, ec);
  BOOST_REQUIRE_MESSAGE(!ec, "ec: " << ec);

  BOOST_REQUIRE_EQUAL(0, file.seek(asioext::seek_origin::from_current, 0));
  BOOST_REQUIRE_EQUAL(10, file.seek(asioext::seek_origin::from_current, 10));
  BOOST_REQUIRE_EQUAL(10, file.position());
  BOOST_REQUIRE_EQUAL(20, file.seek(asioext::seek_origin::from_current, 10));
  BOOST_REQUIRE_EQUAL(20, file.position());
  BOOST_REQUIRE_EQUAL(10, file.seek(asioext::seek_origin::from_current, -10));

  char buffer[10] = {0, };
  BOOST_REQUIRE_EQUAL(10, asio::write(file, asio::buffer(buffer)));

  // size is now 20
  BOOST_REQUIRE_EQUAL(10, file.seek(asioext::seek_origin::from_end, -10));
}

template <class FileService>
struct write_handler
{
  write_handler(asioext::basic_file<FileService>& file)
    : file_(file)
    , state_(0)
  {
    // ctor
  }

  void operator()(const error_code& ec, std::size_t bytes_transferred)
  {
    BOOST_REQUIRE_MESSAGE(!ec,
                          "Operation " << state_ << " failed with: " << ec);
    switch (state_) {
      case 0: {
        state_ = 1;
        BOOST_REQUIRE_EQUAL(0, bytes_transferred);
        BOOST_REQUIRE_NO_THROW(asio::async_write(file_,
            asio::buffer(test_data, test_data_size),
            ASIOEXT_MOVE_CAST(write_handler)(*this)));
        break;
      }
      case 1: {
        BOOST_REQUIRE_EQUAL(test_data_size, bytes_transferred);
        break;
      }
    }
  }

  asioext::basic_file<FileService>& file_;
  int state_;
};

template <class FileService>
struct read_handler
{
  read_handler(asioext::basic_file<FileService>& file,
               const asio::mutable_buffer& buffer)
    : file_(file)
    , buffer_(buffer)
    , state_(0)
  {
    // ctor
  }

  void operator()(const error_code& ec, std::size_t bytes_transferred)
  {
    BOOST_REQUIRE_MESSAGE(!ec,
                          "Operation " << state_ << " failed with: " << ec);
    switch (state_) {
      case 0: {
        state_ = 1;
        BOOST_REQUIRE_EQUAL(0, bytes_transferred);
        BOOST_REQUIRE_NO_THROW(asio::async_read(file_,
            asio::buffer(buffer_),
            ASIOEXT_MOVE_CAST(read_handler)(*this)));
        break;
      }
      case 1: {
        BOOST_REQUIRE_EQUAL(test_data_size, bytes_transferred);
        BOOST_REQUIRE_EQUAL(0, std::memcmp(test_data,
                                           asio::buffer_cast<char*>(buffer_),
                                           test_data_size));
        break;
      }
    }
  }

  asioext::basic_file<FileService>& file_;
  asio::mutable_buffer buffer_;
  int state_;
};

BOOST_AUTO_TEST_CASE_TEMPLATE(async_read_write, FileService, service_types)
{
  test_file_rm_guard rguard1(test_filename);

  asio::io_context io_context;
  asioext::basic_file<FileService> file(io_context);

  asioext::error_code ec;
  file.open(test_filename,
            open_flags::access_write | open_flags::create_always, ec);
  BOOST_REQUIRE_MESSAGE(!ec, "ec: " << ec);

  BOOST_REQUIRE_NO_THROW(asio::async_write(file, asio::buffer(test_data, 0),
                                           write_handler<FileService>(file)));

  // Run the just enqueued operations.
  io_context.run();
  io_context.reset();

  BOOST_REQUIRE_NO_THROW(file.close());

  file.open(test_filename,
            open_flags::access_read | open_flags::open_existing, ec);
  BOOST_REQUIRE_MESSAGE(!ec, "ec: " << ec);

  char buffer[128];
  BOOST_REQUIRE_NO_THROW(asio::async_read(
      file, asio::buffer(buffer, 0),
      read_handler<FileService>(file,
                                asio::mutable_buffer(buffer, test_data_size))
  ));

  // Run the just enqueued operations.
  io_context.run();
  io_context.reset();
}

BOOST_AUTO_TEST_CASE_TEMPLATE(async_read_write_at, FileService, service_types)
{
  test_file_rm_guard rguard1(test_filename);

  asio::io_context io_context;
  asioext::basic_file<FileService> file(io_context);

  asioext::error_code ec;
  file.open(test_filename,
            open_flags::access_write | open_flags::create_always, ec);
  BOOST_REQUIRE_MESSAGE(!ec, "ec: " << ec);

  BOOST_REQUIRE_NO_THROW(asio::async_write_at(
      file, 0, asio::buffer(test_data, 0),
      write_handler<FileService>(file)));

  // Run the just enqueued operations.
  io_context.run();
  io_context.reset();

  BOOST_REQUIRE_NO_THROW(file.close());

  file.open(test_filename,
            open_flags::access_read | open_flags::open_existing, ec);
  BOOST_REQUIRE_MESSAGE(!ec, "ec: " << ec);

  char buffer[128];
  BOOST_REQUIRE_NO_THROW(asio::async_read_at(
      file, 0, asio::buffer(buffer, 0),
      read_handler<FileService>(file,
                                asio::mutable_buffer(buffer, test_data_size))
  ));

  // Run the just enqueued operations.
  io_context.run();
  io_context.reset();
}

template <class FileService>
struct write_cancel_handler
{
  void operator()(const error_code& ec, std::size_t bytes_transferred)
  {
    BOOST_REQUIRE_EQUAL(ec, asio::error::operation_aborted);
  }
};

template <class FileService>
struct cancel_handler
{
  cancel_handler(asioext::basic_file<FileService>& file)
    : file_(file)
    , work_(file.get_io_service())
  {
    // ctor
  }

  void operator()()
  {
    asio::async_write(
        file_, asio::buffer(test_data, test_data_size),
        write_cancel_handler<FileService>());

    // Cancel the just enqueued operation. Since we have only
    // one thread (which is currently executing this function),
    // we can be sure, that the cancellation must succeed before the
    // operation starts.
    file_.cancel();
  }

  asioext::basic_file<FileService>& file_;
  asio::io_context::work work_;
};

BOOST_AUTO_TEST_CASE(async_read_write_cancel)
{
  typedef thread_pool_file_service FileService;

  test_file_rm_guard rguard1(test_filename);

  asio::io_context io_context;

  FileService* svc = new FileService(io_context, 1);
  asio::add_service(io_context, svc);

  asioext::basic_file<FileService> file(io_context);

  asioext::error_code ec;
  file.open(test_filename,
            open_flags::access_write | open_flags::create_always, ec);
  BOOST_REQUIRE_MESSAGE(!ec, "ec: " << ec);
  BOOST_REQUIRE(file.is_open());

  asio::post(svc->get_thread_pool(), cancel_handler<FileService>(file));

  // Run the just enqueued operations.
  io_context.run();
  io_context.reset();
}

BOOST_AUTO_TEST_SUITE_END()

ASIOEXT_NS_END


text:
#include "unmount.h"
#include "common/to_do.h"
#include <boost/process/io.hpp>
#include <boost/process/search_path.hpp>
#include <boost/process/system.hpp>

namespace dogbox::fuse
{
    void unmount(std::filesystem::path const &mount_point)
    {
        boost::process::ipstream standard_error;
        if (boost::process::system(boost::process::search_path("fusermount"), "-zu", mount_point.string(),
                                   boost::process::std_out > stdout, boost::process::std_err > standard_error,
                                   boost::process::std_in < stdin) != 0)
        {
            std::string output;
            std::getline(standard_error, output);
            if (output != "/bin/fusermount: entry for " + mount_point.string() + " not found in /etc/mtab")
            {
                TO_DO();
            }
        }
    }
}

ext: cpp

max_stars_repo_name: TyRoXx/dogbox

max_issues_repo_name: TyRoXx/dogbox

max_forks_repo_name: TyRoXx/dogbox


text:
//    Copyright 2017 Rainer Gemulla
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
/** \file
 *
 * Illustrates matrix factorization with parallel SGD. We first create factors and then a data matrix
 * from these factors. This process ensures that we know the best factorization of the input.
 * These matrices are distributed across a cluster. We then try to reconstruct the factors
 * using PSGD.
 *
 * Run with: psgd
 * (make sure to use a production build, otherwise it will be slow)
 */
#include <iostream>
#include <sstream>

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/math/distributions/normal.hpp>
#include <boost/random/uniform_real.hpp>

#include <util/evaluation.h>

#include <mpi2/mpi2.h>
#include <mf/mf.h>

log4cxx::LoggerPtr logger(log4cxx::Logger::getLogger("main"));

using namespace std;
using namespace mf;
using namespace mpi2;
using namespace rg;
using namespace boost::numeric::ublas;

// type of SGD
typedef UpdateTruncate<UpdateNzslL2> Update;
typedef UpdateLock<Update> UpdateL;
typedef RegularizeNone Regularize;
typedef SumLoss<NzslLoss, L2Loss> Loss;
typedef NzslLoss TestLoss;

MPI2_TYPE_TRAITS(UpdateL);

int main(int argc, char* argv[]) {
	// initialize mf library and mpi2
	boost::mpi::communicator& world = mfInit(argc, argv);

	// parameters for the factorization
	mf_size_type size1 = 10000;
	mf_size_type size2 = 10000;
	mf_size_type nnz = 1000000;
	double sigma = sqrt(10); // standard deviation
	double lambda = 1/sigma/sigma;
	mf_size_type r = 10;

	// parameters for distribution
	int tasks = 4;

	// parameters for SGD
	double eps0 = 0.01;
	mf_size_type epochs = 20;
	SgdOrder order = SGD_ORDER_WOR;
	PsgdShuffle shuffle = PSGD_SHUFFLE_PARALLEL;
	Update update = Update(UpdateNzslL2(lambda), -10*sigma, 10*sigma); // truncate for numerical stability
	UpdateL updateLock = UpdateL(update, size1, size2); // with locking
	Regularize regularize;
	Loss loss((NzslLoss()), L2Loss(lambda));
	TestLoss testLoss;
	mf_size_type testNnz = nnz/100;
	BalanceType balanceType = BALANCE_NONE;
	BalanceMethod balanceMethod = BALANCE_OPTIMAL;

	// start mf library
	mfStart();

	if (world.rank() == 0)
	{
#ifndef NDEBUG
		LOG4CXX_WARN(logger, "Warning: Debug mode activated (runtimes may be slow).");
#endif
		LOG4CXX_INFO(logger, "Using " << tasks << " parallel tasks");

		// TODO: distribute matrix generation
		// generate original factors by sampling from a normal(0,sigma) distribution
		Random32 random; // note: this takes a default seed (not randomized!)
		DenseMatrix wIn(size1, r);
		DenseMatrixCM hIn(r, size2);
		generateRandom(wIn, random, boost::normal_distribution<>(0, sigma));
		generateRandom(hIn, random, boost::normal_distribution<>(0, sigma));

		// generate a sparse matrix by selecting random entries from the generated factors
		// and add small Gaussian noise
		SparseMatrix v;
		generateRandom(v, nnz, wIn, hIn, random);
		addRandom(v, random, boost::normal_distribution<>(0, 0.1));
		LOG4CXX_INFO(logger, "Data matrix: "
			<< v.size1() << " x " << v.size2() << ", " << v.nnz() << " nonzeros");
		LOG4CXX_INFO(logger, "Loss with original factors: " << loss((FactorizationData<>(v, wIn, hIn))));

		// create a test matrix (without noise)
		SparseMatrix vTest;
		generateRandom(vTest, testNnz, wIn, hIn, random);
		LOG4CXX_INFO(logger, "Test matrix: "
			<< v.size1() << " x " << v.size2() << ", " << vTest.nnz() << " nonzeros");

		// take a small sample and remove empty rows/columns
		ProjectedSparseMatrix Vsample;
		projectRandomSubmatrix(random, v, Vsample, v.size1()/5, v.size2()/5);
		projectFrequent(Vsample, 0);
		LOG4CXX_INFO(logger, "Sample matrix: "
			<< Vsample.data.size1() << " x " << Vsample.data.size2()
			<< ", " << Vsample.data.nnz() << " nonzeros");

		// generate initial factors by sampling from a uniform[-0.5,0.5] distribution
		DenseMatrix w(size1, r);
		DenseMatrixCM h(r, size2);
		generateRandom(w, random, boost::uniform_real<>(-0.5, 0.5));
		generateRandom(h, random, boost::uniform_real<>(-0.5, 0.5));

		// initialize
		Timer t;
		PsgdRunner psgdRunner(random);
		PsgdJob<Update,Regularize> psgdJob(v, w, h, update, regularize, order, tasks, shuffle);
		PsgdJob<UpdateL,Regularize> psgdJobLock(v, w, h, updateLock, regularize, order, tasks, shuffle);
		ParallelDecayAuto<Update,Regularize,Loss> decay(psgdJob, loss, Vsample, eps0, tasks);
		Trace trace;

		// print the test loss
		FactorizationData<> testData(vTest, w, h);
		LOG4CXX_INFO(logger, "Initial test loss: " << testLoss(testData));

		// run PSGD to try to reconstruct the original factors
		t.start();
//		psgdRunner.run(psgdJob, loss, epochs, decay, trace, balanceType, balanceMethod, &testData, &testLoss);
		psgdRunner.run(psgdJobLock, loss, epochs, decay, trace, balanceType, balanceMethod, &testData, &testLoss);

		t.stop();
		LOG4CXX_INFO(logger, "Total time: " << t);

		// print the test loss
		LOG4CXX_INFO(logger, "Final test loss: " << testLoss(testData));

		// write trace to an R file
		LOG4CXX_INFO(logger, "Writing trace to " << "/tmp/psgd-trace.R");
		trace.toRfile("/tmp/psgd-trace.R", "psgd");
	}

	mfStop();
	mfFinalize();

	return 0;
}

ext: cc

max_stars_repo_name: Hui-Li/DSGDPP

max_issues_repo_name: Hui-Li/DSGDPP

max_forks_repo_name: Hui-Li/DSGDPP


text:
/********************************************************************************
 * Copyright 2013 The Robotics Group, The Maersk Mc-Kinney Moller Institute,
 * Faculty of Engineering, University of Southern Denmark
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ********************************************************************************/

#include <ctime>

#include <rw/geometry/Cylinder.hpp>
#include <rw/geometry/Tube.hpp>
#include <rw/loaders/WorkCellLoader.hpp>
#include <rw/models/Object.hpp>

#include <rwlibs/assembly/AssemblyTask.hpp>
#include <rwlibs/assembly/CircularPiHControlStrategy.hpp>
#include <rwlibs/assembly/CircularPiHParameterization.hpp>
#include <rwlibs/task/Task.hpp>

#include <boost/program_options/options_description.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/program_options/parsers.hpp>

using namespace rw::core;
using namespace rw::geometry;
using namespace rw::math;
using namespace rw::models;
using namespace rw::loaders;
using namespace rwlibs::assembly;
using namespace rwlibs::task;

using namespace boost::program_options;

static std::string getTimeString() {
	time_t now = time(0);
	tm* time = localtime(&now);
	std::stringstream datestream;
	int day = time->tm_mday;
	int month = time->tm_mon+1;
	int year = time->tm_year+1900;
	int hour = time->tm_hour;
	int min = time->tm_min;
	int sec = time->tm_sec;
	datestream << ((day < 10)? "0": "") << day << "/";
	datestream << ((month < 10)? "0": "") << month << "-";
	datestream << year << " ";
	datestream << ((hour < 10)? "0": "") << hour << ":";
	datestream << ((min < 10)? "0": "") << min << ":";
	datestream << ((sec < 10)? "0": "") << sec;
	return datestream.str();
}

int main(int argc, char** argv) {
	options_description desc("Allowed options");
	desc.add_options()
	        		("help", "Produce this help message.")
	        		("output,o", value<std::string>()->default_value("tasks.assembly.xml"), "the output file.")
	        		("wc,w", value<std::string>()->default_value(""), "The workcell (optional). Used for automatic extraction of data.")
	        		("peg,p", value<std::string>()->default_value("Peg"), "The name of the Peg (required).")
	        		("hole,h", value<std::string>()->default_value("Hole"), "The name of the Hole (required).")
	        		("pegController", value<std::string>()->default_value(""), "The name of the controller for the peg (optional).")
	        		("holeController", value<std::string>()->default_value(""), "The name of the controller for the hole (optional).")
	        		("pegFlexibilityFrames", value<std::vector<std::string> >()->multitoken(), "Intermediate flexible frames that will have its transformations saved (optional).")
	        		("holeFlexibilityFrames", value<std::vector<std::string> >()->multitoken(), "Intermediate flexible frames that will have its transformations saved (optional).")
	        		("bodyContactSensors", value<std::vector<std::string> >()->multitoken(), "Save contacts from body contact sensors.")
	        		("prad", value<double>(), "Radius of the peg (can be extracted from workcell if Cylinder).")
	        		("plen", value<double>(), "Length of the peg (can be extracted from workcell if Cylinder).")
	        		("hrad", value<double>(), "Radius of the hole (can be extracted from workcell if Tube).")
	        		("hlen", value<double>(), "Length of the hole (can be extracted from workcell if Tube).")
	        		("pegTCP", value<std::string>()->default_value(""), "TCP frame for Peg (optional).")
	        		("holeTCP", value<std::string>()->default_value(""), "TCP frame for Hole (optional).")
	        		("pegFTSensor", value<std::string>()->default_value(""), "FTSensor for peg (optional).")
	        		("holeFTSensor", value<std::string>()->default_value(""), "FTSensor for hole (optional).")
	        		;

	variables_map vm;
	store(parse_command_line(argc, argv, desc), vm);
	notify(vm);

	if (vm.count("help")) {
		std::cout << "Usage:\n\n"
				<< "\t" << argv[0] <<" [options]\n"
				<< "\n";
		std::cout << desc << "\n";
		return 1;
	}

	const std::string wcFile = vm["wc"].as<std::string>();
	const std::string pegName = vm["peg"].as<std::string>();
	const std::string holeName = vm["hole"].as<std::string>();
	double prad = 0;
	double plen = 0;
	double hrad = 0;
	double hlen = 0;
	if (vm.count("prad")) prad = vm["prad"].as<double>();
	if (vm.count("plen")) plen = vm["plen"].as<double>();
	if (vm.count("hrad")) hrad = vm["hrad"].as<double>();
	if (vm.count("hlen")) hlen = vm["hlen"].as<double>();

	WorkCell::Ptr wc = NULL;
	if (wcFile != "") {
		wc = WorkCellLoader::Factory::load(wcFile);

		Object::Ptr peg = wc->findObject(pegName);
		Object::Ptr hole = wc->findObject(holeName);

		if (peg == NULL)
			RW_THROW("Peg with given name NOT found in WorkCell.");
		if (hole == NULL)
			RW_THROW("Hole with given name NOT found in WorkCell.");

		if (prad == 0 || plen == 0) {
			bool dataFound = false;
			if (peg != NULL) {
				if (peg->getGeometry().size() == 1) {
					GeometryData::Ptr geo = peg->getGeometry()[0]->getGeometryData();
					if (geo->getType() == GeometryData::CylinderPrim) {
						Cylinder* cyl = (geo.cast<Cylinder>()).get();
						prad = cyl->getRadius();
						plen = cyl->getHeight();
						dataFound = true;
					}
				}
			}
			if (!dataFound)
				RW_THROW("The geometry for the given peg does not allow automatic deduction of prad and plen. Please specify these options!");
		}
		if (hrad == 0 || hlen == 0) {
			bool dataFound = false;
			if (hole != NULL) {
				if (hole->getGeometry().size() == 1) {
					GeometryData::Ptr geo = hole->getGeometry()[0]->getGeometryData();
					if (geo->getType() == GeometryData::TubePrim) {
						Tube* tube = (geo.cast<Tube>()).get();
						hrad = tube->getInnerRadius();
						hlen = tube->getHeight();
						dataFound = true;
					}
				}
			}
			if (!dataFound)
				RW_THROW("The geometry for the given hole does not allow automatic deduction of hrad and hlen. Please specify these options!");
		}
	} else {
		if (prad == 0 || plen == 0 || hrad == 0 || hlen == 0) {
			RW_THROW("Please specify prad, plen, hrad and hlen options or specify wc option for a workcell with the parameters!");
		}
	}

	CircularPiHControlStrategy::Ptr strategy = ownedPtr(new CircularPiHControlStrategy());
	CircularPiHParameterization::Ptr parameters = ownedPtr(new CircularPiHParameterization(hrad,hlen,prad,plen,Pi/4.));
	parameters->distanceA = 0.015;

	AssemblyTask::Ptr task = ownedPtr(new AssemblyTask());
	task->maleID = pegName;
	task->femaleID = holeName;
	task->femaleTmaleTarget = Transform3D<>::identity();
	task->strategy = strategy;
	task->parameters = parameters;

	task->maleTCP = vm["pegTCP"].as<std::string>();
	task->femaleTCP = vm["holeTCP"].as<std::string>();

	task->taskID = "1";
	if (wc != NULL)
		task->workcellName = wc->getName();
	else
		task->workcellName = "";
	task->generator = "GenerateCircularPiHTasks in RobWorkSim/example/tools";
	task->date = getTimeString();
	//task->author = "author";

	task->malePoseController = vm["pegController"].as<std::string>();
	task->femalePoseController = vm["holeController"].as<std::string>();
	task->maleFTSensor = vm["pegFTSensor"].as<std::string>();
	task->femaleFTSensor = vm["holeFTSensor"].as<std::string>();
	if (vm.count("pegFlexibilityFrames"))
		task->maleFlexFrames = vm["pegFlexibilityFrames"].as<std::vector<std::string> >();
	if (vm.count("holeFlexibilityFrames"))
		task->femaleFlexFrames = vm["holeFlexibilityFrames"].as<std::vector<std::string> >();
	if (vm.count("bodyContactSensors"))
		task->bodyContactSensors = vm["bodyContactSensors"].as<std::vector<std::string> >();

	std::vector<AssemblyTask::Ptr> tasks;
	tasks.push_back(task);
	AssemblyTask::saveRWTask(tasks,vm["output"].as<std::string>());

	return 0;
}


text:
#include <ffigen/generate_node_ffi_interface.hpp>
#include <ffigen/utility/error_codes.hpp>
#include <ffigen/utility/exceptions.hpp>
#include <ffigen/utility/logger.hpp>
#include <ffigen/process/clang_facade.hpp>
#include <ffigen/process/filters/include_symbols_in_lib.hpp>
#include <argumentative/argumentative.hpp>
#include <boost/filesystem.hpp>
#include <vector>
#include <string>
#include <list>
#include <stdexcept>
#include <iostream>

namespace fs = boost::filesystem;

void recursive_glob_for_headers(std::list<std::string> & files, fs::path const& path)
{
    fs::recursive_directory_iterator i(path), end;
    for (; i != end; ++i) {
        fs::path const& path(i->path());

        std::string extension = path.extension().string();
        if (extension == ".h" || extension == ".hpp" || extension == ".hxx") {
            files.push_back(path.string());
        }
    }
}

int main(int argc, char ** argv)
{
    using namespace ffigen::utility::logs;
    using namespace ffigen::error_codes;
    using ffigen::fatal_error;
    using namespace argumentative::dsel;

    set_level(levels::INFO);

    bool help_requested = false;
    ffigen::clang_facade clang;
    ffigen::interface_generator generator;

    argumentative::cli cli("node-ffi-generator");

    cli += option("help")([&help_requested] (std::string const&) {
        std::cout << "Generates node-ffi JS bindings using one or more C header files. Embeds clang's parser to do so.\n\n";
        std::cout << "Usage: node-ffi-generator --file=path/to/headers --dest=path/to/jsfiles/destination --src-root=path/headers/root/dir\n\n";
        std::cout << "Options:\n";
        std::cout << "  --file=path/to/file          C header file or directory with header files to process. If a directory,\n";
        std::cout << "                               it is searched recursively for .h, .hpp and .hxx files.\n";
        std::cout << "  --dest=path/to/dir           The destination directory for the mapping files.\n";
        std::cout << "  --src-root=path/to/dir       The root directory of the C library that's being mapped. Helps to determine\n";
        std::cout << "                               the destination's directory structure.\n";
        std::cout << "  --include=path/to/dir        A directory to use when searching for headers.\n";
        std::cout << "  --define=MACRO=DEFINITION    Sets a predefine before parsing header files.\n";
        std::cout << "  --assume-pragma-once         If supplied, every header file will be included only once. Useful if some or\n";
        std::cout << "                               all of the headers have no include guards.\n";
        std::cout << "  --bind-lib=path/to/lib       If a path to an existing shared object is supplied, only the functions found\n";
        std::cout << "                               in the shared object will be included in the generated JS output.\n";
        std::cout << "  --log-level=level        Sets the log level to use. Can be ERROR, WARNING, INFO, DEBUG or VERBOSE.\n";
        std::cout << std::flush;

        help_requested = true;
    });

    cli += option("file", "", option_value::required)([&clang] (std::string const& value) {
        // TODO: should support glob expressions
        fs::path path(value);
        if (fs::is_directory(path)) {
            recursive_glob_for_headers(clang.files_to_process, path);
        } else if (fs::is_regular_file(path)) {
            clang.files_to_process.push_back(value);
        } else {
            throw fatal_error(std::string("'") + value + "' supplied in --file option does not exist.", INVALID_ARGUMENT);
        }

        debug() << "Processed --file argument '" << value << "'" << std::endl;
    });

    cli += option("dest", "", option_value::required)([&generator] (std::string const& value) {
        fs::path path(value);

        if (!fs::is_directory(path)) {
            throw fatal_error(std::string("Destination '") + value + "' is not a valid directory.", INVALID_ARGUMENT);
        }

        generator.dest_root = path;

        debug() << "Processed --dest argument '" << value << "'" << std::endl;
    });

    cli += option("src-root", "", option_value::required)([&clang, &generator] (std::string const& value) {
        fs::path path(value);

        if (!fs::is_directory(path)) {
            throw fatal_error(std::string("ERROR: Source root directory '") + value + "' is not a valid directory.", INVALID_ARGUMENT);
        }

        generator.src_root = fs::canonical(path);
        clang.include_directories.push_back(generator.src_root.string());

        debug() << "Processed --src-root argument " << generator.src_root << std::endl;
    });

    cli += option("log-level", "", option_value::required)([] (std::string const& value) {
        if (value == "ERROR") {
            set_level(levels::ERROR);
        } else if (value == "WARNING") {
            set_level(levels::WARNING);
        } else if (value == "INFO") {
            set_level(levels::INFO);
        } else if (value == "DEBUG") {
            set_level(levels::DEBUG);
        } else if (value == "VERBOSE") {
            set_level(levels::VERBOSE);
        } else {
            throw fatal_error(std::string("ERROR: Invalid log level supplied in --log-level option '") + value + ";.",
                INVALID_ARGUMENT);
        }
    });

    cli += option("include", "", option_value::required)([&clang] (std::string const& value) {
        if (!fs::is_directory(fs::path(value))) {
            throw fatal_error(std::string("ERROR: Include directory '") + value + "' is not a valid directory.",
                INVALID_ARGUMENT);
        }

        clang.include_directories.push_back(value);
    });

    cli += option("define", "D", option_value::required)([&clang] (std::string const& value) {
        size_t pos = value.find("=");

        std::string name;
        std::string def_value;

        if (pos == std::string::npos) {
            name = value;
            def_value = "";
        } else {
            name = value.substr(0, pos);
            def_value = value.substr(pos + 1);
        }

        clang.predefines[name] = def_value;
    });

    cli += option("assume-pragma-once", "", option_value::none)([&clang] (std::string const& value) {
        clang.assume_pragma_once = true;
    });

    cli += option("bind-lib", "", option_value::required)([&clang] (std::string const& value) {
        clang.symbol_filters.push_back(ffigen::include_symbols_in_lib(value));

        std::cout << "Limiting mapped functions to functions found in '" << value << "'." << std::endl;
    });

    try {
        cli.parse(argv, argv + argc);

        if (help_requested) { // TODO: should be a way to exit w/ success from closure...
            return 0;
        }

        if (clang.files_to_process.empty()) {
            std::cout << "ERROR: Required option 'file' not supplied.\n";
            return MISSING_ARGUMENT;
        }

        generator.validate();

        ffigen::generate_node_ffi_interface(clang, generator);
    } catch (ffigen::fatal_error const& ex) {
        std::cout << "ERROR: " << ex.what() << std::endl;
        return ex.error_code;
    } catch (std::exception const& ex) {
        std::cout << "UNEXPECTED ERROR: " << ex.what() << std::endl;
        return UNKNOWN_ERROR;
    }
}

max_stars_repo_name: diosmosis/node-ffi-generator

max_issues_repo_name: diosmosis/node-ffi-generator

max_forks_repo_name: diosmosis/node-ffi-generator


text:
///\file pngs2video.cpp
///\author Ethan Knox
///\date 7/22/2020.

#include "../include/pngs2video.h"
#include "../include/clean.h"
#include <boost/process.hpp>
#include <fmt/format.h>
#include <iostream>

///\brief Creates a video of the simulation
///
///Uses ffmpeg to convert the png frames into both a gif and mp4, then the now
///obsolete frames are deleted
///\todo Don't delete these images if future option to save them is selected
///
/// \return void
void pngs2video(Ising &p)
{
    std::cout << "\nCreating mp4... ";
    boost::process::system(fmt::format("ffmpeg -nostats -loglevel 0 -i {0}/frame%d.png {1}", p.outputdir.string(), (p.outputdir/"output.mp4").string()).c_str());
    std::cout << "Done!\n" << std::endl;

    std::cout << "\nCreating gif... ";
    boost::process::system(fmt::format("ffmpeg -nostats -loglevel 0 -i {0}/frame%d.png {1}", p.outputdir.string(), (p.outputdir/"output.gif").string()).c_str());
    std::cout << "Done!\n" << std::endl;

    clean_pngs(p);
}


text:
//==============================================================================
//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//         Copyright 2011 - 2012   MetaScale SAS
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_CORE_FUNCTIONS_EXPAND_TO_HPP_INCLUDED
#define NT2_CORE_FUNCTIONS_EXPAND_TO_HPP_INCLUDED

#include <nt2/include/functor.hpp>
#include <nt2/core/container/dsl/value_type.hpp>
#include <nt2/core/container/dsl/size.hpp>
#include <nt2/sdk/meta/boxed_size.hpp>
#include <nt2/sdk/meta/value_as.hpp>

#include <nt2/sdk/parameters.hpp>
#include <boost/preprocessor/repetition/repeat_from_to.hpp>
#include <boost/preprocessor/arithmetic/inc.hpp>

namespace nt2
{
  namespace tag
  {
   /*!
     @brief expand_to generic tag

     Represents the expand_to function in generic contexts.

     @par Models:
        Hierarchy
   **/
    struct expand_to_ : ext::elementwise_<expand_to_>
    {
      /// @brief Parent hierarchy
      typedef ext::elementwise_<expand_to_> parent;
      template<class... Args>
      static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args)
      BOOST_AUTO_DECLTYPE_BODY( dispatching_expand_to_( ext::adl_helper(), static_cast<Args&&>(args)... ) )
    };
  }
  namespace ext
  {
   template<class Site, class... Ts>
   BOOST_FORCEINLINE generic_dispatcher<tag::expand_to_, Site> dispatching_expand_to_(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...)
   {
     return generic_dispatcher<tag::expand_to_, Site>();
   }
   template<class... Args>
   struct impl_expand_to_;
  }

  /*!
    Expands expression to a given size enabling singleton expansion

    @par semantic:

    expand_to(a,siz) is conceptually equivalent (for additive element
    types) to bsxfun(plus, a, zeros(siz))

    size(a) and @c siz must be such that for every involved dimension
    @c i size(a, i) == siz(i) or 1.

    Whenever a dimension of @c a or @c b is singleton (i.e equal to
    one), expand_to virtually replicates the array along that
    dimension to match the given dimension in siz.

    @param a0 expression to process
    @param a1 size to expand to
    @return an expression which eventually will evaluate to the result
  **/

  #define M0(z,n,t)                                                           \
  NT2_FUNCTION_IMPLEMENTATION(nt2::tag::expand_to_, expand_to, n)             \
  /**/

  BOOST_PP_REPEAT_FROM_TO(2,BOOST_PP_INC(BOOST_PP_INC(NT2_MAX_DIMENSIONS)),M0,~)
  #undef M0
}
namespace nt2 { namespace ext
{
  /// INTERNAL ONLY
  template<class Domain, class Expr,int N>
  struct  size_of<nt2::tag::expand_to_,Domain,N,Expr>
        : meta::boxed_size<Expr,1>
  {};

  /// INTERNAL ONLY
  template<class Domain, class Expr, int N>
  struct  value_type<nt2::tag::expand_to_,Domain,N,Expr>
        : meta::value_as<Expr,0>
  {};
} }

#endif

ext: hpp


text:
#ifndef VECTOR_MATH_HPP
# define VECTOR_MATH_HPP

#include <Eigen/Dense>

using Eigen::Matrix3d;
using Eigen::Vector3d;

const double ANGLE_SMALL = 1e-12;

Matrix3d skew(const Vector3d& a) {
  Matrix3d ax;
  ax << 0.0, -a(2), a(1),
    a(2), 0.0, -a(0),
    -a(1), a(0), 0.0;
  return ax;
}

/** @brief Convert a rotation vector to a DCM.
 *
 * @param[in]   v   rotation vector (unit rotation axis multiplied by
 *                  angle about that vector)
 *
 * @returns A 3D matrix.
 */
Matrix3d rotvec_to_matrix(const Vector3d& v) {
  double v_mag = v.norm();
  double c     = std::cos(v_mag);
  double s     = std::sin(v_mag);

  Vector3d vu = v / v_mag;

  Matrix3d T;
  if (v_mag < ANGLE_SMALL) T = Matrix3d::Identity();
  else {
    // Reference: https://github.com/mohawkjohn/pyquat/blob/master/pyquat/pyquat.c
    // Line 932
    T << c + vu[0]*vu[0] * (1.0 - c),
      vu[0]*vu[1] * (1.0 - c) + vu[2] * s,
      vu[0]*vu[2] * (1.0 - c) - vu[1] * s,
      vu[0]*vu[1] * (1.0 - c) - vu[2] * s,
      c + vu[1]*vu[1] * (1.0 - c),
      vu[1]*vu[2] * (1.0 - c) + vu[0] * s,
      vu[0]*vu[2] * (1.0 - c) + vu[1] * s,
      vu[1]*vu[2] * (1.0 - c) - vu[0] * s,
      c + vu[2]*vu[2] * (1.0 - c);
  }

  return T;
}

#endif

max_stars_repo_name: openlunar/nav

max_issues_repo_name: openlunar/nav

max_forks_repo_name: openlunar/nav