text:
//****************************************************************************
// (c) 2008, 2009 by the openOR Team
//****************************************************************************
// The contents of this file are available under the GPL v2.0 license
// or under the openOR comercial license. see
//   /Doc/openOR_free_license.txt or
//   /Doc/openOR_comercial_license.txt
// for Details.
//****************************************************************************
//! OPENOR_INTERFACE_FILE(openOR_core)
//****************************************************************************
//! @file
//! @ingroup openOR_core

#ifndef openOR_Plugin_detail_Wrapper_hpp
#define openOR_Plugin_detail_Wrapper_hpp

#include <boost/tr1/memory.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/assert.hpp>

#include <openOR/Utility/is_base_of.hpp>
#include <openOR/Plugin/detail/WrapperBase.hpp>

// This is for use with Qt objects, so that we can handle Qt's memory
// management transparently. Neither run-/link- nor compile-time
// dependencies are introduced!
class QObject;

namespace openOR {
   namespace Plugin {
      namespace Detail {

         //----------------------------------------------------------------------------
         //! \brief Wrapper for objects with auto-delete or without delete.
         //! \tparam ImplType implementation type
         //! \tparam AutoDelete If true, the object will be deleted if no smart pointer points to it; if false, no deleting is called
         //! \internal
         //----------------------------------------------------------------------------
         template<class ImplType, bool AutoDelete = true>
         struct Wrapper : public WrapperBase<ImplType> {

            struct DefaultDelete {
               void operator()(Wrapper* p) { delete p; }
            };

            struct NoDelete {
               void operator()(Wrapper* p) {}
            };

            typedef Wrapper WrapperType;
            typedef typename boost::mpl::if_c<AutoDelete, DefaultDelete, NoDelete>::type Deleter;

            Wrapper() :
               WrapperBase<ImplType>()
            {}

            template<class Param0>
            Wrapper(Param0 param0) :
               WrapperBase<ImplType>(param0)
            {}

            template<class Param0, class Param1>
            Wrapper(Param0 param0, Param1 param1) :
               WrapperBase<ImplType>(param0, param1)
            {}

            template<class Param0, class Param1, class Param2>
            Wrapper(Param0 param0, Param1 param1, Param2 param2) :
               WrapperBase<ImplType>(param0, param1, param2)
            {}

            virtual ~Wrapper() {}

            //----------------------------------------------------------------------------
            //! \brief Returns deleter for smart pointer creation.
            //----------------------------------------------------------------------------
            Deleter deleter() const {
               return Deleter();
            }

         };

         //----------------------------------------------------------------------------
         //! \brief Wrapper for objects derived from QObject (Qt)
         //! \tparam ImplType implementation type (ImplType must be derived from QObject)
         //! \internal
         //----------------------------------------------------------------------------
         template<class ImplType>
         struct QObjectWrapper : public WrapperBase<ImplType> {

            BOOST_MPL_ASSERT_MSG((Utility::is_base_of<QObject,ImplType>::value), FOLLOWING_TYPE_MUST_BE_DERIVED_FROM_QOBJECT, (ImplType));
            typedef QObjectWrapper WrapperType;

            struct Deleter {

               Deleter(const std::tr1::shared_ptr<bool>& pIsQObjectAlreadyDeleted) :
                  m_pIsQObjectAlreadyDeleted(pIsQObjectAlreadyDeleted)
               {}
               Deleter(const Deleter& rhs) :
                  m_pIsQObjectAlreadyDeleted(rhs.m_pIsQObjectAlreadyDeleted)
               {}

               void operator()(QObjectWrapper* p) {
                  if (!(*m_pIsQObjectAlreadyDeleted || p->parent())) {
                     delete p;
                  }
               }

            private:
               const std::tr1::shared_ptr<bool> m_pIsQObjectAlreadyDeleted;

               // To avoid MSVC warning C4512 explicitly define (private) assignment operator for this class.
               Deleter& operator=(const Deleter& tmp);
            };

            QObjectWrapper() :
               WrapperBase<ImplType>()
            {}

            template<class Param0>
            QObjectWrapper(Param0 param0) :
               WrapperBase<ImplType>(param0)
            {}

            template<class Param0, class Param1>
            QObjectWrapper(Param0 param0, Param1 param1) :
               WrapperBase<ImplType>(param0, param1)
            {}

            template<class Param0, class Param1, class Param2>
            QObjectWrapper(Param0 param0, Param1 param1, Param2 param2) :
               WrapperBase<ImplType>(param0, param1, param2)
            {}

            virtual ~QObjectWrapper() {
               if (m_pIsQObjectAlreadyDeleted) {
                  *m_pIsQObjectAlreadyDeleted = true;
               }
            }

            //----------------------------------------------------------------------------
            //! \brief Returns deleter for smart pointer creation.
            //----------------------------------------------------------------------------
            Deleter deleter() const {
               m_pIsQObjectAlreadyDeleted = std::tr1::shared_ptr<bool>(new bool(false));
               return Deleter(m_pIsQObjectAlreadyDeleted);
            }

         private:
            mutable std::tr1::shared_ptr<bool> m_pIsQObjectAlreadyDeleted;

         };

      } // end NS
   }
}

#endif

max_stars_repo_name: avinfinity/UnmanagedCodeSnippets

max_issues_repo_name: avinfinity/UnmanagedCodeSnippets

max_forks_repo_name: avinfinity/UnmanagedCodeSnippets


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

#include "core/util/log.h"

#include <boost/core/null_deleter.hpp>
#include <boost/log/attributes.hpp>
#include <boost/log/core.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/expressions/formatters/date_time.hpp>
#include <boost/log/sinks.hpp>
#include <boost/log/sources/logger.hpp>
#include <boost/log/sources/record_ostream.hpp>
#include <boost/log/sources/severity_channel_logger.hpp>
#include <boost/log/support/date_time.hpp>
#include <boost/make_shared.hpp>
#include <boost/phoenix/bind.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/shared_ptr.hpp>

#include <memory>
#include "src/core/util/filesystem.h"

// TODO(anonimal):
// Boost.Log uses an "application-wide singleton" (note: our logger/sink setup applies globally from instance configuration)
// As a result, logging will not work when in daemon mode. http://www.boost.org/doc/libs/1_63_0/libs/log/doc/html/log/rationale/fork_support.html
// We've worked around this problem in the past by using some very gross hacking but we may be able to apply a cleaner work-around so we can set this up entirely in the core namespace
// (we could create an (inheritable?) logging class with overloaded stream operator and adjust our logging initialization and macro accordingly, or consider other options)
// Also note that a singleton will effect having multiple logging library options (there's no need to do that though when we have huge flexibility with sinks)

BOOST_LOG_GLOBAL_LOGGER_INIT(g_Logger, boost::log::sources::severity_logger_mt) {
  boost::log::sources::severity_logger_mt<boost::log::trivial::severity_level> logger;
  return logger;
}

namespace kovri
{
namespace core
{
namespace logging = boost::log;
namespace expr = boost::log::expressions;
namespace attrs = boost::log::attributes;

std::string GetServerityString(logging::value_ref<
                               logging::trivial::severity_level,
                               logging::trivial::tag::severity> const& severity)
{
  std::stringstream severity_stream;
  severity_stream << "[" << severity << "]";
  return severity_stream.str();
}

std::string SetColor(
    logging::value_ref<
        logging::trivial::severity_level,
        logging::trivial::tag::severity> const& severity,
    bool has_color)
{
  if (has_color)
    {
      if (severity)
        {
          switch (severity.get())
            {
              case logging::trivial::fatal:
              case logging::trivial::error:
                return "\033[31m";  // Red
              case logging::trivial::info:
                return "\033[32m";  // Green
              case logging::trivial::warning:
                return "\033[33m";  // Yellow
              case logging::trivial::debug:
                return "\033[34m";  // Blue
              case logging::trivial::trace:
                return "\033[36m";  // Cyan
            }
        }
      return "\033[0m";  // Reset
    }
  return "";
}

logging::formatter GetFormat(bool has_color)
{
  logging::formatter format =
      expr::stream
      << boost::phoenix::bind(  // TODO(unassigned): replace with std::bind
             &SetColor,
             logging::trivial::severity.or_none(),
             has_color)
      << "["
      << expr::format_date_time(
             expr::attr<boost::posix_time::ptime>("TimeStamp"),
             "%Y.%m.%d %T.%f")
      << "]"
      << " [" << expr::attr<attrs::current_thread_id::value_type>("ThreadID")
      << "] " << std::left << std::setw(10)
      << boost::phoenix::bind(  // TODO(unassigned): replace with std::bind
             &GetServerityString,
             logging::trivial::severity.or_none())
      << expr::smessage << (has_color ? "\033[0m" : "");  // Reset
  return format;
}

void SetupLogging(const boost::program_options::variables_map& kovri_config)
{
  namespace sinks = boost::log::sinks;
  namespace keywords = boost::log::keywords;
  // Get global logger
  // TODO(unassigned): depends on global logging initialization. See notes in log impl
  auto core = logging::core::get();
  // Add core attributes
  core->add_global_attribute("TimeStamp", attrs::utc_clock());
  core->add_global_attribute("ThreadID", attrs::current_thread_id());
  // Get/Set filter log level
  auto log_level = kovri_config["log-level"].as<std::uint16_t>();
  logging::trivial::severity_level severity;
  switch (log_level)
    {
      case 0:
        severity = logging::trivial::fatal;
        break;
      case 1:
        severity = logging::trivial::error;
        break;
      case 2:
        severity = logging::trivial::warning;
        break;
      case 3:
        severity = logging::trivial::info;
        break;
      case 4:
        severity = logging::trivial::debug;
        break;
      case 5:
        severity = logging::trivial::trace;
        break;
      default:
        throw std::invalid_argument(
            "Configuration: invalid log-level, see documentation");
        break;
    };
  core->set_filter(
      expr::attr<logging::trivial::severity_level>("Severity") >= severity);
  // Create text backend + sink
  typedef sinks::synchronous_sink<sinks::text_ostream_backend>
      text_ostream_sink;
  auto text_sink = boost::make_shared<text_ostream_sink>();
  text_sink->locked_backend()->add_stream(
      boost::shared_ptr<std::ostream>(&std::clog, boost::null_deleter()));
  // Create file backend
  typedef sinks::asynchronous_sink<sinks::text_file_backend> text_file_sink;
  auto file_backend = boost::make_shared<sinks::text_file_backend>(
      keywords::file_name =
          kovri_config["log-file-name"].defaulted()
              ? ((core::GetPath(core::Path::Logs) / "kovri_%Y-%m-%d.log").string())
              : kovri_config["log-file-name"].as<std::string>(),
      keywords::time_based_rotation =
          sinks::file::rotation_at_time_point(0, 0, 0));  // Rotate at midnight
  // Auto flush for closer-to-real-time record message reporting
  // Note: our severity levels are processed in reverse
  if (severity <= logging::trivial::debug
      || kovri_config["enable-auto-flush-log"].as<bool>())
    file_backend->auto_flush();
  // Create file sink
  auto file_sink = boost::shared_ptr<text_file_sink>(
      std::make_unique<text_file_sink>(file_backend));
  // Set sink formatting
  text_sink->set_formatter(
      GetFormat(kovri_config["disable-color-log"].as<bool>() ? false : true));
  file_sink->set_formatter(GetFormat(false));
  // Add sinks
  core->add_sink(text_sink);
  core->add_sink(file_sink);
  // Remove sinks if needed (we must first have added sinks to remove)
  if (kovri_config["disable-console-log"].as<bool>())
    core->remove_sink(text_sink);
  if (kovri_config["disable-file-log"].as<bool>())
    core->remove_sink(file_sink);
}

}  // namespace core
}  // namespace kovri

ext: cc

max_stars_repo_name: byterubpay/kovri

max_issues_repo_name: byterubpay/kovri

max_forks_repo_name: byterubpay/kovri


text:
/*
 *          Copyright Schwenk, Kurt <Kurt.Schwenk@gmx.de> 2020
 * Distributed under the Boost Software License, Version 1.0.
 *    (See accompanying file LICENSE_1_0.txt or copy at
 *          http://www.boost.org/LICENSE_1_0.txt)
 */

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

#include <dataflow/blocks/Block.h>
#include <dataflow/channels/Channel.h>
#include <dataflow/executors/ExecutorSeq.h>

using namespace dataflow::blocks;
using namespace dataflow::channels;
using namespace dataflow::executors;

BOOST_AUTO_TEST_CASE(BasicOutputPredicate)
{
    using ValueType = int;
    Channel<ValueType> chanIn;
    Channel<ValueType> chanOut;

    ExecutorSeq executor;

    //Definition passThroughOnlyEvenBlock
    auto passThrough = [](ValueType&& val) { return std::forward<ValueType>(val); };

    auto outputOnlyEven = [](const auto&... inputPack) {
        auto isEven = [](const auto& number) { return number % 2 == 0; };
        return std::array { isEven(inputPack)... };
    };

    Block passThroughOnlyEven { ChannelBundle { chanIn },
        passThrough, ChannelBundle { chanOut }, executor, outputOnlyEven };

    //Test run
    const size_t cycles = 101;

    for (size_t cycle = 0; cycle < cycles; ++cycle) {
        chanIn.push(cycle);
    };

    //Test evaluation
    const size_t cyclesEven = cycles % 2 == 0 ? cycles / 2 : cycles / 2 + 1;

    BOOST_CHECK_EQUAL(chanOut.size(), cyclesEven);

    for (size_t i = 0; i < cyclesEven; ++i) {
        BOOST_CHECK_EQUAL(chanOut.pop().value() % 2, 0);
    }
}

ext: cpp

max_stars_repo_name: Klirxel/DataFlowFramework

max_issues_repo_name: Klirxel/DataFlowFramework

max_forks_repo_name: Klirxel/DataFlowFramework


text:
#include <algorithm>
#include <iostream>
#include <string>

#include <boost/program_options.hpp>

#include "sigmoid.hh"

namespace po = boost::program_options;
using namespace machina;

int main(int argc, char *argv[])
{
  std::string funct;
  int width = 0;
  int depth = 0;
  int scale = 0;

  try {
    po::options_description desc{"Options"};
    desc.add_options()
      ("help,h", "Help")
      ("funct,f", po::value<std::string>(&funct)->required(), "Function")
      ("width,w", po::value<int>(&width)->default_value(8), "Width")
      ("depth,d", po::value<int>(&depth)->default_value(4096), "Depth")
      ("scale,s", po::value<int>(&scale)->default_value(255), "Scale");
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    if (vm.count("help")) {
      std::cout << desc;
      return 0;
    }
    po::notify(vm);
  } catch (const po::error& ex) {
    std::cerr << "ERROR: " << ex.what() << std::endl;
    return 1;
  }

  std::transform(funct.begin(), funct.end(), funct.begin(), ::tolower);

  bool prime;
  if (funct.compare("sigmoid") == 0) {
    prime = false;
  } else if (funct.compare("sigmoid-prime") == 0) {
    prime = true;
  } else {
    std::cerr << "ERROR: unknown function: " << funct << std::endl;
    return 1;
  }

  Sigmoid memory(width, scale, prime);
  for (int val = 0; val < depth >> 1; val++)
    memory << val;
  for (int val = -(depth >> 1); val < 0; val++)
    memory << val;
  std::cout << memory;

  return 0;
}

max_stars_repo_name: bwitherspoon/net

max_issues_repo_name: bwitherspoon/net

max_forks_repo_name: bwitherspoon/net


text:
/*
 * Copyright (c) 2017, Respective Authors.
 *
 * The MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
#include <boost/test/unit_test.hpp>
#include <boost/program_options.hpp>

#include <omo/chain/account_object.hpp>
#include <omo/chain/producer_object.hpp>

#include <omo/utilities/tempdir.hpp>

#include <fc/crypto/digest.hpp>
#include <fc/smart_ref_impl.hpp>

#include <iostream>
#include <iomanip>
#include <sstream>

#include "database_fixture.hpp"

using namespace omo::chain::test;

uint32_t OMO_TESTING_GENESIS_TIMESTAMP = 1431700000;

namespace omo { namespace chain {

using std::cout;
using std::cerr;

database_fixture::database_fixture()
   : app(), db( *app.chain_database() )
{
   try {
   int argc = boost::unit_test::framework::master_test_suite().argc;
   char** argv = boost::unit_test::framework::master_test_suite().argv;
   for( int i=1; i<argc; i++ )
   {
      const std::string arg = argv[i];
      if( arg == "--record-assert-trip" )
         fc::enable_record_assert_trip = true;
      if( arg == "--show-test-names" )
         std::cout << "running test " << boost::unit_test::framework::current_test_case().p_name << std::endl;
   }
   init_account_pub_key = init_account_priv_key.get_public_key();

   boost::program_options::variables_map options;

   genesis_state.initial_timestamp = fc::time_point_sec( OMO_TESTING_GENESIS_TIMESTAMP );

   genesis_state.initial_producer_count = 10;
   for( int i = 0; i < genesis_state.initial_producer_count; ++i )
   {
      auto name = "init"+fc::to_string(i);
      genesis_state.initial_accounts.emplace_back(name,
                                                  init_account_priv_key.get_public_key(),
                                                  init_account_priv_key.get_public_key());
      genesis_state.initial_producers.push_back({name, init_account_priv_key.get_public_key()});
   }
   open_database();

   generate_block();

   set_expiration( db, trx );
   } catch ( const fc::exception& e )
   {
      edump( (e.to_detail_string()) );
      throw;
   }

   return;
}

database_fixture::~database_fixture()
{ try {
   // If we're unwinding due to an exception, don't do any more checks.
   // This way, boost test's last checkpoint tells us approximately where the error was.
   if( !std::uncaught_exception() )
   {
      BOOST_CHECK( db.get_node_properties().skip_flags == database::skip_nothing );
   }

   if( data_dir )
      db.close();
   return;
} FC_CAPTURE_AND_RETHROW() }

fc::ecc::private_key database_fixture::generate_private_key(string seed)
{
   static const fc::ecc::private_key committee = fc::ecc::private_key::regenerate(fc::sha256::hash(string("null_key")));
   if( seed == "null_key" )
      return committee;
   return fc::ecc::private_key::regenerate(fc::sha256::hash(seed));
}

string database_fixture::generate_anon_acct_name()
{
   // names of the form "anon-acct-x123" ; the "x" is necessary
   //    to workaround issue #46
   return "anon-acct-x" + std::to_string( anon_acct_count++ );
}

void database_fixture::open_database()
{
   if( !data_dir ) {
      data_dir = fc::temp_directory( omo::utilities::temp_directory_path() );
      db.open(data_dir->path(), TEST_DB_SIZE, [this]{return genesis_state;});
   }
}

signed_block database_fixture::generate_block(uint32_t skip, const fc::ecc::private_key& key, int miss_blocks)
{
   skip |= database::skip_undo_history_check;
   // skip == ~0 will skip checks specified in database::validation_steps
   auto block = db.generate_block(db.get_slot_time(miss_blocks + 1),
                            db.get_scheduled_producer(miss_blocks + 1),
                            key, skip);
   db.clear_pending();
   return block;
}

void database_fixture::generate_blocks( uint32_t block_count )
{
   for( uint32_t i = 0; i < block_count; ++i )
      generate_block();
}

void database_fixture::generate_blocks(fc::time_point_sec timestamp, bool miss_intermediate_blocks, uint32_t skip)
{
   if( miss_intermediate_blocks )
   {
      generate_block(skip);
      auto slots_to_miss = db.get_slot_at_time(timestamp);
      if( slots_to_miss <= 1 )
         return;
      --slots_to_miss;
      generate_block(skip, init_account_priv_key, slots_to_miss);
      return;
   }
   while( db.head_block_time() < timestamp )
      generate_block(skip);
}

namespace test {

void set_expiration( const database& db, transaction& tx )
{
   const chain_parameters& params = db.get_global_properties().parameters;
   tx.set_reference_block(db.head_block_id());
   tx.set_expiration( db.head_block_time() + fc::seconds( params.block_interval * (params.maintenance_skip_slots + 1) * 3 ) );
   return;
}

bool _push_block( database& db, const signed_block& b, uint32_t skip_flags /* = 0 */ )
{
   return db.push_block( b, skip_flags);
}

signed_transaction _push_transaction( database& db, const signed_transaction& tx, uint32_t skip_flags /* = 0 */ )
{ try {
   auto pt = db.push_transaction( tx, skip_flags );
   return pt;
} FC_CAPTURE_AND_RETHROW((tx)) }

} // omo::chain::test

} } // omo::chain


text:
// -*- mode: c++ -*-
#include "FixedThreadPool.h"
#include <libssh/libsshpp.hpp>
#include <libssh/callbacks.h>
#include <iostream>
#include <cstdlib>
#include <boost/shared_ptr.hpp>
#include <string>
#include <fstream>
#include <arpa/inet.h>
#include <cstdio>
#include <sstream>

using namespace tpool;
using namespace std;
using namespace ssh;
using boost::shared_ptr;

class SshForwardTask : public TaskBase
{
  shared_ptr<Channel> m_forwardChannel;
  sync::Mutex& m_channelGuard;

public:
  SshForwardTask(shared_ptr<Channel> channel, sync::Mutex& channelGuard)
    : m_forwardChannel(channel), m_channelGuard(channelGuard)
  {}

  virtual ~SshForwardTask()
  {}

  virtual void DoRun()
  {
    const int data = 1;
    sync::MutexLocker l(m_channelGuard);
    cout << "forward data: " << data << endl;
    const long networkData = htonl(data);
    m_forwardChannel->write(&networkData, sizeof(data));
  }
};

void ReportSshError(SshException& e)
{
  cerr << "[Error]: " << e.getError() << endl;
  exit(1);
}

shared_ptr<Session> MakeSshSession(const string& host, const int port)
{
  shared_ptr<Session> session(new Session);
  session->setOption(SSH_OPTIONS_HOST, host.c_str());
  session->setOption(SSH_OPTIONS_PORT, port);
  try
    {
      session->connect();
      return session;
    }
  catch (SshException& e)
    {
      ReportSshError(e);
    }
}

void LoginSshSession(shared_ptr<Session> session, const string& username,
		     const string& password)
{
  session->setOption(SSH_OPTIONS_USER, username.c_str());
  try
    {
      if (session->userauthAutopubkey() == SSH_AUTH_SUCCESS)
	{
	  cout << "login successfully" << endl;
	  return;
	}
      cout << "public key auth failed" << endl;
    }
  catch (SshException& e)
    {
      ReportSshError(e);
    }

  try
    {
      if (session->userauthPassword(password.c_str()) != SSH_AUTH_SUCCESS)
	{
	  cerr << "[Error] login failed" << endl;
	  exit(1);
	}
      cout << "login successfully" << endl;
    }
  catch (SshException& e)
    {
      ReportSshError(e);
    }
}

shared_ptr<Channel> MakeCommandChannel(shared_ptr<Session> session,
				       const string& command)
{
  shared_ptr<Channel> execChannel(new Channel(*session));
  try
    {
      execChannel->openSession();
      execChannel->requestPty();
      execChannel->changePtySize(80, 46);
      execChannel->requestShell();
      const string realCommand = command + "\n";
      cout << "realcommand is " << realCommand;
      cout << "size is " << realCommand.size() << endl;
      const int count = execChannel->write(realCommand.c_str(), realCommand.size());
      if (count < realCommand.size())
	{
	  cerr << "[error] shell write" << endl;
	  exit(1);
	}
      return execChannel;
    }
  catch (SshException& e)
    {
      ReportSshError(e);
    }
}

shared_ptr<Channel> MakeDirectForwardChannel(shared_ptr<Session> session,
					     const string& host,
					     const int& port)
{
  shared_ptr<Channel> forwardChannel(new Channel(*session));
  try
    {
      forwardChannel->openForward(host.c_str(), port, "localhost");
      if (!(forwardChannel->isOpen()))
	{
	  cerr << "Forward Channel Open Failed." << endl;
	  exit(1);
	}
      return forwardChannel;
    }
  catch (SshException& e)
    {
      ReportSshError(e);
    }
}

int GetServerPort(shared_ptr<Channel> channel)
{
  char execResult[1024] = {0};
  int count = 0;
  int totalCount = 0;
  int port = 0;
  if (!(channel->isOpen()) || channel->isEof())
    {
      cerr << "[Error] command channel not open" << endl;
      exit(1);
    }
  while (true)
    {
      count = channel->read(execResult + totalCount, 1024);
      totalCount += count;
      string s(execResult, totalCount);
      size_t pos = 0;
      if ((pos = s.find("port:")) != string::npos)
	{
	  istringstream iss(s.substr(pos + 5));
	  iss >> port;
	  break;
	}
    }

  string resultString(execResult, totalCount);
  cout << "exec result: " << resultString << endl;
  return port;
}

static int auth_callback(const char *prompt, char *buf, size_t len,
    int echo, int verify, void *userdata)
{
  char *answer = NULL;
  char *ptr;

  (void) verify;
  (void) userdata;

  if (echo) {
    while ((answer = fgets(buf, len, stdin)) == NULL);
    if ((ptr = strchr(buf, '\n'))) {
      *ptr = '\0';
    }
  } else {
    if (ssh_getpass(prompt, buf, len, 0, 0) < 0) {
        return -1;
    }
    return 0;
  }

  if (answer == NULL) {
    return -1;
  }

  strncpy(buf, answer, len);

  return 0;
}

int main(int argc, char *argv[])
{
  if (argc < 3)
    {
      cerr << "please enter username and password" << endl;
      exit(1);
    }
  const string username = argv[1];
  const string password = argv[2];

  shared_ptr<Session> sshSession(MakeSshSession("127.0.0.1", 22));

  struct ssh_callbacks_struct cb;
  cb.auth_function = auth_callback;
  cb.userdata = NULL;

  ssh_callbacks_init(&cb);
  ssh_set_callbacks(sshSession->getCSession(),&cb);

  LoginSshSession(sshSession, username, password);

  // execute a command
  string remoteCmd;
  getline(cin, remoteCmd);
  shared_ptr<Channel> execChannel(MakeCommandChannel(sshSession, remoteCmd));
  const int port = GetServerPort(execChannel);

  // open a new forward channel
  shared_ptr<Channel> forwardChannel(MakeDirectForwardChannel(sshSession,
							      "127.0.0.1",
							      port));

  {
    LFixedThreadPool threadPool(5);
    sync::Mutex channelGuard;

    for (int i = 0; i < 5; ++i)
      {
	threadPool.AddTask(TaskBase::Ptr(new SshForwardTask(forwardChannel,
							    channelGuard)));
      }

    threadPool.Stop();
  }

  execChannel->sendEof();
  execChannel->close();

  return 0;
}

max_stars_repo_name: airekans/Tpool

max_issues_repo_name: guker/Tpool

max_forks_repo_name: guker/Tpool


text:
/*
 * Copyright (c) 2013-2018 Masahide Kashiwagi (kashi@waseda.jp)
 */

#ifndef KRAW_APPROX_HPP
#define KRAW_APPROX_HPP

// Krawczyk method using approximate solution
// Newton iteration can be applied in advance.

#include <limits>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <kv/interval.hpp>
#include <kv/rdouble.hpp>
#include <kv/interval-vector.hpp>
#include <kv/autodif.hpp>
#include <kv/matrix-inversion.hpp>
#include <kv/make-candidate.hpp>

namespace kv {

namespace ub = boost::numeric::ublas;

template <class T, class F>
bool
krawczyk_approx(F f, const ub::vector<T>& c, ub::vector< interval<T> >& result, int newton_max = 2, int verbose = 1)
{
	int s = c.size();

	ub::vector< interval<T> > I, fc, fi, Rfc, C, K;
	ub::matrix< interval<T> > fdc, fdi, M;
	ub::vector<T> c2, minus;
	ub::matrix<T> R;
	int i, j;
	bool r;
	ub::vector<T> newton_step;
	T tmp, tmp2;

	c2 = c;

	// Newton iteration
	// use interval<T> for argument of f
	// preparing for the case that f can not accept T.

	for (i=0; i<newton_max; i++) {
		C = c2;
		try {
			autodif< interval<T> >::split(f(autodif< interval<T> >::init(C)), fc, fdc);
		}
		catch (std::domain_error& e) {
			return false;
		}
		r = invert(mid(fdc), R);
		if (!r) return false;

		minus = prod(R, mid(fc));

		tmp = 1.;
		tmp2 = 0.;
		for (j=0; j<s; j++) {
			using std::abs;
			tmp = std::max(tmp, abs(c2(j)));
			tmp2 = std::max(tmp2, abs(minus(j)));
		}

		c2 = c2 - minus;
		if (verbose >= 1) {
			std::cout << "newton" << i << ": " << c2 << "\n";
		}
		if (tmp2 <= tmp * std::numeric_limits<T>::epsilon()) break;
	}

	C = c2;
	try {
		autodif< interval<T> >::split(f(autodif< interval<T> >::init(C)), fc, fdc);
	}
	catch (std::domain_error& e) {
		return false;
	}
	r = invert(mid(fdc), R);
	if (!r) return false;
	Rfc = prod(R, fc);

	newton_step.resize(s);
	for (i=0; i<s; i++) {
		newton_step(i) = norm(Rfc(i));
	}

	make_candidate(newton_step);

	I = C;
	for (i=0; i<s; i++) {
		tmp = std::numeric_limits<T>::epsilon() * norm(I(i)) * (s+1) * 2;
		tmp2 = std::numeric_limits<T>::min() * (s+1) * 2;
		if (newton_step(i) < tmp) newton_step(i) = tmp;
		if (newton_step(i) < tmp2) newton_step(i) = tmp2;
		I(i) += newton_step(i) * interval<T>(-1., 1.);
	}

	if (verbose >= 1) {
		std::cout << "I: " << I << "\n";
	}

	try {
		autodif< interval<T> >::split(f(autodif< interval<T> >::init(I)), fi, fdi);
	}
	catch (std::domain_error& e) {
		return false;
	}

	// M = ub::identity_matrix< interval<T> >(s) - prod(R, fdi);
	M = ub::identity_matrix< interval<T> >(s);
	M -= prod(R, fdi);

	K = C - Rfc +  prod(M, I - C);

	if (verbose >= 1) {
		std::cout << "K: " << K << "\n";
	}

	if (proper_subset(K, I)) {
		result = K;
		return true;
	} else {
		return false;
	}
}

namespace krawczyk_approx_sub {

// generate 1-d vector function from scalar function
template <class F>
struct MakeVec {
	F f;
	MakeVec(F f): f(f) {}

	template <class T> ub::vector<T> operator()(const ub::vector<T>& x) {
		ub::vector<T> r(1);
		r(0) = f(x(0));
		return r;
	}
};

} // namespace krawczyk_approx_sub;

// 1 dimensional version

template <class T, class F>
bool
krawczyk_approx(F f, const T& c, interval<T>& result, int newton_max = 2, int verbose = 1)
{
	ub::vector<T> in(1);
	ub::vector< interval<T> > out;
	krawczyk_approx_sub::MakeVec<F> g(f);
	bool r;

	in(0) = c;
	r = krawczyk_approx(g, in, out, newton_max, verbose);
	if (!r) return r;
	result = out(0);
	return r;
}

} // namespace kv

#endif // KRAW_APPROX_HPP

ext: hpp

max_stars_repo_name: soonho-tri/kv

max_issues_repo_name: takafumihoriuchi/HyLaGI

max_forks_repo_name: takafumihoriuchi/HyLaGI


text:
/**
 * @file layer_traits_test.cpp
 * @author Marcus Edel
 *
 * Test the LayerTraits class. Because all of the values are known at compile
 * time, this test is meant to ensure that uses of LayerTraits still compile
 * okay and react as expected.
 */
#include <mlpack/core.hpp>

#include <mlpack/methods/ann/layer/layer_traits.hpp>
#include <mlpack/methods/ann/layer/bias_layer.hpp>
#include <mlpack/methods/ann/layer/multiclass_classification_layer.hpp>

#include <boost/test/unit_test.hpp>
#include "test_tools.hpp"

using namespace mlpack;
using namespace mlpack::ann;

BOOST_AUTO_TEST_SUITE(LayerTraitsTest);

// Test the defaults.
BOOST_AUTO_TEST_CASE(DefaultsTraitsTest)
{
  // An irrelevant non-connection type class is used here so that the default
  // implementation of ConnectionTraits is chosen.
  bool b = LayerTraits<int>::IsBinary;
  BOOST_REQUIRE_EQUAL(b, false);

  b =  LayerTraits<int>::IsOutputLayer;
  BOOST_REQUIRE_EQUAL(b, false);

  b =  LayerTraits<int>::IsBiasLayer;
  BOOST_REQUIRE_EQUAL(b, false);
}

// Test the BiasLayer traits.
BOOST_AUTO_TEST_CASE(BiasLayerTraitsTest)
{
  bool b = LayerTraits<BiasLayer<> >::IsBinary;
  BOOST_REQUIRE_EQUAL(b, false);

  b = LayerTraits<BiasLayer<> >::IsOutputLayer;
  BOOST_REQUIRE_EQUAL(b, false);

  b = LayerTraits<BiasLayer<> >::IsBiasLayer;
  BOOST_REQUIRE_EQUAL(b, true);
}

// Test the MulticlassClassificationLayer traits.
BOOST_AUTO_TEST_CASE(MulticlassClassificationLayerTraitsTest)
{
  bool b = LayerTraits<MulticlassClassificationLayer<> >::IsBinary;
  BOOST_REQUIRE_EQUAL(b, false);

  b = LayerTraits<MulticlassClassificationLayer<> >::IsOutputLayer;
  BOOST_REQUIRE_EQUAL(b, true);

  b = LayerTraits<MulticlassClassificationLayer<> >::IsBiasLayer;
  BOOST_REQUIRE_EQUAL(b, false);
}

BOOST_AUTO_TEST_SUITE_END();


text:
#include <pichi/common/config.hpp>
// Include config.hpp first
#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/beast/core/flat_static_buffer.hpp>
#include <boost/beast/http/empty_body.hpp>
#include <boost/beast/http/message.hpp>
#include <boost/beast/http/read.hpp>
#include <boost/beast/http/string_body.hpp>
#include <boost/beast/http/write.hpp>
#include <boost/filesystem/path.hpp>
#include <fstream>
#include <iostream>
#include <pichi/api/server.hpp>
#include <pichi/common/asserts.hpp>
#include <pichi/common/endpoint.hpp>
#include <pichi/net/adapter.hpp>
#include <pichi/net/helper.hpp>
#include <pichi/net/spawn.hpp>
#include <pichi/vo/to_json.hpp>
#include <rapidjson/document.h>
#include <rapidjson/istreamwrapper.h>
#include <vector>

#ifdef HAS_SIGNAL_H
#include <boost/asio/signal_set.hpp>
#include <signal.h>
#endif  // HAS_SIGNAL_H

using namespace std;
using namespace pichi;
namespace asio = boost::asio;
namespace beast = boost::beast;
namespace fs = boost::filesystem;
namespace http = boost::beast::http;
namespace ip = asio::ip;
namespace json = rapidjson;

using ip::tcp;

static decltype(auto) INGRESSES = "ingresses";
static decltype(auto) EGRESSES = "egresses";
static decltype(auto) RULES = "rules";
static decltype(auto) ROUTE = "route";
static decltype(auto) INDENT = "  ";

static asio::io_context io{1};

static json::Document parseJson(char const* str)
{
  auto doc = json::Document{};
  doc.Parse(str);
  assertFalse(doc.HasParseError());
  return doc;
}

class HttpHelper {
public:
  HttpHelper(ResolveResults&& endpoint, asio::yield_context yield);

  vector<string> get(string const& target);
  void put(string const& target, string const& body);
  void del(string const& target);

private:
  ResolveResults endpoint_;
  asio::yield_context yield_;
};

HttpHelper::HttpHelper(ResolveResults&& endpoint, asio::yield_context yield)
  : endpoint_{move(endpoint)}, yield_{yield}
{
}

vector<string> HttpHelper::get(string const& target)
{
  auto s = tcp::socket{io};
  net::connect(endpoint_, s, yield_);

  auto req = http::request<http::empty_body>{};
  req.method(http::verb::get);
  req.target(target);
  req.version(11);
  http::async_write(s, req, yield_);

  auto buf = beast::flat_static_buffer<1024>{};
  auto resp = http::response<http::string_body>{};
  http::async_read(s, buf, resp, yield_);
  assertTrue(resp.result() == http::status::ok);

  auto doc = parseJson(resp.body().c_str());
  auto ret = vector<string>{};
  transform(doc.MemberBegin(), doc.MemberEnd(), back_inserter(ret),
            [](auto&& member) { return member.name.GetString(); });
  return ret;
}

void HttpHelper::put(string const& target, string const& body)
{
  auto s = tcp::socket{io};
  net::connect(endpoint_, s, yield_);

  auto req = http::request<http::string_body>{};
  req.method(http::verb::put);
  req.target(target);
  req.version(11);
  req.body() = body;
  req.prepare_payload();
  http::async_write(s, req, yield_);

  auto buf = beast::flat_static_buffer<1024>{};
  auto resp = http::response<http::string_body>{};
  http::async_read(s, buf, resp, yield_);
  if (resp.result() != http::status::no_content) cout << INDENT << target << " NOT loaded" << endl;
}

void HttpHelper::del(string const& target)
{
  auto s = tcp::socket{io};
  net::connect(endpoint_, s, yield_);

  auto req = http::request<http::string_body>{};
  req.method(http::verb::delete_);
  req.target(target);
  req.version(11);
  http::async_write(s, req, yield_);

  auto buf = beast::flat_static_buffer<1024>{};
  auto resp = http::response<http::string_body>{};
  http::async_read(s, buf, resp, yield_);
  assertTrue(resp.result() == http::status::no_content);
}

static auto readJson(string const& fn)
{
  auto doc = json::Document{};
  auto ifs = ifstream{fn};
  auto isw = json::IStreamWrapper{ifs};
  doc.ParseStream(isw);
  if (doc.HasParseError() || !doc.IsObject()) {
    cout << "Invalid JSON configuration" << endl;
    doc = json::Document{};
    doc.SetObject();
  }
  return doc;
}

template <typename StringRef>
static void loadSet(HttpHelper& helper, json::Value const& root, StringRef const& category)
{
  auto it = root.FindMember(category);
  if (it == root.MemberEnd() || !it->value.IsObject()) {
    cout << INDENT << category << " NOT loaded" << endl;
    return;
  }

  for (auto&& node : it->value.GetObject())
    helper.put("/"s + category + "/" + node.name.GetString(), vo::toString(node.value));
}

static void load(HttpHelper& helper, string const& fn)
{
  if (fn.empty()) return;
  cout << "Loading configuration: " << fn << endl;
  auto json = readJson(fn);
  loadSet(helper, json, INGRESSES);
  loadSet(helper, json, EGRESSES);
  loadSet(helper, json, RULES);
  if (json.HasMember(ROUTE))
    helper.put("/"s + ROUTE, vo::toString(json[ROUTE]));
  else
    cout << INDENT << ROUTE << " NOT loaded" << endl;
  cout << "Configuration " << fn << " loaded" << endl;
}

#if defined(HAS_SIGNAL_H) && defined(SIGHUP)
static void flush(HttpHelper& helper)
{
  helper.put("/"s + EGRESSES + "/direct", "{\"type\":\"direct\"}"s);
  helper.put("/"s + ROUTE, "{\"default\":\"direct\",\"rules\":[]}"s);

  for (auto&& rule : helper.get("/"s + RULES)) helper.del("/"s + RULES + "/" + rule);
  for (auto&& egress : helper.get("/"s + EGRESSES))
    if (egress != "direct") helper.del("/"s + EGRESSES + "/" + egress);
  for (auto&& ingress : helper.get("/"s + INGRESSES)) helper.del("/"s + INGRESSES + "/" + ingress);

  cout << "Configuration reset" << endl;
}
#endif  // defined(HAS_SIGNAL_H) && defined(SIGHUP)

void run(string const& bind, uint16_t port, string const& fn, string const& mmdb)
{
  auto server = api::Server{io, mmdb.c_str()};
  server.listen(bind, port);

  // FIXME load & flush aren't designed to be the atomic operations.
  net::spawn(
      io,
      [=](auto yield) {
        auto resolver = tcp::resolver{io};
        auto helper = HttpHelper{resolver.async_resolve(bind, to_string(port), yield), yield};
        load(helper, fn);

#if defined(HAS_SIGNAL_H) && defined(SIGHUP)
        auto ss = asio::signal_set{io};
        while (true) {
          ss.add(SIGHUP);
          ss.async_wait(yield);
          flush(helper);
          load(helper, fn);
        }
#endif  // defined(HAS_SIGNAL_H) && defined(SIGHUP)
      },
      [](auto, auto) noexcept { io.stop(); });

  io.run();
}

max_stars_repo_name: imuzi/pichi

max_issues_repo_name: imuzi/pichi

max_forks_repo_name: imuzi/pichi


text:
//
// $Id: SpectrumList_Waters.cpp 10200 2016-11-17 16:39:48Z pcbrefugee $
//
//
// Original author: Matt Chambers <matt.chambers .@. vanderbilt.edu>
//
// Copyright 2009 Vanderbilt University - Nashville, TN 37232
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

#define PWIZ_SOURCE

#include "SpectrumList_Waters.hpp"

#ifdef PWIZ_READER_WATERS
#include "pwiz/utility/misc/SHA1Calculator.hpp"
#include "pwiz/utility/misc/Filesystem.hpp"
#include "pwiz/utility/misc/Std.hpp"
#include "Reader_Waters_Detail.hpp"
#include <boost/spirit/include/karma.hpp>
#include "boost/foreach_field.hpp"

namespace pwiz {
namespace msdata {
namespace detail {

using namespace Waters;

SpectrumList_Waters::SpectrumList_Waters(MSData& msd, RawDataPtr rawdata, const Reader::Config& config)
    : msd_(msd), rawdata_(rawdata), config_(config)
{
    createIndex();
}

PWIZ_API_DECL size_t SpectrumList_Waters::size() const
{
    return size_;
}

PWIZ_API_DECL const SpectrumIdentity& SpectrumList_Waters::spectrumIdentity(size_t index) const
{
    if (index>size_)
        throw runtime_error("[SpectrumList_Waters::spectrumIdentity()] Bad index: "
                            + lexical_cast<string>(index));
    return index_[index];
}

PWIZ_API_DECL size_t SpectrumList_Waters::find(const string& id) const
{
    map<string, size_t>::const_iterator scanItr = idToIndexMap_.find(id);
    if (scanItr == idToIndexMap_.end())
        return size_;
    return scanItr->second;
}

PWIZ_API_DECL SpectrumPtr SpectrumList_Waters::spectrum(size_t index, bool getBinaryData) const
{
    return spectrum(index, getBinaryData ? DetailLevel_FullData : DetailLevel_FullMetadata, 0.0, 0.0, 0.0);
}

PWIZ_API_DECL SpectrumPtr SpectrumList_Waters::spectrum(size_t index, DetailLevel detailLevel) const
{
    return spectrum(index, detailLevel, 0.0, 0.0, 0.0);
}

PWIZ_API_DECL SpectrumPtr SpectrumList_Waters::spectrum(size_t index, bool getBinaryData, double lockmassMzPosScans, double lockmassMzNegScans, double lockmassTolerance) const
{
    return spectrum(index, getBinaryData ? DetailLevel_FullData : DetailLevel_FullMetadata, lockmassMzPosScans, lockmassMzNegScans, lockmassTolerance);
}

PWIZ_API_DECL SpectrumPtr SpectrumList_Waters::spectrum(size_t index, DetailLevel detailLevel, double lockmassMzPosScans, double lockmassMzNegScans, double lockmassTolerance) const
{
    boost::lock_guard<boost::mutex> lock(readMutex);  // lock_guard will unlock mutex when out of scope or when exception thrown (during destruction)
    if (index >= size_)
        throw runtime_error("[SpectrumList_Waters::spectrum()] Bad index: "
                            + lexical_cast<string>(index));

    // allocate a new Spectrum
    SpectrumPtr result(new Spectrum);
    if (!result.get())
        throw runtime_error("[SpectrumList_Waters::spectrum()] Allocation error.");

    IndexEntry& ie = index_[index];

    result->index = ie.index;
    result->id = ie.id;

    // TODO: fix Serializer_mzXML so it supports non-default sourceFilePtrs
    //size_t sourceFileIndex = ie.functionPtr->getFunctionNumber() - 1;
    //result->sourceFilePtr = msd_.fileDescription.sourceFilePtrs[sourceFileIndex];

    /*float laserAimX = pExScanStats_->LaserAimXPos;
    float laserAimY = pExScanStats_->LaserAimYPos;
    //if (scanInfo->ionizationType() == IonizationType_MALDI)
    {
        result->spotID = (format("%dx%d") % laserAimX % laserAimY).str();
    }*/

    result->scanList.set(MS_no_combination);
    result->scanList.scans.push_back(Scan());
    Scan& scan = result->scanList.scans[0];
    scan.instrumentConfigurationPtr = msd_.run.defaultInstrumentConfigurationPtr;

    //scan.instrumentConfigurationPtr =
        //findInstrumentConfiguration(msd_, translate(scanInfo->massAnalyzerType()));

    int msLevel;
    CVID spectrumType;
    translateFunctionType(WatersToPwizFunctionType(rawdata_->Info.GetFunctionType(ie.function)), msLevel, spectrumType);

    result->set(spectrumType);
    result->set(MS_ms_level, msLevel);

    scan.set(MS_preset_scan_configuration, ie.function+1);

    if (detailLevel == DetailLevel_InstantMetadata)
        return result;

    using ::Waters::Lib::MassLynxRaw::MSScanStats;
    const MSScanStats& scanStats = rawdata_->GetScanStats(ie.function, ie.block >= 0 ? ie.block : ie.scan);

    scan.set(MS_scan_start_time, scanStats.rt, UO_minute);

    PwizPolarityType polarityType = WatersToPwizPolarityType(rawdata_->Info.GetIonMode(ie.function));
    if (polarityType != PolarityType_Unknown)
        result->set(translate(polarityType));
    double lockmassMz = (polarityType == PolarityType_Negative) ? lockmassMzNegScans : lockmassMzPosScans;
    if (lockmassMz != 0.0)
    {
        if (!rawdata_->ApplyLockMass(lockmassMz, lockmassTolerance)) // TODO: if false (cannot apply lockmass), log a warning
            warn_once("[SpectrumList_Waters] failed to apply lockmass correction");
    }
    else
        rawdata_->RemoveLockMass();

    if (scanStats.isContinuumScan)
        result->set(MS_profile_spectrum);
    else
        result->set(MS_centroid_spectrum);

    // block >= 0 is ion mobility
    if (ie.block < 0)
    {
        // scanStats values don't match the ion mobility data arrays
        // CONSIDER: in the ion mobility case, get these values from the actual data arrays
        result->set(MS_base_peak_m_z, scanStats.basePeakMass);
        result->set(MS_base_peak_intensity, scanStats.basePeakIntensity);
        result->set(MS_total_ion_current, scanStats.tic);
        result->defaultArrayLength = scanStats.peaksInScan;
    }
    else
        result->defaultArrayLength = 0;

    float minMZ, maxMZ;
    rawdata_->Info.GetAcquisitionMassRange(ie.function, minMZ, maxMZ);
    scan.scanWindows.push_back(ScanWindow(minMZ, maxMZ, MS_m_z));

    if (detailLevel < DetailLevel_FastMetadata)
        return result;

    const RawData::ExtendedScanStatsByName& extendedScanStatsByName = rawdata_->GetExtendedScanStats(ie.function);

    // block >= 0 is ion mobility
    if (ie.block >= 0)
    {
        double driftTime = rawdata_->GetDriftTime(ie.function, ie.block, ie.scan);
        scan.set(MS_ion_mobility_drift_time, driftTime, UO_millisecond);
    }

    if (msLevel > 1)
    {
        RawData::ExtendedScanStatsByName::const_iterator setMassItr = extendedScanStatsByName.find("Set Mass");
        if (setMassItr != extendedScanStatsByName.end())
        {
            size_t tofScanIndex = ie.block >= 0 ? std::min(setMassItr->second.size()-1, (size_t) ie.block) : ie.scan;

            float setMass = boost::any_cast<float>(setMassItr->second[tofScanIndex]);
            if (setMass > 0)
            {
                Precursor precursor;
                SelectedIon selectedIon(setMass);
                precursor.isolationWindow.set(MS_isolation_window_target_m_z, setMass, MS_m_z);

                precursor.activation.set(MS_beam_type_collision_induced_dissociation); // AFAIK there is no Waters instrument with a trap collision cell

                RawData::ExtendedScanStatsByName::const_iterator ceItr = extendedScanStatsByName.find("Collision Energy");
                if (ceItr != extendedScanStatsByName.end() &&
                    boost::any_cast<float>(ceItr->second[tofScanIndex]) > 0)
                    precursor.activation.set(MS_collision_energy, boost::any_cast<float>(ceItr->second[tofScanIndex]), UO_electronvolt);

                precursor.selectedIons.push_back(selectedIon);
                result->precursors.push_back(precursor);
            }
        }
    }

    if (detailLevel < DetailLevel_FullMetadata)
        return result;

    if (detailLevel == DetailLevel_FullData || detailLevel == DetailLevel_FullMetadata)
    {
        vector<float> masses, intensities;

        if (ie.block >= 0)
        {
            MassLynxRawScanReader& scanReader = rawdata_->GetCompressedDataClusterForBlock(ie.function, ie.block);
            scanReader.readSpectrum(ie.function, ie.block, ie.scan, masses, intensities);
            result->defaultArrayLength = masses.size();

            if (detailLevel == DetailLevel_FullMetadata)
                return result;
        }
        else // not ion mobility
        {
            if (detailLevel != DetailLevel_FullMetadata)
                rawdata_->ScanReader.readSpectrum(ie.function, ie.scan, masses, intensities);
        }

	    vector<double> mzArray(masses.begin(), masses.end());
        vector<double> intensityArray(intensities.begin(), intensities.end());
	    result->swapMZIntensityArrays(mzArray, intensityArray, MS_number_of_detector_counts); // Donate mass and intensity buffers to result vectors
    }

    return result;
}

PWIZ_API_DECL void SpectrumList_Waters::initializeCoefficients() const
{
    if (calibrationCoefficients_.empty())
    {
        // the header property is something like: 6.08e-3,9.99e-1,-2.84e-6,7.63e-8,-6.91e-10,T1
        string coefficients = rawdata_->GetHeaderProp("Cal Function 1");
        vector<string> tokens;
        bal::split(tokens, coefficients, bal::is_any_of(","));
        if (tokens.size() < 5) // I don't know what the T1 is for, but it doesn't seem important
            throw runtime_error("[SpectrumList_Waters::spectrum()] error parsing calibration coefficients: " + coefficients);
        calibrationCoefficients_.resize(5);
        try
        {
            for (size_t i=0; i < 5; ++i)
                calibrationCoefficients_[i] = lexical_cast<double>(tokens[i]);
        }
        catch (bad_lexical_cast&)
        {
            throw runtime_error("[SpectrumList_Waters::spectrum()] error parsing calibration coefficients: " + coefficients);
        }
    }

}

PWIZ_API_DECL double SpectrumList_Waters::calibrate(const double& mz) const
{
    const vector<double>& c = calibrationCoefficients_;
    double sqrtMz = sqrt(mz);
    double x = c[0] + c[1]*sqrtMz + c[2]*mz + c[3]*mz*sqrtMz + c[4]*mz*mz;
    return x*x;
}

PWIZ_API_DECL pwiz::analysis::Spectrum3DPtr SpectrumList_Waters::spectrum3d(double scanStartTime, const boost::icl::interval_set<double>& driftTimeRanges) const
{
    pwiz::analysis::Spectrum3DPtr result(new pwiz::analysis::Spectrum3D);

    if (scanTimeToFunctionAndBlockMap_.empty()) // implies no ion mobility data
        return result;

    boost::container::flat_map<double, vector<pair<int, int> > >::const_iterator findItr = scanTimeToFunctionAndBlockMap_.lower_bound(floor(scanStartTime * 1e6) / 1e6);
    if (findItr == scanTimeToFunctionAndBlockMap_.end() || findItr->first - 1e-6 > scanStartTime)
        return result;

    for (size_t pair = 0; pair < findItr->second.size(); ++pair)
    {
        int function = findItr->second[pair].first;
        int block = findItr->second[pair].first;

        int axisLength = 0, nonZeroDataPoints = 0, numScansInBlock = 0;

        MassLynxRawScanReader& cdc = rawdata_->GetCompressedDataClusterForBlock(function, block);
        vector<float>& imsMasses = imsMasses_;
        vector<float>& imsIntensities = imsIntensities_;

        numScansInBlock = rawdata_->Info.GetDriftScansInFunction(function);

        for (int scan = 0; scan < numScansInBlock; ++scan)
        {
            double driftTime = rawdata_->GetDriftTime(function, block, scan);

            if (driftTimeRanges.find(driftTime) == driftTimeRanges.end())
                continue;

            cdc.readSpectrum(function, block, scan, imsMasses, imsIntensities);

            boost::container::flat_map<double, float>& driftSpectrum = (*result)[driftTime];

            //driftSpectrum[imsCalibratedMasses_[imsMasses[0] - 1]] = 0;
            for (int i = 0, end = imsMasses.size(); i < end; ++i)
            {
                driftSpectrum[imsMasses[i]] = imsIntensities[i];
            }
            //driftSpectrum[imsCalibratedMasses_[massIndices[nonZeroDataPoints - 1] + 1]] = 0;
        }
    }

    return result;
}

PWIZ_API_DECL void SpectrumList_Waters::createIndex()
{
    using namespace boost::spirit::karma;

    map<double, std::pair<int, int> > functionAndScanByRetentionTime;

    int numScansInBlock = 0;   // number of drift scans per compressed block

    BOOST_FOREACH(int function, rawdata_->FunctionIndexList())
    {
        int msLevel;
        CVID spectrumType;

        try { translateFunctionType(WatersToPwizFunctionType(rawdata_->Info.GetFunctionType(function)), msLevel, spectrumType); }
        catch(...) // unable to translate function type
        {
            cerr << "[SpectrumList_Waters::createIndex] Unable to translate function type \"" + rawdata_->Info.GetFunctionTypeString(function) + "\"" << endl;
            continue;
        }

        if (spectrumType == MS_SRM_spectrum ||
            spectrumType == MS_SIM_spectrum ||
            spectrumType == MS_constant_neutral_loss_spectrum ||
            spectrumType == MS_constant_neutral_gain_spectrum)
            continue;

        int scanCount = rawdata_->Info.GetScansInFunction(function);

        const vector<MSScanStats>& scanStats = rawdata_->GetAllScanStatsForFunction(function);
        if (scanStats.size() != scanCount)
            throw runtime_error("[SpectrumList_Waters::createIndex] scanStats.size() not equal to scanCount");

        if (!config_.combineIonMobilitySpectra && rawdata_->IonMobilityByFunctionIndex()[function])
        {
            numScansInBlock = rawdata_->Info.GetDriftScansInFunction(function);

            scanTimeToFunctionAndBlockMap_.reserve(scanCount);

            for (int i = 0; i < scanCount; ++i)
                scanTimeToFunctionAndBlockMap_[scanStats[i].rt * 60].push_back(make_pair(function, i));
        }
        else
        {
            for (int i=0; i < scanCount; ++i)
                functionAndScanByRetentionTime[scanStats[i].rt] = make_pair(function, i);
        }
    }

    typedef pair<int, int> FunctionScanPair;
    BOOST_FOREACH_FIELD((double rt)(const FunctionScanPair& functionScanPair), functionAndScanByRetentionTime)
    {
        index_.push_back(IndexEntry());
        IndexEntry& ie = index_.back();
        ie.function = functionScanPair.first;
        ie.process = 0;
        ie.block = -1; // block < 0 is not ion mobility
        ie.scan = functionScanPair.second;
        ie.index = index_.size() - 1;

        std::back_insert_iterator<std::string> sink(ie.id);
        generate(sink,
                 "function=" << int_ << " process=" << int_ << " scan=" << int_,
                 (ie.function + 1), ie.process, (ie.scan + 1));
        idToIndexMap_[ie.id] = ie.index;
    }

    BOOST_FOREACH_FIELD((double rt)(const vector<FunctionScanPair>& functionBlockPairs), scanTimeToFunctionAndBlockMap_)
    {
        BOOST_FOREACH(const FunctionScanPair& functionBlockPair, functionBlockPairs)
        {
            for (int j = 0; j < numScansInBlock; ++j)
            {
                index_.push_back(IndexEntry());
                IndexEntry& ie = index_.back();
                ie.function = functionBlockPair.first;
                ie.process = 0;
                ie.block = functionBlockPair.second;
                ie.scan = j;
                ie.index = index_.size() - 1;

                std::back_insert_iterator<std::string> sink(ie.id);
                generate(sink,
                         "function=" << int_ << " process=" << int_ << " scan=" << int_,
                         (ie.function + 1), ie.process, ((numScansInBlock*ie.block) + ie.scan + 1));
                idToIndexMap_[ie.id] = ie.index;
            }
        }
    }

    size_ = index_.size();
}

} // detail
} // msdata
} // pwiz

#else // PWIZ_READER_WATERS

//
// non-MSVC implementation
//

namespace pwiz {
namespace msdata {
namespace detail {

namespace {const SpectrumIdentity emptyIdentity;}

size_t SpectrumList_Waters::size() const {return 0;}
const SpectrumIdentity& SpectrumList_Waters::spectrumIdentity(size_t index) const {return emptyIdentity;}
size_t SpectrumList_Waters::find(const std::string& id) const {return 0;}
SpectrumPtr SpectrumList_Waters::spectrum(size_t index, bool getBinaryData) const {return SpectrumPtr();}
SpectrumPtr SpectrumList_Waters::spectrum(size_t index, DetailLevel detailLevel) const { return SpectrumPtr(); }
SpectrumPtr SpectrumList_Waters::spectrum(size_t index, bool getBinaryData, double lockmassMzPosScans, double lockmassMzNegScans, double lockmassTolerance) const { return SpectrumPtr(); }
SpectrumPtr SpectrumList_Waters::spectrum(size_t index, DetailLevel detailLevel, double lockmassMzPosScans, double lockmassMzNegScans, double lockmassTolerance) const { return SpectrumPtr(); }
PWIZ_API_DECL pwiz::analysis::Spectrum3DPtr SpectrumList_Waters::spectrum3d(double scanStartTime, const boost::icl::interval_set<double>& driftTimeRanges) const { return pwiz::analysis::Spectrum3DPtr(); }

} // detail
} // msdata
} // pwiz

#endif // PWIZ_READER_WATERS

max_stars_repo_name: shze/pwizard-deb

max_issues_repo_name: shze/pwizard-deb

max_forks_repo_name: shze/pwizard-deb


text: #include <boost/asio/windows/stream_handle_service.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#ifndef octomap_trigger_hpp_
#define octomap_trigger_hpp_

#include <lcm/lcm.h>
#include <Eigen/Dense>
#include <Eigen/StdVector>

struct Isometry3dTime{
  Isometry3dTime(int64_t utime, const Eigen::Isometry3d & pose) : utime(utime), pose(pose) {}
    int64_t utime;
    Eigen::Isometry3d pose;
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};

///////////////////////////////////////////////////////////////
class octomap_trigger{
  public:
    octomap_trigger(lcm_t* publish_lcm,lcm_t* subscribe_lcm);

    int initialize(int argc, char **argv);

    ~octomap_trigger(){
    }

  private:
    lcm_t* publish_lcm_;
    lcm_t* subscribe_lcm_;
    BotParam *param;
    BotFrames *frames;

    bot_core_pose_t *bot_pose_last;

    int64_t         last_velodyne_data_utime;
    int64_t           last_pose_utime;

    Isometry3dTime current_poseT;
    bool current_pose_init; // have we started
    Isometry3dTime null_poseT;
    Isometry3dTime local_poseT; // LIDAR pose where we started the most recent local map

    // Fixed transform [initally hardcoded]:
    Eigen::Isometry3d camera_to_lidar;

    // Params for new ocotomap:
    double xdim_,ydim_, zdim_;
    double res_;
    int id_;

    static void pose_handler_aux(const lcm_recv_buf_t* rbuf,
                                const char* channel,
                                const bot_core_pose_t* msg,
                                void* user_data) {
      ((octomap_trigger *) user_data)->pose_handler(msg);
    }
    void pose_handler(const bot_core_pose_t *msg);

};

#endif

max_stars_repo_name: liangfok/oh-distro

max_issues_repo_name: liangfok/oh-distro

max_forks_repo_name: liangfok/oh-distro


text:
// generate by pypp <https://github.com/mugwort-rc/pypp>
// original source code: SPK_Plane.h

#include <Extensions/Zones/SPK_Plane.h>
#include <boost/python.hpp>

class PlaneWrapper :
	public SPK::Plane,
	public boost::python::wrapper<SPK::Plane>
{
public:
	using SPK::Plane::Plane;
	std::string getClassName() const {
		if (auto getClassName = this->get_override("getClassName")) {
			return getClassName();
		}
		else {
			return Plane::getClassName();
		}
	}
	void generatePosition(SPK::Particle & particle, bool full) const {
		if (auto generatePosition = this->get_override("generatePosition")) {
			generatePosition(particle, full);
		}
		else {
			Plane::generatePosition(particle, full);
		}
	}
	bool contains(const SPK::Vector3D & v) const {
		if (auto contains = this->get_override("contains")) {
			return contains(v);
		}
		else {
			return Plane::contains(v);
		}
	}
	bool intersects(const SPK::Vector3D & v0, const SPK::Vector3D & v1, SPK::Vector3D * intersection, SPK::Vector3D * normal) const {
		if (auto intersects = this->get_override("intersects")) {
			return intersects(v0, v1, intersection, normal);
		}
		else {
			return Plane::intersects(v0, v1, intersection, normal);
		}
	}
	void moveAtBorder(SPK::Vector3D & v, bool inside) const {
		if (auto moveAtBorder = this->get_override("moveAtBorder")) {
			moveAtBorder(v, inside);
		}
		else {
			Plane::moveAtBorder(v, inside);
		}
	}
	SPK::Vector3D computeNormal(const SPK::Vector3D & point) const {
		if (auto computeNormal = this->get_override("computeNormal")) {
			return computeNormal(point);
		}
		else {
			return Plane::computeNormal(point);
		}
	}
	void innerUpdateTransform() {
		if (auto innerUpdateTransform = this->get_override("_innerUpdateTransform")) {
			innerUpdateTransform();
		}
		else {
			Plane::innerUpdateTransform();
		}
	}
};

BOOST_PYTHON_FUNCTION_OVERLOADS(create_orverload, SPK::Plane::create, 0, 2)

void init_SPK_Plane_h() {

	boost::python::class_<PlaneWrapper, boost::python::bases<SPK::Zone>, std::shared_ptr<SPK::Plane>>("Plane",
		boost::python::init<boost::python::optional<const SPK::Vector3D &, const SPK::Vector3D &>>(
			":brief: Constructor of Plane\n"
			":param position: the position of the Plane\n"
			":param normal: the normal of the Plane\n"))
		.def("getClassName", &SPK::Plane::getClassName)
		.def("create", &SPK::Plane::create, create_orverload(
			":brief: Creates and registers a new Plane\n"
			":param position: the position of the Plane\n"
			":param normal: the normal of the Plane\n"
			":return: a new registered plane\n"
			":since: 1.04.00\n")
			[boost::python::return_value_policy<boost::python::reference_existing_object>()])
		.def("setNormal", &SPK::Plane::setNormal,
			":brief: Sets the normal of this Plane\n"
			"\n"
			"Note that the normal is normalized internally.\n"
			"\n"
			":param normal:  the normal of this Plane\n")
		.def("getNormal", &SPK::Plane::getNormal,
			":brief: Gets the normal of this Plane\n"
			":return: the normal of this Plane\n",
			boost::python::return_value_policy<boost::python::copy_const_reference>())
		.def("getTransformedNormal", &SPK::Plane::getTransformedNormal,
			":brief: Gets the transformed normal of this Plane\n"
			":return: the transformed normal of this Plane\n"
			":since: 1.05.00\n",
			boost::python::return_value_policy<boost::python::copy_const_reference>())
		.def("generatePosition", &SPK::Plane::generatePosition)
		.def("contains", &SPK::Plane::contains)
		.def("intersects", &SPK::Plane::intersects)
		.def("moveAtBorder", &SPK::Plane::moveAtBorder)
		.def("computeNormal", &SPK::Plane::computeNormal)
		.staticmethod("create")
		;
}

max_stars_repo_name: chromia/pyspk

max_issues_repo_name: chromia/pyspk

max_forks_repo_name: chromia/pyspk


text:
#if !defined(BOOST_PP_IS_ITERATING)

///// header body

#ifndef BOOST_MPL_QUOTE_HPP_INCLUDED
#define BOOST_MPL_QUOTE_HPP_INCLUDED

// Copyright Aleksey Gurtovoy 2000-2008
//
// 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/mpl for documentation.

// $Id$
// $Date$
// $Revision$

#if !defined(BOOST_MPL_PREPROCESSING_MODE)
#   include <boost/mpl/void.hpp>
#   include <boost/mpl/aux_/has_type.hpp>
#endif

#include <boost/mpl/aux_/config/bcc.hpp>
#include <boost/mpl/aux_/config/ttp.hpp>

#if defined(BOOST_MPL_CFG_NO_TEMPLATE_TEMPLATE_PARAMETERS) \
    && !defined(BOOST_MPL_CFG_BCC590_WORKAROUNDS)
#   define BOOST_MPL_CFG_NO_QUOTE_TEMPLATE
#endif

#if !defined(BOOST_MPL_CFG_NO_IMPLICIT_METAFUNCTIONS) \
    && defined(BOOST_MPL_CFG_NO_HAS_XXX)
#   define BOOST_MPL_CFG_NO_IMPLICIT_METAFUNCTIONS
#endif

#include <boost/mpl/aux_/config/use_preprocessed.hpp>

#if !defined(BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS) \
 && !defined(BOOST_MPL_PREPROCESSING_MODE)

#   define BOOST_MPL_PREPROCESSED_HEADER quote.hpp
#   include <boost/mpl/aux_/include_preprocessed.hpp>

#else

#   include <boost/mpl/limits/arity.hpp>
#   include <boost/mpl/aux_/preprocessor/params.hpp>
#   include <boost/mpl/aux_/config/ctps.hpp>
#   include <boost/mpl/aux_/config/workaround.hpp>

#   include <boost/preprocessor/iterate.hpp>
#   include <boost/preprocessor/cat.hpp>

#if !defined(BOOST_MPL_CFG_NO_QUOTE_TEMPLATE)

namespace boost { namespace mpl {

#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)

template< typename T, bool has_type_ >
struct quote_impl
// GCC has a problem with metafunction forwarding when T is a
// specialization of a template called 'type'.
# if BOOST_WORKAROUND(__GNUC__, BOOST_TESTED_AT(4)) \
    && BOOST_WORKAROUND(__GNUC_MINOR__, BOOST_TESTED_AT(0)) \
    && BOOST_WORKAROUND(__GNUC_PATCHLEVEL__, BOOST_TESTED_AT(2))
{
    typedef typename T::type type;
};
# else
    : T
{
};
# endif

template< typename T >
struct quote_impl<T,false>
{
    typedef T type;
};

#else // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION

template< bool > struct quote_impl
{
    template< typename T > struct result_
        : T
    {
    };
};

template<> struct quote_impl<false>
{
    template< typename T > struct result_
    {
        typedef T type;
    };
};

#endif

#define BOOST_PP_ITERATION_PARAMS_1 \
    (3,(1, BOOST_MPL_LIMIT_METAFUNCTION_ARITY, <boost/mpl/quote.hpp>))
#include BOOST_PP_ITERATE()

}}

#endif // BOOST_MPL_CFG_NO_QUOTE_TEMPLATE

#endif // BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS
#endif // BOOST_MPL_QUOTE_HPP_INCLUDED

///// iteration

#else
#define i_ BOOST_PP_FRAME_ITERATION(1)

template<
      template< BOOST_MPL_PP_PARAMS(i_, typename P) > class F
    , typename Tag = void_
    >
struct BOOST_PP_CAT(quote,i_)
{
    template< BOOST_MPL_PP_PARAMS(i_, typename U) > struct apply
#if defined(BOOST_MPL_CFG_BCC590_WORKAROUNDS)
    {
        typedef typename quote_impl<
              F< BOOST_MPL_PP_PARAMS(i_, U) >
            , aux::has_type< F< BOOST_MPL_PP_PARAMS(i_, U) > >::value
            >::type type;
    };
#elif !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
        : quote_impl<
              F< BOOST_MPL_PP_PARAMS(i_, U) >
            , aux::has_type< F< BOOST_MPL_PP_PARAMS(i_, U) > >::value
            >
    {
    };
#else
        : quote_impl< aux::has_type< F< BOOST_MPL_PP_PARAMS(i_, U) > >::value >
            ::template result_< F< BOOST_MPL_PP_PARAMS(i_, U) > >
    {
    };
#endif
};

#undef i_
#endif // BOOST_PP_IS_ITERATING


text:
#ifndef BOOST_THREAD_CONDITION_VARIABLE_PTHREAD_HPP
#define BOOST_THREAD_CONDITION_VARIABLE_PTHREAD_HPP
// 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)
// (C) Copyright 2007-10 Anthony Williams
// (C) Copyright 2011-2012 Vicente J. Botet Escriba

#include <boost/thread/detail/platform_time.hpp>
#include <boost/thread/pthread/pthread_mutex_scoped_lock.hpp>
#include <boost/thread/pthread/pthread_helpers.hpp>

#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
#include <boost/thread/interruption.hpp>
#include <boost/thread/pthread/thread_data.hpp>
#endif
#include <boost/thread/pthread/condition_variable_fwd.hpp>
#ifdef BOOST_THREAD_USES_CHRONO
#include <boost/chrono/system_clocks.hpp>
#include <boost/chrono/ceil.hpp>
#endif
#include <boost/thread/detail/delete.hpp>

#include <algorithm>

#include <boost/config/abi_prefix.hpp>

namespace boost
{
    namespace thread_cv_detail
    {
        template<typename MutexType>
        struct lock_on_exit
        {
            MutexType* m;

            lock_on_exit():
                m(0)
            {}

            void activate(MutexType& m_)
            {
                m_.unlock();
                m=&m_;
            }
            void deactivate()
            {
                if (m)
                {
                    m->lock();
                }
                m = 0;
            }
            ~lock_on_exit() BOOST_NOEXCEPT_IF(false)
            {
                if (m)
                {
                    m->lock();
                }
           }
        };
    }

    inline void condition_variable::wait(unique_lock<mutex>& m)
    {
#if defined BOOST_THREAD_THROW_IF_PRECONDITION_NOT_SATISFIED
        if(! m.owns_lock())
        {
            boost::throw_exception(condition_error(-1, "boost::condition_variable::wait() failed precondition mutex not owned"));
        }
#endif
        int res=0;
        {
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
            thread_cv_detail::lock_on_exit<unique_lock<mutex> > guard;
            detail::interruption_checker check_for_interruption(&internal_mutex,&cond);
            pthread_mutex_t* the_mutex = &internal_mutex;
            guard.activate(m);
            res = posix::pthread_cond_wait(&cond,the_mutex);
            check_for_interruption.unlock_if_locked();
            guard.deactivate();
#else
            pthread_mutex_t* the_mutex = m.mutex()->native_handle();
            res = posix::pthread_cond_wait(&cond,the_mutex);
#endif
        }
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
        this_thread::interruption_point();
#endif
        if(res)
        {
            boost::throw_exception(condition_error(res, "boost::condition_variable::wait failed in pthread_cond_wait"));
        }
    }

    // When this function returns true:
    // * A notification (or sometimes a spurious OS signal) has been received
    // * Do not assume that the timeout has not been reached
    // * Do not assume that the predicate has been changed
    //
    // When this function returns false:
    // * The timeout has been reached
    // * Do not assume that a notification has not been received
    // * Do not assume that the predicate has not been changed
    inline bool condition_variable::do_wait_until(
                unique_lock<mutex>& m,
                detail::internal_platform_timepoint const &timeout)
    {
#if defined BOOST_THREAD_THROW_IF_PRECONDITION_NOT_SATISFIED
        if (!m.owns_lock())
        {
            boost::throw_exception(condition_error(EPERM, "boost::condition_variable::do_wait_until() failed precondition mutex not owned"));
        }
#endif
        int cond_res;
        {
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
            thread_cv_detail::lock_on_exit<unique_lock<mutex> > guard;
            detail::interruption_checker check_for_interruption(&internal_mutex,&cond);
            pthread_mutex_t* the_mutex = &internal_mutex;
            guard.activate(m);
            cond_res=posix::pthread_cond_timedwait(&cond,the_mutex,&timeout.getTs());
            check_for_interruption.unlock_if_locked();
            guard.deactivate();
#else
            pthread_mutex_t* the_mutex = m.mutex()->native_handle();
            cond_res=posix::pthread_cond_timedwait(&cond,the_mutex,&timeout.getTs());
#endif
        }
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
        this_thread::interruption_point();
#endif
        if(cond_res==ETIMEDOUT)
        {
            return false;
        }
        if(cond_res)
        {
            boost::throw_exception(condition_error(cond_res, "boost::condition_variable::do_wait_until failed in pthread_cond_timedwait"));
        }
        return true;
    }

    inline void condition_variable::notify_one() BOOST_NOEXCEPT
    {
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
        boost::pthread::pthread_mutex_scoped_lock internal_lock(&internal_mutex);
#endif
        BOOST_VERIFY(!posix::pthread_cond_signal(&cond));
    }

    inline void condition_variable::notify_all() BOOST_NOEXCEPT
    {
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
        boost::pthread::pthread_mutex_scoped_lock internal_lock(&internal_mutex);
#endif
        BOOST_VERIFY(!posix::pthread_cond_broadcast(&cond));
    }

    class condition_variable_any
    {
        pthread_mutex_t internal_mutex;
        pthread_cond_t cond;

    public:
        BOOST_THREAD_NO_COPYABLE(condition_variable_any)
        condition_variable_any()
        {
            int const res=posix::pthread_mutex_init(&internal_mutex);
            if(res)
            {
                boost::throw_exception(thread_resource_error(res, "boost::condition_variable_any::condition_variable_any() failed in pthread_mutex_init"));
            }
            int const res2 = posix::pthread_cond_init(&cond);
            if(res2)
            {
                BOOST_VERIFY(!posix::pthread_mutex_destroy(&internal_mutex));
                boost::throw_exception(thread_resource_error(res2, "boost::condition_variable_any::condition_variable_any() failed in pthread_cond_init"));
            }
        }
        ~condition_variable_any()
        {
            BOOST_VERIFY(!posix::pthread_mutex_destroy(&internal_mutex));
            BOOST_VERIFY(!posix::pthread_cond_destroy(&cond));
        }

        template<typename lock_type>
        void wait(lock_type& m)
        {
            int res=0;
            {
                thread_cv_detail::lock_on_exit<lock_type> guard;
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
                detail::interruption_checker check_for_interruption(&internal_mutex,&cond);
#else
                boost::pthread::pthread_mutex_scoped_lock check_for_interruption(&internal_mutex);
#endif
                guard.activate(m);
                res=posix::pthread_cond_wait(&cond,&internal_mutex);
                check_for_interruption.unlock_if_locked();
                guard.deactivate();
            }
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
            this_thread::interruption_point();
#endif
            if(res)
            {
                boost::throw_exception(condition_error(res, "boost::condition_variable_any::wait() failed in pthread_cond_wait"));
            }
        }

        template<typename lock_type,typename predicate_type>
        void wait(lock_type& m,predicate_type pred)
        {
            while (!pred())
            {
                wait(m);
            }
        }

#if defined BOOST_THREAD_USES_DATETIME
        template<typename lock_type>
        bool timed_wait(lock_type& m,boost::system_time const& abs_time)
        {
#if defined BOOST_THREAD_WAIT_BUG
            const detail::real_platform_timepoint ts(abs_time + BOOST_THREAD_WAIT_BUG);
#else
            const detail::real_platform_timepoint ts(abs_time);
#endif
#if defined BOOST_THREAD_INTERNAL_CLOCK_IS_MONO
            // The system time may jump while this function is waiting. To compensate for this and time
            // out near the correct time, we could call do_wait_until() in a loop with a short timeout
            // and recheck the time remaining each time through the loop. However, because we can't
            // check the predicate each time do_wait_until() completes, this introduces the possibility
            // of not exiting the function when a notification occurs, since do_wait_until() may report
            // that it timed out even though a notification was received. The best this function can do
            // is report correctly whether or not it reached the timeout time.
            const detail::platform_duration d(ts - detail::real_platform_clock::now());
            do_wait_until(m, detail::internal_platform_clock::now() + d);
            return ts > detail::real_platform_clock::now();
#else
            return do_wait_until(m, ts);
#endif
        }
        template<typename lock_type>
        bool timed_wait(lock_type& m,::boost::xtime const& abs_time)
        {
            return timed_wait(m,system_time(abs_time));
        }

        template<typename lock_type,typename duration_type>
        bool timed_wait(lock_type& m,duration_type const& wait_duration)
        {
            if (wait_duration.is_pos_infinity())
            {
                wait(m);
                return true;
            }
            if (wait_duration.is_special())
            {
                return true;
            }
            detail::platform_duration d(wait_duration);
#if defined(BOOST_THREAD_HAS_MONO_CLOCK) && !defined(BOOST_THREAD_INTERNAL_CLOCK_IS_MONO)
            // The system time may jump while this function is waiting. To compensate for this and time
            // out near the correct time, we could call do_wait_until() in a loop with a short timeout
            // and recheck the time remaining each time through the loop. However, because we can't
            // check the predicate each time do_wait_until() completes, this introduces the possibility
            // of not exiting the function when a notification occurs, since do_wait_until() may report
            // that it timed out even though a notification was received. The best this function can do
            // is report correctly whether or not it reached the timeout time.
            const detail::mono_platform_timepoint ts(detail::mono_platform_clock::now() + d);
            do_wait_until(m, detail::internal_platform_clock::now() + d);
            return ts > detail::mono_platform_clock::now();
#else
            return do_wait_until(m, detail::internal_platform_clock::now() + d);
#endif
        }

        template<typename lock_type,typename predicate_type>
        bool timed_wait(lock_type& m,boost::system_time const& abs_time, predicate_type pred)
        {
#if defined BOOST_THREAD_WAIT_BUG
            const detail::real_platform_timepoint ts(abs_time + BOOST_THREAD_WAIT_BUG);
#else
            const detail::real_platform_timepoint ts(abs_time);
#endif
            while (!pred())
            {
#if defined BOOST_THREAD_INTERNAL_CLOCK_IS_MONO
                // The system time may jump while this function is waiting. To compensate for this
                // and time out near the correct time, we call do_wait_until() in a loop with a
                // short timeout and recheck the time remaining each time through the loop.
                detail::platform_duration d(ts - detail::real_platform_clock::now());
                if (d <= detail::platform_duration::zero()) break; // timeout occurred
                d = (std::min)(d, detail::platform_milliseconds(BOOST_THREAD_POLL_INTERVAL_MILLISECONDS));
                do_wait_until(m, detail::internal_platform_clock::now() + d);
#else
                if (!do_wait_until(m, ts)) break; // timeout occurred
#endif
            }
            return pred();
        }

        template<typename lock_type,typename predicate_type>
        bool timed_wait(lock_type& m,::boost::xtime const& abs_time, predicate_type pred)
        {
            return timed_wait(m,system_time(abs_time),pred);
        }

        template<typename lock_type,typename duration_type,typename predicate_type>
        bool timed_wait(lock_type& m,duration_type const& wait_duration,predicate_type pred)
        {
            if (wait_duration.is_pos_infinity())
            {
                while (!pred())
                {
                    wait(m);
                }
                return true;
            }
            if (wait_duration.is_special())
            {
                return pred();
            }
            detail::platform_duration d(wait_duration);
#if defined(BOOST_THREAD_HAS_MONO_CLOCK) && !defined(BOOST_THREAD_INTERNAL_CLOCK_IS_MONO)
            // The system time may jump while this function is waiting. To compensate for this
            // and time out near the correct time, we call do_wait_until() in a loop with a
            // short timeout and recheck the time remaining each time through the loop.
            const detail::mono_platform_timepoint ts(detail::mono_platform_clock::now() + d);
            while (!pred())
            {
                if (d <= detail::platform_duration::zero()) break; // timeout occurred
                d = (std::min)(d, detail::platform_milliseconds(BOOST_THREAD_POLL_INTERVAL_MILLISECONDS));
                do_wait_until(m, detail::internal_platform_clock::now() + d);
                d = ts - detail::mono_platform_clock::now();
            }
#else
            const detail::internal_platform_timepoint ts(detail::internal_platform_clock::now() + d);
            while (!pred())
            {
                if (!do_wait_until(m, ts)) break; // timeout occurred
            }
#endif
            return pred();
        }
#endif

#ifdef BOOST_THREAD_USES_CHRONO
        template <class lock_type,class Duration>
        cv_status
        wait_until(
                lock_type& lock,
                const chrono::time_point<detail::internal_chrono_clock, Duration>& t)
        {
            const boost::detail::internal_platform_timepoint ts(t);
            if (do_wait_until(lock, ts)) return cv_status::no_timeout;
            else return cv_status::timeout;
        }

        template <class lock_type, class Clock, class Duration>
        cv_status
        wait_until(
                lock_type& lock,
                const chrono::time_point<Clock, Duration>& t)
        {
            // The system time may jump while this function is waiting. To compensate for this and time
            // out near the correct time, we could call do_wait_until() in a loop with a short timeout
            // and recheck the time remaining each time through the loop. However, because we can't
            // check the predicate each time do_wait_until() completes, this introduces the possibility
            // of not exiting the function when a notification occurs, since do_wait_until() may report
            // that it timed out even though a notification was received. The best this function can do
            // is report correctly whether or not it reached the timeout time.
            typedef typename common_type<Duration, typename Clock::duration>::type common_duration;
            common_duration d(t - Clock::now());
            do_wait_until(lock, detail::internal_chrono_clock::now() + d);
            if (t > Clock::now()) return cv_status::no_timeout;
            else return cv_status::timeout;
        }

        template <class lock_type, class Rep, class Period>
        cv_status
        wait_for(
                lock_type& lock,
                const chrono::duration<Rep, Period>& d)
        {
            return wait_until(lock, chrono::steady_clock::now() + d);
        }

        template <class lock_type, class Duration, class Predicate>
        bool
        wait_until(
                lock_type& lock,
                const chrono::time_point<detail::internal_chrono_clock, Duration>& t,
                Predicate pred)
        {
            const detail::internal_platform_timepoint ts(t);
            while (!pred())
            {
                if (!do_wait_until(lock, ts)) break; // timeout occurred
            }
            return pred();
        }

        template <class lock_type, class Clock, class Duration, class Predicate>
        bool
        wait_until(
                lock_type& lock,
                const chrono::time_point<Clock, Duration>& t,
                Predicate pred)
        {
            // The system time may jump while this function is waiting. To compensate for this
            // and time out near the correct time, we call do_wait_until() in a loop with a
            // short timeout and recheck the time remaining each time through the loop.
            typedef typename common_type<Duration, typename Clock::duration>::type common_duration;
            while (!pred())
            {
                common_duration d(t - Clock::now());
                if (d <= common_duration::zero()) break; // timeout occurred
                d = (std::min)(d, common_duration(chrono::milliseconds(BOOST_THREAD_POLL_INTERVAL_MILLISECONDS)));
                do_wait_until(lock, detail::internal_platform_clock::now() + detail::platform_duration(d));
            }
            return pred();
        }

        template <class lock_type, class Rep, class Period, class Predicate>
        bool
        wait_for(
                lock_type& lock,
                const chrono::duration<Rep, Period>& d,
                Predicate pred)
        {
            return wait_until(lock, chrono::steady_clock::now() + d, boost::move(pred));
        }
#endif

        void notify_one() BOOST_NOEXCEPT
        {
            boost::pthread::pthread_mutex_scoped_lock internal_lock(&internal_mutex);
            BOOST_VERIFY(!posix::pthread_cond_signal(&cond));
        }

        void notify_all() BOOST_NOEXCEPT
        {
            boost::pthread::pthread_mutex_scoped_lock internal_lock(&internal_mutex);
            BOOST_VERIFY(!posix::pthread_cond_broadcast(&cond));
        }
    private:

        // When this function returns true:
        // * A notification (or sometimes a spurious OS signal) has been received
        // * Do not assume that the timeout has not been reached
        // * Do not assume that the predicate has been changed
        //
        // When this function returns false:
        // * The timeout has been reached
        // * Do not assume that a notification has not been received
        // * Do not assume that the predicate has not been changed
        template <class lock_type>
        bool do_wait_until(
          lock_type& m,
          detail::internal_platform_timepoint const &timeout)
        {
          int res=0;
          {
              thread_cv_detail::lock_on_exit<lock_type> guard;
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
              detail::interruption_checker check_for_interruption(&internal_mutex,&cond);
#else
              boost::pthread::pthread_mutex_scoped_lock check_for_interruption(&internal_mutex);
#endif
              guard.activate(m);
              res=posix::pthread_cond_timedwait(&cond,&internal_mutex,&timeout.getTs());
              check_for_interruption.unlock_if_locked();
              guard.deactivate();
          }
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
          this_thread::interruption_point();
#endif
          if(res==ETIMEDOUT)
          {
              return false;
          }
          if(res)
          {
              boost::throw_exception(condition_error(res, "boost::condition_variable_any::do_wait_until() failed in pthread_cond_timedwait"));
          }
          return true;
        }
    };
}

#include <boost/config/abi_suffix.hpp>

#endif

max_stars_repo_name: kindlychung/mediasoup-sfu-cpp

max_issues_repo_name: kindlychung/mediasoup-sfu-cpp

max_forks_repo_name: kindlychung/mediasoup-sfu-cpp