text:
// Copyright (c) 2019-present, Facebook, Inc.
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.

#include <boost/range/size_type.hpp>
#include <devmand/channels/cli/QueuedCli.h>

namespace devmand {
namespace channels {
namespace cli {

using namespace std;
using namespace folly;

shared_ptr<QueuedCli> QueuedCli::make(
    string id,
    shared_ptr<Cli> cli,
    shared_ptr<Executor> parentExecutor,
    const long capacity) {
  return std::make_shared<QueuedCli>(id, cli, parentExecutor, capacity);
}

QueuedCli::QueuedCli(
    string _id,
    shared_ptr<Cli> _cli,
    shared_ptr<Executor> _parentExecutor,
    const long capacity)
    : id(_id),
      sharedCli(_cli),
      sharedParentExecutor(_parentExecutor),
      sharedSerialExecutorKeepAlive(
          make_shared<Executor::KeepAlive<SerialExecutor>>(
              SerialExecutor::create(
                  Executor::getKeepAliveToken(_parentExecutor.get())))) {
  queuedParameters = std::make_shared<QueuedParameters>(
      id, sharedCli, sharedSerialExecutorKeepAlive, capacity);
}

SemiFuture<Unit> QueuedCli::destroy() {
  MLOG(MDEBUG) << "[" << id << "] "
               << "destroy: started";
  // call underlying destroy()
  SemiFuture<Unit> innerDestroy = sharedCli->destroy();

  MLOG(MDEBUG) << "[" << id << "] "
               << "destroy: dequeuing " << queuedParameters->queue->size()
               << " items";
  {
    QueueEntry queueEntry;
    while (queuedParameters->queue->try_dequeue(queueEntry)) {
      MLOG(MDEBUG) << "[" << id << "] (" << queueEntry.command << ") "
                   << "destroy: fulfilling promise with exception";
      queueEntry.promise->setException(runtime_error("QCli: Shutting down"));
    }
  } // drop queueEntry to release queuedParameters from its obtain.. function
  MLOG(MDEBUG) << "[" << id << "] "
               << "destroy: done";
  return innerDestroy;
}

QueuedCli::~QueuedCli() {
  MLOG(MDEBUG) << "[" << id << "] "
               << "~QCli: started";
  destroy().get();
  queuedParameters = nullptr;
  sharedSerialExecutorKeepAlive = nullptr;
  sharedParentExecutor = nullptr;
  sharedCli = nullptr;
  MLOG(MDEBUG) << "[" << id << "] "
               << "~QCli: done";
}

SemiFuture<string> QueuedCli::executeRead(const ReadCommand cmd) {
  boost::recursive_mutex::scoped_lock scoped_lock(writeCommandMutex);
  MLOG(MDEBUG) << "[" << queuedParameters->id << "] "
               << "Invoking read command: \"" << cmd << "\"";
  return executeSomething(cmd, "QCli.executeRead", [cmd](shared_ptr<Cli> cli) {
    return cli->executeRead(cmd);
  });
}

SemiFuture<string> QueuedCli::executeWrite(const WriteCommand cmd) {
  boost::recursive_mutex::scoped_lock scoped_lock(writeCommandMutex);
  MLOG(MDEBUG) << "[" << queuedParameters->id << "] "
               << "Invoking write command: \"" << cmd << "\"";
  Command command = cmd;
  if (!command.isMultiCommand()) {
    // Single line config command, execute with read
    return executeRead(ReadCommand::create(cmd.raw(), true)); //skip cache
  }

  const vector<Command>& commands = command.splitMultiCommand();
  vector<Future<string>> commmandsFutures;

  for (unsigned long i = 0; i < (commands.size() - 1); i++) {
    commmandsFutures.emplace_back(
        executeSomething(
            commands.at(i),
            "QCli.executeWrite",
            [cmd = commands.at(i)](shared_ptr<Cli> cli) {
              return cli->executeWrite(WriteCommand::create(cmd));
            })
            .via(sharedSerialExecutorKeepAlive->get()));
  }

  commmandsFutures.emplace_back(
      executeRead(ReadCommand::create(commands.back().raw(), true)) //skip cache
          .via(sharedSerialExecutorKeepAlive->get()));

  return reduce(
             commmandsFutures.begin(),
             commmandsFutures.end(),
             string(""),
             [](string s1, string s2) { return s1 + s2; })
      .semi();
}

SemiFuture<string> QueuedCli::executeSomething(
    const Command& cmd,
    const string& prefix,
    function<SemiFuture<string>(shared_ptr<Cli>)> innerFunc) {
  shared_ptr<Promise<string>> promise = make_shared<Promise<string>>();
  QueueEntry queueEntry = QueueEntry{move(innerFunc), promise, cmd, prefix};
  MLOG(MDEBUG) << "1[" << queuedParameters->id << "] (" << queueEntry.command
               << ") " << prefix << " adding to queue ('" << cmd << "')";

  bool success = queuedParameters->queue->try_enqueue(move(queueEntry));

  if (!success) {
    promise->setException(runtime_error("QCli: queue is full"));
    return promise->getFuture().semi();
  }

  if (!queuedParameters->isProcessing) {
    triggerDequeue(queuedParameters);
  }
  return promise->getFuture().semi();
}

/*
 * Start queue reading on consumer thread if queue contains new items.
 * It is safe to call this method anytime, it is thread safe.
 */
void QueuedCli::triggerDequeue(shared_ptr<QueuedParameters> queuedParameters) {
  if (shared_ptr<Executor::KeepAlive<SerialExecutor>> serialExecutor =
          queuedParameters->serialExecutorKeepAlive.lock()) {
    // switch to consumer thread
    via(serialExecutor->get(), [params = queuedParameters]() {
      MLOG(MDEBUG) << "[" << params->id << "] "
                   << "QCli.isProcessing:" << params->isProcessing
                   << ", queue size:" << params->queue->size();
      // do nothing if still waiting for remote device to respond
      if (params->isProcessing) {
        // waiting for response
        return;
      }
      QueueEntry queueEntry;
      // try to obtain entry from queue
      if (!params->queue->try_dequeue(queueEntry)) {
        // nothing in the queue
        return;
      }

      if (shared_ptr<Cli> cli = params->cli.lock()) {
        if (shared_ptr<Executor::KeepAlive<SerialExecutor>> serialExecutor2 =
                params->serialExecutorKeepAlive.lock()) {
          startProcessing(move(queueEntry), params, cli, serialExecutor2);
          return;
        }
      }
      // fail fast if qcli is destroyed
      MLOG(MDEBUG) << "[" << params->id << "] (" << queueEntry.command << ") "
                   << queueEntry.loggingPrefix << " Shutting down";
      queueEntry.promise->setException(
          DisconnectedException("SSH session expired"));
    });
  } else {
    MLOG(MDEBUG) << "[" << queuedParameters->id
                 << "] Cannot obtain serial executor";
    // locking weak pointers failed, do nothing as object was destroyed
  }
}

void QueuedCli::startProcessing(
    QueueEntry queueEntry,
    shared_ptr<QueuedParameters> params,
    shared_ptr<Cli> cli,
    shared_ptr<Executor::KeepAlive<SerialExecutor>> executor) {
  params->isProcessing = true;
  SemiFuture<string> cliFuture = queueEntry.obtainFutureFromCli(cli);
  MLOG(MDEBUG) << "[" << params->id << "] (" << queueEntry.command << ") "
               << queueEntry.loggingPrefix
               << " dequeued and cli future obtained";

  move(cliFuture)
      .via(executor->get())
      .thenValue([params, queueEntry](string result) -> Future<Unit> {
        // after cliFuture completes, finish processing on consumer thread
        onDequeueSuccess(params, queueEntry, result);
        return unit;
      })
      .thenError([params, queueEntry](exception_wrapper e) -> Future<Unit> {
        onDequeueError(params, queueEntry, e);
        return unit;
      });
}

void QueuedCli::onDequeueSuccess(
    const shared_ptr<QueuedParameters>& params,
    const QueuedCli::QueueEntry& queueEntry,
    const string& result) {
  MLOG(MDEBUG) << "[" << params->id << "] (" << queueEntry.command << ") "
               << queueEntry.loggingPrefix << " succeeded";
  params->isProcessing = false;
  queueEntry.promise->setValue(result);
  triggerDequeue(params);
}

void QueuedCli::onDequeueError(
    const shared_ptr<QueuedParameters>& params,
    const QueuedCli::QueueEntry& queueEntry,
    const exception_wrapper& e) {
  MLOG(MDEBUG) << "[" << params->id << "] (" << queueEntry.command << ") "
               << queueEntry.loggingPrefix << " failed with exception '"
               << e.what() << "'";
  params->isProcessing = false;
  queueEntry.promise->setException(e);
  triggerDequeue(params);
}

QueuedCli::QueuedParameters::QueuedParameters(
    const string& _id,
    weak_ptr<Cli> _cli,
    weak_ptr<Executor::KeepAlive<SerialExecutor>> _serialExecutorKeepAlive,
    const long capacity)
    : id(_id),
      cli(_cli),
      serialExecutorKeepAlive(_serialExecutorKeepAlive),
      queue(std::make_unique<CliQueue>(capacity)) {}
} // namespace cli
} // namespace channels
} // namespace devmand

max_stars_repo_name: apbuteau/magma

max_issues_repo_name: apbuteau/magma

max_forks_repo_name: apbuteau/magma


text:
#include <cradle/gui/app/instance.hpp>

#include <wx/glcanvas.h>
#include <wx/msgdlg.h>
#include <cradle/external/clean.hpp>
#include <json\json.h>

#include <boost/program_options.hpp>

#include <alia/ui/utilities/styling.hpp>

#include <cradle/gui/app/internals.hpp>
#include <cradle/gui/app/top_level_ui.hpp>
#include <cradle/gui/internals.hpp>
#include <cradle/io/file.hpp>

namespace cradle {

void reset_task_groups(app_instance& instance)
{
    instance.task_groups.clear();
    instance.phantom_task_groups.clear();
    push_task_group(instance,
        instance.controller->get_root_task_group_controller());
    clear_data_block(instance.task_stack_ui_block);
}

bool static
initialize_app_instance(app_instance& instance,
    unsigned argc, wxCmdLineArgsArray const& argv)
{
    auto& controller = *instance.controller;

    auto app_info = controller.get_app_info();
    instance.info = app_info;

    instance.selected_page = app_level_page::APP_CONTENTS;

    instance.state_write_back_requested = false;

    shared_app_config shared_config;
    try
    {
        shared_config = read_shared_app_config();
    }
    catch (...)
    {
        shared_config = shared_app_config(none, 100, none);
    }
    instance.shared_config = shared_config;

    instance.crash_reporter.begin(
        shared_config.crash_dir ?
            get(shared_config.crash_dir) :
            file_path("."),
        app_info.thinknode_app_id,
        app_info.local_version_id);

    boost::filesystem::path executable_path((char const*)argv[0].ToUTF8());

    namespace po = boost::program_options;

    po::options_description desc("Supported options");
    desc.add_options()
        ("help", "show help message")
        ("version", "show version information")
        ("style-file", po::value<string>(), "set style file")
        ("realm", po::value<string>(), "specify the realm to use (by ID)")
        ("username", po::value<string>(), "set username for authentication")
        ("password", po::value<string>(), "set password for authentication")
        ("token", po::value<string>(), "set token for authentication")
    ;

    auto additional_arguments = controller.get_app_command_line_arguments();
    for (auto const& argument : additional_arguments)
    {
        //throw exception(string(argument.first));
        desc.add_options()
            (argument.first, po::value<string>(), argument.second)
        ;
    }

    po::positional_options_description p;

    po::variables_map vm;
    po::store(po::command_line_parser(argc, argv).
        options(desc).positional(p).run(), vm);
    po::notify(vm);

    if (vm.count("help"))
    {
        // TODO: This doesn't actually end up going to the Windows console.
        std::cout << desc << "\n";
        return false;
    }

    app_config config;
    try
    {
        config = read_app_config(app_info.thinknode_app_id);
    }
    catch (...)
    {
        config =
            app_config(
                none, none,
                regular_app_window_state(
                    none, make_vector<int>(850, 1000), false, true),
                430,
                350,
                make_layout_vector(0,0),
                1.0);
    }
    instance.config.set(config);

    instance.api_url = read_app_config_file("config.txt", "api_url");

    instance.gui_system.reset(new gui_system);
    initialize_gui_system(&*instance.gui_system,
        shared_config.cache_dir ?
            get(shared_config.cache_dir) :
            get_default_cache_dir("Astroid2"),
        "",
        shared_config.cache_size * int64_t(0x40000000),
        file_path("ca-bundle.crt"));

    // See if the username is available from the command-line or the config.
    if (vm.count("username"))
    {
        auto username = vm["username"].as<string>();
        instance.username.set(username);
    }
    else if (config.username)
    {
        instance.username.set(get(config.username));
    }

    // If token is provide from command-line use it to login with
    if(vm.count("token"))
    {
        auto token = vm["token"].as<string>();
        instance.token.set(token);
        sign_in_wih_token(instance, vm["token"].as<string>());
    }
    // If a password and username are specified on the command-line, initiate the
    // sign-in process.
    else if (vm.count("password") && vm.count("username"))
    {
        start_sign_in(instance, instance.username.get(), vm["password"].as<string>());
    }

    // See if the realm ID is available from the command-line or the config.
    // And if it is, select it.
    if (vm.count("realm"))
    {
        auto realm_id = vm["realm"].as<string>();
        instance.realm_id.set(realm_id);
    }
    else if (config.realm_id)
    {
        auto realm_id = get(config.realm_id);
        instance.realm_id.set(realm_id);
    }

    if (vm.count("style-file"))
    {
        instance.style_file_path = vm["style-file"].as<string>();
    }
    else
    {
        instance.style_file_path = (executable_path.branch_path() /
            "alia.style").string<std::string>();
    }

    // Process any app specific command line arguments
    controller.process_app_command_line_arguments(vm);

    reset_task_groups(instance);

    style_tree_ptr style = parse_style_file(instance.style_file_path.c_str());

    auto* window_controller = new app_window_controller;
    alia__shared_ptr<alia::app_window_controller>
        window_controller_ptr(window_controller);
    window_controller->instance = &instance;

    controller.register_tasks();

    int gl_canvas_attribs[] = {
        WX_GL_RGBA,
        WX_GL_DOUBLEBUFFER,
        WX_GL_STENCIL_SIZE, 1,
        WX_GL_SAMPLE_BUFFERS, 1,
        WX_GL_SAMPLES, 4,
        0 };
    auto* frame =
        create_wx_framed_window(
            app_info.app_name,
            window_controller_ptr, style,
            to_alia(instance.config.get().window_state),
            gl_canvas_attribs);
    #if defined(__WXMSW__)
        frame->SetIcon(wxICON(wxSTD_FRAME));
    #endif

    return true;
}

void static
shut_down_app_instance(app_instance& instance)
{
    clear_all_jobs(*instance.gui_system->bg);
    instance.gui_system.reset();
}

untyped_application::untyped_application(app_controller_interface* controller)
{
    instance = new app_instance;
    instance->controller.reset(controller);

    int attribs[] = { WX_GL_DOUBLEBUFFER, 0 };
    if (!this->InitGLVisual(attribs))
    {
        wxMessageBox("OpenGL not available");
        instance->return_code = -1;
    }
    else
        instance->return_code = 0;
}

untyped_application::~untyped_application()
{
    delete instance;
}

bool untyped_application::OnInit()
{
    try
    {
        return initialize_app_instance(*instance, argc, argv);
    }
    catch (std::exception& e)
    {
        wxMessageBox(std::string("An error occurred during application"
            " initialization.\n\n") + e.what());
        instance->return_code = -1;
    }
    catch (...)
    {
        wxMessageBox("An unknown error occurred during application"
            " initialization.");
        instance->return_code = -1;
    }
    return true;
}

int untyped_application::OnRun()
{
    if (instance->return_code == 0)
        return wxGLApp::OnRun();
    else
        return instance->return_code;
}

int untyped_application::OnExit()
{
    shut_down_app_instance(*instance);

    delete instance;
    instance = 0;

    return wxGLApp::OnExit();
}

}

ext: cpp

max_stars_repo_name: dotdecimal/open-cradle

max_issues_repo_name: dotdecimal/open-cradle

max_forks_repo_name: dotdecimal/open-cradle


text: #include <boost/qvm/quat_access.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
//------------------------------------------------------------------------------
//                         SparseMatrixUtil1
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool.
//
// Copyright (c) 2002 - 2020 United States Government as represented by the
// Administrator of The National Aeronautics and Space Administration.
// All Other Rights Reserved.
//
// Author: Youngkwang Kim
// Created: 2015/07/08
//
// NOTE: This is a static utility class.  The constructors, destructor, and
// operator= are not implemented.  No instances of this class can be
// instantiated.
/**
 */
//------------------------------------------------------------------------------
#ifndef SparseMatrixUtil_hpp
#define SparseMatrixUtil_hpp

/// for std::vector's min_element, max_element
#include <algorithm>
#include "csaltdefs.hpp"
#include "Rvector.hpp"
#include "Rmatrix.hpp"

// ublas related preprocessor starts
/// we are not using any BOOST libraries
#define BOOST_ALL_NO_LIB
/// turning off unnecessary checks in debug mode.
#define BOOST_UBLAS_NDEBUG
/// include ublas related headers
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/operation.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_sparse.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/vector_sparse.hpp>
#include <boost/numeric/ublas/vector_proxy.hpp>
// ublas related inclusion ends

using boost::numeric::ublas::compressed_matrix;

// define RSMatrix; they can be replaced with other
// data types.
typedef compressed_matrix<Real> RSMatrix;

// it is recommended not to use Iterators in the
// outside of sparse matrix utility!
// because using Iterators are BOOST dependent!

//typedef compressed_matrix<Real>::iterator1 Iterator1;
//typedef compressed_matrix<Real>::iterator2 Iterator2;
//typedef compressed_matrix<Real>::const_iterator1 ConstIterator1;
//typedef compressed_matrix<Real>::const_iterator2 ConstIterator2;

class CSALT_API SparseMatrixUtil
{
public:

   // set methods

   /// set the element of sparse matrix
   static void SetElement(RSMatrix  &spMat,
                          Integer rowIdx, Integer colIdx, Real value);

   /// set the size/resize of the sparse matrix
   static void SetSize(RSMatrix &spMat,
                       Integer rowSize, Integer colSize);

   /// set the sparsity pattern of the entire sparse matrix with zeros or ones
   /// NOTE that: changing sparsity pattern takes some time;
   ///      so it is desirable to set sparsity pattern with zeros, first;
   ///      then fill the values at the last.
   ///      this approach it useful for user jacobian and hessian matrices.
   static void SetSparsityPattern(RSMatrix &spMat,
                                  Integer  rowSize, Integer colSize,
                                  const IntegerArray *rowIdxVec,
                                  const IntegerArray *colIdxVec,
                                  bool  hasZeros = false);

   /// set the data of the entire sparse matrix
   static void SetSparseMatrix(RSMatrix &spMat,
                               Integer rowSize, Integer colSize,
                               const IntegerArray *rowIdxVec,
                               const IntegerArray *colIdxVec,
                               const std::vector<Real> *valueVec);

   /// set the data of the entire sparse matrix
   static void SetSparseMatrix(RSMatrix &spMat,
                               Integer rowSize, Integer colSize,
                               const IntegerArray *rowIdxVec,
                               const IntegerArray *colIdxVec,
                               const Rvector *valueVec);

   /// set the data of a part of the sparse matrix
   /// if the isNotAdding option is off, then
   /// the addition to the existing sparse matrix is done.
   static void SetSparseBLockMatrix(RSMatrix  &spMat,
                                    Integer   rowOffSet, Integer colOffSet,
                                    const IntegerArray *rowIdxVec,
                                    const IntegerArray *colIdxVec,
                                    const std::vector<Real> *valueVec,
                                    bool isNotAdding = true);

   /// set the data of a part of the sparse matrix
   /// if the isNotAdding option is off, then
   /// the addition to the existing sparse matrix is done.
   static void SetSparseBLockMatrix(RSMatrix  &spMat,
                                    Integer rowOffSet, Integer colOffSet,
                                    const IntegerArray *rowIdxVec,
                                    const IntegerArray *colIdxVec,
                                    const Rvector *valueVec,
                                    bool isNotAdding = true);

   /// set the data of a part of the sparse matrix
   /// if the isNotAdding option is off, then
   /// the addition to the existing sparse matrix is done.
   static void SetSparseBLockMatrix(RSMatrix  &spMat,
                                    Integer rowOffSet, Integer colOffSet,
                                    const RSMatrix  *spBlockMat,
                                    bool isNotAdding = true);

   /// set the data of a part of the sparse matrix
   /// if the isNotAdding option is off, then
   /// the addition to the existing sparse matrix is done.
   static void SetSparseBLockMatrix(RSMatrix  &spMat,
                                    Integer rowOffSet, Integer colOffSet,
                                    const Rmatrix  *blockMat,
                                    bool isNotAdding = true);

   /// get methods
   static Real GetElement(const RSMatrix  *spMat,
                          Integer rowIdx, Integer colIdx);

   static Integer GetNumRows(const RSMatrix  *spMat);
   static Integer GetNumColumns(const RSMatrix  *spMat);

   /// get the sparsity pattern of the sparse matrix
   static RSMatrix GetSparsityPattern(const RSMatrix *spMat,
                                      bool hasZeros = false);

   /// get the sparsity pattern of the sparse matrix
   static void GetSparsityPattern(const RSMatrix *spMat,
                                 IntegerArray &rowIdxVec,
                                 IntegerArray &colIdxVec);

   /// set the data of the entire sparse matrix
   static void GetThreeVectorForm(const RSMatrix  *spMat,
                                 IntegerArray &rowIdxVec,
                                 IntegerArray &colIdxVec,
                                 std::vector<Real> &valueVec);

   /// set the data of the entire sparse matrix
   static void GetThreeVectorForm(const RSMatrix *spMat,
                                 IntegerArray &rowIdxVec,
                                 IntegerArray &colIdxVec,
                                 Rvector &valueVec);

   /// set the data of a part of the sparse matrix
   static void GetThreeVectorForm(const RSMatrix *spMat,
                                 Integer rowIdxLB, Integer rowIdxUB,
                                 Integer colIdxLB, Integer colIdxUB,
                                 IntegerArray &rowIdxVec,
                                 IntegerArray &colIdxVec,
                                 std::vector<Real> &valueVec);

   /// set the data of a part of the sparse matrix
   static void GetThreeVectorForm(const RSMatrix *spMat,
                                 Integer rowIdxLB, Integer rowIdxUB,
                                 Integer colIdxLB, Integer colIdxUB,
                                 IntegerArray &rowIdxVec,
                                 IntegerArray &colIdxVec,
                                 Rvector &valueVec);

   /// get the number of non zero elements of the sparse matrix
   static Integer GetNumNonZeroElements(const RSMatrix *spMat);

   /// Get sum(abs(element)) throughout a sparse matrix.
   /// useful especially when calculating errors
   static Real GetAbsTotalSum(const RSMatrix *spMat);

   // various utilities

   /// perform product between sparse matrix and dense vector
   /// B = A*V (initialize = true); where A and B are sparse matrices, and
   /// V is a dense vector
   /// B += A*V (initialize = false); where A and B are sparse matrices, and
   /// V is a dense vector
   static void fast_prod(const RSMatrix *spMat,
                         const std::vector<Real> *vec,
                         std::vector<Real> &result, bool initialize = true);

   /// perform product between sparse matrix and dense vector
   /// B = A*V (initialize = true); where A and B are sparse matrices, and
   /// V is a dense vector
   /// B += A*V (initialize = false); where A and B are sparse matrices, and
   /// V is a dense vector
   static void fast_prod(const RSMatrix *spMat,
                         const Rvector  *vec,
                         Rvector &result, bool initialize = true);

   /// perform C = A*B (initialize = true);
   /// or C+= A*B (initialize = false) using axpy_prod of
   /// SparseMatrixUtil::ublas
   static void fast_prod(const RSMatrix *spMat1,
                         const RSMatrix *spMat2,
                         RSMatrix &resultMat,
                         bool initialize = true);

   /// print all the nonzero elements to the screen
   static void PrintNonZeroElements(const RSMatrix *spMat,
                                    bool rowOrder = true);

   /// replicate sparse block matrix pattern with row and column repetition and
   /// return spMat
   static void ReplicateSparseMatrix(const RSMatrix *spBlockMat,
                                    Integer numRowRepetition,
                                    Integer numColRepetition,
                                    RSMatrix &spMat);

   /// check whether the given matrix is zero matrix or not
   static bool IsZeroMatrix(const RSMatrix *spMat);

   // convert RSMatrix to Rmatrix
   static Rmatrix RSMatrixToRmatrix(const RSMatrix *spMat,
                                    Integer rowLB, Integer rowUB,
                                    Integer colLB, Integer colUB);

   // convert RSMatrix to Rmatrix
   static Rmatrix RSMatrixToRmatrix(const RSMatrix *spMat);

   /// copy the data of the input matrix into output matrix
   static RSMatrix CopySparseMatrix(const RSMatrix *spMat);

   /// copy the data of the input matrix into output matrix
   static void CopySparseMatrix(const RSMatrix &copyFrom, RSMatrix &copyTo);

private:
   /// private constructors, destructor, operator=   *** UNIMPLEMENTED ***
   SparseMatrixUtil();
   SparseMatrixUtil(const SparseMatrixUtil &copy);
   SparseMatrixUtil& operator=(const SparseMatrixUtil &copy);
   ~SparseMatrixUtil();
};

#endif // SparseMatrixUtil_hpp


text:
#include <cctbx/boost_python/flex_fwd.h>

#include <boost/python.hpp>
#include <boost/python/class.hpp>
#include <boost/python/args.hpp>
#include <boost/python/return_value_policy.hpp>
#include <boost/python/copy_const_reference.hpp>
#include <cctbx/geometry_restraints/nonbonded_sorted.h>

namespace cctbx { namespace geometry_restraints {
namespace {

  struct nonbonded_sorted_asu_proxies_base_wrappers : boost::python::pickle_suite
  {
    typedef nonbonded_sorted_asu_proxies_base w_t;

    static boost::python::tuple
      getstate(w_t const& self)
    {
      return boost::python::make_tuple(
        self.asu_mappings(),
        self.simple,
        self.asu
        );
    }

    static void
      setstate(w_t& self, boost::python::tuple state)
    {
      self.asu_mappings_owner_ = boost::python::extract< boost::shared_ptr<direct_space_asu::asu_mappings<> > >(state[0]);
      self.simple = boost::python::extract< af::shared<nonbonded_simple_proxy> >(state[1]);
      self.asu = boost::python::extract< af::shared<nonbonded_asu_proxy> >(state[2]);
      self.asu_mappings_ = self.asu_mappings_owner_.get();
    }

    static void
    wrap()
    {
      using namespace boost::python;
      typedef return_value_policy<copy_const_reference> ccr;
      class_<w_t>("nonbonded_sorted_asu_proxies_base", no_init)
        .def(init<
          boost::shared_ptr<asu_mappings> const&>(
            (arg("asu_mappings"))))
        .def("asu_mappings", &w_t::asu_mappings, ccr())
        .def("process",
          (void(w_t::*)(nonbonded_simple_proxy const&)) &w_t::process,
            (arg("proxy")))
        .def("process",
          (void(w_t::*)(af::const_ref<nonbonded_simple_proxy> const&))
            &w_t::process,
          (arg("proxies")))
        .def("process",
          (void(w_t::*)(nonbonded_asu_proxy const&, bool)) &w_t::process,
            (arg("proxy"), arg("sym_excl_flag")=false))
        .def("process",
          (void(w_t::*)(af::const_ref<nonbonded_asu_proxy> const&))
            &w_t::process,
          (arg("proxies")))
        .def("n_total", &w_t::n_total)
        .def_readonly("simple", &w_t::simple)
        .def_readonly("asu", &w_t::asu)
        .def_pickle(nonbonded_sorted_asu_proxies_base_wrappers())
        ;
    }
  };

  struct nonbonded_sorted_asu_proxies_wrappers : boost::python::pickle_suite
  {
    typedef nonbonded_sorted_asu_proxies w_t;

    static boost::python::tuple
      getinitargs(w_t const& self)
    {
        return boost::python::make_tuple(self.asu_mappings());
    }

    static void
    wrap()
    {
      using namespace boost::python;
      class_<w_t, bases<nonbonded_sorted_asu_proxies_base> >(
        "nonbonded_sorted_asu_proxies", no_init)
        .def(init<
          boost::shared_ptr<asu_mappings> const&>(
            (arg("asu_mappings"))))
        .def(init<
          af::const_ref<std::size_t> const&,
          af::const_ref<std::size_t> const&,
          af::const_ref<std::size_t> const&,
          af::const_ref<std::size_t> const&,
          nonbonded_params const&,
          af::const_ref<std::string> const&,
          af::const_ref<int> const&,
          double,
          double,
          std::vector<crystal::pair_asu_table<> > const&>((
            arg("model_indices"),
            arg("conformer_indices"),
            arg("sym_excl_indices"),
            arg("donor_acceptor_excl_groups"),
            arg("nonbonded_params"),
            arg("nonbonded_types"),
            arg("nonbonded_charges"),
            arg("nonbonded_distance_cutoff_plus_buffer"),
            arg("min_cubicle_edge"),
            arg("shell_asu_tables"))))
        .def_readonly("n_unknown_nonbonded_type_pairs",
          &w_t::n_unknown_nonbonded_type_pairs)
        .def_readonly("min_vdw_distance", &w_t::min_vdw_distance)
        .def_readonly("max_vdw_distance", &w_t::max_vdw_distance)
        .def_pickle(nonbonded_sorted_asu_proxies_wrappers())
        ;
    }
  };

  void
  wrap_all()
  {
    nonbonded_sorted_asu_proxies_base_wrappers::wrap();
    nonbonded_sorted_asu_proxies_wrappers::wrap();
  }

} // namespace <anonymous>

namespace boost_python {

  void
  wrap_nonbonded_sorted() { wrap_all(); }

}}} // namespace cctbx::geometry_restraints::boost_python


text:
/* Author: Wolfgang Bangerth, University of Heidelberg, 1999 */

/*    $Id: step-2.cc 27657 2012-11-21 13:19:08Z bangerth $       */
/*                                                                */
/*    Copyright (C) 1999-2003, 2006, 2008-2012 by the deal.II authors */
/*                                                                */
/*    This file is subject to QPL and may not be  distributed     */
/*    without copyright and license information. Please refer     */
/*    to the file deal.II/doc/license.html for the  text  and     */
/*    further information on this license.                        */

// The first few includes are just like in the previous program, so do not
// require additional comments:
#include <deal.II/grid/tria.h>
#include <deal.II/grid/tria_accessor.h>
#include <deal.II/grid/tria_iterator.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/tria_boundary_lib.h>

// However, the next file is new. We need this include file for the
// association of degrees of freedom ("DoF"s) to vertices, lines, and cells:
#include <deal.II/dofs/dof_handler.h>

// The following include contains the description of the bilinear finite
// element, including the facts that it has one degree of freedom on each
// vertex of the triangulation, but none on faces and none in the interior of
// the cells.
//
// (In fact, the file contains the description of Lagrange elements in
// general, i.e. also the quadratic, cubic, etc versions, and not only for 2d
// but also 1d and 3d.)
#include <deal.II/fe/fe_q.h>
// In the following file, several tools for manipulating degrees of freedom
// can be found:
#include <deal.II/dofs/dof_tools.h>
// We will use a sparse matrix to visualize the pattern of nonzero entries
// resulting from the distribution of degrees of freedom on the grid. That
// class can be found here:
#include <deal.II/lac/sparse_matrix.h>
// We will also need to use an intermediate sparsity patter structure, which
// is found in this file:
#include <deal.II/lac/compressed_sparsity_pattern.h>

// We will want to use a special algorithm to renumber degrees of freedom. It
// is declared here:
#include <deal.II/dofs/dof_renumbering.h>

// And this is again needed for C++ output:
#include <fstream>

// Finally, as in step-1, we import the deal.II namespace into the global
// scope:
using namespace dealii;

// @sect3{Mesh generation}

// This is the function that produced the circular grid in the previous step-1
// example program. The sole difference is that it returns the grid it
// produces via its argument.
//
// The details of what the function does are explained in step-1. The only
// thing we would like to comment on is this:
//
// Since we want to export the triangulation through this function's
// parameter, we need to make sure that the boundary object lives at least as
// long as the triangulation does. However, in step-1, the boundary object is
// a local variable, and it would be deleted at the end of the function, which
// is too early. We avoid the problem by declaring it 'static' which makes
// sure that the object is initialized the first time control the program
// passes this point, but at the same time assures that it lives until the end
// of the program.
void make_grid (Triangulation<2> &triangulation)
{
  const Point<2> center (1,0);
  const double inner_radius = 0.5,
               outer_radius = 1.0;
  GridGenerator::hyper_shell (triangulation,
                              center, inner_radius, outer_radius,
                              10);

  static const HyperShellBoundary<2> boundary_description(center);
  triangulation.set_boundary (0, boundary_description);

  for (unsigned int step=0; step<5; ++step)
    {
      Triangulation<2>::active_cell_iterator
      cell = triangulation.begin_active(),
      endc = triangulation.end();

      for (; cell!=endc; ++cell)
        for (unsigned int v=0;
             v < GeometryInfo<2>::vertices_per_cell;
             ++v)
          {
            const double distance_from_center
              = center.distance (cell->vertex(v));

            if (std::fabs(distance_from_center - inner_radius) < 1e-10)
              {
                cell->set_refine_flag ();
                break;
              }
          }

      triangulation.execute_coarsening_and_refinement ();
    }
}

// @sect3{Creation of a DoFHandler}

// Up to now, we only have a grid, i.e. some geometrical (the position of the
// vertices) and some topological information (how vertices are connected to
// lines, and lines to cells, as well as which cells neighbor which other
// cells). To use numerical algorithms, one needs some logic information in
// addition to that: we would like to associate degree of freedom numbers to
// each vertex (or line, or cell, in case we were using higher order elements)
// to later generate matrices and vectors which describe a finite element
// field on the triangulation.
//
// This function shows how to do this. The object to consider is the
// DoFHandler class template.  Before we do so, however, we first
// need something that describes how many degrees of freedom are to be
// associated to each of these objects. Since this is one aspect of the
// definition of a finite element space, the finite element base class stores
// this information. In the present context, we therefore create an object of
// the derived class FE_Q that describes Lagrange elements. Its
// constructor takes one argument that states the polynomial degree of the
// element, which here is one (indicating a bi-linear element); this then
// corresponds to one degree of freedom for each vertex, while there are none
// on lines and inside the quadrilateral. A value of, say, three given to the
// constructor would instead give us a bi-cubic element with one degree of
// freedom per vertex, two per line, and four inside the cell. In general,
// FE_Q denotes the family of continuous elements with complete
// polynomials (i.e. tensor-product polynomials) up to the specified order.
//
// We first need to create an object of this class and then pass it on to the
// DoFHandler object to allocate storage for the degrees of
// freedom (in deal.II lingo: we distribute degrees of
// freedom). Note that the DoFHandler object will store a reference to
// this finite element object, so we have to make sure its lifetime is at
// least as long as that of the DoFHandler; one way to make sure
// this is so is to make it static as well, in order to prevent its preemptive
// destruction. (However, the library would warn us if we forgot about this
// and abort the program if that occured. You can check this, if you want, by
// removing the 'static' declaration.)
void distribute_dofs (DoFHandler<2> &dof_handler)
{
  // As described above, let us first create a finite element object, and then
  // use it to allocate degrees of freedom on the triangulation with which the
  // dof_handler object is associated:
  static const FE_Q<2> finite_element(1);
  dof_handler.distribute_dofs (finite_element);

  // Now that we have associated a degree of freedom with a global number to
  // each vertex, we wonder how to visualize this?  There is no simple way to
  // directly visualize the DoF number associated with each vertex. However,
  // such information would hardly ever be truly important, since the
  // numbering itself is more or less arbitrary. There are more important
  // factors, of which we will demonstrate one in the following.
  //
  // Associated with each vertex of the triangulation is a shape
  // function. Assume we want to solve something like Laplace's equation, then
  // the different matrix entries will be the integrals over the gradient of
  // each pair of such shape functions. Obviously, since the shape functions
  // are nonzero only on the cells adjacent to the vertex they are associated
  // with, matrix entries will be nonzero only if the supports of the shape
  // functions associated to that column and row %numbers intersect. This is
  // only the case for adjacent shape functions, and therefore only for
  // adjacent vertices. Now, since the vertices are numbered more or less
  // randomly by the above function (DoFHandler::distribute_dofs), the pattern
  // of nonzero entries in the matrix will be somewhat ragged, and we will
  // take a look at it now.
  //
  // First we have to create a structure which we use to store the places of
  // nonzero elements. This can then later be used by one or more sparse
  // matrix objects that store the values of the entries in the locations
  // stored by this sparsity pattern. The class that stores the locations is
  // the SparsityPattern class. As it turns out, however, this class has some
  // drawbacks when we try to fill it right away: its data structures are set
  // up in such a way that we need to have an estimate for the maximal number
  // of entries we may wish to have in each row. In two space dimensions,
  // reasonable values for this estimate are available through the
  // DoFHandler::max_couplings_between_dofs() function, but in three
  // dimensions the function almost always severely overestimates the true
  // number, leading to a lot of wasted memory, sometimes too much for the
  // machine used, even if the unused memory can be released immediately after
  // computing the sparsity pattern. In order to avoid this, we use an
  // intermediate object of type CompressedSparsityPattern that uses a
  // different %internal data structure and that we can later copy into the
  // SparsityPattern object without much overhead. (Some more information on
  // these data structures can be found in the @ref Sparsity module.) In order
  // to initialize this intermediate data structure, we have to give it the
  // size of the matrix, which in our case will be square with as many rows
  // and columns as there are degrees of freedom on the grid:
  CompressedSparsityPattern compressed_sparsity_pattern(dof_handler.n_dofs(),
                                                        dof_handler.n_dofs());

  // We then fill this object with the places where nonzero elements will be
  // located given the present numbering of degrees of freedom:
  DoFTools::make_sparsity_pattern (dof_handler, compressed_sparsity_pattern);

  // Now we are ready to create the actual sparsity pattern that we could
  // later use for our matrix. It will just contain the data already assembled
  // in the CompressedSparsityPattern.
  SparsityPattern sparsity_pattern;
  sparsity_pattern.copy_from (compressed_sparsity_pattern);

  // With this, we can now write the results to a file:
  std::ofstream out ("sparsity_pattern.1");
  sparsity_pattern.print_gnuplot (out);
  // The result is in GNUPLOT format, where in each line of the output file,
  // the coordinates of one nonzero entry are listed. The output will be shown
  // below.
  //
  // If you look at it, you will note that the sparsity pattern is
  // symmetric. This should not come as a surprise, since we have not given
  // the DoFTools::make_sparsity_pattern any information that
  // would indicate that our bilinear form may couple shape functions in a
  // non-symmetric way. You will also note that it has several distinct
  // region, which stem from the fact that the numbering starts from the
  // coarsest cells and moves on to the finer ones; since they are all
  // distributed symmetrically around the origin, this shows up again in the
  // sparsity pattern.
}

// @sect3{Renumbering of DoFs}

// In the sparsity pattern produced above, the nonzero entries extended quite
// far off from the diagonal. For some algorithms, for example for incomplete
// LU decompositions or Gauss-Seidel preconditioners, this is unfavorable, and
// we will show a simple way how to improve this situation.
//
// Remember that for an entry $(i,j)$ in the matrix to be nonzero, the
// supports of the shape functions i and j needed to intersect (otherwise in
// the integral, the integrand would be zero everywhere since either the one
// or the other shape function is zero at some point). However, the supports
// of shape functions intersected only if they were adjacent to each other, so
// in order to have the nonzero entries clustered around the diagonal (where
// $i$ equals $j$), we would like to have adjacent shape functions to be
// numbered with indices (DoF numbers) that differ not too much.
//
// This can be accomplished by a simple front marching algorithm, where one
// starts at a given vertex and gives it the index zero. Then, its neighbors
// are numbered successively, making their indices close to the original
// one. Then, their neighbors, if not yet numbered, are numbered, and so on.
//
// One algorithm that adds a little bit of sophistication along these lines is
// the one by Cuthill and McKee. We will use it in the following function to
// renumber the degrees of freedom such that the resulting sparsity pattern is
// more localized around the diagonal. The only interesting part of the
// function is the first call to DoFRenumbering::Cuthill_McKee,
// the rest is essentially as before:
void renumber_dofs (DoFHandler<2> &dof_handler)
{
  DoFRenumbering::Cuthill_McKee (dof_handler);

  CompressedSparsityPattern compressed_sparsity_pattern(dof_handler.n_dofs(),
                                                        dof_handler.n_dofs());
  DoFTools::make_sparsity_pattern (dof_handler, compressed_sparsity_pattern);

  SparsityPattern sparsity_pattern;
  sparsity_pattern.copy_from (compressed_sparsity_pattern);

  std::ofstream out ("sparsity_pattern.2");
  sparsity_pattern.print_gnuplot (out);
}

// Again, the output is shown below. Note that the nonzero entries are
// clustered far better around the diagonal than before. This effect is even
// more distinguished for larger matrices (the present one has 1260 rows and
// columns, but large matrices often have several 100,000s).

// It is worth noting that the DoFRenumbering class offers a
// number of other algorithms as well to renumber degrees of freedom. For
// example, it would of course be ideal if all couplings were in the lower or
// upper triangular part of a matrix, since then solving the linear system
// would among to only forward or backward substitution. This is of course
// unachievable for symmetric sparsity patterns, but in some special
// situations involving transport equations, this is possible by enumerating
// degrees of freedom from the inflow boundary along streamlines to the
// outflow boundary. Not surprisingly, DoFRenumbering also has
// algorithms for this.

// @sect3{The main function}

// Finally, this is the main program. The only thing it does is to allocate
// and create the triangulation, then create a DoFHandler object
// and associate it to the triangulation, and finally call above two functions
// on it:
int main ()
{
  Triangulation<2> triangulation;
  make_grid (triangulation);

  DoFHandler<2> dof_handler (triangulation);

  distribute_dofs (dof_handler);
  renumber_dofs (dof_handler);
}

ext: cc

max_stars_repo_name: wathen/PhD

max_issues_repo_name: wathen/PhD

max_forks_repo_name: wathen/PhD


text:
#include <memo/silo/Mirror.hh>

#include <boost/algorithm/string.hpp>

#include <elle/factory.hh>
#include <elle/from-string.hh>
#include <elle/reactor/Scope.hh>

#include <memo/model/Address.hh>

ELLE_LOG_COMPONENT("memo.silo.Mirror");

namespace memo
{
  namespace silo
  {
    Mirror::Mirror(std::vector<std::unique_ptr<Silo>> backend,
                   bool balance_reads, bool parallel)
      : _balance_reads(balance_reads)
      , _backend(std::move(backend))
      , _read_counter(0)
      , _parallel(parallel)
    {}

    elle::Buffer
    Mirror::_get(Key k) const
    {
      const_cast<Mirror*>(this)->_read_counter++;
      int target = _balance_reads? _read_counter % _backend.size() : 0;
      return _backend[target]->get(k);
    }

    int
    Mirror::_set(Key k, elle::Buffer const& value, bool insert, bool update)
    {
      if (_parallel)
        elle::With<elle::reactor::Scope>() << [&] (elle::reactor::Scope& s)
        {
          for (auto& e: _backend)
          {
            Silo* ptr = e.get();
            s.run_background("mirror set", [&,ptr] {
                ptr->set(k, value, insert, update);
              });
          }
          s.wait();
        };
      else
        for (auto& e: _backend)
          e->set(k, value, insert, update);
      return 0;
    }

    int
    Mirror::_erase(Key k)
    {
      if (_parallel)
      {
        elle::With<elle::reactor::Scope>() << [&] (elle::reactor::Scope& s)
        {
          for (auto& e: _backend)
          {
            Silo* ptr = e.get();
            s.run_background("mirror erase", [&,ptr] { ptr->erase(k);});
          }
          s.wait();
        };
      }
      else
      {
        for (auto& e: _backend)
        {
          e->erase(k);
        }
      }

      return 0;
    }

    std::vector<Key>
    Mirror::_list()
    {
      return _backend.front()->list();
    }

    namespace
    {
      std::unique_ptr<Silo>
      make(std::vector<std::string> const& args)
      {
        bool const balance_reads = elle::from_string<bool>(args[0]);
        bool const parallel = elle::from_string<bool>(args[1]);
        auto backends = std::vector<std::unique_ptr<Silo>>{};
        // FIXME: we don't check that i+1 is ok.
        for (int i = 2; i < signed(args.size()); i += 2)
          backends.emplace_back(instantiate(args[i], args[i+1]));
        return std::make_unique<Mirror>(std::move(backends), balance_reads, parallel);
      }
    }

    struct MirrorSiloConfig
      : public SiloConfig
    {
      bool parallel;
      bool balance;
      std::vector<std::unique_ptr<SiloConfig>> storage;

      MirrorSiloConfig(std::string name,
                          boost::optional<int64_t> capacity,
                          boost::optional<std::string> description)
        : SiloConfig(
            std::move(name), std::move(capacity), std::move(description))
      {}

      MirrorSiloConfig(elle::serialization::SerializerIn& s)
        : SiloConfig(s)
      {
        this->serialize(s);
      }

      void
      serialize(elle::serialization::Serializer& s) override
      {
        SiloConfig::serialize(s);
        s.serialize("parallel", this->parallel);
        s.serialize("balance", this->balance);
        s.serialize("backend", this->storage);
      }

      virtual
      std::unique_ptr<memo::silo::Silo>
      make() override
      {
        std::vector<std::unique_ptr<memo::silo::Silo>> s;
        for(auto const& c: storage)
        {
          ELLE_ASSERT(!!c);
          s.push_back(c->make());
        }
        return std::make_unique<memo::silo::Mirror>(
          std::move(s), balance, parallel);
      }
    };

    static const elle::serialization::Hierarchy<SiloConfig>::
    Register<MirrorSiloConfig>
    _register_MirrorSiloConfig("mirror");
  }
}

FACTORY_REGISTER(memo::silo::Silo, "mirror", &memo::silo::make);

max_stars_repo_name: infinit/memo

max_issues_repo_name: infinit/memo

max_forks_repo_name: infinit/memo


text:
#pragma once
#ifndef LVR2_IO_HDF5_ARRAYIO_HPP
#define LVR2_IO_HDF5_ARRAYIO_HPP

#include "lvr2/io/hdf5/HDF5FeatureBase.hpp"
#include <boost/shared_array.hpp>

namespace lvr2 {

namespace hdf5features {

template<typename Derived>
class ArrayIO {
public:

    template<typename T>
    boost::shared_array<T> loadArray(
        std::string groupName,
        std::string datasetName,
        size_t& size);

    template<typename T>
    boost::shared_array<T> load(
        std::string groupName,
        std::string datasetName,
        size_t& size);

    template<typename T>
    boost::shared_array<T> load(
        std::string groupName,
        std::string datasetName,
        std::vector<size_t>& dim);

    template<typename T>
    boost::shared_array<T> load(
        HighFive::Group& g,
        std::string datasetName,
        std::vector<size_t>& dim
    );

    template<typename T>
    void save(
        std::string groupName,
        std::string datasetName,
        size_t size,
        boost::shared_array<T> data);

    template<typename T>
    void save(
        std::string groupName,
        std::string datasetName,
        std::vector<size_t>& dimensions,
        boost::shared_array<T> data);

    template<typename T>
    void save(
        std::string groupName,
        std::string datasetName,
        std::vector<size_t>& dimensions,
        std::vector<hsize_t>& chunkSize,
        boost::shared_array<T> data);

    template<typename T>
    void save(HighFive::Group& g,
        std::string datasetName,
        std::vector<size_t>& dim,
        std::vector<hsize_t>& chunkSize,
        boost::shared_array<T>& data);

protected:
    Derived* m_file_access = static_cast<Derived*>(this);

};

} // namespace hdf5_features

} // namespace lvr2

#include "ArrayIO.tcc"

#endif

max_stars_repo_name: uos/lvr

max_issues_repo_name: uos/lvr

max_forks_repo_name: uos/lvr


text:
//
// Copyright (c) 2009 Rutger ter Borg
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef BOOST_NUMERIC_BINDINGS_DETAIL_ADAPTOR_HPP
#define BOOST_NUMERIC_BINDINGS_DETAIL_ADAPTOR_HPP

#include <boost/mpl/map.hpp>
#include <boost/numeric/bindings/detail/copy_const.hpp>
#include <boost/numeric/bindings/is_numeric.hpp>
#include <boost/numeric/bindings/tag.hpp>
#include <boost/type_traits/remove_const.hpp>
#include <boost/utility/enable_if.hpp>

namespace boost {
namespace numeric {
namespace bindings {
namespace detail {

template< typename T, typename Id, typename Enable = void >
struct adaptor {
    typedef mpl::map<
        mpl::pair< tag::value_type, void >
    > property_map;
};

template< typename T >
struct is_adaptable: is_numeric< typename mpl::at<
        typename adaptor< typename boost::remove_const<T>::type, T >::property_map,
        tag::value_type >::type > {};

template< typename T, typename Enable = void >
struct adaptor_access {};

template< typename T >
struct adaptor_access< T, typename boost::enable_if< is_adaptable<T> >::type >:
    adaptor< typename boost::remove_const<T>::type, T > {};

} // namespace detail
} // namespace bindings
} // namespace numeric
} // namespace boost

#include <boost/numeric/bindings/detail/pod.hpp>
#include <boost/numeric/bindings/detail/property_map.hpp>

#endif

max_stars_repo_name: ljktest/siconos

max_issues_repo_name: ljktest/siconos

max_forks_repo_name: ljktest/siconos


text:
/*

Copyright (c) 2005-2018, University of Oxford.
All rights reserved.

University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.

This file is part of Chaste.

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 University of Oxford nor the names of its
   contributors may be used to endorse or promote products derived from this
   software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef _STEADYSTATEEXTRAPOLATIONRUNNER_HPP_
#define _STEADYSTATEEXTRAPOLATIONRUNNER_HPP_

#ifdef CHASTE_CVODE

#include "AbstractSteadyStateRunner.hpp"
#include <boost/circular_buffer.hpp>
//#include "VectorHelperFunctions.hpp"

class SteadyStateExtrapolationRunner : public AbstractSteadyStateRunner
{

  /**
 * This class is to get a cell model to steady state by using extrapolation.
 *
 * We use the Mixed Root Mean Square (MRMS) error to measure how far from the steady state
 * we are. The PMCC of the MRMS errors is then used to check whether we can approxiamte the
 * decay of the state variables with an exponential. We then use simple linear regression
 * to find this exponential and extrapolate the variables.
 */

private:
  /* The number of points to use for our PMCC calculation and simple linear regression*/
  const unsigned int mBufferSize = 50;
  /*The maximum number of times we will attempt to extrapolate*/
  const unsigned int mMaxJumps = 100;
  /*The MRMS value for which we are close enough to the steady state that the absolute error in APD90 is probably less that 0.01ms*/
  const double mThreshold = 1.8e-07;
  /** Relative and absolute tolerances */
  const double TolRel = 1e-8;
  const double TolAbs = 1e-8;
  /** How far to extrapolate towards our approximation of the limit of the state variable. */
  double  mExtrapolationCoefficient = 0.9;
  /** The period and duration of the regular stimulus function */
  double  mPeriod;
  double  mDuration;
  /**The terminal state variables of the last pace we calculated*/
  std::vector<double> mStateVariables;
  /*The final state variables before the last extrapolation. This is used to reset in case an extrapolation causes an error*/
  std::vector<double> mSafeStateVariables;

  /** The stimulus used to pace the model - this must be a RegularStimulus */
  boost::shared_ptr<RegularStimulus> mpStimulus;

  /**Contains mBufferSize previous values of each state variable*/
  boost::circular_buffer<std::vector<double>>  mStatesBuffer;
  /**Contains mBufferSize previous values of each state vMRMS value*/
  boost::circular_buffer<double> mMrmsBuffer;

  /**Keeps track of the number of times we have extrapolated*/
  unsigned int mJumps = 0;

  /**Run the cell to steady state */
  virtual void RunToSteadyStateImplementation();

  /**
     * Calculate the MRMS error between two vectors
     *
     * @param A  The second vector
     * @param B  The first  vector
     */
  double CalculateMrms(std::vector<double> A, std::vector<double> B);

  /**
     * Calculate the PMCC of a circular_buffer of variables. This is used to calculate the PMCC of the previous MRMS values.
     *
     * @param values The values that we are calculating the PMCC of.
     */

  double CalculatePMCC(boost::circular_buffer<double> values){
    if(values.size()<=2 || values.size() <= 2){
      return -NAN;
    }

    const unsigned int N = values.size();
    const double sum_x = N*(N-1)/2;
    const double sum_x2 = (N-1)*N*(2*N-1)/6;

  double  sum_y = 0, sum_y2 = 0, sum_xy = 0;

  for(unsigned int i = 0; i < N; i++){
    sum_y += values[i];
    sum_y2+= values[i]*values[i];
    sum_xy+= i*values[i];
  }
  double pmcc = (N*sum_xy - sum_x*sum_y)/sqrt((N*sum_x2 - sum_x*sum_x)*(N*sum_y2 - sum_y*sum_y));
  return pmcc;
  }

    /**
     * Calculate the PMCC of a circular_buffer of (x,y) pairs. This is used to calculate the PMCC of the previous MRMS values.
     *
     * @param x The x values of the (x,y) pairs
     *
     * @param y The y values of the (x,y) pairs
 */

  double CalculatePMCC(std::vector<double> x, std::vector<double> y){
    const unsigned int N = x.size();
    if(x.size() <= 2){
      /*We don't have enough values*/
      return -NAN;
    }
    double sum_x = 0, sum_x2 = 0, sum_y = 0, sum_y2 = 0, sum_xy = 0;

    /*Calculate the required sums */
    for(unsigned int i = 0; i < N; i++){
      sum_x  += x[i];
      sum_x2 += x[i]*x[i];
      sum_y  += y[i];
      sum_y2 += y[i]*y[i];
      sum_xy += x[i]*y[i];
    }
    /*Return the PMCC*/
    return (N*sum_xy - sum_x*sum_y)/sqrt((N*sum_x2 - sum_x*sum_x)*(N*sum_y2 - sum_y*sum_y));
  }

  /**
   * Applies the extrapolation method to one state variable if it is sensible to do so. Returns
   * true if the state variable has been extrapolated.
   *
   * @state_index The index of the state variable that we wish to extrapolate
   */
  bool ExtrapolateState(unsigned int state_index);

   /**
   * Applies the extrapolation method to every state variable
   *
   * @state_index The index of the state variable that we wish to extrapolate
   */
  bool ExtrapolateStates();

  /**
   * Simulates one pace and extrapolates the state variables if the PMCC
   * of the previous MRMS values is approximately -1
   */
  bool RunPace();

public:
/**
     * Constructor of a helper class for getting action potential models to steady state.
     *
     * @param pModel  The cell model to run to steady state.
     * @param period  The period for the model to be paced at.
     */

  SteadyStateExtrapolationRunner(boost::shared_ptr<AbstractCvodeCell> pModel, double period)
    : AbstractSteadyStateRunner(pModel), mPeriod(period){
    /*This ensures that we are using a regular stimulus*/
    mpStimulus = mpModel->UseCellMLDefaultStimulus();
    mpStimulus->SetPeriod(mPeriod);
    mDuration = mpStimulus->GetDuration();

    /* Set Solver Tolerances */
    mpModel->SetTolerances(TolRel, TolAbs);

    /* Set the maximum number of timesteps for CVODE to use. This prevents
     * CV_TOO_MUCH_WORK errors */
    mpModel->SetMaxSteps(1e5);

    /* Initialise mStateVariables */
    mStateVariables = mpModel->GetStdVecStateVariables();

    /* Set the capacity of the circular buffers */
    mMrmsBuffer.set_capacity(mBufferSize);
    mStatesBuffer.set_capacity(mBufferSize);
  };

};

#endif // CHASTE_CVODE

#endif // _STEADYSTATEEXTRAPOLATIONRUNNER_HPP_

max_stars_repo_name: joeyshuttleworth/Chaste

max_issues_repo_name: joeyshuttleworth/Chaste

max_forks_repo_name: joeyshuttleworth/Chaste


text:
/////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga  2007-2012
//
// 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)
//
// See http://www.boost.org/libs/intrusive for documentation.
//
/////////////////////////////////////////////////////////////////////////////
//[doc_bucket_traits
#include <boost/intrusive/unordered_set.hpp>
#include <boost/functional/hash.hpp>
#include <vector>

using namespace boost::intrusive;

//A class to be inserted in an unordered_set
class MyClass : public unordered_set_base_hook<>
{
   int int_;

   public:
   MyClass(int i = 0) : int_(i)
   {}

   friend bool operator==(const MyClass &l, const MyClass &r)
      {  return l.int_ == r.int_;   }
   friend std::size_t hash_value(const MyClass &v)
      {  return boost::hash_value(v.int_); }
};

//Define the base hook option
typedef base_hook< unordered_set_base_hook<> >     BaseHookOption;

//Obtain the types of the bucket and the bucket pointer
typedef unordered_bucket<BaseHookOption>::type     BucketType;
typedef unordered_bucket_ptr<BaseHookOption>::type BucketPtr;

//The custom bucket traits.
class custom_bucket_traits
{
   public:
   static const int NumBuckets = 100;

   custom_bucket_traits(BucketPtr buckets)
      :  buckets_(buckets)
   {}

   //Functions to be implemented by custom bucket traits
   BucketPtr   bucket_begin() const {  return buckets_;  }
   std::size_t bucket_count() const {  return NumBuckets;}

   private:
   BucketPtr buckets_;
};

//Define the container using the custom bucket traits
typedef unordered_set<MyClass, bucket_traits<custom_bucket_traits> > BucketTraitsUset;

int main()
{
   typedef std::vector<MyClass>::iterator VectIt;
   std::vector<MyClass> values;

   //Fill values
   for(int i = 0; i < 100; ++i)  values.push_back(MyClass(i));

   //Now create the bucket array and the custom bucket traits object
   BucketType buckets[custom_bucket_traits::NumBuckets];
   custom_bucket_traits btraits(buckets);

   //Now create the unordered set
   BucketTraitsUset uset(btraits);

   //Insert the values in the unordered set
   for(VectIt it(values.begin()), itend(values.end()); it != itend; ++it)
      uset.insert(*it);

   return 0;
}
//]

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
/*<-
Copyright (c) 2016 Barrett Adair

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

#include <boost/callable_traits/detail/config.hpp>

#ifndef BOOST_CLBL_TRTS_ENABLE_NOEXCEPT_TYPES
int main(){}
#else

#include <boost/callable_traits/add_noexcept.hpp>
#include "test.hpp"

template<typename Noexcept, typename NotNoexcept>
void test() {

    CT_ASSERT(std::is_same<Noexcept,  TRAIT(add_noexcept, NotNoexcept)>::value);

    //sanity check
    CT_ASSERT(!std::is_same<Noexcept, NotNoexcept>::value);
}

#define TEST_NOEXCEPT(not_noexcept) test<not_noexcept noexcept, not_noexcept>()

int main() {

    TEST_NOEXCEPT(int(int) &);
    TEST_NOEXCEPT(int(*)(int));
    TEST_NOEXCEPT(int(int, ...) &&);
    TEST_NOEXCEPT(int(*)(int, ...));

    struct foo;

    TEST_NOEXCEPT(int(foo::*)(int));
    TEST_NOEXCEPT(int(foo::*)(int) const);
    TEST_NOEXCEPT(int(foo::*)(int, ...));
    TEST_NOEXCEPT(int(foo::*)(int, ...) volatile);
}

#endif // #ifndef BOOST_CLBL_TRTS_ENABLE_NOEXCEPT_TYPES


text:
// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Stefan Girke

#ifndef DUNE_STUFF_COMMON_TUPLE_HH
#define DUNE_STUFF_COMMON_TUPLE_HH

#include <dune/common/tuples.hh>
#include <dune/common/typetraits.hh>

#include <boost/mpl/if.hpp>
#include <boost/mpl/deref.hpp>
#include <boost/mpl/begin.hpp>
#include <boost/mpl/end.hpp>
#include <boost/mpl/next.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/type_traits.hpp>

#define TMAX(t_, no_) (Dune::tuple_size<t_>::value >= (no_ + 1) ? no_ : 0)
#define TELE(t_, s_, no_) typename Dune::tuple_element<TMAX(t_, no_), t_>::type::s_

template <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, size_t Size>
struct RightTrimTuple
{
  typedef Dune::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9> type;
};

template <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9>
struct RightTrimTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, 9>
{
  typedef Dune::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9> type;
};

template <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9>
struct RightTrimTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, 8>
{
  typedef Dune::tuple<T1, T2, T3, T4, T5, T6, T7, T8> type;
};

template <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9>
struct RightTrimTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, 7>
{
  typedef Dune::tuple<T1, T2, T3, T4, T5, T6, T7> type;
};

template <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9>
struct RightTrimTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, 6>
{
  typedef Dune::tuple<T1, T2, T3, T4, T5, T6> type;
};

template <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9>
struct RightTrimTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, 5>
{
  typedef Dune::tuple<T1, T2, T3, T4, T5> type;
};

template <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9>
struct RightTrimTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, 4>
{
  typedef Dune::tuple<T1, T2, T3, T4> type;
};

template <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9>
struct RightTrimTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, 3>
{
  typedef Dune::tuple<T1, T2, T3> type;
};

template <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9>
struct RightTrimTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, 2>
{
  typedef Dune::tuple<T1, T2> type;
};

template <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9>
struct RightTrimTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, 1>
{
  typedef Dune::tuple<T1> type;
};

#define TUPLE_TYPEDEFS_2_TUPLE(t_, s_)                                                                                \
  typename RightTrimTuple<TELE(t_, s_, 0),                                                                             \
                          TELE(t_, s_, 1),                                                                             \
                          TELE(t_, s_, 2),                                                                             \
                          TELE(t_, s_, 3),                                                                             \
                          TELE(t_, s_, 4),                                                                             \
                          TELE(t_, s_, 5),                                                                             \
                          TELE(t_, s_, 6),                                                                             \
                          TELE(t_, s_, 7),                                                                             \
                          TELE(t_, s_, 8),                                                                             \
                          Dune::tuple_size<t_>::value>::type

/**
 * @def TUPLE_TYPEDEFS_2_TUPLE( t_, s_ )
 *
 * @brief extracts types of the elements of a Dune::tuple and
 * creates a new Dune::tuple with these extracted types.
 *
 * first argument: the tuple type
 * second argument: the typedef of the elements of the tuple
 *
 * example:
 * Let two classes be given:
 *
 * @code
 * class A
 * {
 *   public:
 *   typedef int MyFancyType;
 * };
 *
 * class B
 * {
 *   public:
 *   typedef int MyFancyType;
 * };
 * @endcode
 *
 * Define a tuple, i.e.
 *
 * @code
 * typedef Dune::tuple< A, B, B >
 *   MyTuple;
 * @endcode
 *
 * Instead of writing
 *
 * @code
 * typedef Dune::tuple< typename tuple_element<0,MyTuple>::type::MyFancyType,
 *                      typename tuple_element<1,MyTuple>::type::MyFancyType,
 *                      typename tuple_element<2,MyTuple>::type::MyFancyType >
 *   MySubTupleType;
 * @endcode
 *
 * just write
 *
 * @code
 * typedef TUPLE_TYPEDEFS_2_TUPLE( MyTuple, MyFancyType )
 *   MySubTupleType;
 * @endcode
 *
 * without (general) restriction to the size
 * of the tuple @c MyTuple. Enjoy it!
 */

namespace Dune {
namespace Stuff {
namespace Common {

//! split our function wrapper into sep pointers for Datawriter input
template <class T1, class T2 = T1, class T3 = T2, class T4 = T3>
struct TupleSerializer
{
  typedef Dune::
      tuple<const typename T1::DiscreteVelocityFunctionType*, const typename T1::DiscretePressureFunctionType*,
            const typename T2::DiscreteVelocityFunctionType*, const typename T2::DiscretePressureFunctionType*,
            const typename T3::DiscreteVelocityFunctionType*, const typename T3::DiscretePressureFunctionType*,
            const typename T4::DiscreteVelocityFunctionType*, const typename T4::DiscretePressureFunctionType*>
          TupleType;

  static TupleType& getTuple(T1& t1, T2& t2, T3& t3, T4& t4)
  {
    // yay for dangling pointers, but using a local static here fubared sequential runs with diff grid
    TupleType* t = new TupleType(&(t1.discreteVelocity()),
                                 &(t1.discretePressure()),
                                 &(t2.discreteVelocity()),
                                 &(t2.discretePressure()),
                                 &(t3.discreteVelocity()),
                                 &(t3.discretePressure()),
                                 &(t4.discreteVelocity()),
                                 &(t4.discretePressure()));

    return *t;
  } // getTuple

  static TupleType& getTuple(T1& t1, T2& t2, T3& t3)
  {
    // yay for dangling pointers, but using a local static here fubared sequential runs with diff grid
    TupleType* t = new TupleType(&(t1.discreteVelocity()),
                                 &(t1.discretePressure()),
                                 &(t2.discreteVelocity()),
                                 &(t2.discretePressure()),
                                 &(t3.discreteVelocity()),
                                 &(t3.discretePressure()),
                                 nullptr,
                                 nullptr);

    return *t;
  } // getTuple

  static TupleType& getTuple(T1& t1, T2& t2)
  {
    // yay for dangling pointers, but using a local static here fubared sequential runs with diff grid
    TupleType* t = new TupleType(&(t1.discreteVelocity()),
                                 &(t1.discretePressure()),
                                 &(t2.discreteVelocity()),
                                 &(t2.discretePressure()),
                                 nullptr,
                                 nullptr,
                                 nullptr,
                                 nullptr);

    return *t;
  } // getTuple

  static TupleType& getTuple(T1& t1)
  {
    // yay for dangling pointers, but using a local static here fubared sequential runs with diff grid
    TupleType* t = new TupleType(
        &(t1.discreteVelocity()), &(t1.discretePressure()), nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);

    return *t;
  } // getTuple
};

template <class T1, class T2 = T1, class T3 = T1, class T4 = T1, class T5 = T1, class T6 = T1, class T7 = T1,
          class T8 = T1, class T9 = T1>
struct FullTuple : public Dune::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9>
{
  FullTuple(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9)
    : Dune::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9>(t1, t2, t3, t4, t5, t6, t7, t8, t9)
  {
  }
};

// reduced from
// http://stackoverflow.com/questions/1492204/is-it-possible-to-generate-types-with-all-combinations-of-template-arguments
namespace TupleProduct {
using boost::is_same;
using boost::mpl::begin;
using boost::mpl::end;
using boost::mpl::next;
using boost::mpl::if_;
using boost::mpl::deref;

size_t total_recursions = 0;

struct end_of_recursion_tag
{
  template <class... Args>
  static void Run(Args&&... /*args*/)
  {
    std::cout << "end of " << total_recursions << " recursions\n";
  }
};

template <class UTypes,  // Forward Sequence, e.g. boost::mpl::vector
          class VTypes,  // Forward Sequence, e.g. boost::mpl::vector
          class TestFunc // class type that has a nested templated run() member function
          >
struct Combine
{
  // forward declaration
  template <class UIterator, class VIterator>
  struct Generate;

  // this class implements recursion body
  template <class UIterator, class VIterator>
  struct Next
  {
    // u_begin is not necessary ;)
    // it would be cheaper not to pre-declare all of them since we force evaluation
    // however this dramatically increase the readability
    typedef typename begin<VTypes>::type v_begin;

    typedef typename end<UTypes>::type u_end;
    typedef typename end<VTypes>::type v_end;

    typedef typename next<UIterator>::type u_next;
    typedef typename next<VIterator>::type v_next;

    typedef
        typename if_<boost::is_same<v_next, v_end>,
                     typename if_<boost::is_same<u_next, u_end>, end_of_recursion_tag, Generate<u_next, v_begin>>::type,
                     Generate<UIterator, v_next>>::type type;
  };

  //  this class run test on generated types in thos round and go to next*/
  template <class UIterator = typename begin<UTypes>::type, class VIterator = typename begin<VTypes>::type>
  struct Generate
  {
    //  generate <<next>> target type
    typedef typename Next<UIterator, VIterator>::type next_type;

    static void Run()
    {
      // increment recursion counter
      ++total_recursions;

      // test on the generated types of this round of recursion
      TestFunc::template run<typename deref<UIterator>::type, typename deref<VIterator>::type>();

      // go to the next round of recursion
      next_type::Run();
    }

    template <class... Args>
    static void Run(Args&&... args)
    {
      // increment recursion counter
      ++total_recursions;

      // test on the generated types of this round of recursion
      TestFunc::template run<typename deref<UIterator>::type, typename deref<VIterator>::type>(
          std::forward<Args>(args)...);

      // go to the next round of recursion
      next_type::Run(std::forward<Args>(args)...);
    }
  };
};

} // namespace TupleProduct

} // namespace Common
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_COMMON_TUPLE_HH

ext: hh

max_stars_repo_name: ftalbrecht/dune-stuff-simplified

max_issues_repo_name: ftalbrecht/dune-stuff-simplified

max_forks_repo_name: ftalbrecht/dune-stuff-simplified


text:
/**
 *  @file
 *  @copyright defined in eos/LICENSE.txt
 */
#include <eos/wallet_plugin/wallet_plugin.hpp>
#include <eos/wallet_plugin/wallet_manager.hpp>
#include <boost/filesystem/path.hpp>
#include <chrono>

namespace fc { class variant; }

namespace eosio {

wallet_plugin::wallet_plugin()
  : wallet_manager_ptr(new wallet_manager()) {
}

wallet_manager& wallet_plugin::get_wallet_manager() {
   return *wallet_manager_ptr;
}

void wallet_plugin::set_program_options(options_description& cli, options_description& cfg) {
   cli.add_options()
         ("wallet-dir", bpo::value<boost::filesystem::path>()->default_value("."),
          "The path of the wallet files (absolute path or relative to application data dir)")
         ("unlock-timeout", bpo::value<int64_t>(),
          "Timeout for unlocked wallet in seconds. "
                "Wallets will automatically lock after specified number of seconds of inactivity. "
                "Activity is defined as any wallet command e.g. list-wallets.")
         ;
}

void wallet_plugin::plugin_initialize(const variables_map& options) {
   ilog("initializing wallet plugin");

   if (options.count("wallet-dir")) {
      auto dir = options.at("wallet-dir").as<boost::filesystem::path>();
      if (dir.is_relative())
         wallet_manager_ptr->set_dir(app().data_dir() / dir);
      else
         wallet_manager_ptr->set_dir(dir);
   }
   if (options.count("unlock-timeout")) {
      auto timeout = options.at("unlock-timeout").as<int64_t>();
      std::chrono::seconds t(timeout);
      wallet_manager_ptr->set_timeout(t);
   }
}
} // namespace eos

max_stars_repo_name: cj-oci/eos

max_issues_repo_name: cj-oci/eos

max_forks_repo_name: cj-oci/eos


text:
#ifndef POSE_EDGE_HPP
#define POSE_EDGE_HPP

#include <Eigen/Geometry>
#include <opencv2/core/core.hpp>
#include <g2o/core/block_solver.h>
#include <g2o/types/slam3d/types_slam3d.h>
#include <g2o/core/optimization_algorithm_levenberg.h>
#include <g2o/solvers/dense/linear_solver_dense.h>
#include <g2o/types/sba/types_six_dof_expmap.h>
#include <g2o/core/robust_kernel.h>
#include <g2o/types/slam3d/se3quat.h>
#include <g2o/core/robust_kernel_impl.h>
#include <g2o/core/base_unary_edge.h>
#include "g2o/solvers/csparse/linear_solver_csparse.h"
#include <g2o/solvers/cholmod/linear_solver_cholmod.h>
#include <g2o/solvers/dense/linear_solver_dense.h>
#include "../helper.hpp"

class PoseEdge:public g2o::BaseUnaryEdge<1, Eigen::VectorXd, g2o::VertexSE3Expmap>
{
public:
  EIGEN_MAKE_ALIGNED_OPERATOR_NEW

  PoseEdge(const Eigen::Vector3d& point, const Eigen::Matrix3d& K, const cv::Mat& img)
  : start_point(point), fx(K(0,0)), fy(K(1,1)), cx(K(0,2)), cy(K(1,2)), dest_img(img)
  {}

  void computeError();

  void linearizeOplus();

    virtual bool read(std::istream& /*is*/)
    {
      std::cerr << __PRETTY_FUNCTION__ << " not implemented yet" << std::endl;
      return false;
    }

    virtual bool write(std::ostream& /*os*/) const
    {
      std::cerr << __PRETTY_FUNCTION__ << " not implemented yet" << std::endl;
      return false;
    }

private:

  Eigen::Vector3d start_point;
  double fx=0, fy=0, cx=0, cy=0;
  const cv::Mat& dest_img;
};

#endif

max_stars_repo_name: jiawei-mo/dsvo

max_issues_repo_name: jiawei-mo/dsvo

max_forks_repo_name: jiawei-mo/dsvo


text:
/*
 * GridTools
 *
 * Copyright (c) 2014-2019, ETH Zurich
 * All rights reserved.
 *
 * Please, refer to the LICENSE file in the root directory.
 * SPDX-License-Identifier: BSD-3-Clause
 */

#pragma once

#include <boost/mpl/fold.hpp>
#include <boost/mpl/push_back.hpp>
#include <boost/mpl/range_c.hpp>
#include <boost/mpl/vector_c.hpp>

#include "../meta/utility.hpp"
#include "generic_metafunctions/replace.hpp"
#include "generic_metafunctions/sequence_unpacker.hpp"
#include "layout_map.hpp"
#include "selector.hpp"

namespace gridtools {
    /** \ingroup common
        @{
        \ingroup layout
        @{
    */

    /** \brief Compute the reverse of a layout. For instance the reverse of
        `layout_map<1,0,-1,2>` is `layout<1,2,-1,0>`

        \tparam LayoutMap The layout map to process
    */
    template <typename LayoutMap>
    struct reverse_map;

    /// \private
    template <int_t... Is>
    struct reverse_map<layout_map<Is...>> {
        static constexpr int max = layout_map<Is...>::max();
        using type = layout_map<(Is < 0 ? Is : max - Is)...>;
    };

    template <typename DATALO, typename PROCLO>
    struct layout_transform;

    template <int_t I1, int_t I2, int_t P1, int_t P2>
    struct layout_transform<layout_map<I1, I2>, layout_map<P1, P2>> {
        typedef layout_map<I1, I2> L1;
        typedef layout_map<P1, P2> L2;

        static constexpr int_t N1 = L1::template at<P1>();
        static constexpr int_t N2 = L1::template at<P2>();

        typedef layout_map<N1, N2> type;
    };

    template <int_t I1, int_t I2, int_t I3, int_t P1, int_t P2, int_t P3>
    struct layout_transform<layout_map<I1, I2, I3>, layout_map<P1, P2, P3>> {
        typedef layout_map<I1, I2, I3> L1;
        typedef layout_map<P1, P2, P3> L2;

        static constexpr int_t N1 = L1::template at<P1>();
        static constexpr int_t N2 = L1::template at<P2>();
        static constexpr int_t N3 = L1::template at<P3>();

        typedef layout_map<N1, N2, N3> type;
    };

    /*
     * metafunction to filter out some of the dimensions of a layout map, determined by the DimSelector
     * Example of use: filter_layout<layout_map<0,1,2,3>, selector<1,1,0,1 > == layout_map<0,1,-1,2>
     */
    template <typename Layout, typename DimSelector>
    struct filter_layout;

    template <typename Layout, bool... Bitmask>
    struct filter_layout<Layout, selector<Bitmask...>> {
        typedef selector<Bitmask...> dim_selector_t;
        GT_STATIC_ASSERT((is_selector<dim_selector_t>::value), "Error: Dimension selector is wrong");
        typedef boost::mpl::vector_c<bool, Bitmask...> dim_selector_vec_t;
        GT_STATIC_ASSERT((is_layout_map<Layout>::value), "Error: need a layout map type");
        GT_STATIC_ASSERT(
            (sizeof...(Bitmask) >= Layout::masked_length), "Error: need to specifiy at least 4 dimensions");

        template <uint_t NumNullDims, typename Seq_>
        struct data_ {
            typedef Seq_ seq_t;
            static constexpr const uint_t num_null_dims = NumNullDims;
        };

        template <typename Data, typename Index>
        struct insert_index_at_pos {

            template <typename Data_, typename Position>
            struct insert_a_null {
                typedef data_<Data_::num_null_dims + 1,
                    typename replace<typename Data_::seq_t, Position, static_int<-1>>::type>
                    type;
            };

            template <typename Data_, typename Position>
            struct insert_a_pos_index {
                typedef data_<Data_::num_null_dims,
                    typename replace<typename Data_::seq_t,
                        Position,
                        static_int<Layout::template at<Position::value>() - Data_::num_null_dims>>::type>
                    type;
            };
            typedef static_int<Layout::template find<Index::value>()> position_t;
            typedef typename boost::mpl::if_c<(boost::mpl::at_c<dim_selector_vec_t, position_t::value>::type::value ==
                                                  false),
                typename insert_a_null<Data, position_t>::type,
                typename insert_a_pos_index<Data, position_t>::type>::type type;
        };

        typedef typename boost::mpl::fold<boost::mpl::range_c<int, 0, Layout::masked_length>,
            boost::mpl::vector0<>,
            boost::mpl::push_back<boost::mpl::_1, static_int<0>>>::type initial_vector;

        typedef data_<0, initial_vector> initial_data;
        typedef typename boost::mpl::fold<boost::mpl::range_c<int, 0, Layout::masked_length>,
            initial_data,
            insert_index_at_pos<boost::mpl::_1, boost::mpl::_2>>::type new_layout_indices_data_t;

        typedef typename new_layout_indices_data_t::seq_t new_layout_indices_t;

        template <typename T>
        struct indices_to_layout;

        template <typename... Args>
        struct indices_to_layout<variadic_typedef<Args...>> {
            using type = layout_map<Args::value...>;
        };

        typedef typename indices_to_layout<typename sequence_unpacker<new_layout_indices_t>::type>::type type;
    };

    namespace impl {
        template <int_t Val, int_t NExtraDim>
        struct inc_ {
            static const int_t value = Val == -1 ? -1 : Val + NExtraDim;
        };
    } // namespace impl

    enum class InsertLocation { pre, post };

    template <typename LayoutMap, uint_t NExtraDim, InsertLocation Location = InsertLocation::post>
    struct extend_layout_map;

    /*
     * metafunction to extend a layout_map with certain number of dimensions.
     * Example of use:
     * a) extend_layout_map< layout_map<0, 1, 3, 2>, 3> == layout_map<3, 4, 6, 5, 0, 1, 2>
     * b) extend_layout_map< layout_map<0, 1, 3, 2>, 3, InsertLocation::pre> == layout_map<0, 1, 2, 3, 4, 6, 5>
     */
    template <uint_t NExtraDim, int_t... Args, InsertLocation Location>
    struct extend_layout_map<layout_map<Args...>, NExtraDim, Location> {

        template <InsertLocation Loc, typename T, int_t... InitialInts>
        struct build_ext_layout;

        // build an extended layout
        template <int_t... Indices, int_t... InitialIndices>
        struct build_ext_layout<InsertLocation::post, meta::integer_sequence<int_t, Indices...>, InitialIndices...> {
            typedef layout_map<InitialIndices..., Indices...> type;
        };
        template <int_t... Indices, int_t... InitialIndices>
        struct build_ext_layout<InsertLocation::pre, meta::integer_sequence<int_t, Indices...>, InitialIndices...> {
            typedef layout_map<Indices..., InitialIndices...> type;
        };

        using seq = meta::make_integer_sequence<int_t, NExtraDim>;

        typedef typename build_ext_layout<Location, seq, impl::inc_<Args, NExtraDim>::value...>::type type;
    };

    template <int_t D>
    struct default_layout_map {
        using type = typename extend_layout_map<layout_map<>, D, InsertLocation::pre>::type;
    };

    template <int_t D>
    using default_layout_map_t = typename default_layout_map<D>::type;

    /** @} */
    /** @} */
} // namespace gridtools

max_stars_repo_name: mbianco/gridtools

max_issues_repo_name: mbianco/gridtools

max_forks_repo_name: mbianco/gridtools


text:
#include "arith_uint256.h"
#include "chainparams.h"
#include "lbry.h"
#include "main.h"
#include "test/test_bitcoin.h"
#include "hash.h"
#include <cstdio>
#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(lbry_tests, TestingSetup)

//1 test block 1 difficulty, should be a max retarget
BOOST_AUTO_TEST_CASE(get_block_1_difficulty)
{
    SelectParams(CBaseChainParams::MAIN);
    const Consensus::Params& params = Params().GetConsensus();

    CBlockIndex pindexLast;
    int64_t nFirstBlockTime = 1386475638;

    pindexLast.nHeight = 0;
    pindexLast.nTime = 1386475638;
    pindexLast.nBits = 0x1f00ffff ;//starting difficulty, also limit
    unsigned int out = CalculateLbryNextWorkRequired(&pindexLast, nFirstBlockTime, params);
    arith_uint256 a;
    a.SetCompact(out);
    unsigned int expected = 0x1f00e146;
    BOOST_CHECK_EQUAL(out,expected);

}

// test max retarget (difficulty increase)
BOOST_AUTO_TEST_CASE(max_retarget)
{
    SelectParams(CBaseChainParams::MAIN);
    const Consensus::Params& params = Params().GetConsensus();

    CBlockIndex pindexLast;
    int64_t nFirstBlockTime = 1386475638;

    pindexLast.nHeight = 100;
    pindexLast.nTime = nFirstBlockTime;
    pindexLast.nBits = 0x1f00a000 ;

    unsigned int out = CalculateLbryNextWorkRequired(&pindexLast, nFirstBlockTime, params);
    arith_uint256 a;
    a.SetCompact(out);
    unsigned int expected = 0x1f008ccc;
    BOOST_CHECK_EQUAL(out,expected);

}

// test min retarget (difficulty decrease)
BOOST_AUTO_TEST_CASE(min_retarget)
{
    SelectParams(CBaseChainParams::MAIN);
    const Consensus::Params& params = Params().GetConsensus();

    CBlockIndex pindexLast;
    int64_t nFirstBlockTime = 1386475638;

    pindexLast.nHeight = 101;
    pindexLast.nTime = nFirstBlockTime + 60*20 ;
    pindexLast.nBits = 0x1f00a000;

    unsigned int out = CalculateLbryNextWorkRequired(&pindexLast, nFirstBlockTime, params);
    arith_uint256 a;
    a.SetCompact(out);
    unsigned int expected = 0x1f00f000;
    BOOST_CHECK_EQUAL(out,expected);

}

// test to see if pow limit is not exceeded
BOOST_AUTO_TEST_CASE(pow_limit_check)
{
    SelectParams(CBaseChainParams::MAIN);
    const Consensus::Params& params = Params().GetConsensus();

    CBlockIndex pindexLast;
    int64_t nFirstBlockTime = 1386475638;

    pindexLast.nHeight = 102;
    pindexLast.nTime = nFirstBlockTime + 600 ; //took a long time to generate book, will try to reduce difficulty but it would hit limit
    pindexLast.nBits = 0x1f00ffff ;

    unsigned int out = CalculateLbryNextWorkRequired(&pindexLast, nFirstBlockTime, params);
    arith_uint256 a;
    a.SetCompact(out);
    unsigned int expected = 0x1f00ffff;
    BOOST_CHECK_EQUAL(out,expected);

}

boost::test_tools::predicate_result
check_powhash_equals(std::string test_string,std::string expected_hash_hex)
{
    std::vector<unsigned char> test_vect(test_string.begin(),test_string.end());
    uint256 expected;
    expected.SetHex(expected_hash_hex);
    uint256 hash = PoWHash(test_vect);

    //std::cout<<"hash :"<<hash.ToString()<<"\n";

    if (hash == expected){
        return true;
    }
    else
    {
        boost::test_tools::predicate_result res( false );
        res.message() << "Hash of " << test_string << " != " << expected_hash_hex;
        return res;
    }
}

BOOST_AUTO_TEST_CASE(lbry_pow_test)
{

    BOOST_CHECK(check_powhash_equals("test string","485f3920d48a0448034b0852d1489cfa475341176838c7d36896765221be35ce"));
    BOOST_CHECK(check_powhash_equals(std::string(70,'a'),"eb44af2f41e7c6522fb8be4773661be5baa430b8b2c3a670247e9ab060608b75"));
    BOOST_CHECK(check_powhash_equals(std::string(140,'d'),"74044747b7c1ff867eb09a84d026b02d8dc539fb6adcec3536f3dfa9266495d9"));

}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: frkl/lbrycrd

max_issues_repo_name: frkl/lbrycrd

max_forks_repo_name: frkl/lbrycrd


text:
#include "filenames.h"

#include <possumwood_sdk/app.h>

#include <QAction>
#include <QApplication>
#include <QFileDialog>
#include <QHBoxLayout>
#include <QMainWindow>
#include <QSizePolicy>
#include <QStyle>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/predicate.hpp>

filenames_ui::filenames_ui() {
	m_widget = new QWidget(NULL);

	QHBoxLayout* layout = new QHBoxLayout(m_widget);
	layout->setContentsMargins(0, 0, 0, 0);

	m_textEdit = new QTextEdit();

	QSizePolicy sp = m_textEdit->sizePolicy();
	sp.setVerticalPolicy(QSizePolicy::MinimumExpanding);
	m_textEdit->setSizePolicy(sp);

	m_textEdit->setLineWrapMode(QTextEdit::NoWrap);

	layout->addWidget(m_textEdit, 1);

	m_textEditConnection =
	    QObject::connect(m_textEdit, &QTextEdit::textChanged, [this]() -> void { callValueChangedCallbacks(); });

	m_browseButton = new QToolButton();
	m_browseButton->setIcon(m_browseButton->style()->standardIcon(QStyle::SP_DialogOpenButton));
	layout->addWidget(m_browseButton);

	m_buttonConnection = QObject::connect(m_browseButton, &QToolButton::released, [this]() -> void {
		QStringList paths = m_textEdit->toPlainText().split('\n');

		// expand all the starting paths
		for(auto& p : paths)
			p = possumwood::Filepath::fromString(p.toStdString()).toPath().string().c_str();

		// get a parent path to start at
		QString parentPath = possumwood::App::instance().filename().toPath().parent_path().string().c_str();
		if(!paths.empty())
			parentPath = boost::filesystem::path(paths[0].toStdString()).parent_path().string().c_str();

		// run the file dialog using fully expanded absolute paths
		paths = QFileDialog::getOpenFileNames(possumwood::App::instance().mainWindow(), "Select input files...",
		                                      parentPath, boost::algorithm::join(m_value.extensions(), ";;").c_str());

		// compress all the paths from the UI
		for(auto& p : paths)
			p = possumwood::Filepath::fromPath(p.toStdString()).toString().c_str();

		m_textEdit->setText(paths.join('\n'));
	});
}

filenames_ui::~filenames_ui() {
	QObject::disconnect(m_textEditConnection);
	QObject::disconnect(m_buttonConnection);
}

void filenames_ui::get(possumwood::Filenames& value) const {
	value.clear();

	for(auto& s : m_textEdit->toPlainText().split('\n'))
		value.addFilename(possumwood::Filepath::fromString(s.toStdString()));
}

void filenames_ui::set(const possumwood::Filenames& value) {
	m_value = value;

	QString content;
	for(auto& f : value.filenames())
		content = content + (f.toString() + "\n").c_str();
	content = content.trimmed();

	const bool bs = m_textEdit->blockSignals(true);
	m_textEdit->setText(content);
	m_textEdit->blockSignals(bs);
}

QWidget* filenames_ui::widget() {
	return m_widget;
}

void filenames_ui::onFlagsChanged(unsigned flags) {
	m_browseButton->setDisabled(flags & kDisabled || flags & kOutput);
	m_textEdit->setDisabled(flags & kDisabled);
	m_textEdit->setReadOnly(flags & kOutput);
}

max_stars_repo_name: martin-pr/possumwood

max_issues_repo_name: martin-pr/possumwood

max_forks_repo_name: martin-pr/possumwood