text:
#include "net/wrtc/Observers.hpp" // IWYU pragma: associated
#include "log/Logger.hpp"
#include "net/NetworkManagerBase.hpp"
#include "net/wrtc/WRTCServer.hpp"
#include "net/wrtc/WRTCSession.hpp"
#include "net/SessionPair.hpp"
#include <boost/beast/http.hpp>
#include <boost/beast/websocket.hpp>
#include <iostream>
#include <string>
#include <thread>
#include <webrtc/api/peerconnectioninterface.h>
#include <webrtc/rtc_base/scoped_ref_ptr.h>

namespace gloer {
namespace net {
namespace wrtc {

void CSDO::OnSuccess(webrtc::SessionDescriptionInterface* sdi) {
  LOG(INFO) << std::this_thread::get_id() << ":"
            << "CreateSessionDescriptionObserver::OnSuccess";

  LOG(WARNING) << "CSDO::OnSuccess as " << (isServer_ ? "server" : "offer");

  if (sdi == nullptr) {
    LOG(WARNING) << "CSDO::OnSuccess INVALID SDI";
    return;
  }

  /*LOG(INFO) << std::this_thread::get_id() << ":"
            << "CreateSessionDescriptionObserver::OnSuccess";
  parent.onSuccessCSD(desc);*/

  if (!nm_->getRunner()) {
    LOG(WARNING) << "empty m_observer";
    return;
  }

  auto spt = wrtcSess_.lock();
  if (spt) {
    if (isServer_) {
      spt->updateDataChannelState();
      spt->onAnswerCreated(sdi);
      spt->updateDataChannelState();
    } else {
      spt->updateDataChannelState();
      spt->onOfferCreated(sdi);
      spt->updateDataChannelState();
    }
  } else {
    LOG(WARNING) << "wrtcSess_ expired";
    return;
  }
}

// PeerConnection cannot create an answer in a state other than have-remote-offer or
// have-local-pranswer
void CSDO::OnFailure(const std::string& error) {
  LOG(WARNING) << std::this_thread::get_id() << ":"
               << "CreateSessionDescriptionObserver::OnFailure\n"
               << error;
  LOG(WARNING) << "CSDO::OnFailure";

  if (!nm_->getRunner()) {
    LOG(WARNING) << "empty m_observer";
    return;
  }

  auto spt = wrtcSess_.lock();
  if (spt) {
    spt->updateDataChannelState();
    spt->setFullyCreated(true); // allows auto-deletion
  } else {
    LOG(WARNING) << "wrtcSess_ expired";
    return;
  }
}

// Change in state of the Data Channel.
void DCO::OnStateChange() {
  LOG(INFO) << std::this_thread::get_id() << ":"
            << "DCO::OnStateChange";

  if (!nm_->getRunner()) {
    LOG(WARNING) << "empty m_observer";
    return;
  }

  // TODO: need it? >>>
  // m_observer->data_channel_count++;

  auto spt = wrtcSess_.lock();
  if (spt) {
    auto wrtcSessId = spt->getId(); // remember id before session deletion
    spt->updateDataChannelState();

    webrtc::DataChannelInterface::DataState state = webrtc::DataChannelInterface::kClosed;

    if (spt && spt->dataChannelI_ && spt->dataChannelI_.get()) {
      state = spt->dataChannelI_->state();
    }

    switch (state) {
    case webrtc::DataChannelInterface::kConnecting: {
      if (spt) {
        RTC_DCHECK(spt->isDataChannelOpen() == false);
        // spt->onDataChannelConnecting();
      }
      LOG(INFO) << "DCO::OnStateChange: data channel connecting!";
      break;
    }
    case webrtc::DataChannelInterface::kOpen: {
      if (spt) {
        RTC_DCHECK(spt->isDataChannelOpen() == true);
        // spt->onDataChannelOpen();
      }

      ////////
      // spt->dataChannelI_->Send(webrtc::DataBuffer("1dsaadsadsasddddd"));

      LOG(INFO) << "DCO::OnStateChange: data channel open!";
      break;
    }
    case webrtc::DataChannelInterface::kClosing: {
      LOG(INFO) << "DCO::OnStateChange: data channel closing!";
      LOG(WARNING) << "webrtc::DataChannelInterface::kClosing";
      if (spt) {
        LOG(WARNING) << "webrtc::DataChannelInterface::kClosing";
        RTC_DCHECK(spt->isDataChannelOpen() == true);
        spt->setFullyCreated(true); // allows auto-deletion
      }
      break;
    }
    case webrtc::DataChannelInterface::kClosed: {
      LOG(WARNING) << "webrtc::DataChannelInterface::kClosed";
      if (spt) {
        RTC_DCHECK(spt->isDataChannelOpen() == false);
        // spt->onDataChannelClose();
      }

      {
        // unregisterSession don`t call CloseDataChannel -> onDataChannelClose
        // because dataChannelI_->state() != webrtc::DataChannelInterface::kClosed
        nm_->sessionManager().unregisterSession(wrtcSessId);
      }

      LOG(INFO) << "DCO::OnStateChange: data channel not open!";
      break;
    }
    default: { LOG(INFO) << "DCO::OnStateChange: unknown data channel state! " << state; }
    }
  } else {
    LOG(WARNING) << "wrtcSess_ expired";
    return;
  }
}

void DCO::OnBufferedAmountChange(uint64_t /* previous_amount */) {

  // TODO https://github.com/vmolsa/libcrtc/blob/master/src/rtcdatachannel.cc#L146
  /*if (_threshold && previous_amount > _threshold && _channel->buffered_amount() < _threshold) {
    onbufferedamountlow();
  }*/

  // TODO
  // https://github.com/RainwayApp/spitfire/blob/dbc65868d71b80f612acd3f4b8b9bd481c4a21df/Spitfire/DataChannelObserver.cpp

  /*
    if (!m_client)
        return;

    if (previousAmount <= m_channel->buffered_amount())
        return;

    callOnMainThread([protectedClient = makeRef(*m_client), amount = m_channel->buffered_amount()] {
        protectedClient->bufferedAmountIsDecreasing(static_cast<size_t>(amount));
    });
   */
}

// Message received.
void DCO::OnMessage(const webrtc::DataBuffer& buffer) {
  const std::string data = std::string(buffer.data.data<char>(), buffer.size());
  LOG(WARNING) << std::this_thread::get_id() << ":"
               << "DCO::OnMessage = " << data;

  if (!nm_->getRunner()) {
    LOG(WARNING) << "empty m_observer";
    return;
  }

  // TODO if (buffer->binary)
  /*
    std::unique_ptr<webrtc::DataBuffer> protectedBuffer(new webrtc::DataBuffer(buffer));
    callOnMainThread([protectedClient = makeRef(*m_client), buffer = WTFMove(protectedBuffer)] {
        const char* data = reinterpret_cast<const char*>(buffer->data.data<char>());
        if (buffer->binary)
            protectedClient->didReceiveRawData(data, buffer->size());
        else
            protectedClient->didReceiveStringData(String::fromUTF8(data, buffer->size()));
    });
   */

  auto spt = wrtcSess_.lock();
  const auto wrtcSessId = spt->getId();
  if (spt) {
    if (spt->isClosing()) {
      // session is closing...
      nm_->sessionManager().unregisterSession(wrtcSessId);
      return;
    }
    spt->onDataChannelMessage(buffer);
  } else {
    LOG(WARNING) << "wrtcSess_ expired";
    return;
  }
}

// Triggered when a remote peer opens a data channel.
void PCO::OnDataChannel(rtc::scoped_refptr<webrtc::DataChannelInterface> channel) {
  LOG(INFO) << std::this_thread::get_id() << ":"
            << "PCO::OnDataChannel";

  RTC_DCHECK(nm_->getRunner() != nullptr);
  if (!nm_->getRunner()) {
    LOG(WARNING) << "empty m_observer";
    return;
  }

  RTC_DCHECK(channel.get() != nullptr);
  if (!channel || !channel.get()) {
    LOG(WARNING) << "OnDataChannel: empty DataChannelInterface";
    return;
  }

  /*auto spt = wrtcSess_.lock();
  if (spt) {
    spt->onDataChannelCreated(channel);
  } else {
    LOG(WARNING) << "wrtcSess_ expired";
  }*/

  LOG(WARNING) << "PCO::OnDataChannel for id = " << static_cast<std::string>(webrtcConnId_);
  std::shared_ptr<WRTCSession> wrtcSess = nm_->sessionManager().getSessById(webrtcConnId_);

  RTC_DCHECK(wrtcSess.get() != nullptr);
  if (wrtcSess == nullptr || !wrtcSess.get()) {
    // LOG(WARNING) << "PCO::OnDataChannel: invalid webrtc session with id = " << static_cast<std::string>(webrtcConnId_);
    nm_->sessionManager().unregisterSession(webrtcConnId_);
    return;
  }

  RTC_DCHECK(wrtcSess.get() != nullptr);
  if (wrtcSess.get()) {
    // calls wrtcSess->updateDataChannelState();
    wrtcSess->onDataChannelCreated(nm_, channel);
  }

  // TODO _manager->onIceCandidate(candidate->sdp_mid().c_str(), candidate->sdp_mline_index(),
  // sdp.c_str());
  // https://github.com/RainwayApp/spitfire/blob/master/Spitfire/PeerConnectionObserver.cpp
}

// Override ICE candidate.
void PCO::OnIceCandidate(const webrtc::IceCandidateInterface* candidate) {
  LOG(INFO) << std::this_thread::get_id() << ":"
            << "PCO::OnIceCandidate";

  RTC_DCHECK(candidate != nullptr);
  if (!candidate) {
    LOG(WARNING) << "OnIceCandidate: empty candidate";
    return;
  }

  // TODO filter candidate->candidate().url()

  RTC_DCHECK(nm_->getRunner() != nullptr);
  if (!nm_->getRunner()) {
    LOG(WARNING) << "OnIceCandidate: empty m_observer";
    return;
  }

  std::shared_ptr<WRTCSession> wrtcSess = nm_->sessionManager().getSessById(webrtcConnId_);
  RTC_DCHECK(wrtcSess.get() != nullptr);
  if (!wrtcSess.get()) {
    LOG(WARNING) << "PCO::OnIceCandidate: invalid webrtc session with id = " << static_cast<std::string>(webrtcConnId_);
    nm_->sessionManager().unregisterSession(webrtcConnId_);
    return;
  }

  RTC_DCHECK(wrtcSess.get() != nullptr);
  if (wrtcSess.get()) {
    wrtcSess->updateDataChannelState();
  }

  WRTCSession::onIceCandidate(nm_, wsSession_.lock(), wsConnId_, candidate);
}

void PCO::OnSignalingChange(webrtc::PeerConnectionInterface::SignalingState new_state) {
  LOG(INFO) << std::this_thread::get_id() << ":"
            << "PeerConnectionObserver::SignalingChange(" << new_state << ")";

  std::string state;
  bool needClose = false;

  switch (new_state) {
    // @see w3c.github.io/webrtc-pc/#state-definitions
  case webrtc::PeerConnectionInterface::SignalingState::kClosed: {
    state = "kClosed";
    needClose = true;
    break;
  }
  case webrtc::PeerConnectionInterface::SignalingState::kStable: {
    /*
     * There is no offer/answer exchange in progress.
     * This is also the initial state,
     * in which case the local and remote descriptions are empty.
     */
    state = "kStable";
    break;
  }
  case webrtc::PeerConnectionInterface::SignalingState::kHaveLocalOffer: {
    state = "kHaveLocalOffer";
    break;
  }
  case webrtc::PeerConnectionInterface::SignalingState::kHaveRemoteOffer: {
    state = "kHaveRemoteOffer";
    break;
  }
  case webrtc::PeerConnectionInterface::SignalingState::kHaveLocalPrAnswer: {
    /*
     * A remote description of type "offer" has been successfully applied
     * and a local description of type "pranswer" has been successfully applied.
     */
    state = "kHaveLocalPrAnswer";
    break;
  }
  case webrtc::PeerConnectionInterface::SignalingState::kHaveRemotePrAnswer: {
    state = "kHaveRemotePrAnswer";
    break;
  }
  default:
    state = "unknown";
    break;
  }

  LOG(INFO) << "OnSignalingChange to " << state;

  {
    std::shared_ptr<WRTCSession> wrtcSess = nm_->sessionManager().getSessById(webrtcConnId_);
    if (wrtcSess && wrtcSess.get()) {
      // LOG(WARNING) << "PCO::OnSignalingChange: invalid webrtc session with id = " <<
      // webrtcConnId_; nm_->getRunner()->unregisterSession(webrtcConnId_); // use needClose

      if (needClose) {
        // LOG(WARNING) << "PCO::OnSignalingChange: closed session with id = " << static_cast<std::string>(webrtcConnId_);
        // wrtcSess->close_s(false); // called from unregisterSession
      }

      wrtcSess->updateDataChannelState();
    }
  }

  if (needClose) {
    nm_->sessionManager().unregisterSession(webrtcConnId_);
  }
}

// Triggered when media is received on a new stream from remote peer.
void PCO::OnAddStream(rtc::scoped_refptr<webrtc::MediaStreamInterface> /* stream*/) {
  LOG(INFO) << std::this_thread::get_id() << ":"
            << "PeerConnectionObserver::AddStream";
}

// Triggered when a remote peer close a stream.
void PCO::OnRemoveStream(rtc::scoped_refptr<webrtc::MediaStreamInterface> /* stream*/) {
  LOG(INFO) << std::this_thread::get_id() << ":"
            << "PeerConnectionObserver::RemoveStream";

  std::shared_ptr<WRTCSession> wrtcSess = nm_->sessionManager().getSessById(webrtcConnId_);
  if (wrtcSess.get()) {
    // LOG(WARNING) << "PCO::OnRemoveStream: invalid webrtc session with id = " <<
    // webrtcConnId_;
    // wrtcSess->close_s(false); // called from unregisterSession
  }
  nm_->sessionManager().unregisterSession(webrtcConnId_);
}

// Triggered when renegotiation is needed. For example, an ICE restart
// has begun.
void PCO::OnRenegotiationNeeded() {
  LOG(INFO) << std::this_thread::get_id() << ":"
            << "PeerConnectionObserver::RenegotiationNeeded";
}

// Called any time the IceConnectionState changes.
//
// Note that our ICE states lag behind the standard slightly. The most
// notable differences include the fact that "failed" occurs after 15
// seconds, not 30, and this actually represents a combination ICE + DTLS
// state, so it may be "failed" if DTLS fails while ICE succeeds.
void PCO::OnIceConnectionChange(webrtc::PeerConnectionInterface::IceConnectionState new_state) {
  LOG(INFO) << std::this_thread::get_id() << ":"
            << "PCO::IceConnectionChange(" << static_cast<int>(new_state) << ")";

  std::string state;
  bool needClose = false;

  switch (new_state) {
    // @see w3c.github.io/webrtc-pc/#rtcpeerconnectionstate-enum
  case webrtc::PeerConnectionInterface::kIceConnectionNew: {
    // Waiting for the other to answer
    state = "kIceConnectionNew";
    break;
  }
  case webrtc::PeerConnectionInterface::kIceConnectionChecking: {
    // Trying to establish a connection with the other
    state = "kIceConnectionChecking";
    break;
  }
  case webrtc::PeerConnectionInterface::kIceConnectionConnected: {
    // 	Established a connection and started a chat
    state = "kIceConnectionConnected";
    break;
  }
  case webrtc::PeerConnectionInterface::kIceConnectionCompleted: {
    // In chat
    state = "kIceConnectionCompleted";
    break;
  }
  case webrtc::PeerConnectionInterface::kIceConnectionFailed: {
    LOG(WARNING) << "PeerConnectionInterface::kIceConnectionFailed";
    state = "kIceConnectionFailed";
    needClose = true;
    break;
  }
  case webrtc::PeerConnectionInterface::kIceConnectionDisconnected: {
    LOG(WARNING) << "PeerConnectionInterface::kIceConnectionDisconnected";
    state = "kIceConnectionDisconnected";
    needClose = true;
    break;
  }
  case webrtc::PeerConnectionInterface::kIceConnectionClosed: {
    LOG(WARNING) << "PeerConnectionInterface::kIceConnectionClosed";
    state = "kIceConnectionClosed";
    needClose = true;
    break;
  }
  case webrtc::PeerConnectionInterface::kIceConnectionMax:
    // TODO
    /* not in
     * developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/iceConnectionState
     */
    {
      LOG(WARNING) << "PeerConnectionInterface::kIceConnectionMax";
      state = "kIceConnectionMax";
      needClose = true;
      break;
    }
  default:
    state = "unknown";
    break;
  }

  LOG(INFO) << "OnIceConnectionChange to " << state;

  {
    std::shared_ptr<WRTCSession> wrtcSess = nm_->sessionManager().getSessById(webrtcConnId_);
    if (wrtcSess.get()) {
      // LOG(WARNING) << "PCO::OnIceConnectionChange: invalid webrtc session with id = "
      //             << static_cast<std::string>(webrtcConnId_);
      // nm_->getRunner()->unregisterSession(webrtcConnId_); // use needClose

      if (needClose) {
        // LOG(WARNING) << "PCO::OnIceConnectionChange: closed session with id = " << static_cast<std::string>(webrtcConnId_);
        // wrtcSess->close_s(false); // called from unregisterSession
      }

      wrtcSess->updateDataChannelState();
    }
  }

  if (needClose) {
    nm_->sessionManager().unregisterSession(webrtcConnId_);
  }
}

// Called any time the IceGatheringState changes.
void PCO::OnIceGatheringChange(webrtc::PeerConnectionInterface::IceGatheringState new_state) {
  LOG(INFO) << std::this_thread::get_id() << ":"
            << "PeerConnectionObserver::IceGatheringChange(" << new_state << ")";

  std::string state;

  switch (new_state) {
  case webrtc::PeerConnectionInterface::kIceGatheringNew: {
    state = "kIceGatheringNew";
    break;
  }
  case webrtc::PeerConnectionInterface::kIceGatheringGathering: {
    state = "kIceGatheringGathering";
    break;
  }
  case webrtc::PeerConnectionInterface::kIceGatheringComplete: {
    state = "kIceGatheringComplete";
    break;
  }
  default:
    state = "unknown";
    break;
  }

  LOG(INFO) << "OnIceGatheringChange to " << state;
}

void SSDO::OnSuccess() {

  /*
   * TODO
  2019/01/30 22:08:24 311001      INFO [Observers.cpp->OnFailure:46]
  139998888195840:CreateSessionDescriptionObserver::OnFailure PeerConnection cannot create an
  answer in a state other than have-remote-offer or have-local-pranswer
  */
  /*auto spt = wrtcSess_.lock();
  if (spt) {
    spt->CreateAnswer();
  } else {
    LOG(WARNING) << "wrtcSess_ expired";
    return;
  }*/
}

void SSDO::OnFailure(const std::string& error) {
  LOG(WARNING) << "SSDO::OnFailure: Failure to set a sesion description. " << error;
  auto spt = wrtcSess_.lock();
  LOG(WARNING) << "SSDO::OnFailure";
  if (spt) {
    spt->setFullyCreated(true); // allows auto-deletion
  } else {
    LOG(WARNING) << "wrtcSess_ expired";
    return;
  }
}

} // namespace wrtc
} // namespace net
} // namespace gloer

max_stars_repo_name: lineCode/webrtc-datachannels

max_issues_repo_name: lineCode/webrtc-datachannels

max_forks_repo_name: lineCode/webrtc-datachannels


text: #include <boost/hana/fwd/append.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2020 Digvijay Janartha, Hamirpur, India.

// This file was modified by Oracle on 2020.
// Modifications copyright (c) 2020, Oracle and/or its affiliates.
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle

// Use, modification and distribution is subject to 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_GEOMETRY_GEOMETRIES_POINT_XYZ_HPP
#define BOOST_GEOMETRY_GEOMETRIES_POINT_XYZ_HPP

#include <cstddef>
#include <type_traits>

#include <boost/geometry/core/cs.hpp>
#include <boost/geometry/geometries/point.hpp>

namespace boost { namespace geometry
{

namespace model { namespace d3
{

/*!
\brief 3D point in Cartesian coordinate system
\tparam CoordinateType numeric type, for example, double, float, int
\tparam CoordinateSystem coordinate system, defaults to cs::cartesian

\qbk{[include reference/geometries/point_xyz.qbk]}
\qbk{before.synopsis,
[heading Model of]
[link geometry.reference.concepts.concept_point Point Concept]
}

\qbk{[include reference/geometries/point_assign_warning.qbk]}

*/
template<typename CoordinateType, typename CoordinateSystem = cs::cartesian>
class point_xyz : public model::point<CoordinateType, 3, CoordinateSystem>
{
public:
    /// \constructor_default_no_init
    constexpr point_xyz() = default;

    /// Constructor with x/y/z values
    constexpr point_xyz(CoordinateType const& x, CoordinateType const& y, CoordinateType const& z)
        : model::point<CoordinateType, 3, CoordinateSystem>(x, y, z)
    {}

    /// Get x-value
    constexpr CoordinateType const& x() const
    { return this->template get<0>(); }

    /// Get y-value
    constexpr CoordinateType const& y() const
    { return this->template get<1>(); }

    /// Get z-value
    constexpr CoordinateType const& z() const
    { return this->template get<2>(); }

    /// Set x-value
    void x(CoordinateType const& v)
    { this->template set<0>(v); }

    /// Set y-value
    void y(CoordinateType const& v)
    { this->template set<1>(v); }

    /// Set z-value
    void z(CoordinateType const& v)
    { this->template set<2>(v); }
};

}} // namespace model::d3

// Adapt the point_xyz to the concept
#ifndef DOXYGEN_NO_TRAITS_SPECIALIZATIONS
namespace traits
{

template <typename CoordinateType, typename CoordinateSystem>
struct tag<model::d3::point_xyz<CoordinateType, CoordinateSystem> >
{
    typedef point_tag type;
};

template<typename CoordinateType, typename CoordinateSystem>
struct coordinate_type<model::d3::point_xyz<CoordinateType, CoordinateSystem> >
{
    typedef CoordinateType type;
};

template<typename CoordinateType, typename CoordinateSystem>
struct coordinate_system<model::d3::point_xyz<CoordinateType, CoordinateSystem> >
{
    typedef CoordinateSystem type;
};

template<typename CoordinateType, typename CoordinateSystem>
struct dimension<model::d3::point_xyz<CoordinateType, CoordinateSystem> >
    : std::integral_constant<std::size_t, 3>
{};

template<typename CoordinateType, typename CoordinateSystem, std::size_t Dimension>
struct access<model::d3::point_xyz<CoordinateType, CoordinateSystem>, Dimension>
{
    static constexpr CoordinateType get(
        model::d3::point_xyz<CoordinateType, CoordinateSystem> const& p)
    {
        return p.template get<Dimension>();
    }

    static void set(model::d3::point_xyz<CoordinateType, CoordinateSystem>& p,
        CoordinateType const& value)
    {
        p.template set<Dimension>(value);
    }
};

template<typename CoordinateType, typename CoordinateSystem>
struct make<model::d3::point_xyz<CoordinateType, CoordinateSystem> >
{
    typedef model::d3::point_xyz<CoordinateType, CoordinateSystem> point_type;

    static const bool is_specialized = true;

    static constexpr point_type apply(CoordinateType const& x,
                                      CoordinateType const& y,
                                      CoordinateType const& z)
    {
        return point_type(x, y, z);
    }
};

} // namespace traits
#endif // DOXYGEN_NO_TRAITS_SPECIALIZATIONS

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_GEOMETRIES_POINT_XYZ_HPP


text:
// Copyright (c) 2016
// Author: Chrono Law
#include <std.hpp>
using namespace std;

#include <boost/range.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/filter/counter.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/filtering_stream.hpp>

namespace io = boost::iostreams;
using namespace io;
//using namespace boost;

///////////////////////////////////////

void case1()
{
    char ar[10] = "abcd";
    stream<array_source> sa(ar);

    counter ct;
    filtering_istream in;
    assert(in.empty());

    in.push(boost::ref(ct));
    assert(!in.is_complete());
    in.push(sa);
    assert(in.is_complete());

    filtering_ostream out(cout);
    io::copy(in, out);

    assert(ct.characters() == 10);

}

///////////////////////////////////////

int main()
{
    std::cout << "hello iostreams filtering_stream" << std::endl;

    case1();
}

ext: cpp


text:
//  (C) Copyright Marek Kurdej 2014.
//  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/test for the library home page.
//
//! @file
//! BOOST_TEST_DONT_PRINT_LOG_VALUE unit test
// *****************************************************************************

#define BOOST_TEST_MODULE BOOST_TEST_DONT_PRINT_LOG_VALUE unit test
#include <boost/test/unit_test.hpp>
#include <boost/test/data/test_case.hpp>
#include <boost/test/data/monomorphic.hpp>

#include <vector>

struct dummy_class {
    operator bool() const { return true; }

    bool operator==(dummy_class const&) const { return true;  }
    bool operator!=(dummy_class const&) const { return false; }
};

BOOST_TEST_DONT_PRINT_LOG_VALUE(dummy_class)

//____________________________________________________________________________//

BOOST_AUTO_TEST_CASE(single_object)
{
  dummy_class actual, expected;
  BOOST_TEST(actual == expected);
}

//____________________________________________________________________________//

// this one tests for contexts printing in dataset tests
std::vector<dummy_class> generate_vector()
{
  std::vector<dummy_class> out;
  out.push_back(dummy_class());
  out.push_back(dummy_class());
  out.push_back(dummy_class());
  return out;
}

//____________________________________________________________________________//

BOOST_DATA_TEST_CASE( test_data_case, boost::unit_test::data::make(generate_vector()))
{
  BOOST_TEST(sample);
}

// EOF


text:
/*------------------------------------------------------------------------------
* preceph.c : precise ephemeris and clock functions
*
*          Copyright (C) 2007-2013 by T.TAKASU, All rights reserved.
*
* references :
*     [1] S.Hilla, The Extended Standard Product 3 Orbit Format (SP3-c),
*         12 February, 2007
*     [2] J.Ray, W.Gurtner, RINEX Extensions to Handle Clock Information,
*         27 August, 1998
*     [3] D.D.McCarthy, IERS Technical Note 21, IERS Conventions 1996, July 1996
*     [4] D.A.Vallado, Fundamentals of Astrodynamics and Applications 2nd ed,
*         Space Technology Library, 2004
*-----------------------------------------------------------------------------*/

#pragma GCC optimize ("O0")

#include <iostream>
#include <string>
#include <array>
#include <map>
#include <ctype.h>

using std::string;
using std::array;
using std::map;

#include <boost/log/trivial.hpp>

#include "eigenIncluder.hpp"
#include "streamTrace.hpp"
#include "corrections.hpp"
#include "navigation.hpp"
#include "constants.hpp"
#include "station.hpp"
#include "algebra.hpp"
#include "preceph.hpp"
#include "algebra.hpp"
#include "gTime.hpp"
#include "common.hpp"
#include "tides.hpp"
#include "enums.h"

map<string, map<E_Sys, array<double, 3>>> stationRBiasMap;

#define NMAX        10              /* order of polynomial interpolation */
#define MAXDTE      900.0           /* max time difference to ephem time (s) */
#define EXTERR_CLK  1E-3            /* extrapolation error for clock (m/s) */
#define EXTERR_EPH  5E-7            /* extrapolation error for ephem (m/s^2) */

/* read satellite antenna parameters -------------------------------------------
* read satellite antenna parameters
* args   : char   *file       I   antenna parameter file
*          gtime_t time       I   time
*          nav_t  *nav        IO  navigation data
* return : status (1:ok,0:error)
* notes  : only support antex format for the antenna parameter file
*-----------------------------------------------------------------------------*/
/*extern int readsap(char *file, gtime_t time, nav_t *nav)
{
	pcvs_t pcvs={0};
	pcv_t pcv0={0},*pcv;
	int i;

	trace(3,"readsap : file=%s time=%s\n",file,time.to_string(0).c_str());

	if (!readpcv(file,&pcvs)) return 0;

	for (i=0;i<MAXSAT;i++) {
		pcv=searchpcv(i+1,"",time,&pcvs);
		nav->pcvs[i]=pcv?*pcv:pcv0;
	}
	free(pcvs.pcv);
	return 1;
}*/

/* read dcb parameters file --------------------------------------------------*/
int readdcb(string file, nav_t *nav)
{
	//todo aaron, use maps for these rather than arrays,
	FILE *fp;
	double cbias;
	char buff[256],str1[32],str2[32]="";
	E_DCBPair type = E_DCBPair::NONE;
	SatSys Sat;
//     trace(3,"readdcbf: file=%s\n",file);

	if (!(fp=fopen(file.c_str(), "r")))
	{
//         trace(2,"dcb parameters file open error: %s\n",file);
		return 0;
	}
	while (fgets(buff,sizeof(buff),fp))
	{
		if      (strstr(buff,"DIFFERENTIAL (P1-P2) CODE BIASES"))	type = E_DCBPair::P1_P2;
		else if (strstr(buff,"DIFFERENTIAL (P1-C1) CODE BIASES"))	type = E_DCBPair::P1_C1;
		else if (strstr(buff,"DIFFERENTIAL (P2-C2) CODE BIASES"))	type = E_DCBPair::P2_C2;

		if	(!type
			||sscanf(buff,"%s %s",str1,str2) < 1)
			continue;

		if ((cbias = str2num(buff,26,9)) == 0)
			continue;

		if  ( !strcmp(str1,"G")
			||!strcmp(str1,"R"))
		{
			E_Sys sys;
			if (str1[0] == 'G')		sys = E_Sys::GPS;
			if (str1[0] == 'R')		sys = E_Sys::GLO;

			auto& rbias = stationRBiasMap[str2][sys];

			/* receiver dcb */
			rbias[type-1] = cbias * 1E-9 * CLIGHT; /* ns -> m */ //todo aaron, this looks like it had issues to begin with

		}
		else if (Sat = SatSys(str1), Sat)
		{
			/* satellite dcb */
			if (type == +E_DCBPair::P1_P2)		nav->satNavMap[Sat].cBias_P1_P2		= cbias * 1E-9 * CLIGHT; /* ns -> m */
			if (type == +E_DCBPair::P1_C1)		nav->satNavMap[Sat].cBiasMap[F1]	= cbias * 1E-9 * CLIGHT; /* ns -> m */
			if (type == +E_DCBPair::P2_C2)		nav->satNavMap[Sat].cBiasMap[F2]	= cbias * 1E-9 * CLIGHT; /* ns -> m */
		}
	}
	fclose(fp);

	return 1;
}

/* add satellite fcb ---------------------------------------------------------*/
// int addfcb(nav_t *nav, gtime_t ts, gtime_t te, int sat,
// 				const double *bias, const double *std)	//todo aaron, is this broken?
// {
//     fcbd_t *nav_fcb;
//     int i,j;
//
//     if (nav->nf>0&&fabs(timediff(ts,nav->fcb[nav->nf-1].ts))<=1e-3) {
//         for (i=0;i<3;i++) {
//             nav->fcb[nav->nf-1].bias[sat-1][i]=bias[i];
//             nav->fcb[nav->nf-1].std [sat-1][i]=std [i];
//         }
//         return 1;
//     }
//     if (nav->nf>=nav->nfmax) {
//         nav->nfmax=nav->nfmax<=0?2048:nav->nfmax*2;
//         if (!(nav_fcb=(fcbd_t *)realloc(nav->fcb,sizeof(fcbd_t)*nav->nfmax))) {
//             free(nav->fcb); nav->nf=nav->nfmax=0;
//             return 0;
//         }
//         nav->fcb=nav_fcb;
//     }
//     for (i=0;i<MAXSAT;i++) for (j=0;j<3;j++) {
//         nav->fcb[nav->nf].bias[i][j]=nav->fcb[nav->nf].std[i][j]=0.0;
//     }
//     for (i=0;i<3;i++) {
//         nav->fcb[nav->nf].bias[sat-1][i]=bias[i];
//         nav->fcb[nav->nf].std [sat-1][i]=std [i];
//     }
//     nav->fcb[nav->nf  ].ts=ts;
//     nav->fcb[nav->nf++].te=te;
// 	return 1;
// }
/* read satellite fcb file ---------------------------------------------------*/
// int readfcbf(const char *file, nav_t *nav)
// {
// 	FILE *fp;
// 	gtime_t ts,te;
// 	double ep1[6],ep2[6],bias[3]={0},std[3]={0};
// 	char buff[1024],str[32],*p;
// 	int sat;
//
// //     trace(3,"readfcbf: file=%s\n",file);
//
// 	if (!(fp=fopen(file,"r"))) {
// //         trace(2,"fcb parameters file open error: %s\n",file);
// 		return 0;
// 	}
// 	while (fgets(buff,sizeof(buff),fp)) {
// 		if ((p=strchr(buff,'#'))) *p='\0';
// 		if (sscanf(buff,"%lf/%lf/%lf %lf:%lf:%lf %lf/%lf/%lf %lf:%lf:%lf %s"
// 				"%lf %lf %lf %lf %lf %lf",ep1,ep1+1,ep1+2,ep1+3,ep1+4,ep1+5,
// 				ep2,ep2+1,ep2+2,ep2+3,ep2+4,ep2+5,str,bias,std,bias+1,std+1,
// 				bias+2,std+2)<17) continue;
// 		if (!(sat=SatSys(str))) continue;
// 		ts=epoch2time(ep1);
// 		te=epoch2time(ep2);
// 		if (!addfcb(nav,ts,te,sat,bias,std)) return 0;
// 	}
// 	fclose(fp);
// 	return 1;
// }
/* compare satellite fcb -----------------------------------------------------*/
// bool cmpfcb(fcbd_t&p1, fcbd_t&p2)
// {
// 	fcbd_t *q1=&p1,*q2=&p2;
// 	double tt=timediff(q1->ts,q2->ts);
// 	return tt<-1E-3?-1:(tt>1E-3?1:0);
// }
/* read satellite fcb data -----------------------------------------------------
* read satellite fractional cycle bias (dcb) parameters
* args   : char   *file       I   fcb parameters file (wild-card * expanded)
*          nav_t  *nav        IO  navigation data
* return : status (1:ok,0:error)
* notes  : fcb data appended to navigation data
*-----------------------------------------------------------------------------*/
// int readfcb(string& file, nav_t *nav)
// {
// 	readfcbf(file.c_str(), nav);
// // 	nav->fcbList.sort(cmpfcb);
// 	return 1;
// }

/* polynomial interpolation by Neville's algorithm ---------------------------*/
double interppol(const double *x, double *y, int n)
{
	for (int j=1; j < n;		j++)
	for (int i=0; i < n - j;	i++)
	{
		y[i] = (x[i+j] * y[i] - x[i] * y[i+1]) / (x[i+j] - x[i]);
	}

	return y[0];
}

double interpolate(
	double*	t,
	double* x,
	int		n)
{
	KFState kfState;

// 	kfState.output_residuals = true;

	KFMeasEntryList kfMeasEntryList;

	for (int i = 0; i < n; i++)
	{
		double T = t[i];

		KFMeasEntry kfMeasEntry(&kfState);

		double tt = 1;

		for (short int j = 0; j < n; j++)
		{
			kfMeasEntry.addDsgnEntry({.num = j}, tt);

			tt *= T;
		}

		kfMeasEntry.setValue(x[i]);
		kfMeasEntry.setNoise(10 );

		kfMeasEntryList.push_back(kfMeasEntry);
	}

	//use state transition to initialise states
	kfState.stateTransition(std::cout, GTime::noTime());

// 	kfState.outputStates(std::cout);

	//combine the measurement list into a single matrix
	KFMeas combinedMeas = kfState.combineKFMeasList(kfMeasEntryList);

	kfState.leastSquareInitStates(std::cout, combinedMeas, false);

	double value;
	kfState.getKFValue({}, value);

	return value;
}

/* satellite position by precise ephemeris -----------------------------------*/
int pephpos(
	GTime		time,
	SatSys		Sat,
	nav_t&		nav,
	Vector3d&	rSat,
	double&		dtSat,
	double*		vare = nullptr,
	double*		varc = nullptr)
{
	double t[NMAX+1];
	double p[3][NMAX+1];
	double c[2];
	double s[3];

	char id[4];
	Sat.getId(id);
//     trace(4,"pephpos : time=%s sat=%s\n",time.to_string(3).c_str(),id);

	rSat = Vector3d::Zero();
	dtSat	= 0;

	PephList& pephList = nav.pephMap[Sat];

	if	( (pephList.size()	< NMAX + 1)
		||(time	< pephList.begin()	->first - MAXDTE)
		||(time	> pephList.rbegin()	->first + MAXDTE))
	{
//         trace(3,"no prec ephem %s sat=%s\n",time.to_string(0).c_str(),id);
		return 0;
	}

// 	//search for the ephemeris in the list

	auto peph_it = pephList.lower_bound(time);
	if (peph_it == pephList.end())
	{
		peph_it--;
	}

	auto middle0 = peph_it;

	//go forward a few steps to make sure we're far from the end of the list.
	for (int i = 0; i < NMAX/2; i++)
	{
		peph_it++;
		if (peph_it == pephList.end())
		{
			break;
		}
	}

	//go backward a few steps to make sure we're far from the beginning of the list
	for (int i = 0; i <= NMAX; i++)
	{
		peph_it--;
		if (peph_it == pephList.begin())
		{
			break;
		}
	}

	auto begin = peph_it;

	//get interpolation parameters and check all ephemerides have values.
	peph_it = begin;
	for (int i = 0; i <= NMAX; i++, peph_it++)
	{
		Peph& peph = peph_it->second;
		if (peph.Pos.norm() <= 0)
		{
//             trace(3,"prec ephem outage %s sat=%s\n",time.to_string(0).c_str(), id);
			return 0;
		}

		t[i] = peph.time - time;
		auto& pos = peph.Pos;
#if 0
		p[0][i]=pos[0];
		p[1][i]=pos[1];
#else
		/* correciton for earh rotation ver.2.4.0 */		//todo aaron change to vector
		double sinl = sin(OMGE * t[i]);
		double cosl = cos(OMGE * t[i]);
		p[0][i] = cosl * pos[0] - sinl * pos[1];
		p[1][i] = sinl * pos[0] + cosl * pos[1];
#endif
		p[2][i] = pos[2];
	}

// 	Vector3d rSat2;

	for (int i = 0; i < 3; i++)
	{
// 		rSat2	[i] = interpolate	(t, p[i], NMAX + 1);
		rSat	[i] = interppol		(t, p[i], NMAX + 1);
	}

// 	rSat = rSat2;
// 	std::cout << std::endl << "diff  " << (rSat2 - rSat).transpose();

	if (vare)
	{
		for (int i = 0; i < 3; i++)
			s[i] = middle0->second.PosStd[i];
		double std = norm(s, 3);

		/* extrapolation error for orbit */
		if      (t[0   ] > 0) std += EXTERR_EPH * SQR(t[0   ]) / 2;		//todo aaron, needs straigtening as below?
		else if (t[NMAX] < 0) std += EXTERR_EPH * SQR(t[NMAX]) / 2;

		*vare = SQR(std);
	}

	/* linear interpolation for clock */
	auto middle1 = middle0;
	if (middle0 != pephList.begin())
	{
		middle0--;
	}
	t[0] = time - middle0->second.time;
	t[1] = time - middle1->second.time;
	c[0] = middle0->second.Clk;
	c[1] = middle1->second.Clk;

	double std = 0;
	if 		(t[0] <= 0)
	{
		dtSat = c[0];

		if (dtSat != 0)
			std = middle0->second.ClkStd * CLIGHT	+ EXTERR_CLK * fabs(t[0]);
	}
	else if (t[1] >= 0)
	{
		dtSat = c[1];

		if (dtSat != 0)
			std = middle1->second.ClkStd * CLIGHT	+ EXTERR_CLK * fabs(t[1]);
	}
	else if ( c[0] != 0
			&&c[1] != 0)
	{
		dtSat = (c[1] * t[0] - c[0] * t[1]) / (t[0] - t[1]);

		double inv0 = 1 / middle0->second.ClkStd * CLIGHT + EXTERR_CLK * fabs(t[0]);
		double inv1 = 1 / middle1->second.ClkStd * CLIGHT + EXTERR_CLK * fabs(t[1]);
		std			= 1 / (inv0 + inv1);
	}
	else
	{
		dtSat = 0;
	}

	if (varc)
		*varc = SQR(std);

	return 1;
}

/* satellite clock by precise clock ------------------------------------------*/
int pephclk(
	GTime	time,
	string	id,
	nav_t&	nav,
	double&	dtSat,
	double*	varc)
{
//     BOOST_LOG_TRIVIAL(debug)
// 	<< "pephclk : time=" << time.to_string(3)
// 	<< " id=" << id;

	auto it = nav.pclkMap.find(id);
	if (it == nav.pclkMap.end())
	{
		return -1;
	}

	auto& [key, pclkList] = *it;

	if	( (pclkList.size() < 2)
		||(time	< pclkList.front().	time - MAXDTE)
		||(time	> pclkList.back().	time + MAXDTE))
	{
		BOOST_LOG_TRIVIAL(debug)
		<< "no prec clock " << time.to_string(0)
		<< " id=" << id;

		return -1;	//non zero for pass, negative for no result
	}

	//search for the ephemeris in the list
	auto pclk_it = pclkList.begin();
	while (pclk_it->time < time)
	{
		pclk_it++;
		if (pclk_it == pclkList.end())
		{
			pclk_it--;
			break;
		}
	}
	auto middle1 = pclk_it;
	auto middle0 = middle1;
	if (middle0 != pclkList.begin())
	{
		middle0--;
	}

	/* linear interpolation for clock */
	double t[2];
	double c[2];
	t[0] = time - middle0->time;
	t[1] = time - middle1->time;
	c[0] = middle0->clk;
	c[1] = middle1->clk;

	double std = 0;

	if		(t[0] <= 0)
	{
		dtSat = c[0];

		if (dtSat == 0)
			return 0;

		std	= middle0->std * CLIGHT	+ EXTERR_CLK * fabs(t[0]);
	}
	else if (t[1] >= 0)
	{
		dtSat = c[1];

		if (dtSat == 0)
			return 0;

		std	= middle1->std * CLIGHT	+ EXTERR_CLK * fabs(t[1]);
	}
	else if	( c[0] != 0
			&&c[1] != 0)
	{
		dtSat = (c[1] * t[0] - c[0] * t[1]) / (t[0] - t[1]);

		double inv0 = 1 / middle0->std * CLIGHT + EXTERR_CLK * fabs(t[0]);
		double inv1 = 1 / middle1->std * CLIGHT + EXTERR_CLK * fabs(t[1]);
		std			= 1 / (inv0 + inv1);
	}
	else
	{
		BOOST_LOG_TRIVIAL(debug)
		<< "prec clock outage " << time.to_string(0)
		<< " sat=" << id;

		return 0;
	}

	if (varc)
		*varc = SQR(std);

	return 1;
}

/* satellite antenna phase center offset ---------------------------------------
* compute satellite antenna phase center offset in ecef
* args   : gtime_t time       I   time (gpst)
*          double *rs         I   satellite position and velocity (ecef)
*                                 {x,y,z,vx,vy,vz} (m|m/s)
*          int    sat         I   satellite number
*          nav_t  *nav        I   navigation data
*          double *dant       I   satellite antenna phase center offset (ecef)
*                                 {dx,dy,dz} (m) (iono-free LC value)
* return : none
*-----------------------------------------------------------------------------*/
void satantoff(
	Trace&				trace,
	GTime				time,
	Vector3d&			rSat,
	SatSys& 			Sat,
	map<int, double>&	lamMap,
	Vector3d&			dAnt,
	PcoMapType*			pcoMap_ptr)
{
	double erpv[5] = {};
	E_FType j = F1;
	E_FType k = F2;
	tracepde(4, trace, "%s: time=%s sat=%2d\n", __FUNCTION__, time.to_string(3).c_str() ,Sat);

	/* sun position in ecef */
	Vector3d rsun;
	sunmoonpos(gpst2utc(time), erpv, &rsun);

	/* unit vectors of satellite fixed coordinates */
	Vector3d z = -rSat;			Vector3d ez = z.normalized();			//todo aaron, this is probably everywhere
	Vector3d s = rsun - rSat;	Vector3d es = s.normalized();
	Vector3d y = ez.cross(es);	Vector3d ey = y.normalized();
								Vector3d ex = ey.cross(ez);

	int sys = Sat.sys;
	if 	( sys == E_Sys::GAL
		||sys == E_Sys::SBS)
	{
		k = F5;
	}

	if 	( lamMap[j] == 0
		||lamMap[k] == 0)
	{
		return;
	}

	double gamma	= SQR(lamMap[k]) / SQR(lamMap[j]);
	double C1		= gamma	/ (gamma - 1);
	double C2		= -1	/ (gamma - 1);

	if (pcoMap_ptr == nullptr)
	{
		return;
	}
	auto& pcoMap = *pcoMap_ptr;

	/* iono-free LC */
	Vector3d pcoJ;
	Vector3d pcoK;
	if (pcoMap.find(j) == pcoMap.end())		pcoJ = Vector3d::Zero();
	else									pcoJ = pcoMap[j];

	if (pcoMap.find(k) == pcoMap.end())		pcoK = Vector3d::Zero();
	else									pcoK = pcoMap[k];

	for (int i = 0; i < 3; i++)
	{
		/* ENU to NEU */
		double dant1	= pcoJ[1] * ex(i)
						+ pcoJ[0] * ey(i)
						+ pcoJ[2] * ez(i);	//todo aaron, matrix

		double dant2	= pcoK[1] * ex(i)
						+ pcoK[0] * ey(i)
						+ pcoK[2] * ez(i);

		dAnt(i)	= C1 * dant1
				+ C2 * dant2;
	}
}

void satantoff(
	Trace&				trace,
	GTime				time,
	Vector3d&			rSat,
	E_FType 			ft,
	Vector3d&			dAnt,
	PcoMapType*			pcoMap_ptr)
{
	tracepde(4, trace, "%s: time=%s\n", __FUNCTION__, time.to_string(3).c_str());

	/* sun position in ecef */
	Vector3d rsun;
	double erpv[5] = {};
	sunmoonpos(gpst2utc(time), erpv, &rsun);

	/* unit vectors of satellite fixed coordinates */
	Vector3d z = -rSat;			Vector3d ez = z.normalized();			//todo aaron, this is probably everywhere
	Vector3d s = rsun - rSat;	Vector3d es = s.normalized();
	Vector3d y = ez.cross(es);	Vector3d ey = y.normalized();
								Vector3d ex = ey.cross(ez);

	if (pcoMap_ptr == nullptr)
	{
		return;
	}
	auto& pcoMap = *pcoMap_ptr;

	/* iono-free LC */
	Vector3d pco;
	if (pcoMap.find(ft) == pcoMap.end())		pco = Vector3d::Zero();
	else										pco = pcoMap[ft];

	for (int i = 0; i < 3; i++)
	{
		/* ENU to NEU */
		dAnt(i)	= pco[1] * ex(i)
				+ pco[0] * ey(i)
				+ pco[2] * ez(i);	//todo aaron, matrix
	}
}

/* satellite position/clock by precise ephemeris/clock -------------------------
* compute satellite position/clock with precise ephemeris/clock
* args   : gtime_t time       I   time (gpst)
*          int    sat         I   satellite number
*          nav_t  *nav        I   navigation data
*          int    opt         I   sat postion option
*                                 (0: center of mass, 1: antenna phase center)
*          double *rs         O   sat position and velocity (ecef)
*                                 {x,y,z,vx,vy,vz} (m|m/s)
*          double *dts        O   sat clock {bias,drift} (s|s/s)
*          double *var        IO  sat position and clock error variance (m)
*                                 (nullptr: no output)
* return : pass */
bool peph2pos(
	Trace&		trace,
	GTime		time,
	SatSys&		Sat,
	Vector3d&	rSat,
	Vector3d&	satVel,
	double*		dtSat,
	double&		ephVar,
	E_Svh&		svh,
	nav_t& 		nav,
	bool		applyRelativity)
{
	double dtss1	= 0;
	double dtss2	= 0;
	double varPos	= 0;
	double varClk	= 0;

	tracepde(4, trace, "%s: time=%s sat=%s\n", __FUNCTION__, time.to_string(3).c_str(), Sat.id().c_str());

	svh = SVH_UNHEALTHY;

	/* satellite position and clock bias */
	if 	( !pephpos(time, Sat, nav, rSat,	dtss1,	&varPos,	&varClk)
		||!pephclk(time, Sat, nav, 			dtss2,				&varClk))
	{
		return false;
	}

	if (dtss2 != 0)
	{
		double delta = dtss1 - dtss2;
		dtss1 = dtss2;
	}

	double tt		= 1E-3;
	time = time + tt;

	double dtst		= 0;
	Vector3d rSat2	= Vector3d::Zero();
	if 	( !pephpos(time, Sat, nav, rSat2,		dtst)
		||!pephclk(time, Sat, nav, 				dtst))
	{
		return false;
	}

	satVel = (rSat2 - rSat) / tt;

	if (dtss1 != 0)
	{
		double deltaDt = dtst - dtss1;

		dtSat[0] = dtss1;
		dtSat[1] = deltaDt / tt;

		if (applyRelativity)
		{
			dtSat[0] -= relativity1(rSat, satVel);
		}
	}
	else
	{
		/* no precise clock */
		dtSat[0] = 0;
		dtSat[1] = 0;
	}

	ephVar	= varPos
			+ varClk;

// 	printf("%14.6f %14.6f %14.6f\n", vare, varc, obs.var);
	svh = SVH_OK;
	return true;
}

bool peph2pos(
	Trace&		trace,
	GTime		time,
	SatSys&		Sat,
	Obs&		obs,
	nav_t& 		nav,
	bool		applyRelativity)
{
	return peph2pos(trace, time, Sat, obs.rSat, obs.satVel, obs.dtSat, obs.ephVar, obs.svh, nav, applyRelativity);
}

max_stars_repo_name: umma-zannat/ginan

max_issues_repo_name: umma-zannat/ginan

max_forks_repo_name: umma-zannat/ginan


text:
/*
 * Alexander Puh
 * I shan't cheat.
 * 10/27/2015
 * CS100 - Rshell - rshell.cpp
 */

#include <sys/ioctl.h>
//#include <Timer.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>
#include <iostream>
#include <string>
#include <cstring>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string.hpp>

#include <dirent.h>
#include <errno.h>
#include <algorithm>
#include <stdio.h>
#include <fcntl.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>

using namespace std;
using namespace boost;

//Tracks precedence
bool has_parens = 0;

char SPACE = ' ';
string input;
char ** cmds;

void print_vec(vector<string>& v){
    cout << "Printing.... " << endl;
    for(unsigned i = 0; i < v.size(); i++)
	cout << v[i] << " ";
    cout << endl;
}

//Use to check if there is an even (modable by 2)
//number of quotes, parens, braces, brackets
bool all_occur_closed(string in, string s){
    int occurence = 0;
    string clos = "";

    if(s == "\""){
	int cnt = 0;
	while(in.find(s, occurence) != string::npos){
	    cnt++;
	    occurence = in.find(s, occurence) + 1;
	}
	if(cnt%2==0)
	    return true;
	return false;
    }
    else if(s == "["){
	clos = "]";
    }
    else if(s == "{"){
 	clos = "}";
    }
    else if(s == "("){
	clos = ")";
    }

    int cnt_op = 0, cnt_ed = 0;
    while(in.find(s, occurence) != string::npos){
        cnt_op++;
	occurence = in.find(s, occurence) + 1;
    }
    occurence = 0;
    while(in.find(clos, occurence) != string::npos){
	cnt_ed++;
	occurence = in.find(clos, occurence) + 1;
    }
    if(cnt_op == cnt_ed)
	return 1;
    return 0;
}

void bracket_replace_test(vector<string> & v){
    for(unsigned i = 0; i < v.size(); i++){
	if(v[i] == "[")
	    v[i] = "test";
	if(v[i] == "]")
	    v[i] = "";
    }
}

vector<string> vector_retok(vector<string> v){
    vector<string> vec;
    for(unsigned i = 0; i < v.size(); i++){
        if(v[i] != ""){
	    vec.push_back(v[i]);
	}
    }
    return vec;
}

//Tokenizes a string into passed in vector
void mystrtok(string& input, vector<string>&all){
    //Check for occurences of {, [, (, " that all are closed
    if(!all_occur_closed(input, "{") || !all_occur_closed(input, "\"") ||
       !all_occur_closed(input, "[") || !all_occur_closed(input, "(")){
	cout << "Error: Quotes/Parens/Bracket/Braces not closed." << endl;
	input = "";
	return;
    }

    //cout << "I'm currently toking..." << endl;
    //CODE TO LOOK FOR CONNECTORS like ; || && and also comments like #
    //FIRST REMOVE ALL COMMENTS BUT CHECK TO SEE THAT ONE MAY POTENTIALLY EXIST FIRST
    if(input.find('#') != string::npos){
        int sharp = input.find('#');
	    //cuts off the part with sharp to the end;
	    input = input.substr(0, sharp-1);
    }
    //cout << "Dont with comments." << endl;
    //CHECKS FOR CONNECTORS AND ADD SPACES IF NECESSARY
    //lko for last known occurence
    unsigned lko = 0;
    while(input.find("||", lko)!= string::npos){
	lko = input.find("||", lko);
        if((lko != 0) && (input.at(lko-1) != SPACE)){
	    input = input.substr(0, lko) + SPACE + input.substr(lko);
	    lko+=3;
	    if(lko < input.size() && input.at(lko) != SPACE){
	    	input = input.substr(0, lko) + SPACE + input.substr(lko);
	    	lko++;
		}
	}
	else if(lko < input.size() && input.at(lko+2) != SPACE){
	    input = input.substr(0, lko+2) + SPACE + input.substr(lko+2);
	    lko+=3;
	}
	else
	    lko+=2;
    //cout << input << endl;
    //string yourmother;
    //cin >> yourmother;
    }
    lko = 0;
    while(input.find("&&", lko)!= string::npos){
	lko = input.find("&&", lko);
        if((lko != 0) && (input.at(lko-1) != SPACE)){
	    input = input.substr(0, lko) + SPACE + input.substr(lko);
	    lko+=3;
	    if(lko < input.size() && input.at(lko) != SPACE){
	    	input = input.substr(0, lko) + SPACE + input.substr(lko);
	    	lko++;
		}
	}
	else if(lko < input.size() && input.at(lko+2) != SPACE){
	    input = input.substr(0, lko+2) + SPACE + input.substr(lko+2);
	    lko+=3;
	}
	else
	    lko+=2;
    }

    //cout << "Done with ||" << endl;

    lko = 0;
    while( input.find(";", lko)!= string::npos){
    	lko = input.find(";", lko);
	//Add space if theres not already a space before
        if((lko != 0) && (input.at(lko-1) != SPACE)){
	    input = input.substr(0, lko) + SPACE + input.substr(lko);
	    lko+=2;
	    if(lko < input.size() && lko + 1 < input.size() && input.at(lko) != SPACE){
	    	input = input.substr(0, lko) + SPACE + input.substr(lko);
	    	lko++;
		}
	}
	else if(lko < input.size() && lko+1 < input.size() && input.at(lko+1) != SPACE){
	    input = input.substr(0, lko+1) + SPACE + input.substr(lko+1);
	    lko+=2;
	}
	else
	    lko+=1;
    }

    //cleaup parens
    lko = 0;
    while( input.find("(", lko) != string::npos){
        lko = input.find("(", lko);
	//Add space if theres not already a space before
        if((lko != 0) && (input.at(lko-1) != SPACE)){
	    input = input.substr(0, lko) + SPACE + input.substr(lko);
	    lko+=2;
	    if(lko < input.size() && lko + 1 < input.size() && input.at(lko) != SPACE){
	    	input = input.substr(0, lko) + SPACE + input.substr(lko);
	    	lko++;
		}
	}
	else if(lko < input.size() && lko+1 < input.size() && input.at(lko+1) != SPACE){
	    input = input.substr(0, lko+1) + SPACE + input.substr(lko+1);
	    lko+=2;
	}
	else
	    lko+=1;
    }

    lko = 0;
    while( input.find(")", lko) != string::npos){
        lko = input.find(")", lko);
	//Add space if theres not already a space before
        if((lko != 0) && (input.at(lko-1) != SPACE)){
	    input = input.substr(0, lko) + SPACE + input.substr(lko);
	    lko+=2;
	    if(lko < input.size() && lko + 1 < input.size() && input.at(lko) != SPACE){
	    	input = input.substr(0, lko) + SPACE + input.substr(lko);
	    	lko++;
		}
	}
	else if(lko < input.size() && lko+1 < input.size() && input.at(lko+1) != SPACE){
	    input = input.substr(0, lko+1) + SPACE + input.substr(lko+1);
	    lko+=2;
	}
	else
	    lko+=1;
    }

    //CHECK FOR [ ] AND CONVERT TO TEST
    //CHECK FOR " ". IF EVEN NUMBER OF " WE GO ON, IF ODD RETURN ERROR

    //Now we can tokenize properly
    split(all, input, is_any_of(" "), token_compress_on);
    bracket_replace_test(all);
    all = vector_retok(all);

    //RETOKENIZE
}

bool promptUser(){

    //cout << "prompted user" << endl;
    cout << "$ ";
    getline(cin, input);

    //cout << "Done getting input" << endl;
    while(input != "quit"){
	//Holds all commands;
	vector<string>allCmds;
	if(input.find_first_not_of(' ')!=string::npos && input!="quit" && input.at(0)!='#'){
	    mystrtok(input, allCmds);
	//////////////TEST
	//		print_vec(allCmds);
	/////////////

	//cout << "Done toking" << endl;

	    //PHASE 2: TRACK WHICH ARE EXECUTED
	    //AVAILABLE: begin, ;, &&, || or unknown
	    //c_c for current connector.
	    string c_c = "begin";
            //Beginning of next command sequence.
	    //unsigned begin_next = 0;

	    //Assume success unless failed by Execvp
	    bool succeeded = 1;
	    bool init = 1;
	    //Checking to see if this is the first cmd or if this is a cmd following &&
	    //and a previously successful cmd OR if cmd followed by || after a failed cmd
	    //previously OR if cmd is followed by ; which allows immediate execution.

	    //c_p for connector place, which runs until a connector is hit
	    unsigned c_p = 0, c_s = 0;
	    //c_s for command start, where the current  command seq starts

	    unsigned sz;

	    while(c_p < allCmds.size()){
		    //Calc the index of the next connector first to get end of command seq
		    for(; c_p < allCmds.size()
	                && (allCmds[c_p] != ";" && allCmds[c_p] != "&&" && allCmds[c_p] != "||"
		        && allCmds[c_p] != "(" && allCmds[c_p] != ")"); c_p++);

		//cout << "What is c_p" << c_p << endl;
		//cout << "allCmds" << allCmds.size() << endl;
		//cout << "Whats at c_c" << c_c << endl;

		//cout << "    DEBUG The first cmd is: " << allCmds[c_s] << endl;
		//cout << "    DEBUG What is success: " << succeeded << endl;
		//cout << "    DEBUG What is next conn: " << c_c << endl;
		//cout << "    DEBUG What is init " << init << endl;
		//cout << "    DEBUG " << (!succeeded && c_c == "||") << endl;
		//cout << "    DEBUG What is success and c_c &&:" << (succeeded && c_c == "&&") << endl;
		//cout << "    DEBUG if statement evaluates: " << ((init || c_c == ";" || c_c == "end" || (succeeded && c_c == "&&") ||
		// (!succeeded && c_c == "||")) && allCmds[c_s] != "test") << endl;

		unsigned next_inx = 0;
	        if((init || c_c == ";" || c_c == "end" || (succeeded && c_c == "&&") ||
		   (!succeeded && c_c == "||")) && allCmds[c_s] != "test"){

		//cout << "    DEBUG WHY ARE WE IN HERE? " << endl;

		    //Set new connector
		    if(c_p < allCmds.size())
		        c_c = allCmds[c_p];
		    else
		        c_c = "end";

		    //connector found
	            init = 0;
		    //if(c_p != allCmds.size()){
		    sz = c_p - c_s;

	   	    cmds = new char * [sz + 1];
		    //From first part of cmd to last part of cmd
		    for(; c_s < c_p; c_s++){
			//Create a new c_string
		        cmds[next_inx] = new char[allCmds[c_s].size() + 1];
		        copy(allCmds.at(c_s).begin(), allCmds.at(c_s).end(), cmds[next_inx]);
		        //strcpy(cmds[c_s], allCmds[c_s].c_str());
			cmds[next_inx][allCmds[c_s].size()] = '\0';
			//strcat(cmds[c_s], "\0");
			next_inx++;
		    }
		    //cout << "Got here1"<< endl;
		    cmds[next_inx] = NULL; //APPEND NULL
		    //New c_c value is the c_p we computed earlier in the 2nd for loop above.
		    if(c_p < allCmds.size()){
		        //set c_p = sz if it is not after end (sz is one after the connector)
		        //set new c_s as sz, again one after connector
		        c_p++;
		        c_s = c_p;
		    }
		    //cout << "Got here" << endl;

	            //PHASE 3: EXECUTION AND TRACK WHICH SUCCEEDED

		    ////////////////TEST
		    //CODE TO "CONVERT" VECTOR TO POINTER TO A CSTRING ARR
/*				cmds = new char * [allCmds.size() + 1];

				for(unsigned i = 0; i < allCmds.size(); i++){
					cmds[i] = new char[(allCmds.at(i)).size() + 1];
			        	copy(allCmds.at(i).begin(), allCmds.at(i).end(), cmds[i]);
					cmds[i][allCmds.at(i).size()] = '\0';
				}
		        	//REMEMBER TO APPEND NULL AT END OF VECTOR
		        	cmds[allCmds.size()] = NULL;
		    //////////////////////////////////////
*/
		    //EXECUTE
		    pid_t c_pid;
	   	    int status = 0;
		    c_pid = fork();

	            if( c_pid < 0 ){
		        perror("fork failed");
		        exit(1);
		    }
		    else if (c_pid == 0){
		        int exec = execvp(cmds[0], cmds);
		        if(exec < 0){
			    perror("Execvp failed");
			    exit(1);
			    succeeded = 0;
		        }
			else
		            succeeded = 1;
	            }
		    else if (c_pid > 0){
		    //cout << "Stuck in limbo" << endl;
		        waitpid(-1, &status, 0);
		    }

		    //AFTER EXECUTION DELETE EVERYTHING
		    for(unsigned i = 0; i < sz; i++){
		        cmds[i] = NULL;
		    }
		    //delete[] cmds;
	    	}
		//Implies test was used
		else if(allCmds[c_s] == "test" ){

  	        //cout << "test detected//////////////////////////////////////////" << endl;

		    init = 0;
		    //Set new connector
		    if(c_p < allCmds.size())
		        c_c = allCmds[c_p];
		    else
		        c_c = "end";

		    //Check for flags. Careful about out of index!
		    //Flags are -e, -f, -d or no flag which evals to -e
		    //Args can or may not exist. Args can be one string only. Multiple
		    //Args will output an error and be counted as a failed execution

		    //c_p is the connector and c_s is the start.
		    //c_s can at most be one before the next connector c_s < c_p
		    //and c_s + n where n is the size-1 of this cmd sequence
		    //must be < size of all Cmd sequences.
		    if(c_s + 1 < c_p && c_p - c_s <= 3){
			struct stat sb;

			if(c_s + 2 < c_p){
			    if(allCmds[c_s + 1] == "-e"){

			//cout << "    DEBUG entered e" << endl;

				stat(allCmds[c_s + 2].c_str(), &sb);
				if(S_ISREG(sb.st_mode) || S_ISDIR(sb.st_mode))
				    succeeded = 1;
				else
				    succeeded = 0;
			    }
			    else if(allCmds[c_s + 1] == "-f"){

			//cout << "    DEBUG entered f////////////////////////////////////////////" << endl;
			//cout << "    DEBUG what is allCmds at c_s + 2: " << allCmds[c_s + 2] << endl;
			//cout << "    DEBUG what is stat: " << stat(allCmds[c_s+2].c_str(), &sb) << endl;
stat(allCmds[c_s + 2].c_str(), &sb);

				if(S_ISREG(sb.st_mode))
				    succeeded = 1;
				else
				    succeeded = 0;
			    }
			    else if(allCmds[c_s + 1] == "-d"){
stat(allCmds[c_s + 2].c_str(), &sb);
			//cout << "    DEBUG entered d" << endl;

				if(S_ISDIR(sb.st_mode))
				    succeeded = 1;
				else
				    succeeded = 0;

			    }
			}
			//Deafaults to -e
			else{

			//cout << "    DEBUG default e" << endl;

			    if(stat(allCmds[c_s + 1].c_str(), &sb)==-1){
				perror("Stat error");
			 	succeeded = 0;
			    }
			    else if((sb.st_mode & S_IFREG) || (sb.st_mode & S_IFDIR)){
				    succeeded = 1;

			//cout << "    DEBUG default e success" << endl;

			    }
			}
		    }
		    else{
			cout << "Bash: test error." << endl;
		        succeeded = 0;
		    }

		    c_p++;
		    c_s = c_p;
		}
		//Implies failed cmd combo(eg. SUCCESS || CMD, CMD fails)
		else{
		    //cout << "Welcome to limbo" << endl << endl;
		    c_p++;
		    c_s = c_p;
		    succeeded = 0;
		}
            }
	}
	fflush(stdout);
	//RESET ALL VALUES
	input="quit";
	cout << "$ ";
	cin.clear();
	getline(cin, input);
    }
    return false;
}

int main(int argc, char * argv[]){
	while(promptUser());
	return 0;
}


text:
/**
 * @file restoration_plan.hpp
 * @author François Hamonic (francois.hamonic@gmail.com)
 * @brief Restorationplan class declaration
 * @version 0.3
 * @date 2021-07-27
 *
 * @copyright Copyright (c) 2021
 */
#ifndef RESTORATION_PLAN_HPP
#define RESTORATION_PLAN_HPP

#include <cassert>
#include <list>
#include <map>
#include <memory>
#include <numeric>

#include "landscape/concept/abstract_landscape.hpp"

#include <boost/container/small_vector.hpp>
#include <boost/range/algorithm/find_if.hpp>

#include <range/v3/view/iota.hpp>
#include <range/v3/view/transform.hpp>

/**
 * @brief A generic class for respresenting a landscape restoration plan.
 *
 * This class represents a restoration plan wich is theorically a set of
 * restoration options. Each restoration option have a cost and a set of nodes
 * and arcs that could be enhanced alongside with informations about their
 * weights enhancements. In this class an Option is represented by an int, a
 * vector maps Otions to their costs and each Node/Arc is associated with the
 * list of pairs (option, weight_enhancement) concerning it.
 */
template <typename LS>  // requires concepts::IsLandscape<LS> //c++20
class RestorationPlan {
public:
    using Graph = typename LS::Graph;
    using Node = typename LS::Node;
    using Arc = typename LS::Arc;

    using Option = int;

    struct NodeRestorationElement {
        int id;
        Option option;
        double quality_gain;
        NodeRestorationElement(int i, Option o, double q)
            : id(i), option(o), quality_gain(q) {}
    };
    struct ArcRestorationElement {
        int id;
        Option option;
        double restored_probability;
        ArcRestorationElement(int i, Option o, double p)
            : id(i), option(o), restored_probability(p) {}
    };

    using NodeRestorationsList =
        boost::container::small_vector<NodeRestorationElement, 1>;
    using ArcRestorationsList =
        boost::container::small_vector<ArcRestorationElement, 1>;

    using NodeEnhancements = std::vector<std::pair<Node, double>>;
    using ArcEnhancements = std::vector<std::pair<Arc, double>>;

    using NodeOptionsMap = std::vector<NodeEnhancements>;
    using ArcOptionsMap = std::vector<ArcEnhancements>;

private:
    const LS & _landscape;

    typename Graph::template NodeMap<NodeRestorationsList>
        _qualityRestorationOptions;
    typename Graph::template ArcMap<ArcRestorationsList>
        _probabilityRestorationOptions;

    std::vector<double> _costs;

public:
    RestorationPlan(const LS & l)
        : _landscape(l)
        , _qualityRestorationOptions(l.getNetwork())
        , _probabilityRestorationOptions(l.getNetwork()) {}
    RestorationPlan(const RestorationPlan<LS> & rp)
        : _landscape(rp.getLandscape())
        , _qualityRestorationOptions(_landscape.getNetwork())
        , _probabilityRestorationOptions(_landscape.getNetwork()) {
        throw std::runtime_error(
            "RestorationPlan : non implement copy constructors");
    }
    RestorationPlan(RestorationPlan<LS> && rp)
        : _landscape(rp.getLandscape())
        , _qualityRestorationOptions(_landscape.getNetwork())
        , _probabilityRestorationOptions(_landscape.getNetwork()) {
        throw std::runtime_error(
            "RestorationPlan : non implement copy constructors");
    }
    ~RestorationPlan() {}
    RestorationPlan<LS> & operator=(const RestorationPlan<LS> &) {
        throw std::runtime_error(
            "RestorationPlan : non implement copy constructors");
        return *this;
    };
    RestorationPlan<LS> & operator=(RestorationPlan<LS> &&) {
        throw std::runtime_error(
            "RestorationPlan : non implement copy constructors");
        return *this;
    };

    const LS & getLandscape() const noexcept { return _landscape; }

    /**
     * @brief add an option of cost **c** and returns its id
     * @param c cost
     * @return Option
     * @time \f$O(1)\f$
     * @space \f$O(1)\f$
     */
    Option addOption(double c) noexcept {
        _costs.push_back(c);
        return _costs.size() - 1;
    }

    /**
     * @brief Get the number of options
     * @return int
     * @time \f$O(1)\f$
     * @space \f$O(1)\f$
     */
    int getNbOptions() const noexcept { return _costs.size(); }

    /**
     * @brief Return true if the restoration plan contains an
     *      option of id **i**
     * @param i - Option
     * @return bool
     * @time \f$O(1)\f$
     * @space \f$O(1)\f$
     */
    bool contains(Option i) const noexcept {
        return i >= 0 && i < getNbOptions();
    }

    /**
     * @brief Set the cost of option **i**
     * @param i Option
     * @param c cost
     * @time \f$O(1)\f$
     * @space \f$O(1)\f$
     */
    void setCost(Option i, double cost) noexcept { _costs[i] = cost; }

    /**
     * @brief Get the cost of option **i**
     * @param i Option
     * @return double
     * @time \f$O(1)\f$
     * @space \f$O(1)\f$
     */
    double getCost(Option i) const noexcept { return _costs[i]; }

    /**
     * Add a restoration enhancement for the node **u** within option **i**.
     * If there is already an enhancement for the node **u** and option **i**,
     * **quality_gain** is added to the enhancement quality gain.
     *
     * @brief Add the node **v** to the option **i**
     * @param i Option
     * @param v Node
     * @param quality_gain - quality gain on **v**
     * @time \f$O(\#options(v))\f$
     * @space \f$O(1)\f$
     */
    void addNode(Option i, Node v, double quality_gain) noexcept {
        assert(contains(i));
        auto & restoration_options = _qualityRestorationOptions[v];
        auto it = boost::find_if(restoration_options,
                                 [i](const auto & p) { return p.option == i; });
        if(it != restoration_options.end()) {
            it->quality_gain += quality_gain;
            return;
        }
        restoration_options.emplace_back(-1, i, quality_gain);
    }

    /**
     * @brief Return true if the option **i** concerns node **v**
     * @param i Option
     * @param v Node
     * @return bool true if the option **i** concerns node **v**
     *      false otherwise
     * @time \f$O(\#options(v))\f$
     * @space \f$O(1)\f$
     */
    bool contains(Option i, Node v) const noexcept {
        assert(contains(i));
        auto & restoration_options = _qualityRestorationOptions[v];
        return std::any_of(restoration_options.begin(),
                           restoration_options.end(),
                           [i](const auto & p) { return p.option == i; });
    }

    /**
     * @brief Remove the node **v** from the option **i**
     * @param i Option
     * @param v Node
     * @time \f$O(\#options(v))\f$
     * @space \f$O(1)\f$
     */
    void removeNode(Option i, Node v) noexcept {
        assert(contains(i));
        auto & restoration_options = _qualityRestorationOptions[v];
        auto it = boost::find_if(restoration_options,
                                 [i](const auto & p) { return p.option == i; });
        if(it == restoration_options.end()) return;
        restoration_options.erase(it);
    }

    /**
     * @brief Test if there is an option concerning the node **v**
     * @param v Node
     * @return bool true if the option **i** concerns node **v**
     *      false otherwise
     * @time \f$O(1)\f$
     * @space \f$O(1)\f$
     */
    bool contains(Node v) const noexcept {
        return _qualityRestorationOptions[v].size() > 0;
    }

    /**
     * @brief Remove the node **v** from every option
     * @param v Node
     * @time \f$O(1)\f$
     * @space \f$O(1)\f$
     */
    void removeNode(Node v) noexcept { _qualityRestorationOptions[v].clear(); }

    /**
     * Add a restoration enhancement for the arc **a** within option **i**.
     * If there is already an enhancement for the arc **a** and option **i**,
     * the restored probability is updated to keep the maximum value.
     *
     * @brief Add the arc **a** to the option **i**
     * @param i Option
     * @param a Arc
     * @param restored_probability - restored probability of **a**
     * @time \f$O(\#options(a))\f$
     * @space \f$O(1)\f$
     */
    void addArc(Option i, Arc a, double restored_probability) noexcept {
        assert(contains(i));
        auto & restoration_options = _probabilityRestorationOptions[a];
        auto it = boost::find_if(restoration_options,
                                 [i](const auto & p) { return p.option == i; });
        if(it != restoration_options.end()) {
            it->restored_probability =
                std::max(restored_probability, it->restored_probability);
            return;
        }
        restoration_options.emplace_back(-1, i, restored_probability);
    }

    /**
     * @brief Return true if the option **i** concerns arc **a**
     * @param i Option
     * @param a Arc
     * @return bool true if the option **i** concerns arc **a** false otherwise
     * @time \f$O(\#options(a))\f$
     * @space \f$O(1)\f$
     */
    bool contains(Option i, Arc a) const noexcept {
        assert(contains(i));
        auto & restoration_options = _probabilityRestorationOptions[a];
        return std::any_of(restoration_options.begin(),
                           restoration_options.end(),
                           [i](const auto & p) { return p.option == i; });
    }

    /**
     * @brief Remove the arc **a** from the option **i**
     * @param i Option
     * @param a Arc
     * @time \f$O(\#options(a))\f$
     * @space \f$O(1)\f$
     */
    void removeArc(Option i, Arc a) noexcept {
        assert(contains(i));
        auto & restoration_options = _probabilityRestorationOptions[a];
        auto it = boost::find_if(restoration_options,
                                 [i](const auto & p) { return p.option == i; });
        if(it == restoration_options.end()) return;
        restoration_options.erase(it);
    }

    /**
     * @brief Test if there is an option concerning the arc **a**
     * @param a Arc
     * @return bool true if the option **i** concerns arc **a** false otherwise
     * @time \f$O(1)\f$
     * @space \f$O(1)\f$
     */
    bool contains(Arc a) const noexcept {
        return _probabilityRestorationOptions[a].size() > 0;
    }

    /**
     * @brief Remove the arc **a** from every option
     * @param a Arc
     * @time \f$O(1)\f$
     * @space \f$O(1)\f$
     */
    void removeArc(Arc a) noexcept {
        _probabilityRestorationOptions[a].clear();
    }

    /**
     * @brief Get the number of possible actions concerning nodes
     * @return int
     * @time \f$O(|V|)\f$
     * @space \f$O(1)\f$
     */
    int getNbNodeRestorationElements() const noexcept {
        const Graph & graph = _landscape.getNetwork();
        int count = 0;
        for(typename Graph::NodeIt u(graph); u != lemon::INVALID; ++u)
            count += _qualityRestorationOptions[u].size();
        return count;
    }

    /**
     * @brief Get the number of possible actions concerning nodes
     * @return int
     * @time \f$O(|A|)\f$
     * @space \f$O(1)\f$
     */
    int getNbArcRestorationElements() const noexcept {
        const Graph & graph = _landscape.getNetwork();
        int count = 0;
        for(typename Graph::ArcIt a(graph); a != lemon::INVALID; ++a)
            count += _probabilityRestorationOptions[a].size();
        return count;
    }

    /**
     * @brief Get the number of nodes and arcs concerned by at least one option
     * @return int
     * @time \f$O(1)\f$
     * @space \f$O(1)\f$
     */
    int getNbElements() const noexcept {
        return getNbNodeRestorationElements() + getNbArcRestorationElements();
    }

    /**
     * @brief Initializes nodes restoration elements ids.
     * @time \f$O(|V| * \#options)\f$
     * @space \f$O(1)\f$
     */
    void initNodeElementIDs() {
        const Graph & graph = _landscape.getNetwork();
        int count = 0;
        for(typename Graph::NodeIt u(graph); u != lemon::INVALID; ++u)
            for(auto & restoration_element : _qualityRestorationOptions[u])
                restoration_element.id = count++;
    }

    /**
     * @brief Initializes arcs restoration elements ids.
     * @time \f$O(|A| * \#options)\f$
     * @space \f$O(1)\f$
     */
    void initArcElementIDs() {
        const Graph & graph = _landscape.getNetwork();
        int count = 0;
        for(typename Graph::ArcIt a(graph); a != lemon::INVALID; ++a)
            for(auto & restoration_element : _probabilityRestorationOptions[a])
                restoration_element.id = count++;
    }

    /**
     * @brief Initializes restoration elements ids.
     * @time \f$O((|V| + |A|) * \#options)\f$
     * @space \f$O(1)\f$
     */
    void initElementIDs() {
        initNodeElementIDs();
        initArcElementIDs();
    }

    /**
     * @brief
     * @return NodeOptionsMap
     * @time \f$O(|V| * \#options)\f$
     * @space \f$O(|V| * \#options)\f$
     */
    NodeOptionsMap computeNodeOptionsMap() const {
        NodeOptionsMap nodeOptionsMap(getNbOptions());
        for(typename Graph::NodeIt v(_landscape.getNetwork());
            v != lemon::INVALID; ++v)
            for(auto const & e : _qualityRestorationOptions[v])
                nodeOptionsMap[e.option].emplace_back(v, e.quality_gain);
        return nodeOptionsMap;
    }

    /**
     * @brief
     * @return ArcOptionsMap
     * @time \f$O(|A| * \#options)\f$
     * @space \f$O(|A| * \#options)\f$
     */
    ArcOptionsMap computeArcOptionsMap() const {
        ArcOptionsMap arcOptionsMap(getNbOptions());
        for(typename Graph::ArcIt a(_landscape.getNetwork());
            a != lemon::INVALID; ++a)
            for(auto const & e : _probabilityRestorationOptions[a])
                arcOptionsMap[e.option].emplace_back(a, e.restored_probability);
        return arcOptionsMap;
    }

    /**
     * @brief Returns the restoration options concerning the node **u**
     * @param u Node
     * @return NodeRestorationsList
     * @time \f$O(1)\f$
     * @space \f$O(1)\f$
     */
    const NodeRestorationsList & operator[](Node u) const noexcept {
        return _qualityRestorationOptions[u];
    }

    /**
     * @brief Returns the restoration options concerning the arc **a**
     * @param a Arc
     * @return ArcRestorationsList
     * @time \f$O(1)\f$
     * @space \f$O(1)\f$
     */
    const ArcRestorationsList & operator[](Arc a) const noexcept {
        return _probabilityRestorationOptions[a];
    }

    /**
     * @brief Returns the restoration options concerning the node **u**
     * @param u Node
     * @return NodeRestorationsList
     * @time \f$O(1)\f$
     * @space \f$O(1)\f$
     */
    NodeRestorationsList & operator[](Node u) noexcept {
        return _qualityRestorationOptions[u];
    }

    /**
     * @brief Returns the restoration options concerning the arc **a**
     * @param a Arc
     * @return ArcRestorationsList
     * @time \f$O(1)\f$
     * @space \f$O(1)\f$
     */
    ArcRestorationsList & operator[](Arc a) noexcept {
        return _probabilityRestorationOptions[a];
    }

    /**
     * @brief Computes the total cost of the restoration plan, i.e. sum of
     * options costs
     * @return double
     */
    double totalCost() const noexcept {
        return std::accumulate(_costs.begin(), _costs.end(), 0.0);
    }

    /**
     * @brief Return a view for iterating over the option objects
     * @return auto
     */
    auto options() const {
        // auto view = ranges::views::transform(
        //     ranges::iota_view<int, int>(0, static_cast<int>(getNbOptions())),
        //     [](int constr_id) { return Option(constr_id); });
        auto view = ranges::iota_view<int, int>(0, static_cast<int>(getNbOptions()));
        return view;
    }
};

template <typename LS>  // requires concepts::IsLandscape<LS> //c++20
std::ostream & operator<<(std::ostream & in, const RestorationPlan<LS> & plan);

#endif  // RESTORATION_PLAN_2_HPP


text:
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// test_vector.cpp

// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// Use, modification and distribution is subject to 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)

// should pass compilation and execution

#include <cstddef> // NULL
#include <fstream>

#include <boost/config.hpp>
#include <cstdio> // remove
#if defined(BOOST_NO_STDC_NAMESPACE)
namespace std {
using ::remove;
}
#endif
#include "A.hpp"
#include "A.ipp"
#include "io_fixture.hpp"
#include <boost/serialization/vector.hpp>
#include <boost/static_assert.hpp>
#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_CASE(std_vector_int, io_fixture)
{
    std::vector<int> v;
    v.push_back(42);
    v.push_back(100);
    check_roundtrip_collection(v);
}

BOOST_FIXTURE_TEST_CASE(std_vector_bool, io_fixture)
{
    std::vector<bool> v;
    v.push_back(false);
    v.push_back(true);
    v.push_back(false);
    v.push_back(false);
    v.push_back(true);
    check_roundtrip_collection(v);
}

BOOST_FIXTURE_TEST_CASE(std_vector_A, io_fixture)
{
    std::vector<A> v;
    v.push_back(A());
    v.push_back(A());
    check_roundtrip_collection(v);
}

// class without default constructor
struct X
{
    // BOOST_DELETED_FUNCTION(X());
  public:
    int m_i;
    X(const X& x) : m_i(x.m_i) {}
    X(const int& i) : m_i(i) {}
    bool operator==(const X& rhs) const { return m_i == rhs.m_i; }
    template <class Archive>
    void serialize(Archive& ar, const unsigned int /*version*/)
    {
        ar& BOOST_SERIALIZATION_NVP(m_i);
    }
};

template <class Archive>
inline void save_construct_data(Archive& ar, const X* x,
                                const unsigned int /* file_version */
                                )
{
    // variable used for construction
    ar << boost::serialization::make_nvp("i", x->m_i);
}

template <class Archive>
inline void load_construct_data(Archive& ar, X* x,
                                const unsigned int /* file_version */
                                )
{
    int i;
    ar >> boost::serialization::make_nvp("i", i);
    ::new (x) X(i);
}

std::ostream& operator<<(std::ostream& os, const X& x)
{
    return os << "<X, m_i: " << x.m_i << ">";
}

BOOST_FIXTURE_TEST_CASE(std_vector_non_default_ctor, io_fixture)
{
    std::vector<X> v;
    v.push_back(X(123));
    v.push_back(X(456));
    check_roundtrip_collection(v);
}

max_stars_repo_name: rwols/yaml-archive

max_issues_repo_name: rwols/yaml-archive

max_forks_repo_name: rwols/yaml-archive


text:
/*******************************************************************************
 *
 * MIT License
 *
 * Copyright 2019-2020 Advanced Micro Devices, Inc.
 *
 * 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 "TestData.hpp"

#include <glob.h>
#include <unistd.h>

#include <boost/version.hpp>

#if BOOST_VERSION >= 106100
#include <boost/dll/runtime_symbol_info.hpp>
#else
#define TEST_DATA_USE_PROC_EXE
#endif

#include <Tensile/Utils.hpp>

TestData::operator bool() const
{
    return boost::filesystem::is_directory(dataDir());
}

TestData TestData::Invalid()
{
    return TestData(invalid_data());
}

TestData TestData::Env(std::string const& varName)
{
    char* var = getenv(varName.c_str());

    if(var == nullptr)
        return Invalid();

    return TestData(var);
}

boost::filesystem::path TestData::dataDir() const
{
    return m_dataDir;
}

boost::filesystem::path TestData::file(std::string const& filename) const
{
    auto simple = dataDir() / filename;
    if(boost::filesystem::is_regular_file(simple))
        return simple;

    auto datFile = file(filename, "dat");
    if(boost::filesystem::is_regular_file(datFile))
        return datFile;

    auto yamlFile = file(filename, "yaml");
    if(boost::filesystem::is_regular_file(yamlFile))
        return yamlFile;

    return simple;
}

boost::filesystem::path TestData::file(std::string const& filename,
                                       std::string const& extension) const
{
    return dataDir() / (filename + "." + extension);
}

std::vector<boost::filesystem::path> TestData::glob(std::string const& pattern) const
{
    std::string wholePattern = (dataDir() / pattern).native();

    glob_t result;
    result.gl_pathc = 0;
    result.gl_pathv = nullptr;
    result.gl_offs  = 0;

    int err = ::glob(wholePattern.c_str(), 0, nullptr, &result);

    // This way globfree will be called regardless of if an exception is thrown.
    std::shared_ptr<glob_t> guard(&result, globfree);

    if(err == GLOB_NOSPACE || err == GLOB_ABORTED)
        throw std::runtime_error(Tensile::concatenate("Glob ", wholePattern, " failed."));

    std::vector<boost::filesystem::path> rv(result.gl_pathc);

    for(size_t i = 0; i < result.gl_pathc; i++)
        rv[i] = result.gl_pathv[i];

    return rv;
}

boost::filesystem::path TestData::ProgramLocation()
{
#ifdef TEST_DATA_USE_PROC_EXE
    return boost::filesystem::read_symlink("/proc/self/exe");
#else
    return boost::dll::program_location();
#endif
}

TestData::TestData()
    : m_dataDir(ProgramLocation().parent_path() / "data")
{
}

TestData::TestData(std::string const& dataDir)
    : m_dataDir(dataDir)
{
}

TestData::TestData(invalid_data) {}

max_stars_repo_name: JeremyAdamHart/Tensile

max_issues_repo_name: JeremyAdamHart/Tensile

max_forks_repo_name: amdkila/Tensile


text:
#ifndef _YAHTTP_ROUTER_HPP
#define _YAHTTP_ROUTER_HPP 1
/* @file
 * @brief Defines router class and support structures
 */
#ifdef HAVE_CXX11
#include <functional>
#include <tuple>
#define HAVE_CPP_FUNC_PTR
#define IGNORE std::ignore
namespace funcptr = std;
#else
#ifdef HAVE_BOOST
#include <boost/function.hpp>
#include <boost/tuple/tuple.hpp>
#define IGNORE boost::tuples::ignore
namespace funcptr = boost;
#define HAVE_CPP_FUNC_PTR
#else
#warn "You need to configure with boost or have C++11 capable compiler for router"
#endif
#endif

#ifdef HAVE_CPP_FUNC_PTR
#include <vector>
#include <utility>

namespace YaHTTP {
  typedef funcptr::function <void(Request* req, Response* resp)> THandlerFunction; //!< Handler function pointer
  typedef funcptr::tuple<std::string, std::string, THandlerFunction, std::string> TRoute; //!< Route tuple (method, urlmask, handler, name)
  typedef std::vector<TRoute> TRouteList; //!< List of routes in order of evaluation

  /*! Implements simple router.

This class implements a router for masked urls. The URL mask syntax is as of follows

/<masked>/url<number>/<hi>.<format>

You can use <*param> to denote that everything will be matched and consumed into the parameter, including slash (/). Use <*> to denote that URL
is consumed but not stored. Note that only path is matched, scheme, host and url parameters are ignored.
   */
  class Router {
  private:
    Router() {};
    static Router router; //<! Singleton instance of Router
  public:
    void map(const std::string& method, const std::string& url, THandlerFunction handler, const std::string& name); //<! Instance method for mapping urls
    bool route(Request *req, THandlerFunction& handler); //<! Instance method for performing routing
    void printRoutes(std::ostream &os); //<! Instance method for printing routes
    std::pair<std::string, std::string> urlFor(const std::string &name, const strstr_map_t& arguments); //<! Instance method for generating paths

/*! Map an URL.
If method is left empty, it will match any method. Name is also optional, but needed if you want to find it for making URLs
*/
    static void Map(const std::string& method, const std::string& url, THandlerFunction handler, const std::string& name = "") { router.map(method, url, handler, name); };
    static void Get(const std::string& url, THandlerFunction handler, const std::string& name = "") { router.map("GET", url, handler, name); }; //<! Helper for mapping GET
    static void Post(const std::string& url, THandlerFunction handler, const std::string& name = "") { router.map("POST", url, handler, name); }; //<! Helper for mapping POST
    static void Put(const std::string& url, THandlerFunction handler, const std::string& name = "") { router.map("PUT", url, handler, name); }; //<! Helper for mapping PUT
    static void Patch(const std::string& url, THandlerFunction handler, const std::string& name = "") { router.map("PATCH", url, handler, name); }; //<! Helper for mapping PATCH
    static void Delete(const std::string& url, THandlerFunction handler, const std::string& name = "") { router.map("DELETE", url, handler, name); }; //<! Helper for mapping DELETE
    static void Any(const std::string& url, THandlerFunction handler, const std::string& name = "") { router.map("", url, handler, name); }; //<! Helper for mapping any method

    static bool Route(Request *req, THandlerFunction& handler) { return router.route(req, handler); }; //<! Performs routing based on req->url.path
    static void PrintRoutes(std::ostream &os) { router.printRoutes(os); }; //<! Prints all known routes to given output stream

    static std::pair<std::string, std::string> URLFor(const std::string &name, const strstr_map_t& arguments) { return router.urlFor(name,arguments); }; //<! Generates url from named route and arguments. Missing arguments are assumed empty
    static const TRouteList& GetRoutes() { return router.routes; } //<! Reference to route list

    TRouteList routes; //<! Instance variable for routes
  };
};
#endif

#endif

max_stars_repo_name: pieterlexis/yahttp

max_issues_repo_name: pieterlexis/yahttp

max_forks_repo_name: pieterlexis/yahttp