text:
#include <muse/chain/protocol/base_operations.hpp>
#include <fc/io/json.hpp>

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

namespace muse { namespace chain {

   inline void validate_url(const string& url )
   {
      FC_ASSERT(url.size() < MUSE_MAX_URL_LENGTH );
      FC_ASSERT(boost::starts_with( url, "ipfs://" ) );
            //TODO_MUSE - more checks...
   }

   bool inline is_asset_type( asset asset, asset_id_type asset_id )
   {
      return asset.asset_id == asset_id;
   }

   void account_create_operation::validate() const
   {
      FC_ASSERT( is_valid_account_name( new_account_name ), "Invalid account name" );
      FC_ASSERT( is_asset_type( fee, MUSE_SYMBOL ), "Account creation fee must be MUSE" );
      owner.validate();
      active.validate();

      if ( json_metadata.size() > 0 )
      {
         FC_ASSERT( fc::is_utf8(json_metadata), "JSON Metadata not formatted in UTF8" );
         //FC_ASSERT( fc::json::is_valid(json_metadata), "JSON Metadata not valid JSON" );
      }
      FC_ASSERT( fee >= asset( 0, MUSE_SYMBOL ) );
   }

   void account_update_operation::validate() const
   {
      FC_ASSERT( is_valid_account_name( account ) );
      if( owner )
         owner->validate();
      if (active)
         active->validate();

      if ( json_metadata.size() > 0 )
      {
         FC_ASSERT( fc::is_utf8(json_metadata), "JSON Metadata not formatted in UTF8" );
         //FC_ASSERT( fc::json::is_valid(json_metadata), "JSON Metadata not valid JSON" );
      }
   }

   void challenge_authority_operation::validate()const
    {
      FC_ASSERT( is_valid_account_name( challenger ), "challenger account name invalid" );
      FC_ASSERT( is_valid_account_name( challenged ), "challenged account name invalid" );
      FC_ASSERT( challenged != challenger );
   }

   void prove_authority_operation::validate()const
   {
      FC_ASSERT( is_valid_account_name( challenged ), "challenged account name invalid" );
   }

   void transfer_operation::validate() const
   { try {
      FC_ASSERT( is_valid_account_name( from ), "Invalid 'from' account name" );
      FC_ASSERT( is_valid_account_name( to ), "Invalid 'to' account name" );
      FC_ASSERT( amount.amount > 0, "Cannot transfer a negative amount (aka: stealing)" );
      FC_ASSERT( memo.size() < MUSE_MAX_MEMO_SIZE, "Memo is too large" );
      FC_ASSERT( fc::is_utf8( memo ), "Memo is not UTF8" );
   } FC_CAPTURE_AND_RETHROW( (*this) ) }

   void transfer_to_vesting_operation::validate() const
   {
      FC_ASSERT( is_valid_account_name( from ), "From account name invalid" );
      FC_ASSERT( is_asset_type( amount, MUSE_SYMBOL ), "Amount must be MUSE" );
      if ( !to.empty() ) FC_ASSERT( is_valid_account_name( to ), "To account name invalid" );
      FC_ASSERT( amount > asset( 0, MUSE_SYMBOL ), "Must transfer a nonzero amount" );
   }

   void withdraw_vesting_operation::validate() const
   {
      FC_ASSERT( is_valid_account_name( account ), "Account name invalid" );
      FC_ASSERT( is_asset_type( vesting_shares, VESTS_SYMBOL), "Amount must be VESTS"  );
   }

   void set_withdraw_vesting_route_operation::validate() const
   {
      FC_ASSERT( is_valid_account_name( from_account ), "Account name invalid" );
      FC_ASSERT( is_valid_account_name( to_account ), "Account name invalid" );
      FC_ASSERT( 0 <= percent && percent <= MUSE_100_PERCENT, "Percent must be valid muse percent" );
   }

   void witness_update_operation::validate() const
   {
      FC_ASSERT( is_valid_account_name( owner ), "Owner account name invalid" );
      FC_ASSERT( url.size() > 0, "URL size must be greater than 0" );
      FC_ASSERT( fc::is_utf8( url ) );
      FC_ASSERT( fee >= asset( 0, MUSE_SYMBOL ) );
      props.validate();
   }

   void account_witness_vote_operation::validate() const
   {
      FC_ASSERT( is_valid_account_name( account ), "Account ${a}", ("a",account)  );
      FC_ASSERT( is_valid_account_name( witness ) );
   }

   void account_witness_proxy_operation::validate() const
   {
      FC_ASSERT( is_valid_account_name( account ) );
      if( proxy.size() )
         FC_ASSERT( is_valid_account_name( proxy ) );
      FC_ASSERT( proxy != account );
   }

   void custom_operation::validate() const {
      /// required auth accounts are the ones whose bandwidth is consumed
      FC_ASSERT( required_auths.size() > 0, "at least on account must be specified" );
   }
   void custom_json_operation::validate() const {
      /// required auth accounts are the ones whose bandwidth is consumed
      FC_ASSERT( (required_auths.size() + required_basic_auths.size()) > 0, "at least on account must be specified" );
      FC_ASSERT( id.size() <= 32 );
      FC_ASSERT( fc::is_utf8(json), "JSON Metadata not formatted in UTF8" );
      //FC_ASSERT( fc::json::is_valid(json), "JSON Metadata not valid JSON" );
   }

   void feed_publish_operation::validate()const
   {
      FC_ASSERT( is_valid_account_name( publisher ) );
      FC_ASSERT( ( is_asset_type( exchange_rate.base, MUSE_SYMBOL ) && is_asset_type( exchange_rate.quote, MBD_SYMBOL ) )
         || ( is_asset_type( exchange_rate.base, MBD_SYMBOL ) && is_asset_type( exchange_rate.quote, MUSE_SYMBOL ) ) );
      exchange_rate.validate();
   }

   void limit_order_create_operation::validate()const
   {
      FC_ASSERT( is_valid_account_name( owner ) );
      FC_ASSERT ( is_asset_type( amount_to_sell, MBD_SYMBOL ) ||  is_asset_type( min_to_receive, MBD_SYMBOL ) );
      FC_ASSERT ( !is_asset_type( min_to_receive, VESTS_SYMBOL ) && !is_asset_type( amount_to_sell, VESTS_SYMBOL ) );
      (amount_to_sell / min_to_receive).validate();
   }
   void limit_order_create2_operation::validate()const
   {
      FC_ASSERT( is_valid_account_name( owner ) );
      FC_ASSERT( amount_to_sell.asset_id == exchange_rate.base.asset_id );
      exchange_rate.validate();

      FC_ASSERT ( is_asset_type( exchange_rate.base, MBD_SYMBOL ) ||  is_asset_type( exchange_rate.quote, MBD_SYMBOL ) );
      FC_ASSERT ( !is_asset_type( exchange_rate.base, VESTS_SYMBOL ) && !is_asset_type( exchange_rate.quote, VESTS_SYMBOL ) );

      FC_ASSERT( (amount_to_sell * exchange_rate).amount > 0 ); // must not round to 0
   }

   void limit_order_cancel_operation::validate()const
   {
      FC_ASSERT( is_valid_account_name( owner ) );
   }

   void convert_operation::validate()const
   {
      FC_ASSERT( is_valid_account_name( owner ) );
      /// only allow conversion from MBD to MUSE, allowing the opposite can enable traders to abuse
      /// market fluxuations through converting large quantities without moving the price.
      FC_ASSERT( is_asset_type( amount, MBD_SYMBOL ) );
      FC_ASSERT( amount.amount > 0 );
   }

   void report_over_production_operation::validate()const
   {
      FC_ASSERT( is_valid_account_name( reporter ) );
      FC_ASSERT( is_valid_account_name( first_block.witness ) );
      FC_ASSERT( first_block.witness   == second_block.witness );
      FC_ASSERT( first_block.timestamp == second_block.timestamp );
      FC_ASSERT( first_block.signee()  == second_block.signee() );
      FC_ASSERT( first_block.id() != second_block.id() );
   }

   void escrow_transfer_operation::validate()const
   {
      FC_ASSERT( is_valid_account_name( from ) );
      FC_ASSERT( is_valid_account_name( to ) );
      FC_ASSERT( is_valid_account_name( agent ) );
      FC_ASSERT( fee.amount >= 0 );
      FC_ASSERT( amount.amount >= 0 );
      FC_ASSERT( from != agent && to != agent );
      FC_ASSERT( fee.asset_id == amount.asset_id );
      FC_ASSERT( amount.asset_id != VESTS_SYMBOL );
   }

   void escrow_dispute_operation::validate()const
   {
      FC_ASSERT( is_valid_account_name( from ) );
      FC_ASSERT( is_valid_account_name( to ) );
      FC_ASSERT( is_valid_account_name( who ) );
      FC_ASSERT( who == from || who == to );
   }

   void escrow_release_operation::validate()const
   {
      FC_ASSERT( is_valid_account_name( from ) );
      FC_ASSERT( is_valid_account_name( to ) );
      FC_ASSERT( is_valid_account_name( who ) );
      FC_ASSERT( amount.amount > 0 );
      FC_ASSERT( amount.asset_id != VESTS_SYMBOL );
   }

   void request_account_recovery_operation::validate()const
   {
      FC_ASSERT( is_valid_account_name( recovery_account ) );
      FC_ASSERT( is_valid_account_name( account_to_recover ) );
      new_owner_authority.validate();
   }

   void recover_account_operation::validate()const
   {
      FC_ASSERT( is_valid_account_name( account_to_recover ) );
      FC_ASSERT( !( new_owner_authority == recent_owner_authority) );
      FC_ASSERT( !new_owner_authority.is_impossible() );
      FC_ASSERT( !recent_owner_authority.is_impossible() );
      FC_ASSERT( new_owner_authority.weight_threshold );
      new_owner_authority.validate();
      recent_owner_authority.validate();
   }

   void change_recovery_account_operation::validate()const
   {
      FC_ASSERT( is_valid_account_name( account_to_recover ) );
      FC_ASSERT( is_valid_account_name( new_recovery_account ) );
   }

} } // muse::chain

max_stars_repo_name: oxarbitrage/Muse-Source

max_issues_repo_name: oxarbitrage/Muse-Source

max_forks_repo_name: oxarbitrage/Muse-Source


text:
#ifndef TM_KIT_TRANSPORT_BOOST_UUID_COMPONENT_HPP_
#define TM_KIT_TRANSPORT_BOOST_UUID_COMPONENT_HPP_

#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/functional/hash.hpp>
#include <boost/lexical_cast.hpp>

#include <tm_kit/basic/ByteData.hpp>
#include <tm_kit/basic/ProtoInterop.hpp>
#include <tm_kit/basic/NlohmannJsonInterop.hpp>

namespace dev { namespace cd606 { namespace tm { namespace transport {

    struct BoostUUIDComponent {
        using IDType = boost::uuids::uuid;
        using IDHash = boost::hash<boost::uuids::uuid>;
        static constexpr std::size_t IDByteRepresentationSize = 16;
        static IDType new_id() {
            return boost::uuids::random_generator()();
        }
        static std::string id_to_string(IDType const &id) {
            return boost::lexical_cast<std::string>(id);
        }
        static IDType id_from_string(std::string const &s) {
            try {
                return boost::lexical_cast<IDType>(s);
            } catch (...) {
                return IDType {};
            }
        }
        static basic::ByteData id_to_bytes(IDType const &id) {
            std::array<char,16> ret;
            std::memcpy(ret.data(), &id, 16);
            return basic::ByteData {std::string {ret.data(), ret.data()+16}};
        }
        static IDType id_from_bytes(basic::ByteDataView const &bytes) {
            if (bytes.content.length() != 16) {
                return IDType {};
            }
            IDType id;
            std::memcpy(&id, bytes.content.data(), 16);
            return id;
        }
        static bool less_comparison_id(IDType const &a, IDType const &b) {
            return std::less<IDType>()(a,b);
        }
    };

} } } }

namespace dev { namespace cd606 { namespace tm { namespace basic { namespace bytedata_utils {

    template <>
    struct RunCBORSerializer<boost::uuids::uuid, void> {
        static std::string apply(boost::uuids::uuid const &id) {
            return RunCBORSerializer<std::string>::apply(boost::lexical_cast<std::string>(id));
        }
        static std::size_t apply(boost::uuids::uuid const &id, char *output) {
            return RunCBORSerializer<std::string>::apply(boost::lexical_cast<std::string>(id), output);
        }
        static std::size_t calculateSize(boost::uuids::uuid const &id) {
            return RunCBORSerializer<std::string>::calculateSize(boost::lexical_cast<std::string>(id));
        }
    };
    template <>
    struct RunCBORDeserializer<boost::uuids::uuid, void> {
        static std::optional<std::tuple<boost::uuids::uuid,size_t>> apply(std::string_view const &s, size_t start) {
            try {
                auto idStr = RunCBORDeserializer<std::string>::apply(s, start);
                if (!idStr) {
                    return std::nullopt;
                }
                boost::uuids::uuid id = boost::lexical_cast<boost::uuids::uuid>(std::get<0>(*idStr));
                return std::tuple<boost::uuids::uuid,size_t> {std::move(id), std::get<1>(*idStr)};
            } catch (boost::bad_lexical_cast const &) {
                return std::nullopt;
            }
        }
        static std::optional<size_t> applyInPlace(boost::uuids::uuid &output, std::string_view const &s, size_t start) {
            try {
                auto idStr = RunCBORDeserializer<std::string>::apply(s, start);
                if (!idStr) {
                    return std::nullopt;
                }
                output = boost::lexical_cast<boost::uuids::uuid>(std::get<0>(*idStr));
                return std::get<1>(*idStr);
            } catch (boost::bad_lexical_cast const &) {
                return std::nullopt;
            }
        }
    };

} } } } }

namespace dev { namespace cd606 { namespace tm { namespace basic { namespace proto_interop {
    template <>
    class ProtoEncoder<boost::uuids::uuid, void> {
    public:
        static constexpr uint64_t thisFieldNumber(uint64_t inputFieldNumber) {
            return inputFieldNumber;
        }
        static constexpr uint64_t nextFieldNumber(uint64_t inputFieldNumber) {
            return inputFieldNumber+1;
        }
        static void write(std::optional<uint64_t> fieldNumber, boost::uuids::uuid const &id, std::ostream &os, bool /*writeDefaultValue*/) {
            ProtoEncoder<std::string>::write(fieldNumber, boost::lexical_cast<std::string>(id), os, false);
        }
    };
    template <>
    struct ProtoWrappable<boost::uuids::uuid, void> {
        static constexpr bool value = true;
    };
    template <>
    class ProtoDecoder<boost::uuids::uuid, void> final : public IProtoDecoder<boost::uuids::uuid> {
    private:
        uint64_t baseFieldNumber_;
    public:
        ProtoDecoder(boost::uuids::uuid *output, uint64_t baseFieldNumber) : IProtoDecoder<boost::uuids::uuid>(output), baseFieldNumber_(baseFieldNumber) {}
        static std::vector<uint64_t> responsibleForFieldNumbers(uint64_t baseFieldNumber) {
            return {baseFieldNumber};
        }
        std::optional<std::size_t> read(boost::uuids::uuid &output, internal::FieldHeader const &fh, std::string_view const &input, std::size_t start) override final {
            std::string s;
            ProtoDecoder<std::string> subDec(&s, baseFieldNumber_);
            auto res = subDec.handle(fh, input, start);
            if (res) {
                try {
                    output = boost::lexical_cast<boost::uuids::uuid>(s);
                } catch (...) {
                    return std::nullopt;
                }
            }
            return res;
        }
    };

} } } } }

namespace dev { namespace cd606 { namespace tm { namespace basic { namespace nlohmann_json_interop {
    template <>
    class JsonEncoder<boost::uuids::uuid, void> {
    public:
        static void write(nlohmann::json &output, std::optional<std::string> const &key, boost::uuids::uuid const &data) {
            auto &o = (key?output[*key]:output);
            o = boost::lexical_cast<std::string>(data);
        }
    };
    template <>
    struct JsonWrappable<boost::uuids::uuid, void> {
        static constexpr bool value = true;
    };
    template <>
    class JsonDecoder<boost::uuids::uuid, void> {
    public:
        static bool read(nlohmann::json const &input, std::optional<std::string> const &key, boost::uuids::uuid &data, JsonFieldMapping const &/*mapping*/=JsonFieldMapping {}) {
            auto const &i = (key?input.at(*key):input);
            if (i.is_null()) {
                data = boost::uuids::uuid {};
                return false;
            } else {
                std::string s;
                i.get_to(s);
                try {
                    data = boost::lexical_cast<boost::uuids::uuid>(s);
                    return true;
                } catch (...) {
                    data = boost::uuids::uuid {};
                    return false;
                }
            }
        }
    };

} } } } }

#endif

ext: hpp


text:
#include "SamplePlugin.hpp"

#include <rw/math/Constants.hpp>
#include <rw/math/Quaternion.hpp>
#include <rw/models/Device.hpp>
#include <rwlibs/opengl/RenderFrame.hpp>
#include <rw/core/Ptr.hpp>

#include <RobWorkStudio.hpp>

#include <QTimer>

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

#include <sstream>
#include <iostream>

using namespace boost::asio;

using rw::core::ownedPtr;
using namespace rw::kinematics;
using namespace rw::math;
using namespace rw::models;
using rwlibs::opengl::RenderFrame;
using rws::RobWorkStudioPlugin;
using boost::asio::ip::udp;

//const int HEAD_IDX = 0;
//const int NECK_IDX = 1;
const int TORSO_IDX = 2;
const int LEFT_SHOULDER_IDX = 3;
const int LEFT_ELBOW_IDX = 4;
//const int LEFT_HAND_IDX = 5;
const int RIGHT_SHOULDER_IDX = 6;
const int RIGHT_ELBOW_IDX = 7;
//const int RIGHT_HAND_IDX = 8;
//const int LEFT_HIP_IDX = 9;
//const int LEFT_KNEE_IDX = 10;
//const int LEFT_FOOT_IDX = 11;
//const int RIGHT_HIP_IDX = 12;
//const int RIGHT_KNEE_IDX = 13;
//const int RIGHT_FOOT_IDX = 14;

SamplePlugin::SamplePlugin():
    RobWorkStudioPlugin("SamplePluginUI", QIcon(":/pa_icon.png")),
    io_service(NULL),
    endpoint(NULL),
    socket(NULL),
    resolver(NULL),
    _transforms(15),
    _rightArm(NULL)	,
    _leftArm(NULL)
{
    setupUi(this);

    // now connect stuff from the ui component
    connect(_connectBtn    ,SIGNAL(pressed()), this, SLOT(btnPressed()) );
    connect(_btn1    ,SIGNAL(pressed()), this, SLOT(btnPressed()) );
    connect(_showDebugBox    ,SIGNAL(changed()), this, SLOT(btnPressed()) );

    //connect(_spinBox  ,SIGNAL(valueChanged(int)), this, SLOT(btnPressed()) );

    _toFrameName.push_back("HEAD_IDX");
    _toFrameName.push_back("NECK_IDX");
    _toFrameName.push_back("TORSO_IDX");
    _toFrameName.push_back("LEFT_SHOULDER_IDX");
    _toFrameName.push_back("LEFT_ELBOW_IDX");
    _toFrameName.push_back("LEFT_HAND_IDX");
    _toFrameName.push_back("RIGHT_SHOULDER_IDX");
    _toFrameName.push_back("RIGHT_ELBOW_IDX");
    _toFrameName.push_back("RIGHT_HAND_IDX");
    _toFrameName.push_back("LEFT_HIP_IDX");
    _toFrameName.push_back("LEFT_KNEE_IDX");
    _toFrameName.push_back("LEFT_FOOT_IDX");
    _toFrameName.push_back("RIGHT_HIP_IDX");
    _toFrameName.push_back("RIGHT_KNEE_IDX");
    _toFrameName.push_back("RIGHT_FOOT_IDX");

    _timer = new QTimer( NULL );
    _timer->setInterval( 10 );
    connect( _timer, SIGNAL(timeout()), this, SLOT(btnPressed()) );

}

SamplePlugin::~SamplePlugin()
{
}

void SamplePlugin::initialize() {
    getRobWorkStudio()->stateChangedEvent().add(boost::bind(&SamplePlugin::stateChangedListener, this, boost::arg<1>()), this);
}

void SamplePlugin::open(WorkCell* workcell)
{
    if(_renderFrame == NULL)
        _renderFrame = ownedPtr( new RenderFrame(0.1f) );

    Frame *worldFrame = workcell->getWorldFrame();

    _drawables.resize(15);
    for(size_t i=0;i<_drawables.size();i++){
        _drawables[i] =
                getRobWorkStudio()->getWorkCellScene()->addRender(_toFrameName[i], _renderFrame, worldFrame);
    }

    _rightArm = workcell->findDevice<Device>("EasyBot1");
    _leftArm = workcell->findDevice<Device>("EasyBot2");

}

void SamplePlugin::close() {
}

namespace {

    Vector3D<> toXZX(const Quaternion<>& qn){
        Quaternion<> q = qn;
        q.normalize();
        Vector3D<> xzx;

        double u[4];
        u[0] = q(0);// W
        u[1] = q(1);
        u[2] = q(2);
        u[3] = q(3);

        double fcn1 =  2*(u[1]*u[3] - u[0]*u[2]);
        double fcn2 =  2*(u[1]*u[2] + u[0]*u[3]);
        double fcn3 =  u[0]*u[0] + u[1]*u[1] - u[2]*u[2] - u[3]*u[3];
        double fcn4 =  2*(u[1]*u[3] + u[0]*u[2]);
        double fcn5 = -2*(u[1]*u[2] - u[0]*u[3]);

        std::cout << fcn1  << " " << fcn2  << " " << fcn3  << " " << fcn4  << " " << fcn5  << std::endl;

        xzx(0) = atan2(fcn1, fcn2);
        xzx(1) = acos(fcn3);
        xzx(2) = atan2(fcn4, fcn5);
        return xzx;
    }

    Vector3D<> toXZX(const Rotation3D<>& R){
        return toXZX(Quaternion<>(R));
    }

}

void SamplePlugin::readUpdateFromUDP(){
    //std::vector<Transform3D<> > transforms(15);
    Q rightAngles(6,0.0), leftAngles(6,0.0);
    try
      {

        //boost::array<char, 1> send_buf  = { 0 };
        //socket.send_to(boost::asio::buffer(send_buf), receiver_endpoint);

        boost::array<float, 720> recv_buf;
        for(int i=0;i<720;i++){
            recv_buf.data()[i]=0.0;
        }

        udp::endpoint sender_endpoint;
        for(int j=0;j<1;j++){
            //size_t len = socket->receive_from( boost::asio::buffer(recv_buf), sender_endpoint);
        	socket->receive_from( boost::asio::buffer(recv_buf), sender_endpoint);

            for(size_t i=0;i<15;i++){
                Vector3D<> pos(recv_buf.data()[12*i+0],
                               recv_buf.data()[12*i+1],
                               recv_buf.data()[12*i+2]);
                Rotation3D<> rot(
                        recv_buf.data()[12*i+3],
                        recv_buf.data()[12*i+4],
                        recv_buf.data()[12*i+5],
                        recv_buf.data()[12*i+6],
                        recv_buf.data()[12*i+7],
                        recv_buf.data()[12*i+8],
                        recv_buf.data()[12*i+9],
                        recv_buf.data()[12*i+10],
                        recv_buf.data()[12*i+11]);

                _transforms[i].R() = rot;
                _transforms[i].P() = pos*0.001; // convert from mm to m

                _drawables[i]->setTransform(_transforms[i]);
            }

            //_transforms[RIGHT_SHOULDER_IDX] = inverse(_transforms[TORSO_IDX])*_transforms[RIGHT_SHOULDER_IDX];
            //_transforms[LEFT_SHOULDER_IDX ] = inverse(_transforms[TORSO_IDX])*_transforms[LEFT_SHOULDER_IDX];

            // the first angle is the rotation of LEFT_SHOULDER_IDX_x-axis around TORSO_IDX_z-axis
            leftAngles[0] = angle(_transforms[TORSO_IDX].R()*-Vector3D<>::x(),
                                  _transforms[LEFT_SHOULDER_IDX].R()*-Vector3D<>::x(),
                                  _transforms[TORSO_IDX].R()*Vector3D<>::y());
            // the second angle is the rotation of negative LEFT_SHOULDER_IDX_x-axis around TORSO_IDX_y-axis
            leftAngles[1] = angle(_transforms[TORSO_IDX].R()*-Vector3D<>::x(),
                                  _transforms[LEFT_SHOULDER_IDX].R()*-Vector3D<>::x(),
                                  _transforms[TORSO_IDX].R()*Vector3D<>::z());
            // the third angle is the rotation of LEFT_SHOULDER_IDX_y-axis around
            //leftAngles[2] = 0;
            // the forth angle is the angle from LEFT_SHOULDER_IDX_x-axis to LEFT_ELBOW_IDX_x-axis around LEFT_SHOULDER_IDX_y-axis
            leftAngles[2] = angle(_transforms[LEFT_SHOULDER_IDX].R()*-Vector3D<>::x(),
                                  _transforms[LEFT_ELBOW_IDX].R()*-Vector3D<>::x(),
                                  _transforms[LEFT_SHOULDER_IDX].R()*Vector3D<>::y());

            // NOW RIGHT ARM
            rightAngles[0] = angle(_transforms[TORSO_IDX].R()*Vector3D<>::x(),
                                  _transforms[RIGHT_SHOULDER_IDX].R()*Vector3D<>::x(),
                                  _transforms[TORSO_IDX].R()*Vector3D<>::y());
            // the second angle is the rotation of negative LEFT_SHOULDER_IDX_x-axis around TORSO_IDX_y-axis
            rightAngles[1] = angle(_transforms[TORSO_IDX].R()*Vector3D<>::x(),
                                  _transforms[RIGHT_SHOULDER_IDX].R()*Vector3D<>::x(),
                                  _transforms[TORSO_IDX].R()*Vector3D<>::z());
            // the third angle is the rotation of LEFT_SHOULDER_IDX_y-axis around
            //rightAngles[2] = 0;
            // the forth angle is the angle from LEFT_SHOULDER_IDX_x-axis to LEFT_ELBOW_IDX_x-axis around LEFT_SHOULDER_IDX_y-axis
            rightAngles[2] = angle(_transforms[RIGHT_SHOULDER_IDX].R()*Vector3D<>::x(),
                                  _transforms[RIGHT_ELBOW_IDX].R()*Vector3D<>::x(),
                                  _transforms[RIGHT_SHOULDER_IDX].R()*Vector3D<>::y());

            // hack because of marvin setup
            leftAngles[0] -= Pi-Pi/4;
            //leftAngles[1] = -leftAngles[1];
            //leftAngles[2] = (-leftAngles[2]);

            rightAngles[0] -= Pi/2.0;
            rightAngles[1] = -rightAngles[1];
            rightAngles[2] = (-rightAngles[2]);

        }
      }
      catch (std::exception& e)
      {
        std::cerr << e.what() << std::endl;
      }
      State state = getRobWorkStudio()->getState();

      if(_rightArm!=NULL){
          Q rq = _rightArm->getQ(state);
          for(size_t ix=0;ix<rq.size(); ix++){
              if(ix>=3)
                  break;
              rq(ix) = rightAngles(ix);
          }
          _rightArm->setQ(rq, state);
      }

      if(_leftArm!=NULL){
          Q rq = _leftArm->getQ(state);
          for(size_t ix=0;ix<rq.size(); ix++){
              if(ix>=6)
                  break;
              rq(ix) = leftAngles(ix);
          }
          _leftArm->setQ(rq, state);
      }

      getRobWorkStudio()->setState(state);
      std::stringstream sstr;
      sstr << (leftAngles*Rad2Deg);
      _anglesLine->setText( sstr.str().c_str() );
      std::stringstream sstr2;
      sstr2 << (rightAngles*Rad2Deg);
      _rightAngleLine->setText( sstr2.str().c_str() );

      //getRobWorkStudio()->postUpdateAndRepaint();

}

void SamplePlugin::btnPressed() {
    QObject *obj = sender();
    if(obj==_connectBtn){
        log().info() << "Button 0\n";

        if(io_service==NULL)
            io_service = new boost::asio::io_service();

        int port = _portSpin->value();
        resolver = new udp::resolver(*io_service);
        endpoint = new udp::endpoint(udp::v4(), port);
        socket = new udp::socket(*io_service, *endpoint);

        boost::asio::socket_base::receive_buffer_size option(4000);
        socket->set_option(option);

        _timer->start();
    } else if(obj==_btn1){
        log().info() << "Button 1\n";
        _timer->stop();
    } else if(obj==_timer){
        readUpdateFromUDP();
    }

}

void SamplePlugin::stateChangedListener(const State& state) {

}

ext: cpp


text:
/**
 * Titanium.UI.View for Windows
 *
 * Copyright (c) 2014 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License.
 * Please see the LICENSE included with this distribution for details.
 */

#include "TitaniumWindows/UI/View.hpp"
#include "TitaniumWindows/UI/WindowsViewLayoutDelegate.hpp"
#include "TitaniumWindows/Utility.hpp"
#include "TitaniumWindows/Filesystem.hpp"
#include "TitaniumWindows/File.hpp"
#include "Titanium/Blob.hpp"

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

namespace TitaniumWindows
{
	namespace UI
	{
		using namespace Windows::UI::Xaml;

		std::vector<std::string> View::fontFiles__;
		std::unordered_map<std::string, std::string> View::fonts__;

		View::View(const JSContext& js_context) TITANIUM_NOEXCEPT
			: Titanium::UI::View(js_context)
		{
			TITANIUM_LOG_DEBUG("TitaniumWindows::UI::View::ctor ", this);
		}

		View::~View()
		{
			TITANIUM_LOG_DEBUG("TitaniumWindows::UI::View::dtor ", this);
		}

		void View::postCallAsConstructor(const JSContext& js_context, const std::vector<JSValue>& arguments)
		{
			Titanium::UI::View::postCallAsConstructor(js_context, arguments);

			canvas__ = ref new Windows::UI::Xaml::Controls::Canvas();

			Titanium::UI::View::setLayoutDelegate<WindowsViewLayoutDelegate>();

			layoutDelegate__->set_defaultHeight(Titanium::UI::LAYOUT::FILL);
			layoutDelegate__->set_defaultWidth(Titanium::UI::LAYOUT::FILL);
			layoutDelegate__->set_autoLayoutForHeight(Titanium::UI::LAYOUT::FILL);
			layoutDelegate__->set_autoLayoutForWidth(Titanium::UI::LAYOUT::FILL);

			getViewLayoutDelegate<WindowsViewLayoutDelegate>()->setComponent(canvas__);
		}

		void View::JSExportInitialize()
		{
			JSExport<View>::SetClassVersion(1);
			JSExport<View>::SetParent(JSExport<Titanium::UI::View>::Class());
		}

		Windows::UI::Xaml::Media::FontFamily^ View::LookupFont(const JSContext& js_context, const std::string& family)
		{
			auto path = family;

			// if we have a cached value, use it
			if (fonts__.count(family) > 0) {
				path = fonts__.at(family);
			} else {

				// load fonts
				if (fontFiles__.size() == 0) {
					const auto titanium_js = js_context.get_global_object().GetProperty("Titanium");
					TITANIUM_ASSERT(titanium_js.IsObject());
					const auto titanium_obj = static_cast<JSObject>(titanium_js);

					const auto filesystem_js = titanium_obj.GetProperty("Filesystem");
					TITANIUM_ASSERT(filesystem_js.IsObject());
					const auto filesystem_obj = static_cast<JSObject>(filesystem_js);
					const auto filesystem = filesystem_obj.GetPrivate<Titanium::FilesystemModule>();

					const auto fontsDirectory = filesystem->getFile(js_context, filesystem->applicationDirectory() + "/fonts");
					fontFiles__ = fontsDirectory->getDirectoryListing();

					// filter fonts, currently only True Type Fonts
					fontFiles__.erase(std::remove_if(fontFiles__.begin(), fontFiles__.end(), [](std::string file) {
						return !boost::ends_with(file, ".ttf");
					}), fontFiles__.end());
				}

				// font file and family specified
				if (boost::contains(family, "#")) {
					path = "/fonts/" + family;

				// font name same as font file
				} else {
					auto family_lower = family;
					boost::to_lower(family_lower);
					for (auto file : fontFiles__) {
						boost::to_lower(file);
						if (boost::starts_with(file, family_lower)) {
							path = "/fonts/" + file + "#" + family;
							break;
						}
					}
				}

				fonts__.emplace(family, path);
			}

			return ref new Windows::UI::Xaml::Media::FontFamily(Utility::ConvertUTF8String(path));
		}

		Windows::UI::Xaml::FrameworkElement^ View::getComponent() TITANIUM_NOEXCEPT
		{
			return getViewLayoutDelegate<WindowsViewLayoutDelegate>()->getComponent();
		}
	} // namespace UI
} // namespace TitaniumWindows


text:
/*******************************************************************************
*
*  Filename    : MCCompare.cc
*  Description : Simple Comparison graphs for MC sample Comparison
*  Author      : Yi-Mu "Enoch" Chen [ ensc@hep1.phys.ntu.edu.tw ]
*
*******************************************************************************/
#include "TstarAnalysis/SignalMCStudy/interface/JetLepMgr.hpp"

#include <boost/program_options.hpp>
#include <iostream>
#include <string>
#include <vector>

using namespace std;
namespace opt = boost::program_options;

/*******************************************************************************
*   Main control flow
*******************************************************************************/
int
main( int argc, char* argv[] )
{
  opt::options_description desc( "options for jet-lep num compare" );
  desc.add_options()
    ( "masslist,m", opt::value<vector<string> >()->multitoken(), "which mass point to compare" );
  ;
  opt::variables_map vm;
  store( parse_command_line( argc, argv, desc ), vm );
  opt::notify( vm );

  cout << "Running jet lep comparison" << endl;

  vector<JetLepMgr*> samplelist;
  for( const auto& mass : vm["masslist"].as<vector<string>>() ){
    samplelist.push_back( new JetLepMgr(mass) );
  }

  MakeJetLepCompare( samplelist );

  for( const auto& sample : samplelist ){
    delete sample ;
  }
  return 0;
}

ext: cc

max_stars_repo_name: NTUHEP-Tstar/TstarAnalysis

max_issues_repo_name: NTUHEP-Tstar/TstarAnalysis

max_forks_repo_name: NTUHEP-Tstar/TstarAnalysis


text:
/* $Id: RemoteUserTool.cpp,v 1.7 2016/01/29 04:34:22 severin Exp $ */

/***

NAME - EEDB::Tools::RemoteUserTool

SYNOPSIS

DESCRIPTION

 Collection of methods to interact in a remote manner with a single ZENBU user system using the
 HMAC authentication protocol. Provides access to all the user manipluations WS API functions
 - upload file
 - delete file
 - edit metadata
 - share data with collaboration
 - list user uploaded data

CONTACT

Jessica Severin <severin@gsc.riken.jp>

LICENSE

 * Software License Agreement (BSD License)
 * ZENBU [EEDB] system
 * copyright (c) 2007-2013 Jessica Severin RIKEN OSC
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Jessica Severin RIKEN OSC 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 ''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 COPYRIGHT HOLDERS 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.

APPENDIX

The rest of the documentation details each of the object methods. Internal methods are usually preceded with a _

***/

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <stdarg.h>
#include <math.h>
#include <sys/time.h>
#include <sys/dir.h>
#include <sys/types.h>
#include <pwd.h>
#include <curl/curl.h>
#include <openssl/hmac.h>
#include <rapidxml.hpp>  //rapidxml must be include before boost
#include <boost/algorithm/string.hpp>
#include <EEDB/Assembly.h>
#include <EEDB/Chrom.h>
#include <EEDB/Experiment.h>
#include <EEDB/Feature.h>
#include <EEDB/FeatureSource.h>
#include <EEDB/EdgeSource.h>
#include <EEDB/Symbol.h>
#include <EEDB/SPStream.h>
#include <EEDB/Peer.h>
#include <EEDB/User.h>
#include <EEDB/Tools/RemoteUserTool.h>

using namespace std;
using namespace MQDB;

const char*  EEDB::Tools::RemoteUserTool::class_name = "EEDB::Tools::RemoteUserTool";

//call out functions
void _tools_remoteusertool_delete_func(MQDB::DBObject *obj) {
  delete (EEDB::Tools::RemoteUserTool*)obj;
}
void _tools_remoteusertool_xml_func(MQDB::DBObject *obj, string &xml_buffer) {
  ((EEDB::Tools::RemoteUserTool*)obj)->_xml(xml_buffer);
}
void _tools_remoteusertool_simple_xml_func(MQDB::DBObject *obj, string &xml_buffer) {
  ((EEDB::Tools::RemoteUserTool*)obj)->_xml(xml_buffer);
}

////////////////////////////////////////////////////////////////////////////
//
// libcurl callback code
//
////////////////////////////////////////////////////////////////////////////

struct RSS_curl_buffer {
  char *memory;
  size_t size;
  size_t alloc_size;
};

static size_t _rss_curl_writeMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
  size_t realsize = size * nmemb;
  struct RSS_curl_buffer *mem = (struct RSS_curl_buffer *)userp;
  //fprintf(stderr, "_rss_curl_writeMemoryCallback %ld\n", realsize);

  if(mem->size + realsize + 1 >= mem->alloc_size) {
    mem->alloc_size += realsize + 2*1024*1024;
    mem->memory = (char*)realloc(mem->memory, mem->alloc_size);
    //fprintf(stderr, "realloc %ld\n", mem->alloc_size);
  }
  if(mem->memory == NULL) {
    // out of memory!
    fprintf(stderr, "curl not enough memory (realloc returned NULL)\n");
    exit(EXIT_FAILURE);
  }

  memcpy(&(mem->memory[mem->size]), contents, realsize);
  mem->size += realsize;
  mem->memory[mem->size] = 0;
  return realsize;
}

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

EEDB::Tools::RemoteUserTool::RemoteUserTool() {
  init();
}

EEDB::Tools::RemoteUserTool::~RemoteUserTool() {
  // we're done with libcurl, so clean it up
  curl_global_cleanup();
}

EEDB::Tools::RemoteUserTool*  EEDB::Tools::RemoteUserTool::new_from_url(string url) {
  EEDB::Tools::RemoteUserTool*   stream = new EEDB::Tools::RemoteUserTool();
  stream->server_url(url);
  if(stream->_init_remote_server()) { return stream; }
  delete stream;
  return NULL;
}

void EEDB::Tools::RemoteUserTool::init() {
  MQDB::DBObject::init();
  _classname                 = EEDB::Tools::RemoteUserTool::class_name;
  _funcptr_delete            = _tools_remoteusertool_delete_func;
  _funcptr_xml               = _tools_remoteusertool_xml_func;
  _funcptr_simple_xml        = _tools_remoteusertool_simple_xml_func;

  //attribute variables
  _web_peer        = NULL;
  _user            = NULL;

  _server_url = "http://fantom.gsc.riken.jp/zenbu/";

  curl_global_init(CURL_GLOBAL_ALL);
}

void EEDB::Tools::RemoteUserTool::display_info() {
  printf("%s\n", display_desc().c_str());
}

string EEDB::Tools::RemoteUserTool::display_desc() {
  string str = "RemoteUserTool";
  return str;
}

string EEDB::Tools::RemoteUserTool::display_contents() {
  return display_desc();
}

void EEDB::Tools::RemoteUserTool::_xml(string &xml_buffer) {
  xml_buffer += "<remote_user_tool>\n";
  xml_buffer += "<server_url>"+ _server_url +"</server_url>\n";
  xml_buffer += "</remote_user_tool>\n";
}

////////////////////////////////////////////////////////////////////////////
//
// configuration methods
//
////////////////////////////////////////////////////////////////////////////

void  EEDB::Tools::RemoteUserTool::server_url(string url) {
  _server_url = url;
}

EEDB::User*  EEDB::Tools::RemoteUserTool::current_user() {
  if(_user) { return _user; }
  _get_cmdline_user();
  return _user;
}

void  EEDB::Tools::RemoteUserTool::set_user(EEDB::User* user) {
  if(_user) { _user->release(); _user=NULL; }
  if(user) {
    user->retain();
    _user = user;
  }
}

bool  EEDB::Tools::RemoteUserTool::_get_cmdline_user() {
  //reads ~/.zenbu/id_hmac to get hmac authentication secret
  int                      fildes;
  off_t                    cfg_len;
  char*                    config_text;

  if(_user) { return true; }
  struct passwd *pw = getpwuid(getuid());
  string path = pw->pw_dir;
  path += "/.zenbu/id_hmac";
  fildes = open(path.c_str(), O_RDONLY, 0x700);
  if(fildes<0) { return false; } //error

  cfg_len = lseek(fildes, 0, SEEK_END);
  //printf("config file %lld bytes long\n", (long long)cfg_len);
  lseek(fildes, 0, SEEK_SET);

  config_text = (char*)malloc(cfg_len+1);
  memset(config_text, 0, cfg_len+1);
  read(fildes, config_text, cfg_len);
  char* email = strtok(config_text, " \t\n");
  char* secret = strtok(NULL, " \t\n");

  printf("[%s] -> [%s]\n", email, secret);

  _user = new EEDB::User();
  if(email)  { _user->email_address(email); }
  if(secret) { _user->hmac_secretkey(secret); }

  free(config_text);
  close(fildes);
  return true;
}

void  EEDB::Tools::RemoteUserTool::set_peer_uuids(string peers) {
  _peers_filter = peers;
}

////////////////////////////////////////////////////////////////////////////
//
// spstream API call back methods
//
////////////////////////////////////////////////////////////////////////////

bool  EEDB::Tools::RemoteUserTool::_init_remote_server() {
  //uses the mode=status method to check if the server is alive
  //gets stats, get webserver uuid, allows initing fake registry_peer
  //http://fantom.gsc.riken.jp/zenbu/cgi/eedb_search.fcgi?mode=status

  rapidxml::xml_document<>       doc;
  rapidxml::xml_node<>           *root_node;

  CURL *curl = curl_easy_init();
  if(!curl) { return false; }

  struct RSS_curl_buffer  chunk;
  chunk.memory = NULL; // will be grown as needed
  chunk.size = 0;    // no data at this point
  chunk.alloc_size = 0;    // no data at this point

  string url = _server_url + "/cgi/eedb_search.fcgi?mode=status";
  //fprintf(stderr, "URL: %s\n", url.c_str());

  curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, _rss_curl_writeMemoryCallback);
  curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
  curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0");

  curl_easy_perform(curl);
  curl_easy_cleanup(curl);

  //fprintf(stderr, "%s\n", chunk.memory);

  char *start_ptr = strstr(chunk.memory, "<zenbu_status>");
  if(!start_ptr) { free(chunk.memory); return  false; }

  //fprintf(stderr, "%s\n", chunk.memory);

  doc.parse<rapidxml::parse_declaration_node | rapidxml::parse_no_data_nodes>(start_ptr);

  root_node = doc.first_node();
  if(!root_node) { free(chunk.memory); return false; }

  rapidxml::xml_node<> *node = root_node->first_node("web_uuid");
  if(!node) { free(chunk.memory); return false; }

  _web_peer = new EEDB::Peer();
  _web_peer->set_uuid(node->value());
  _web_peer->db_url(_server_url);

  free(chunk.memory);
  return true;
}

////////////////////////////////////////////////////////////////////////////
//
// user query methods
//
////////////////////////////////////////////////////////////////////////////

bool  EEDB::Tools::RemoteUserTool::verify_remote_user() {
  //collaborations user is member/owner of
  //might also need to cache peers, but for now try to do without caching
  rapidxml::xml_document<>       doc;
  rapidxml::xml_node<>           *root_node;

  CURL *curl = curl_easy_init();
  if(!curl) { return false; }

  struct RSS_curl_buffer  chunk;
  chunk.memory = NULL;  // will be grown as needed
  chunk.size = 0;       // no data at this point
  chunk.alloc_size = 0; // no data at this point

  string paramXML = "<zenbu_query>";
  if(current_user()) {
    paramXML += "<authenticate><email>"+ _user->email_identity() +"</email>";
    struct timeval  expiretime;
    gettimeofday(&expiretime, NULL); //set to 5min in the future
    long  value = expiretime.tv_sec+300;
    paramXML += "<expires>" +l_to_string(value) + "</expires>";
    paramXML += "</authenticate>";
  }

  paramXML += "<mode>user</mode>";
  paramXML += "</zenbu_query>";
  //fprintf(stderr, "POST: %s\n", paramXML.c_str());

  string url = _server_url + "/cgi/eedb_user.fcgi";
  curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  curl_easy_setopt(curl, CURLOPT_POST, 1);
  curl_easy_setopt(curl, CURLOPT_POSTFIELDS, paramXML.c_str());
  curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, paramXML.length());

  struct curl_slist *slist = NULL;
  slist = curl_slist_append(NULL, "Content-Type: text/xml; charset=utf-8"); // or whatever charset your XML is really using...
  if(_user) {
    string key = _user->hmac_secretkey();
    unsigned int md_len;
    unsigned char* result = HMAC(EVP_sha256(),
                                 (const unsigned char*)key.c_str(), key.length(),
                                 (const unsigned char*)paramXML.c_str(), paramXML.length(), NULL, &md_len);
    static char res_hexstring[64]; //expect 32 so this is safe
    bzero(res_hexstring, 64);
    for(unsigned i = 0; i < md_len; i++) { sprintf(&(res_hexstring[i * 2]), "%02x", result[i]); }

    string credentials = string("x-zenbu-magic: ") + res_hexstring;
    slist = curl_slist_append(slist, credentials.c_str());
  }
  curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);

  curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, _rss_curl_writeMemoryCallback);
  curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
  curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0");

  curl_easy_perform(curl);
  if(slist) { curl_slist_free_all(slist); }
  curl_easy_cleanup(curl);

  //fprintf(stderr, "returned-----\n%s\n", chunk.memory);
  char *start_ptr = strstr(chunk.memory, "<user");
  if(!start_ptr) { free(chunk.memory); return false; }

  doc.parse<rapidxml::parse_declaration_node | rapidxml::parse_no_data_nodes>(start_ptr);

  root_node = doc.first_node();
  if(!root_node) { free(chunk.memory); return false; }

  rapidxml::xml_node<> *node = root_node->first_node("eedb_user");
  EEDB::User *user = NULL;
  if(node) {
    user = new EEDB::User(node);
  }
  if(!user) { return false; }

  //fprintf(stderr, "%s\n", user->xml().c_str());

  free(chunk.memory);
  doc.clear();

  return true;
}

vector<EEDB::Collaboration*>  EEDB::Tools::RemoteUserTool::fetch_user_collaborations() {
  //collaborations user is member/owner of
  //might also need to cache peers, but for now try to do without caching
  rapidxml::xml_document<>       doc;
  rapidxml::xml_node<>           *root_node;

  vector<EEDB::Collaboration*>   collaborations;

  CURL *curl = curl_easy_init();
  if(!curl) { return collaborations; }

  struct RSS_curl_buffer  chunk;
  chunk.memory = NULL;  // will be grown as needed
  chunk.size = 0;       // no data at this point
  chunk.alloc_size = 0; // no data at this point

  string paramXML = "<zenbu_query>";
  if(_user) {
    paramXML += "<authenticate><email>"+ _user->email_identity() +"</email>";
    struct timeval  expiretime;
    gettimeofday(&expiretime, NULL); //set to 5min in the future
    long  value = expiretime.tv_sec+300;
    paramXML += "<expires>" +l_to_string(value) + "</expires>";
    paramXML += "</authenticate>";
  }

  paramXML += "<mode>collaborations</mode>";
  paramXML += "<format>fullxml</format>";  //maybe option for simple_xml
  paramXML += "</zenbu_query>";
  //fprintf(stderr, "POST: %s\n", paramXML.c_str());

  string url = _server_url + "/cgi/eedb_user.fcgi";
  curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  curl_easy_setopt(curl, CURLOPT_POST, 1);
  curl_easy_setopt(curl, CURLOPT_POSTFIELDS, paramXML.c_str());
  curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, paramXML.length());

  struct curl_slist *slist = NULL;
  slist = curl_slist_append(NULL, "Content-Type: text/xml; charset=utf-8"); // or whatever charset your XML is really using...
  if(_user) {
    string key = _user->hmac_secretkey();
    unsigned int md_len;
    unsigned char* result = HMAC(EVP_sha256(),
                                 (const unsigned char*)key.c_str(), key.length(),
                                 (const unsigned char*)paramXML.c_str(), paramXML.length(), NULL, &md_len);
    static char res_hexstring[64]; //expect 32 so this is safe
    bzero(res_hexstring, 64);
    for(unsigned i = 0; i < md_len; i++) { sprintf(&(res_hexstring[i * 2]), "%02x", result[i]); }

    string credentials = string("x-zenbu-magic: ") + res_hexstring;
    slist = curl_slist_append(slist, credentials.c_str());
  }
  curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);

  curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, _rss_curl_writeMemoryCallback);
  curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
  curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0");

  curl_easy_perform(curl);
  if(slist) { curl_slist_free_all(slist); }
  curl_easy_cleanup(curl);

  //fprintf(stderr, "%s\n", chunk.memory);
  char *start_ptr = strstr(chunk.memory, "<collaborations");
  if(!start_ptr) { free(chunk.memory); return collaborations; }

  doc.parse<rapidxml::parse_declaration_node | rapidxml::parse_no_data_nodes>(start_ptr);

  root_node = doc.first_node();
  if(!root_node) { free(chunk.memory); return collaborations; }

  rapidxml::xml_node<> *node = root_node->first_node("collaboration");
  while(node) {
    EEDB::Collaboration *obj = new EEDB::Collaboration(node);
    collaborations.push_back(obj);
    node = node->next_sibling("collaboration");
  }

  free(chunk.memory);
  doc.clear();

  return collaborations;
}

EEDB::SPStream*  EEDB::Tools::RemoteUserTool::stream_uploaded_data_sources(string classname, string filter_logic) {
  rapidxml::xml_document<>       doc;
  rapidxml::xml_node<>           *root_node;

  EEDB::SPStreams::StreamBuffer *streambuffer = new EEDB::SPStreams::StreamBuffer();

  CURL *curl = curl_easy_init();
  if(!curl) { return streambuffer; }

  struct RSS_curl_buffer  chunk;
  chunk.memory = NULL;  // will be grown as needed
  chunk.size = 0;       // no data at this point
  chunk.alloc_size = 0; // no data at this point

  string paramXML = "<zenbu_query>";
  if(current_user()) {
    paramXML += "<authenticate><email>"+ _user->email_identity() +"</email>";
    struct timeval  expiretime;
    gettimeofday(&expiretime, NULL); //set to 5min in the future
    long  value = expiretime.tv_sec+300;
    paramXML += "<expires>" +l_to_string(value) + "</expires>";
    paramXML += "</authenticate>";
  }

  if(classname == "Experiment") { paramXML += "<mode>experiments</mode>"; }
  else if(classname == "FeatureSource") { paramXML += "<mode>feature_sources</mode>"; }
  else { paramXML += "<mode>sources</mode>"; }

  if(!_peers_filter.empty()) { paramXML += "<peers>"+ _peers_filter +"</peers>"; }

  if(!filter_logic.empty()) { paramXML += "<filter>"+filter_logic+"</filter>"; }

  paramXML += "<collab>private</collab><format>fullxml</format></zenbu_query>";
  fprintf(stderr, "POST: %s\n", paramXML.c_str());

  string url = _server_url + "/cgi/eedb_search.fcgi";
  curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  curl_easy_setopt(curl, CURLOPT_POST, 1);
  curl_easy_setopt(curl, CURLOPT_POSTFIELDS, paramXML.c_str());
  curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, paramXML.length());

  struct curl_slist *slist = NULL;
  slist = curl_slist_append(NULL, "Content-Type: text/xml; charset=utf-8"); // or whatever charset your XML is really using...
  if(_user) {
    string key = _user->hmac_secretkey();
    unsigned int md_len;
    unsigned char* result = HMAC(EVP_sha256(),
                                 (const unsigned char*)key.c_str(), key.length(),
                                 (const unsigned char*)paramXML.c_str(), paramXML.length(), NULL, &md_len);
    static char res_hexstring[64]; //expect 32 so this is safe
    bzero(res_hexstring, 64);
    for(unsigned i = 0; i < md_len; i++) { sprintf(&(res_hexstring[i * 2]), "%02x", result[i]); }

    string credentials = string("x-zenbu-magic: ") + res_hexstring;
    slist = curl_slist_append(slist, credentials.c_str());
  }
  curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);

  curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, _rss_curl_writeMemoryCallback);
  curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
  curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0");

  curl_easy_perform(curl);
  if(slist) { curl_slist_free_all(slist); }
  curl_easy_cleanup(curl);

  //fprintf(stderr, "%s\n", chunk.memory);
  char *start_ptr = NULL;
  if(classname == "Experiment") { start_ptr = strstr(chunk.memory, "<experiments"); }
  else if(classname == "FeatureSource") { start_ptr = strstr(chunk.memory, "<feature_sources"); }
  else { start_ptr = strstr(chunk.memory, "<sources"); }
  if(!start_ptr) { free(chunk.memory); return streambuffer; }

  doc.parse<rapidxml::parse_declaration_node | rapidxml::parse_no_data_nodes>(start_ptr);

  root_node = doc.first_node();
  if(!root_node) { free(chunk.memory); return streambuffer; }

  rapidxml::xml_node<> *node;
  node = root_node->first_node("peer");
  while(node) {
    EEDB::Peer *peer = EEDB::Peer::new_from_xml(node);
    streambuffer->add_object(peer);
    node = node->next_sibling("peer");
  }
  node = root_node->first_node("experiment");
  while(node) {
    EEDB::Experiment *source = new EEDB::Experiment(node, true);
    streambuffer->add_object(source);
    node = node->next_sibling("experiment");
  }
  node = root_node->first_node("featuresource");
  while(node) {
    EEDB::FeatureSource *source = new EEDB::FeatureSource(node);
    streambuffer->add_object(source);
    node = node->next_sibling("featuresource");
  }

  free(chunk.memory);
  doc.clear();

  return streambuffer;
}


text:
// Copyright 2021, Beeri 15.  All rights reserved.
// Author: Roman Gershman (romange@gmail.com)
//

#include "util/tls/tls_engine.h"

#include <string_view>
#include <openssl/err.h>

#include <boost/fiber/fiber.hpp>
#include <boost/fiber/operations.hpp>

#include "base/gtest.h"
#include "base/logging.h"

namespace util {
namespace tls {

using namespace std;
using namespace boost;

string SSLError(unsigned long e) {
  char buf[256];
  ERR_error_string_n(e, buf, sizeof(buf));
  return buf;
}

static int VerifyCallback(int ok, X509_STORE_CTX* ctx) {
  LOG(WARNING) << "verify_callback: " << ok;
  return 1;
}

SSL_CTX* CreateSslCntx() {
  SSL_CTX* ctx = SSL_CTX_new(TLS_method());

  SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);

  SSL_CTX_set_options(ctx, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);

  // SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL);
  SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, VerifyCallback);

  // Can also be defined using "ADH:@SECLEVEL=0" cipher string below.
  SSL_CTX_set_security_level(ctx, 0);

  CHECK_EQ(1, SSL_CTX_set_cipher_list(ctx, "ADH"));

  return ctx;
}
class SslStreamTest : public testing::Test {
 public:
  struct Options {
    string name;

    unsigned mutate_indx = 0;
    uint8_t mutate_val = 0;
    bool drain_output = false;

    Options(std::string_view v) : name{v} {
    }
  };

  using OpCb = std::function<Engine::OpResult(Engine*)>;

 protected:
  static void SetUpTestSuite() {
  }

  void SetUp() override;

  void TearDown() override {
    client_engine_.reset();
    server_engine_.reset();
  }

  unique_ptr<Engine> client_engine_, server_engine_;
  OpCb srv_handshake_, client_handshake_, shutdown_op_;
  OpCb write_op_, read_op_;

  Options client_opts_{"client"}, srv_opts_{"server"};

  unique_ptr<uint8_t[]> tmp_buf_;
  enum { TMP_CAPACITY = 1024 };
  size_t read_sz_ = 0;
};

void SslStreamTest::SetUp() {
  SSL_CTX* ctx = CreateSslCntx();

  client_engine_.reset(new Engine(ctx));
  server_engine_.reset(new Engine(ctx));
  SSL_CTX_free(ctx);

  // Configure server side.
  SSL* ssl = server_engine_->native_handle();
  SSL_set_options(ssl, SSL_OP_CIPHER_SERVER_PREFERENCE);
  CHECK_EQ(1, SSL_set_dh_auto(ssl, 1));

  tmp_buf_.reset(new uint8_t[TMP_CAPACITY]);

  srv_handshake_ = [](Engine* eng) { return eng->Handshake(Engine::SERVER); };
  client_handshake_ = [](Engine* eng) { return eng->Handshake(Engine::CLIENT); };
  read_op_ = [this](Engine* eng) { return eng->Read(tmp_buf_.get(), TMP_CAPACITY); };
  shutdown_op_ = [](Engine* eng) { return eng->Shutdown(); };
  write_op_ = [this](Engine* eng) {
    return eng->Write(Engine::Buffer{tmp_buf_.get(), TMP_CAPACITY});
  };

  ERR_print_errors_fp(stderr);  // Empties the queue.
}

static unsigned long RunPeer(SslStreamTest::Options opts, SslStreamTest::OpCb cb, Engine* src,
                             Engine* dest) {
  unsigned input_pending = 1;
  while (true) {
    auto op_result = cb(src);
    if (!op_result) {
      return op_result.error();
    }
    VLOG(1) << opts.name << " OpResult: " << *op_result;
    unsigned output_pending = src->OutputPending();
    if (output_pending > 0) {
      if (opts.drain_output)
        src->FetchOutputBuf();
      else {
        auto buf_result = src->PeekOutputBuf();
        CHECK(buf_result);
        VLOG(1) << opts.name << " wrote " << buf_result->size() << " bytes";
        CHECK(!buf_result->empty());

        if (opts.mutate_indx) {
          uint8_t* mem = const_cast<uint8_t*>(buf_result->data());
          mem[opts.mutate_indx % buf_result->size()] = opts.mutate_val;
          opts.mutate_indx = 0;
        }

        auto write_result = dest->WriteBuf(*buf_result);
        if (!write_result) {
          return write_result.error();
        }
        CHECK_GT(*write_result, 0);
        src->ConsumeOutputBuf(*write_result);
      }
    }
    if (*op_result >= 0) {  // Shutdown or empty read/write may return 0.
      return 0;
    }
    if (*op_result == Engine::EOF_STREAM) {
      LOG(WARNING) << opts.name << " stream truncated";
      return 0;
    }

    if (input_pending == 0 && output_pending == 0) {  // dropped connection
      LOG(INFO) << "Dropped connections for " << opts.name;

      return ERR_PACK(ERR_LIB_USER, 0, ERR_R_OPERATION_FAIL);
    }
    this_fiber::yield();
    input_pending = src->InputPending();
    VLOG(1) << "Input size: " << input_pending;
  }
}

TEST_F(SslStreamTest, BIO_s_bio_err) {
  // BIO_new creates a default buffer of 17KB.
  BIO* bio1 = BIO_new(BIO_s_bio());
  constexpr char kData[] = "ROMAN";
  ASSERT_EQ(0, ERR_get_error());

  // -2 - not implemented: https://www.openssl.org/docs/man1.1.1/man3/BIO_write.html
  EXPECT_EQ(-2, BIO_write(bio1, kData, sizeof(kData)));
  int e = ERR_get_error();
  EXPECT_NE(0, e);
  EXPECT_EQ(BIO_F_BIO_WRITE_INTERN, ERR_GET_FUNC(e));
  EXPECT_EQ(BIO_R_UNINITIALIZED, ERR_GET_REASON(e));
  BIO_free(bio1);
}

TEST_F(SslStreamTest, BIO_s_bio_ZeroCopy) {
  BIO *bio1, *bio2;

  // writesize = 0, means we use default 17KB buffer.
  ASSERT_EQ(1, BIO_new_bio_pair(&bio1, 0, &bio2, 0));

  char *buf1 = nullptr, *buf2 = nullptr;

  // Fetch buffer to the direct memory buffer.
  ssize_t write_size = BIO_nwrite0(bio1, &buf1);
  EXPECT_EQ(17 * 1024, write_size);
  memset(buf1, 'a', write_size);

  EXPECT_EQ(write_size, BIO_nwrite(bio1, nullptr, write_size));  // commit.
  EXPECT_EQ(-1, BIO_nwrite(bio1, nullptr, 1));                   // No space to commit.
  EXPECT_EQ(0, BIO_ctrl_get_write_guarantee(bio1));
  EXPECT_EQ(0, BIO_ctrl_pending(bio1));            // 0 read pending.
  EXPECT_EQ(write_size, BIO_ctrl_wpending(bio1));  // 17KB write pending.

  EXPECT_EQ(write_size, BIO_ctrl_pending(bio2));  // 17KB read pending.
  EXPECT_EQ(0, BIO_ctrl_wpending(bio2));          // 0 write pending.

  ASSERT_EQ(write_size, BIO_nread0(bio2, &buf2));
  EXPECT_EQ(0, memcmp(buf1, buf2, write_size));
  EXPECT_EQ(write_size, BIO_nread(bio2, nullptr, write_size));

  // bio1 is empty again.
  EXPECT_EQ(write_size, BIO_ctrl_get_write_guarantee(bio1));

  // Another way to write to BIO without using BIO_nwrite0.
  // Instead of fetching a pointer to buffer, we commit first and then write using memcpy.
  buf1 = nullptr;
  EXPECT_EQ(write_size, BIO_nwrite(bio1, &buf1, write_size));  // commit first.

  // BIO is single-threaded object, hence noone will read from bio2 as long
  // as we do not switch to reading ourselves. Therefore the order of committing and writing is not
  // important.
  memset(buf1, 'a', write_size);

  BIO_free(bio1);
  BIO_free(bio2);
}

TEST_F(SslStreamTest, Handshake) {
  unsigned long cl_err = 0, srv_err = 0;

  auto client_fb = fibers::fiber([&] {
    cl_err = RunPeer(client_opts_, client_handshake_, client_engine_.get(), server_engine_.get());
  });

  auto server_fb = fibers::fiber([&] {
    srv_err = RunPeer(srv_opts_, srv_handshake_, server_engine_.get(), client_engine_.get());
  });

  client_fb.join();
  server_fb.join();
  ASSERT_EQ(0, cl_err);
  ASSERT_EQ(0, srv_err);
}

TEST_F(SslStreamTest, HandshakeErrServer) {
  unsigned long cl_err = 0, srv_err = 0;

  auto client_fb = fibers::fiber([&] {
    cl_err = RunPeer(client_opts_, client_handshake_, client_engine_.get(), server_engine_.get());
  });

  srv_opts_.mutate_indx = 100;
  srv_opts_.mutate_val = 'R';

  auto server_fb = fibers::fiber([&] {
    srv_err = RunPeer(srv_opts_, srv_handshake_, server_engine_.get(), client_engine_.get());
  });

  client_fb.join();
  server_fb.join();

  LOG(INFO) << SSLError(cl_err);
  LOG(INFO) << SSLError(srv_err);

  ASSERT_NE(0, cl_err);
}

TEST_F(SslStreamTest, ReadShutdown) {
  unsigned long cl_err = 0, srv_err = 0;

  auto client_fb = fibers::fiber([&] {
    cl_err = RunPeer(client_opts_, client_handshake_, client_engine_.get(), server_engine_.get());
  });

  auto server_fb = fibers::fiber([&] {
    srv_err = RunPeer(srv_opts_, srv_handshake_, server_engine_.get(), client_engine_.get());
  });

  client_fb.join();
  server_fb.join();

  ASSERT_EQ(0, cl_err);
  ASSERT_EQ(0, srv_err);

  client_fb = fibers::fiber([&] {
    cl_err = RunPeer(client_opts_, shutdown_op_, client_engine_.get(), server_engine_.get());
  });

  server_fb = fibers::fiber(
      [&] { srv_err = RunPeer(srv_opts_, read_op_, server_engine_.get(), client_engine_.get()); });

  server_fb.join();
  client_fb.join();
  ASSERT_EQ(0, cl_err);
  ASSERT_EQ(0, srv_err);

  int shutdown_srv = SSL_get_shutdown(server_engine_->native_handle());
  int shutdown_client = SSL_get_shutdown(client_engine_->native_handle());
  ASSERT_EQ(SSL_RECEIVED_SHUTDOWN, shutdown_srv);
  ASSERT_EQ(SSL_SENT_SHUTDOWN, shutdown_client);

  client_fb = fibers::fiber([&] {
    cl_err = RunPeer(client_opts_, shutdown_op_, client_engine_.get(), server_engine_.get());
  });

  server_fb = fibers::fiber([&] {
    srv_err = RunPeer(srv_opts_, shutdown_op_, server_engine_.get(), client_engine_.get());
  });
  server_fb.join();
  client_fb.join();

  ASSERT_EQ(0, cl_err) << SSLError(cl_err);
  ASSERT_EQ(0, srv_err);

  shutdown_srv = SSL_get_shutdown(server_engine_->native_handle());
  shutdown_client = SSL_get_shutdown(client_engine_->native_handle());
  ASSERT_EQ(SSL_RECEIVED_SHUTDOWN | SSL_SENT_SHUTDOWN, shutdown_srv);
  ASSERT_EQ(shutdown_client, shutdown_srv);
}

TEST_F(SslStreamTest, Write) {
  unsigned long cl_err = 0, srv_err = 0;

  auto client_fb = fibers::fiber([&] {
    cl_err = RunPeer(client_opts_, client_handshake_, client_engine_.get(), server_engine_.get());
  });

  auto server_fb = fibers::fiber([&] {
    srv_err = RunPeer(srv_opts_, srv_handshake_, server_engine_.get(), client_engine_.get());
  });

  client_fb.join();
  server_fb.join();
  client_opts_.drain_output = true;
  for (size_t i = 0; i < 10; ++i) {
    cl_err = RunPeer(client_opts_, write_op_, client_engine_.get(), server_engine_.get());
    ASSERT_EQ(0, cl_err);
  }
}

void BM_TlsWrite(benchmark::State& state) {
  unique_ptr<Engine> client_engine, server_engine;
  SslStreamTest::Options sopts{"srv"}, copts{"client"};
  auto cl_handshake = [](Engine* eng) { return eng->Handshake(Engine::CLIENT); };
  auto srv_handshake = [](Engine* eng) { return eng->Handshake(Engine::SERVER); };
  SSL_CTX* ctx = CreateSslCntx();
  client_engine.reset(new Engine(ctx));
  server_engine.reset(new Engine(ctx));
  SSL_CTX_free(ctx);

  SSL* ssl = server_engine->native_handle();
  CHECK_EQ(1, SSL_set_dh_auto(ssl, 1));

  auto client_fb = fibers::fiber(
      [&] { RunPeer(copts, cl_handshake, client_engine.get(), server_engine.get()); });

  auto server_fb = fibers::fiber(
      [&] { RunPeer(sopts, srv_handshake, server_engine.get(), client_engine.get()); });

  client_fb.join();
  server_fb.join();

  copts.drain_output = true;

  size_t len = state.range(0);
  unique_ptr<uint8_t[]> wb(new uint8_t[len]);
  Engine::Buffer buf{wb.get(), len};

  auto write_cb = [&](Engine* eng) { return eng->Write(buf); };
  while (state.KeepRunning()) {
    CHECK_EQ(0u, RunPeer(copts, write_cb, client_engine.get(), server_engine.get()));
  }
}
BENCHMARK(BM_TlsWrite)->Arg(1024)->Arg(4096)->ArgName("bytes");

}  // namespace tls
}  // namespace util

max_stars_repo_name: romange/helio

max_issues_repo_name: romange/async

max_forks_repo_name: romange/async


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

#include <gtest/gtest.h>

#include <bm/bm_apps/packet_pipe.h>

#include <boost/filesystem.hpp>

#include <string>
#include <memory>
#include <vector>
#include <algorithm>  // for std::fill_n
#include <fstream>
#include <streambuf>

#include "simple_switch.h"

#include "utils.h"

namespace fs = boost::filesystem;

using bm::MatchErrorCode;
using bm::ActionData;
using bm::MatchKeyParam;
using bm::entry_handle_t;

namespace {

void
packet_handler(int port_num, const char *buffer, int len, void *cookie) {
  static_cast<SimpleSwitch *>(cookie)->receive(port_num, buffer, len);
}

}  // namespace

class SimpleSwitch_SwapP4 : public ::testing::Test {
 protected:
  static constexpr size_t kMaxBufSize = 512;

  static constexpr bm::device_id_t device_id{0};

  SimpleSwitch_SwapP4()
      : packet_inject(packet_in_addr) { }

  // Per-test-case set-up.
  // We make the switch a shared resource for all tests. This is mainly because
  // the simple_switch target detaches threads
  static void SetUpTestCase() {
    // bm::Logger::set_logger_console();

    test_switch = new SimpleSwitch(true);  // with swapping

    test_switch->init_objects(json_path_1());

    // packet in - packet out
    test_switch->set_dev_mgr_packet_in(device_id, packet_in_addr, nullptr);
    test_switch->Switch::start();  // there is a start member in SimpleSwitch
    test_switch->set_packet_handler(packet_handler,
                                    static_cast<void *>(test_switch));
    test_switch->start_and_return();
  }

  // Per-test-case tear-down.
  static void TearDownTestCase() {
    delete test_switch;
  }

  virtual void SetUp() {
    packet_inject.start();
    auto cb = std::bind(&PacketInReceiver::receive, &receiver,
                        std::placeholders::_1, std::placeholders::_2,
                        std::placeholders::_3, std::placeholders::_4);
    packet_inject.set_packet_receiver(cb, nullptr);
  }

  virtual void TearDown() {
    // kind of experimental, so reserved for testing
    test_switch->reset_state();
  }

  static std::string json_path_1() {
    return (fs::path(testdata_dir) / fs::path(test_json_1)).string();
  }
  static std::string json_path_2() {
    return (fs::path(testdata_dir) / fs::path(test_json_2)).string();
  }

  void configure_swap_1() {
    test_switch->mt_set_default_action(0, "t_ingress_1", "a11", ActionData());

    std::vector<MatchKeyParam> match_key;
    match_key.emplace_back(MatchKeyParam::Type::EXACT, std::string("\xab"));
    entry_handle_t handle;
    MatchErrorCode rc = test_switch->mt_add_entry(
        0, "t_ingress_1", match_key, "a12", ActionData(), &handle);
    ASSERT_EQ(MatchErrorCode::SUCCESS, rc);
  }

  void configure_swap_2() {
    test_switch->mt_set_default_action(0, "t_ingress_2", "a21", ActionData());

    std::vector<MatchKeyParam> match_key;
    match_key.emplace_back(MatchKeyParam::Type::EXACT, std::string("\xcd"));
    entry_handle_t handle;
    MatchErrorCode rc = test_switch->mt_add_entry(
        0, "t_ingress_2", match_key, "a22", ActionData(), &handle);
    ASSERT_EQ(MatchErrorCode::SUCCESS, rc);
  }

 protected:
  static const std::string packet_in_addr;
  static SimpleSwitch *test_switch;
  bm_apps::PacketInject packet_inject;
  PacketInReceiver receiver{};

 private:
  static const std::string testdata_dir;
  static const std::string test_json_1;
  static const std::string test_json_2;
};

const std::string SimpleSwitch_SwapP4::packet_in_addr =
    "inproc://packets";

SimpleSwitch *SimpleSwitch_SwapP4::test_switch = nullptr;

const std::string SimpleSwitch_SwapP4::testdata_dir = TESTDATADIR;
const std::string SimpleSwitch_SwapP4::test_json_1 = "swap_1.json";
const std::string SimpleSwitch_SwapP4::test_json_2 = "swap_2.json";

TEST_F(SimpleSwitch_SwapP4, Swap) {
  const int port_in = 0;

  bm::RuntimeInterface::ErrorCode rc;
  const auto rc_success = bm::RuntimeInterface::ErrorCode::SUCCESS;

  auto swap_1_check = [this, port_in]() {
    int recv_port = -1;
    char recv_buffer[2];

    const char pkt_1_miss[2] = {'\x00', '\x00'};
    const char pkt_1_hit[2] = {'\xab', '\x00'};
    const int port_1_miss = 1;
    const int port_1_hit = 2;

    packet_inject.send(port_in, pkt_1_miss, sizeof(pkt_1_miss));
    receiver.read(recv_buffer, sizeof(pkt_1_miss), &recv_port);
    ASSERT_EQ(port_1_miss, recv_port);

    packet_inject.send(port_in, pkt_1_hit, sizeof(pkt_1_hit));
    receiver.read(recv_buffer, sizeof(pkt_1_hit), &recv_port);
    ASSERT_EQ(port_1_hit, recv_port);
  };

  auto swap_2_check = [this, port_in]() {
    int recv_port = -1;
    char recv_buffer[4];

    const char pkt_2_miss[4] = {'\x00', '\x00', '\x00', '\x00'};
    const char pkt_2_hit[4] = {'\xcd', '\x00', '\x00', '\x00'};
    const int port_2_miss = 3;
    const int port_2_hit = 4;

    packet_inject.send(port_in, pkt_2_miss, sizeof(pkt_2_miss));
    receiver.read(recv_buffer, sizeof(pkt_2_miss), &recv_port);
    ASSERT_EQ(port_2_miss, recv_port);

    packet_inject.send(port_in, pkt_2_hit, sizeof(pkt_2_hit));
    receiver.read(recv_buffer, sizeof(pkt_2_hit), &recv_port);
    ASSERT_EQ(port_2_hit, recv_port);
  };

  configure_swap_1();

  swap_1_check();

  // load second JSON
  std::ifstream fs(json_path_2(), std::ios::in);
  rc = test_switch->load_new_config(
      std::string(std::istreambuf_iterator<char>(fs),
                  std::istreambuf_iterator<char>()));
  ASSERT_EQ(rc_success, rc);

  swap_1_check();

  configure_swap_2();

  swap_1_check();

  // order swap
  rc = test_switch->swap_configs();
  ASSERT_EQ(rc_success, rc);

  // SimpleSwitch is going to make the swap here

  swap_2_check();
}


text:
#ifndef ANDRES_GRAPH_PYTHON_GRAPH_EXPORTER_HXX
#define ANDRES_GRAPH_PYTHON_GRAPH_EXPORTER_HXX

#include <boost/python/def_visitor.hpp>

namespace bp = boost::python;
namespace agraph = andres::graph;

template<class GRAPH>
class GraphExporter : public bp::def_visitor<GraphExporter<GRAPH> >
{
public:
    typedef GraphExporter<GRAPH> Exporter;
    typedef GRAPH Self;
    friend class def_visitor_access;

    GraphExporter(const std::string & clsName)
    : clsName_(clsName){
    }

    template <class classT>
    void visit(classT& c) const
    {
        c
            .add_property("numberOfVertices", &Self::numberOfVertices)
            .add_property("numberOfEdges",    &Self::numberOfEdges)

            .def("findEdge",&Exporter::findEdge)
            .def("uvIds",&Exporter::uvIds)
        ;
    }

    static bp::tuple findEdge(Self & self, const std::size_t u, const std::size_t v){
        const auto t = self.findEdge(u,v);
        return bp::make_tuple(t.first,t.second);
    }

    static vigra::NumpyAnyArray uvIds(const Self & self){
        vigra::TinyVector<int, 1> shape(self.numberOfEdges());
        vigra::NumpyArray<1, vigra::TinyVector<uint64_t,2> > out;
        out.reshapeIfEmpty(shape);
        for(auto e=0; e<self.numberOfEdges(); ++e){
            out(e)[0] =  self.vertexOfEdge(e, 0);
            out(e)[1] =  self.vertexOfEdge(e, 1);
        }
        return out;
    }

    std::string clsName_;
};

#endif

ext: hxx


text:
/*
   Copyright 2018 Simon Vogl <svogl@voxel.at>
                  Angel Merino-Sastre <amerino@voxel.at>

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
#include <iostream>

#include <boost/log/trivial.hpp>

#include "toffy/filterThread.hpp"

using namespace toffy;
using namespace std;

FilterThread::~FilterThread()
{
    // stop thread, kill all.
    theThread.join();
    inQ.clear();
    outQ.clear(); //TODO: check frames..

    delete f;
}

// init the FT with a number of pre-allocated frames
void FilterThread::init(int numFrames)
{
    for (int i=0;i<numFrames;i++) {
	Frame* f = new Frame();
	inQ.push_back(f);
    }
}

void FilterThread::start()
{
    keepRunning = true;
    //todo: launch thread
    theThread = boost::thread( boost::bind(&FilterThread::loop, this) );

}

void FilterThread::stop()
{
    keepRunning = false;
    inCond.notify_one();
}

Frame* FilterThread::dequeue()
{
    Frame* fr;

    //cout << "FT deq " << outQ.size() << endl;

    if ( outQ.empty() ) {
	boost::mutex mtx;
	boost::unique_lock<boost::mutex> lock(mtx);

	//cout << "FT deq wait " << endl;
	outCond.wait(lock);
    }
    outMtx.lock();
    fr = outQ.front();
    outQ.pop_front();
    outMtx.unlock();
    return fr;
}

void FilterThread::enqueue(Frame* fr)
{
    inMtx.lock();
    inQ.push_back(fr);
    inMtx.unlock();

    inCond.notify_one();
}

void FilterThread::loop()
{
    boost::mutex mtx;
    boost::unique_lock<boost::mutex> lock(mtx);
    Frame* in;

    cout << "FT thread started " << boost::this_thread::get_id() << endl;
    while (keepRunning) {
	while (inQ.empty()) {
	    cout << "FT wait for data" << endl;
	    inCond.wait(lock);
	    if (!keepRunning) {
		cout << "FT loop exit" << endl;
		return;
	    }
	}
	cout << "FT get data" << endl;
	// get one frame
	inMtx.lock();
	in = inQ.front();
	inQ.pop_front();
	inMtx.unlock();

	cout << "FT run filter on " << in << endl;
	// run the filter
	f->filter(*in, *in);

	cout << "FT push result" << endl;
	// post the result
	outMtx.lock();
	outQ.push_back(in);
	outMtx.unlock();
	outCond.notify_all();
    }
    cout << "FT thread loop exit " << boost::this_thread::get_id() << endl;
}

max_stars_repo_name: voxel-dot-at/toffy

max_issues_repo_name: voxel-dot-at/toffy

max_forks_repo_name: voxel-dot-at/toffy


text: #include <boost/mpl/list/list40_c.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino