text:
// 0.1 m/s linear velocity
// 0.2 radian/s angular velocity
#include <ros/ros.h>
#include <string>
#include <chrono>
#include <boost/thread.hpp>
#include <vio/frame_handler_mono.h>
#include <vio/params_helper.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/Imu.h>
#include <geometry_msgs/Twist.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <Eigen/Core>
#include <vio/abstract_camera.h>
#include <vio/camera_loader.h>
#include <vio/frame.h>
#include <vio/getOdom.h>
#include <vio/start.h>
#include <vio/stop.h>
#include <vio/global_optimizer.h>
#include <ros/callback_queue.h>
#if VIO_DEBUG
#include <vio/visualizer.h>
#endif

class VioNode
{
public:
      vio::FrameHandlerMono* vo_;
      vk::AbstractCamera* cam_;
      VioNode();
      ~VioNode();
      void imgCb(const sensor_msgs::ImageConstPtr& msg);
      void imuCb(const sensor_msgs::ImuPtr& imu);
    void cmdCb(const geometry_msgs::TwistPtr &imu);
    void imu_th();
    bool getOdom(vio::getOdom::Request& req, vio::getOdom::Response& res);
    uint trace_id_= 0;
    bool start_=false;
    bool start(vio::start::Request& req, vio::start::Response& res){
        if(req.on==1 && !start_){
            start_=true;
            if(vo_->stage()!=vio::FrameHandlerBase::STAGE_DEFAULT_FRAME) {
                vo_->depthFilter()->startThread();
                vo_->start();
            }else{
                vo_->depthFilter()->startThread();
                vo_->reset();
            }
            imu_the_=new boost::thread(&VioNode::imu_th,this);
            ++trace_id_;
            res.ret=0;
        }else{
            res.ret=100;
        }
        return true;
    };

    bool stop(vio::stop::Request& req, vio::stop::Response& res){
        if(req.off==1 && imu_the_!=NULL){
            start_=false;
            vo_->depthFilter()->stopThread();
#if VIO_DEBUG
    fclose(vo_->log_);
#endif
            imu_the_->interrupt();
            if(imu_the_->get_id()==boost::this_thread::get_id())
                imu_the_->detach();
            else
                imu_the_->join();
            imu_the_=NULL;
            res.ret=0;
        }else{
            res.ret=100;
        }
        return true;
    };
private:
    double* imu_;
    size_t cam_syn_=2;
    ros::Time imu_time_;
    int width;
    int height;
    boost::thread* imu_the_= nullptr;
#if VIO_DEBUG
    vio::Visualizer visualizer_;
#endif
};

VioNode::VioNode() :
      vo_(NULL),
      cam_(NULL)
{
    width=vk::getParam<int>("vio/cam_width", 640);
    height=vk::getParam<int>("vio/cam_height", 480);
    imu_=(double *)calloc(static_cast<std::size_t>(3), sizeof(double));
    if(!vk::camera_loader::loadFromRosNs("vio", cam_))
        throw std::runtime_error("Camera model not correctly specified.");
    Eigen::Matrix<double,3,1> init;
    init<<1e-19,1e-19,1e-19;
    vo_ = new vio::FrameHandlerMono(cam_,init);
    usleep(500);
}

VioNode::~VioNode()
{
    vo_->depthFilter()->stopThread();
    start_=false;
    usleep(5000);
    imu_the_->join();
    delete imu_the_;
    delete vo_;
    delete cam_;
}

void VioNode::imgCb(const sensor_msgs::ImageConstPtr& msg)
{

    if(!start_)return;
      try {
          cv::Mat img=cv_bridge::toCvShare(msg, "mono8")->image;
          if(img.empty())return;
          cv::Mat imgbul,float_img,frame,show;//tem;
          img.convertTo(float_img,CV_64F,1.f/255);
          float_img*=2.0;
          float_img+=0.2;
          float_img.convertTo(frame,CV_8UC1,255);
          cv::Laplacian(frame,imgbul,CV_64F);
          cv::Scalar mean, stddev;
          meanStdDev(imgbul, mean, stddev, cv::Mat());
/*          cv::cvtColor(frame,show,CV_GRAY2RGB);
          imshow("New Image", show);
          cv::waitKey(10);*/
          if(stddev.val[0] * stddev.val[0]< 30.0){
              ROS_WARN("Frame is blur or too dark");
              return;
          }
          vo_->addImage(frame, msg->header.stamp.toSec(),msg->header.stamp);
      } catch (cv_bridge::Exception& e) {
        ROS_ERROR("vo exception: %s", e.what());
      }
}
void VioNode::imuCb(const sensor_msgs::ImuPtr &imu) {
    if(!start_)return;
    double imu_in[3];
    imu_in[0] = 0.2*imu_[0]+0.8*imu->linear_acceleration.x;
    imu_in[1] = 0.2*imu_[1]+0.8*imu->linear_acceleration.y;
    imu_in[2] = 0.2*imu_[2]+0.8*imu->angular_velocity.z;
    memcpy(imu_, imu_in, static_cast<std::size_t>(3*sizeof(double)));
    vo_->UpdateIMU(imu_in,imu->header.stamp);
    imu_time_=imu->header.stamp;
#if VIO_DEBUG
    visualizer_.publishMinimal(vo_->ukfPtr_, imu->header.stamp.toSec());
#endif
}
void VioNode::cmdCb(const geometry_msgs::TwistPtr &cmd) {
    if(!start_)return;
    double _cmd[3]={cmd->linear.x,cmd->linear.y,cmd->angular.z};
    vo_->UpdateCmd(_cmd,imu_time_);
#if VIO_DEBUG
    auto odom=vo_->ukfPtr_.get_location();
    fprintf(vo_->log_,"[%s] Odometry x=%f, y=%f, theta=%f\n",vio::time_in_HH_MM_SS_MMM().c_str(),
            odom.second.se2().translation()(0),odom.second.se2().translation()(1),
            odom.second.pitch());
#endif
}
void VioNode::imu_th(){
    ros::NodeHandle nh;
    ros::CallbackQueue Q;
    nh.setCallbackQueue(&Q);
    ros::Subscriber imu_sub=nh.subscribe(vk::getParam<std::string>("vio/imu_topic", "imu/raw"),1,&VioNode::imuCb, this,ros::TransportHints().tcpNoDelay());
    ros::Subscriber cmd_sub=nh.subscribe(vk::getParam<std::string>("vio/cmd_topic", "cmd/raw"),1,&VioNode::cmdCb, this,ros::TransportHints().tcpNoDelay());
    while(start_ && !boost::this_thread::interruption_requested())
    {
        Q.callOne(ros::WallDuration(10,0.0));
        usleep(5000);
    }

}
bool VioNode::getOdom(vio::getOdom::Request &req, vio::getOdom::Response &res) {
    if(req.get==1){
        res.header.stamp = ros::Time();
        res.header.frame_id = "/world";
        res.header.seq = trace_id_;
        auto odom=vo_->ukfPtr_.get_location();
        //Camera frame z front, x right, y down -> right hands (pitch counts from z)
        //IMU frame y front, x right, z up -> left hands (theta counts from y)
        res.x=odom.second.se2().translation()(0);
        res.y=odom.second.se2().translation()(1);
        res.yaw=-odom.second.pitch();
        res.cov={odom.first(0,0),odom.first(0,1),odom.first(0,2),
                 odom.first(1,0),odom.first(1,1),odom.first(1,2),
                 odom.first(2,0),odom.first(2,1),odom.first(2,2)};
    }
    return true;
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "vio");
  ros::NodeHandle nh;
  ros::CallbackQueue Q;
  nh.setCallbackQueue(&Q);
  VioNode vio;
  ros::ServiceServer start = nh.advertiseService(vk::getParam<std::string>("vio/start", "start"),
                                                 &VioNode::start, &vio);
  ros::ServiceServer stop = nh.advertiseService(vk::getParam<std::string>("vio/stop", "stop"),
                                                &VioNode::stop, &vio);
  ros::ServiceServer getOdom = nh.advertiseService(vk::getParam<std::string>("vio/odom", "get_odom"),
                                                   &VioNode::getOdom, &vio);
  image_transport::ImageTransport it(nh);
  image_transport::Subscriber it_sub = it.subscribe(vk::getParam<std::string>("vio/cam_topic", "camera/image_raw"), 1, &VioNode::imgCb, &vio);
  // start processing callbacks
  while(ros::ok())
  {
      Q.callOne(ros::WallDuration(30,0.0));
  }
  printf("VIO terminated.\n");
  return 0;
}


text:
#pragma once
#include "WebSocket.hpp"
#include "IndexedVector.hpp"
#include "Constructor.hpp"

#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <functional>

class WebSocketServer {
public:
    DISABLE_CPY_MOV_CTOR(WebSocketServer)
    WebSocketServer(const std::string& connectName,
                    const std::string& disconnectName,
                    const std::string& messageName);
    ~WebSocketServer();

    bool listen(const std::string &host, const std::string &port);
    bool stopListen();
    bool isListening() const;

    int getID() const;
    void setID(int id);

    WebsocketConnectionPtr getClient(int id);

    IndexedVector<WebsocketConnection> getClients() const;

    int getClientIDByConnection(WebsocketConnection connection);

private:
    WebsocketServer m_server;
    IndexedVector<WebsocketConnection> m_clients;
    boost::thread m_asioThread;

    int m_id = -1;
    const std::string m_connectName;
    const std::string m_disconnectName;
    const std::string m_messageName;

    bool m_isListen = false;
};

ext: hpp


text:
/**
@file

Copyright John Reid 2006

*/

#include "bio-pch.h"

//#define BOOST_SPIRIT_DEBUG

#include "bio/defs.h"
#include "bio/common.h"
#include "bio/factor.h"

#include <boost/config.hpp>

#if BOOST_VERSION >= 13800
#include <boost/spirit/include/classic_core.hpp>
#include <boost/spirit/include/classic_closure.hpp>
#include <boost/spirit/include/classic_push_back_actor.hpp>
#include <boost/spirit/include/phoenix1.hpp>
#else
#include <boost/spirit/core.hpp>
#include <boost/spirit/attribute/closure.hpp>
#include <boost/spirit/actor/push_back_actor.hpp>
#include <boost/spirit/phoenix.hpp>
#endif //BOOST_VERSION >= 013800

#include <iostream>

BIO_NS_START

namespace spirit {

const std::string test_factor_table =
	"VV  TRANSFAC FACTOR TABLE, Release 11.3 - licensed - 2007-09-10, (C) Biobase GmbH\n"
	"XX\n"
	"//\n"
	"AC  T00001\n"
	"XX\n"
	"ID  T00001\n"
	"XX\n"
	"DT  16.09.1996 (created); ewi.\n"
	"CO  Copyright (C), Biobase GmbH.\n"
	"XX\n"
	"FA  AAF\n"
	"XX\n"
	"OS  human, Homo sapiens\n"
	"OC  eukaryota; animalia; metazoa; chordata; vertebrata; tetrapoda; mammalia; eutheria; primates\n"
	"XX\n"
	"SF  similar to GAF;\n"
	"XX\n"
	"FF  induced by interferon-alpha (15-30'), inhibited by 2-AP;\n"
	"XX\n"
	"BS  R02116; AAF$CONS; Quality: 6.\n"
	"BS  R03064; HS$GBP_02; Quality: 6; GBP, G000264; human, Homo sapiens.\n"
	"XX\n"
	"DR  TRANSPATH: MO000026034.\n"
	"XX\n"
	"RN  [1]; RE0000446.\n"
	"RX  PUBMED: 1901265.\n"
	"RA  Decker T., Lew D. J., Mirkowitch J., Darnell J. E.\n"
	"RT  Cytoplasmic activation of GAF, an IFN-gamma-regulated DNA-binding factor\n"
	"RL  EMBO J. 10:927-932 (1991).\n"
	"RN  [2]; RE0001471.\n"
	"RX  PUBMED: 1833631.\n"
	"RA  Decker T., Lew D. J., Darnell J. E.\n"
	"RT  Two distinct alpha-interferon-dependent signal transduction pathways may contribute to activation of transcription of the guanylate-binding protein gene\n"
	"RL  Mol. Cell. Biol. 11:5147-5153 (1991).\n"
	"XX\n"
	"//\n"
	"AC  T00002\n"
	"XX\n"
	"ID  T00002\n"
	"XX\n"
	"DT  28.10.1992 (created); ewi.\n"
	"DT  02.10.2002 (updated); hom.\n"
	"CO  Copyright (C), Biobase GmbH.\n"
	"XX\n"
	"FA  ACE2\n"
	"XX\n"
	"SY  ACE2; YLR131C.\n"
	"XX\n"
	"OS  yeast, Saccharomyces cerevisiae\n"
	"OC  Eukaryota; Fungi; Ascomycota; Hemiascomycetes; Saccharomycetales; Saccharomycetaceae; Saccharomyces.\n"
	"XX\n"
	"GE  G004153; ACE2.\n"
	"XX\n"
	"HO  SWI5 (S. cerevisiae).\n"
	"XX\n"
	"CL  C0001; CH; 2.3.3.0.1.\n"
	"XX\n"
	"SZ  770 AA; 86.6 kDa (gene) (calc.).\n"
	"XX\n"
	"SQ  MDNVVDPWYINPSGFAKDTQDEEYVQHHDNVNPTIPPPDNYILNNENDDGLDNLLGMDYY\n"
	"SQ  NIDDLLTQELRDLDIPLVPSPKTGDGSSDKKNIDRTWNLGDENNKVSHYSKKSMSSHKRG\n"
	"SQ  LSGTAIFGFLGHNKTLSISSLQQSILNMSKDPQPMELINELGNHNTVKNNNDDFDHIREN\n"
	"SQ  DGENSYLSQVLLKQQEELRIALEKQKEVNEKLEKQLRDNQIQQEKLRKVLEEQEEVAQKL\n"
	"SQ  VSGATNSNSKPGSPVILKTPAMQNGRMKDNAIIVTTNSANGGYQFPPPTLISPRMSNTSI\n"
	"SQ  NGSPSRKYHRQRYPNKSPESNGLNLFSSNSGYLRDSELLSFSPQNYNLNLDGLTYNDHNN\n"
	"SQ  TSDKNNNDKKNSTGDNIFRLFEKTSPGGLSISPRINGNSLRSPFLVGTDKSRDDRYAAGT\n"
	"SQ  FTPRTQLSPIHKKRESVVSTVSTISQLQDDTEPIHMRNTQNPTLRNANALASSSVLPPIP\n"
	"SQ  GSSNNTPIKNSLPQKHVFQHTPVKAPPKNGSNLAPLLNAPDLTDHQLEIKTPIRNNSHCE\n"
	"SQ  VESYPQVPPVTHDIHKSPTLHSTSPLPDEIIPRTTPMKITKKPTTLPPGTIDQYVKELPD\n"
	"SQ  KLFECLYPNCNKVFKRRYNIRSHIQTHLQDRPYSCDFPGCTKAFVRNHDLIRHKISHNAK\n"
	"SQ  KYICPCGKRFNREDALMVHRSRMICTGGKKLEHSINKKLTSPKKSLLDSPHDTSPVKETI\n"
	"SQ  ARDKDGSVLMKMEEQLRDDMRKHGLLDPPPSTAAHEQNSNRTLSNETDAL\n"
	"XX\n"
	"SC  SwissProt #P21192\n"
	"XX\n"
	"FT        1    284   PF00478; IMP dehydrogenase / GMP reductase domain.\n"
	"FT      603    627   PF00096; zf-C2H2.\n"
	"FT      603    627   SM00355; c2h2final6.\n"
	"FT      603    632   PS50157; ZINC_FINGER_C2H2_2.\n"
	"FT      605    627   zinc finger 1.\n"
	"FT      633    657   PF00096; zf-C2H2.\n"
	"FT      633    657   SM00355; c2h2final6.\n"
	"FT      633    662   PS50157; ZINC_FINGER_C2H2_2.\n"
	"FT      635    657   zinc finger 2.\n"
	"FT      664    683   zinc finger 3.\n"
	"XX\n"
	"SF  3 zinc finger motifs;\n"
	"XX\n"
	"FF  cell cycle-regulated activator of metallothionein and chitinase genes;\n"
	"FF  localisation is regulated via phosphorylation state [4];\n"
	"FF  daughter cell-specific localization of Ace2p and coordination of Ace2p-dependent transcription with the mitotic exit network is mediated by the Mob2p and Cbk1p protein kinases [5];\n"
	"XX\n"
	"IN  T03200; ASH1; yeast, Saccharomyces cerevisiae.\n"
	"XX\n"
	"BS  R09745; Y$CTS1_01; Quality: 2; CTS1, G002207; yeast, Saccharomyces cerevisiae.\n"
	"BS  R09744; Y$SIC1_02; Quality: 2; SIC1, G002206; yeast, Saccharomyces cerevisiae.\n"
	"XX\n"
	"DR  EMBL: M55619; SCACE2.\n"
	"DR  SWISSPROT: P21192; ACE2_YEAST.\n"
	"DR  PIR: S12943; TWBYA2.\n"
	"XX\n"
	"RN  [1]; RE0000710.\n"
	"RX  PUBMED: 1730413.\n"
	"RA  Dohrmann P. R., Butler G., Tamai K., Dorland S., Greene J. R., Thiele D. J., Stillman B.\n"
	"RT  Parallel pathways of gene regulation: Homologous regulators SWI5 and ACE2 differentially control transcription of HO and chitinase\n"
	"RL  Genes Dev. 6:93-104 (1992).\n"
	"RN  [2]; RE0001513.\n"
	"RX  PUBMED: 1986241.\n"
	"RA  Butler G., Thiele D. J.\n"
	"RT  ACE2, an activator of yeast metallothionein expression which is homologous to SWI5\n"
	"RL  Mol. Cell. Biol. 11:476-485 (1991).\n"
	"RN  [3]; RE0014327.\n"
	"RX  PUBMED: 10409653.\n"
	"RA  McBride H. J., Yu Y., Stillman D. J.\n"
	"RT  Distinct regions of the Swi5 and Ace2 transcription factors are required for specific gene activation\n"
	"RL  J. Biol. Chem. 274:21029-21036 (1999).\n"
	"RN  [4]; RE0015821.\n"
	"RX  PUBMED: 10517323.\n"
	"RA  O'Conallain C., Doolin M. T., Taggart C., Thornton F., Butler G.\n"
	"RT  Regulated nuclear localisation of the yeast transcription factor Ace2p controls expression of chitinase (CTS1) in Saccharomyces cerevisiae\n"
	"RL  Mol. Gen. Genet. 262:275-282 (1999).\n"
	"RN  [5]; RE0018039.\n"
	"RX  PUBMED: 12196508.\n"
	"RA  Weiss E. L., Kurischko C., Zhang C., Shokat K., Drubin D. G., Luca F. C.\n"
	"RT  The Saccharomyces cerevisiae Mob2p-Cbk1p kinase complex promotes polarized growth and acts with the mitotic exit network to facilitate daughter cell-specific localization of Ace2p transcription factor.\n"
	"RL  J. Cell Biol. 158:885-900 (2002).\n"
	"XX\n"
	"//\n"
	;

using namespace boost::spirit;
#if BOOST_VERSION >= 103500
 using namespace BOOST_SPIRIT_CLASSIC_NS;
#endif

//
// TransData
//
struct transdata_closure : closure< transdata_closure, TransData > {
    member1 val;
};
struct transdata : public grammar< transdata, transdata_closure::context_t >
{
    template < typename ScannerT >
    struct definition
    {
        definition( transdata const& self )
        {
			_rule =
				str_p("C")[self.val=COMPEL_DATA]
				| str_p("ev")[self.val=EVIDENCE_DATA]
				| str_p("T")[self.val=FACTOR_DATA]
				| str_p("FR")[self.val=FRAGMENT_DATA]
				| str_p("G")[self.val=GENE_DATA]
				| str_p("MO")[self.val=MOLECULE_DATA]
				| str_p("M")[self.val=MATRIX_DATA]
				| str_p("CH")[self.val=PATHWAY_DATA]
				| str_p("XN")[self.val=REACTION_DATA]
				| str_p("RE")[self.val=REFERENCE_DATA]
				| str_p("S")[self.val=S_DATA]
				| str_p("R")[self.val=SITE_DATA]
				| str_p("")[self.val=CELL_DATA]
				;
		}
		rule< ScannerT > _rule;
		rule<ScannerT> const& start() const { return _rule; }
	};
};

//
// TableLink
//
struct tablelink_closure : closure< tablelink_closure, TableLink > {
    member1 val;
};
struct tablelink : public grammar< tablelink, tablelink_closure::context_t >
{
    template < typename ScannerT >
    struct definition
    {
        definition( tablelink const& self )
        {
			_rule =
				_transdata[ phoenix::bind(&TableLink::table_id)(self.val) = phoenix::arg1 ]
				>> uint_p[ phoenix::bind(&TableLink::entry_idx)(self.val) = phoenix::arg1 ]
				;
		}
		rule< ScannerT > _rule;
		transdata _transdata;
		rule<ScannerT> const& start() const { return _rule; }
	};
};

//
// FactorLink
//
/*  Commented out because code cannot handle multiple species
struct factorlink_closure : closure< factorlink_closure, FactorLink > {
    member1 val;
};
struct factorlink : public grammar< factorlink, factorlink_closure::context_t >
{
    template < typename ScannerT >
    struct definition
    {
        definition( factorlink const& self )
        {
			//this is what we are trying to parse: "T00526; MyoD; Species: mouse, Mus musculus."
			using namespace phoenix;
			_rule =
				_tablelink[ bind(&FactorLink::link)(self.val) = arg1 ]
				>> "; "
				>> (+(anychar_p - ';'))[ bind(&FactorLink::name)(self.val) = construct_<std::string>(arg1, arg2) ]
				>> "; "
				>> "Species: "
				>> (+(anychar_p - '.'))[ bind(&FactorLink::species[0])(self.val) = construct_<std::string>(arg1, arg2) ]
				>> '.'
				;
		}
		rule< ScannerT > _rule;
		tablelink _tablelink;
		rule<ScannerT> const& start() const { return _rule; }
	};
};
*/

} //namespace spirit
BIO_NS_END

int main()
{
	using namespace BIO_NS;
	using namespace BIO_NS::spirit;

	TransData parsed_transdata;
	//parse("MA", transdata()[assign_a(parsed_transdata)]);

	TableLink parsed_tablelink;
	//parse("M001", tablelink()[assign_a(parsed_tablelink)]);

	FactorLink parsed_factorlink;
	//parse("T00526; MyoD; Species: mouse, Mus musculus.", factorlink()[assign_a(parsed_factorlink)]);

	return 0;
}

ext: cpp

max_stars_repo_name: JohnReid/biopsy

max_issues_repo_name: JohnReid/biopsy

max_forks_repo_name: JohnReid/biopsy


text:
// Copyright 2019 Peter Dimov.
// Distributed under the Boost Software License, Version 1.0.

#include <boost/config.hpp>

#if defined(STD_SINGLE_INSTANCE_DYN_LINK)
# define EXPORT BOOST_SYMBOL_EXPORT
#else
# define EXPORT
#endif

#include <boost/system/error_code.hpp>

#if defined(BOOST_SYSTEM_HAS_SYSTEM_ERROR)

#include <system_error>

namespace lib2
{

EXPORT std::error_code get_system_code()
{
    return boost::system::error_code( 0, boost::system::system_category() );
}

EXPORT std::error_code get_generic_code()
{
    return boost::system::error_code( 0, boost::system::generic_category() );
}

} // namespace lib2

#else

EXPORT void lib2_f()
{
}

#endif


text:
/*!
 * @file
 * Contains unit tests for the @ref Group typeclass.
 */

#include <boost/mpl11/group.hpp>

#include <boost/mpl11/core.hpp>
#include <boost/mpl11/integer.hpp>

#include "test_method_dispatch.hpp"

using namespace boost::mpl11;

///////////////////////////
// Test method dispatching
///////////////////////////
namespace boost { namespace mpl11 {
    template <>
    struct Group<Archetype<0>> : instantiate<Group>::with<Archetype<0>> {
        template <typename, typename> using minus_impl  = method_tag<minus>;
        template <typename>           using negate_impl = method_tag<negate>;
    };
}}

struct test_dispatching
    : method<minus, archetype<0>, archetype<0>>
    // , method<minus, archetype<0>, archetype<1>>
    // , method<minus, archetype<1>, archetype<0>>

    , method<negate, archetype<0>>
{ };

////////////////////////////////
// Test default implementations
////////////////////////////////
using Default = instantiate<Group>::with<Integer>;
static_assert(Default::minus_impl<int_<10>, int_<3>>::value == 10 - 3, "");
static_assert(Default::negate_impl<int_<10>>::value == -10, "");

int main() { }


text:
// =-=-=-=-=-=-=-
// irods includes
#include "irods_error.hpp"
#include "irods_ms_plugin.hpp"

// system library includes

#include <cstring>
#include <cstdlib>
#include <string>
#include <cstring>
#include <regex.h>
#include <string>
#include <vector>
#include <boost/regex.hpp>
#include <boost/algorithm/string/regex.hpp>

// iRODS includes

#include "reDataObjOpr.hpp"
#include "apiHeaderAll.h"
#include "rsApiHandler.hpp"
#include "collection.hpp"
#include "rsDataObjCreate.hpp"
#include "rsDataObjOpen.hpp"
#include "rsDataObjClose.hpp"
#include "rsDataObjRead.hpp"
#include "rsDataObjWrite.hpp"
#include "rsDataObjUnlink.hpp"
#include "rsDataObjRepl.hpp"
#include "rsDataObjCopy.hpp"
#include "rsDataObjChksum.hpp"
#include "rsDataObjLseek.hpp"
#include "rsDataObjPhymv.hpp"
#include "rsDataObjRename.hpp"
#include "rsDataObjTrim.hpp"
#include "rsCollCreate.hpp"
#include "rsRmColl.hpp"
#include "rsPhyPathReg.hpp"
#include "rsObjStat.hpp"
#include "rsDataObjRsync.hpp"
#include "rsOpenCollection.hpp"
#include "rsReadCollection.hpp"
#include "rsCloseCollection.hpp"
#include "rsExecCmd.hpp"
#include "rsCollRepl.hpp"
#include "rsModDataObjMeta.hpp"
#include "rsStructFileExtAndReg.hpp"
#include "rsModDataObjMeta.hpp"
#include "rsStructFileBundle.hpp"
#include "rsPhyBundleColl.hpp"

/* --------------dwm--------------- */

int
msiregister_as_admin( msParam_t *inpParam1, msParam_t *inpParam2,
                msParam_t *inpParam3, msParam_t *inpParam4, msParam_t *outParam,
                ruleExecInfo_t *rei ) {
     rsComm_t *rsComm;
     dataObjInp_t dataObjInp, *myDataObjInp = NULL;

     RE_TEST_MACRO( "    Calling msiPhyPathReg" )

     if ( rei == NULL || rei->rsComm == NULL ) {
         rodsLog( LOG_ERROR,
                  "msiPhyPathReg: input rei or rsComm is NULL" );
         return SYS_INTERNAL_NULL_INPUT_ERR;
     }

     rsComm = rei->rsComm;

     /* parse inpParam1 */
     rei->status = parseMspForDataObjInp( inpParam1, &dataObjInp,
                                          &myDataObjInp, 1 );

     if ( rei->status < 0 ) {
         rodsLogAndErrorMsg( LOG_ERROR, &rsComm->rError, rei->status,
                             "msiPhyPathReg: input inpParam1 error. status = %d", rei->status );
         return rei->status;
     }

     if ( ( rei->status = parseMspForCondInp( inpParam2, &myDataObjInp->condInput,
                          DEST_RESC_NAME_KW ) ) < 0 ) {
         rodsLogAndErrorMsg( LOG_ERROR, &rsComm->rError, rei->status,
                             "msiPhyPathReg: input inpParam2 error. status = %d", rei->status );
         return rei->status;
     }

     if ( ( rei->status = parseMspForCondInp( inpParam3, &myDataObjInp->condInput,
                          FILE_PATH_KW ) ) < 0 ) {
         rodsLogAndErrorMsg( LOG_ERROR, &rsComm->rError, rei->status,
                             "msiPhyPathReg: input inpParam3 error. status = %d", rei->status );
         return rei->status;
     }

     if ( ( rei->status = parseMspForPhyPathReg( inpParam4,
                          &myDataObjInp->condInput ) ) < 0 ) {
         rodsLogAndErrorMsg( LOG_ERROR, &rsComm->rError, rei->status,
                             "msiPhyPathReg: input inpParam4 error. status = %d", rei->status );
         return rei->status;
     }

     // elevate privilege level

     int temp = rei->rsComm->clientUser.authInfo.authFlag;
     rsComm->clientUser.authInfo.authFlag = LOCAL_PRIV_USER_AUTH;

     rei->status = rsPhyPathReg( rsComm, myDataObjInp );

     // restore old privilege level
     rsComm->clientUser.authInfo.authFlag = temp;

     if ( myDataObjInp == &dataObjInp ) {
         clearKeyVal( &myDataObjInp->condInput );
     }

     if ( rei->status >= 0 ) {
         fillIntInMsParam( outParam, rei->status );
     }
     else {
         rodsLogAndErrorMsg( LOG_ERROR, &rsComm->rError, rei->status,
                             "msiPhyPathReg: rsPhyPathReg failed for %s, status = %d",
                             myDataObjInp->objPath,
                             rei->status );
     }

     return rei->status;
}

extern "C"
irods::ms_table_entry* plugin_factory() {
    irods::ms_table_entry* msvc = new irods::ms_table_entry(5);
    msvc->add_operation<
        msParam_t*,
        msParam_t*,
        msParam_t*,
        msParam_t*,
        msParam_t*,
        ruleExecInfo_t*>("msiregister_as_admin",
                         std::function<int(
                             msParam_t*,
                             msParam_t*,
                             msParam_t*,
                             msParam_t*,
                             msParam_t*,
                             ruleExecInfo_t*)>(msiregister_as_admin));
    return msvc;
}


text:
#ifndef HSMM_H
#define HSMM_H

#include <armadillo>
#include <deque>
#include <emissions.hpp>
#include <ForwardBackward.hpp>
#include <json.hpp>
#include <memory>
#include <vector>

namespace hsmm {

    class HSMM {
        public:
            HSMM(std::shared_ptr<AbstractEmission> emission,
                    arma::mat transition, arma::vec pi, arma::mat duration,
                    int min_duration);

            // Inits all the pmfs with the uniform distribution.
            HSMM(std::shared_ptr<AbstractEmission> emission, int nstates,
                    int ndurations, int min_duration);

            void setDuration(arma::mat duration);

            void setEmission(std::shared_ptr<AbstractEmission> emission);

            void setPi(arma::vec pi);

            void setTransition(arma::mat transition);

            void setDurationLearningChoice(std::string choice);

            void setDurationDirichletPrior(arma::mat alphas);

            void setPiFromLabels(arma::field<arma::ivec> seqs);

            void setTransitionFromLabels(arma::field<arma::ivec> seqs);

            void setDurationFromLabels(arma::field<arma::ivec> seqs);

            arma::field<arma::mat> sampleSegments(int nsegments,
                    arma::ivec& hiddenStates,
                    arma::ivec& hiddenDurations);

            arma::field<arma::field<arma::mat>> sampleMultipleSequences(
                    int nsequences, int nsegments,
                    arma::field<arma::ivec>& seqsHiddenStates,
                    arma::field<arma::ivec>& seqsHiddenDurations);

            void init_params_from_data(const arma::field<arma::field<
                    arma::mat>> &obs);

            // Fits the model from multiple sequences.
            bool fit(arma::field<arma::field<arma::mat>> obs,
                    int max_iter, double tol);

            // As above (multiple sequences) but also accepts labels for
            // semi-supervised learning.
            bool fit(arma::field<arma::field<arma::mat>> obs,
                    arma::field<Labels> observed_segments, int max_iter,
                    double tol);

            double loglikelihood(const arma::field<arma::field<
                    arma::mat>>& obs);

            double loglikelihood(
                    const arma::field<arma::field<arma::mat>>& obs,
                    const arma::field<Labels> &observed_segments);

            // Computes the likelihoods w.r.t. the emission model.
            arma::cube computeEmissionsLikelihood(
                    const arma::field<arma::mat>& obs);

            // Computes the loglikelihoods w.r.t. the emission model.
            arma::cube computeEmissionsLogLikelihood(
                    const arma::field<arma::mat>& obs);

            // Returns a json representation of the model.
            nlohmann::json to_stream() const;

            // Reads the parameters from a json file.
            void from_stream(const nlohmann::json &params);

            arma::mat transition_;
            arma::vec pi_;
            arma::mat duration_;
            int ndurations_;
            int min_duration_;
            int nstates_;

            // Parameters of the Dirichlet prior assumed over the duration.
            // By default no prior is assumed \alpha = 1.
            arma::mat dirichlet_alphas_;

            std::shared_ptr<AbstractEmission> emission_;
            std::string duration_learning_choice_;
            bool learning_transitions_;
            bool learning_pi_;
            bool debug_;

        protected:

            std::pair<arma::ivec, arma::ivec>
                    computeViterbiStateDurationSequenceFromLabels(
                    arma::ivec seq);

            // Approximates a discrete (truncate) Gaussian to a given duration.
            arma::mat gaussianMomentMatching(arma::mat duration) const;

            double lower_bound_term_transition(const arma::field<
                    arma::cube> &zetas, const arma::mat& log_transition) const;

            double lower_bound_term_pi(const arma::field<arma::cube> &etas,
                    const arma::vec& log_pi) const;

            double lower_bound_term_duration(const arma::field<
                    arma::cube> &etas, const arma::mat& log_duration) const;
    };

    class OnlineHSMM : public HSMM {
        public:
            OnlineHSMM(std::shared_ptr<AbstractEmissionOnlineSetting> emission,
                    arma::mat transition, arma::vec pi, arma::mat duration,
                    int min_duration);

            std::shared_ptr<AbstractEmissionOnlineSetting> getOnlineEmission(
                    ) const;

            void addNewObservation(const arma::mat& obs);

            void sampleFromPosterior(int &dur, int &offset, int &hs) const;

            arma::field<arma::mat> sampleNextObservations(int nobs) const;

            void printTopKFromPosterior(int k) const;

            arma::vec getStateMarginal() const;

            arma::vec getRunlengthMarginal() const;

            arma::vec getDurationMarginal() const;

            arma::vec getResidualTimeMarginal() const;

            arma::vec getImplicitResidualTimeMarginal() const;

            arma::vec getImplicitDurationMarginal() const;

            double getLastOneStepAheadLoglikelihood() const;

        protected:

            arma::mat getDurationSuffixSum() const;

            int appendToField(arma::field<arma::mat>& current_obs, int idx,
                    const arma::field<arma::mat> new_obs) const;

            // This represents p(y_{t+1} | y_1, y_2, ..., y_t).
            double last_normalization_c_;

            // Logposterior over (d (duration),s (offset),i (hidden state))
            // conditioned on all the observations given so far.
            arma::cube last_log_posterior_;
            std::vector<arma::mat> observations_;
            std::deque<arma::vec> alpha_posteriors_;
    };

    class OnlineHSMMRunlengthBased : public HSMM {
        public:
            OnlineHSMMRunlengthBased(std::shared_ptr<
                    AbstractEmissionObsCondIIDgivenState> emission,
                    arma::mat transition, arma::vec pi, arma::mat duration,
                    int min_duration);

            OnlineHSMMRunlengthBased(std::shared_ptr<
                    AbstractEmissionObsCondIIDgivenState> emission,
                    int nstates, int ndurations, int min_duration);

            void init();

            std::shared_ptr<AbstractEmissionObsCondIIDgivenState>
                    getOnlineDurationAgnosticEmission() const;

            void addNewObservation(const arma::mat& obs);

            arma::vec getRunlengthMarginal() const;

            arma::vec getStateMarginal() const;

            arma::vec getResidualTimeMarginal() const;

            // Based on last_residualtime_posterior_
            arma::vec getStateMarginal2() const;

            double oneStepAheadLoglikelihood(const arma::mat& obs) const;

            double oneStepAheadLoglikelihood2(const arma::mat& obs) const;

        protected:

            double loglikelihood_(int state, const arma::mat& obs) const;

            arma::mat getDurationSuffixSum_() const;

            // Hazard(r): probability that the segment ends "now" given that
            // the current runlength is r.
            arma::mat getHazardFunction_() const;

            // Posterior over (r (runlength a.k.a. offset), i (hidden state))
            arma::mat last_posterior_;

            // Posterior over (l (residual time), i, (hidden state))
            arma::mat last_residualtime_posterior_;

            std::vector<arma::mat> observations_;
    };

};

#endif

max_stars_repo_name: DiegoAE/BOSD

max_issues_repo_name: DiegoAE/BOSD

max_forks_repo_name: DiegoAE/BOSD


text:
/*!
@file
Forward declares `boost::hana::reverse`.

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

#ifndef BOOST_HANA_FWD_REVERSE_HPP
#define BOOST_HANA_FWD_REVERSE_HPP

#include <boost/hana/config.hpp>
#include <boost/hana/core/when.hpp>

BOOST_HANA_NAMESPACE_BEGIN
    //! Reverse a sequence.
    //! @ingroup group-Sequence
    //!
    //! Specifically, `reverse(xs)` is a new sequence containing the same
    //! elements as `xs`, except in reverse order.
    //!
    //!
    //! @param xs
    //! The sequence to reverse.
    //!
    //!
    //! Example
    //! -------
    //! @include example/reverse.cpp
#ifdef BOOST_HANA_DOXYGEN_INVOKED
    constexpr auto reverse = [](auto&& xs) {
        return tag-dispatched;
    };
#else
    template <typename S, typename = void>
    struct reverse_impl : reverse_impl<S, when<true>> { };

    struct reverse_t {
        template <typename Xs>
        constexpr auto operator()(Xs&& xs) const;
    };

    constexpr reverse_t reverse{};
#endif
BOOST_HANA_NAMESPACE_END

#endif // !BOOST_HANA_FWD_REVERSE_HPP

max_stars_repo_name: rudylee/expo

max_issues_repo_name: rudylee/expo

max_forks_repo_name: rudylee/expo


text:
//------------------------------------------------------------------------------
/*
    This file is part of validator-keys-tool:
        https://github.com/ripple/validator-keys-tool
    Copyright (c) 2016 Ripple Labs Inc.

    Permission to use, copy, modify, and/or distribute this software for any
    purpose  with  or without fee is hereby granted, provided that the above
    copyright notice and this permission notice appear in all copies.

    THE  SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
    WITH  REGARD  TO  THIS  SOFTWARE  INCLUDING  ALL  IMPLIED  WARRANTIES  OF
    MERCHANTABILITY  AND  FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    ANY  SPECIAL ,  DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    WHATSOEVER  RESULTING  FROM  LOSS  OF USE, DATA OR PROFITS, WHETHER IN AN
    ACTION  OF  CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================

#include <ValidatorKeys.h>
#include <blocmatrix/basics/base64.h>
#include <blocmatrix/basics/StringUtilities.h>
#include <blocmatrix/json/json_reader.h>
#include <blocmatrix/json/to_string.h>
#include <blocmatrix/protocol/HashPrefix.h>
#include <blocmatrix/protocol/Sign.h>
#include <boost/filesystem.hpp>
#include <fstream>

namespace blocmatrix {

std::string
ValidatorToken::toString () const
{
    Json::Value jv;
    jv["validation_secret_key"] = strHex(secretKey);
    jv["manifest"] = manifest;

    return blocmatrix::base64_encode(to_string(jv));
}

ValidatorKeys::ValidatorKeys (KeyType const& keyType)
    : keyType_ (keyType)
    , tokenSequence_ (0)
    , revoked_ (false)
{
    std::tie (publicKey_, secretKey_) = generateKeyPair (
        keyType_, randomSeed ());
}

ValidatorKeys::ValidatorKeys (
    KeyType const& keyType,
    SecretKey const& secretKey,
    std::uint32_t tokenSequence,
    bool revoked)
    : keyType_ (keyType)
    , secretKey_ (secretKey)
    , tokenSequence_ (tokenSequence)
    , revoked_ (revoked)
{
    publicKey_ = derivePublicKey(keyType_, secretKey_);
}

ValidatorKeys
ValidatorKeys::make_ValidatorKeys (
    boost::filesystem::path const& keyFile)
{
    std::ifstream ifsKeys (keyFile.c_str (), std::ios::in);

    if (! ifsKeys)
        throw std::runtime_error (
            "Failed to open key file: " + keyFile.string());

    Json::Reader reader;
    Json::Value jKeys;
    if (! reader.parse (ifsKeys, jKeys))
    {
        throw std::runtime_error (
            "Unable to parse json key file: " + keyFile.string());
    }

    static std::array<std::string, 4> const requiredFields {{
        "key_type",
        "secret_key",
        "token_sequence",
        "revoked"
    }};

    for (auto field : requiredFields)
    {
        if (! jKeys.isMember(field))
        {
            throw std::runtime_error (
                "Key file '" + keyFile.string() +
                "' is missing \"" + field + "\" field");
        }
    }

    auto const keyType = keyTypeFromString (jKeys["key_type"].asString());
    if (!keyType)
    {
        throw std::runtime_error (
            "Key file '" + keyFile.string() +
            "' contains invalid \"key_type\" field: " +
            jKeys["key_type"].toStyledString());
    }

    auto const secret = parseBase58<SecretKey> (
        TokenType::NodePrivate, jKeys["secret_key"].asString());

    if (! secret)
    {
        throw std::runtime_error (
            "Key file '" + keyFile.string() +
            "' contains invalid \"secret_key\" field: " +
            jKeys["secret_key"].toStyledString());
    }

    std::uint32_t tokenSequence;
    try {
        if (! jKeys["token_sequence"].isIntegral())
            throw std::runtime_error ("");

        tokenSequence = jKeys["token_sequence"].asUInt();
    }
    catch (std::runtime_error&)
    {
        throw std::runtime_error (
            "Key file '" + keyFile.string() +
            "' contains invalid \"token_sequence\" field: " +
            jKeys["token_sequence"].toStyledString());
    }

    if (! jKeys["revoked"].isBool())
        throw std::runtime_error (
            "Key file '" + keyFile.string() +
            "' contains invalid \"revoked\" field: " +
            jKeys["revoked"].toStyledString());

    return ValidatorKeys (
        *keyType, *secret, tokenSequence, jKeys["revoked"].asBool());
}

void
ValidatorKeys::writeToFile (
    boost::filesystem::path const& keyFile) const
{
    using namespace boost::filesystem;

    Json::Value jv;
    jv["key_type"] = to_string(keyType_);
    jv["public_key"] = toBase58(TokenType::NodePublic, publicKey_);
    jv["secret_key"] = toBase58(TokenType::NodePrivate, secretKey_);
    jv["token_sequence"] = Json::UInt (tokenSequence_);
    jv["revoked"] = revoked_;

    if (! keyFile.parent_path().empty())
    {
        boost::system::error_code ec;
        if (! exists (keyFile.parent_path()))
            boost::filesystem::create_directories(keyFile.parent_path(), ec);

        if (ec || ! is_directory (keyFile.parent_path()))
            throw std::runtime_error ("Cannot create directory: " +
                    keyFile.parent_path().string());
    }

    std::ofstream o (keyFile.string (), std::ios_base::trunc);
    if (o.fail())
        throw std::runtime_error ("Cannot open key file: " +
            keyFile.string());

    o << jv.toStyledString();
}

boost::optional<ValidatorToken>
ValidatorKeys::createValidatorToken (
    KeyType const& keyType)
{
    if (revoked () ||
            std::numeric_limits<std::uint32_t>::max () - 1 <= tokenSequence_)
        return boost::none;

    ++tokenSequence_;

    auto const tokenSecret = generateSecretKey (keyType, randomSeed ());
    auto const tokenPublic = derivePublicKey(keyType, tokenSecret);

    STObject st(sfGeneric);
    st[sfSequence] = tokenSequence_;
    st[sfPublicKey] = publicKey_;
    st[sfSigningPubKey] = tokenPublic;

    blocmatrix::sign(st, HashPrefix::manifest, keyType, tokenSecret);

    blocmatrix::sign(st, HashPrefix::manifest, keyType_, secretKey_,
        sfMasterSignature);

    Serializer s;
    st.add(s);

    std::string m (static_cast<char const*> (s.data()), s.size());
    return ValidatorToken {
        blocmatrix::base64_encode(m), tokenSecret };
}

std::string
ValidatorKeys::revoke ()
{
    revoked_ = true;

    STObject st(sfGeneric);
    st[sfSequence] = std::numeric_limits<std::uint32_t>::max ();
    st[sfPublicKey] = publicKey_;

    blocmatrix::sign(st, HashPrefix::manifest, keyType_, secretKey_,
        sfMasterSignature);

    Serializer s;
    st.add(s);

    std::string m (static_cast<char const*> (s.data()), s.size());
    return blocmatrix::base64_encode(m);
}

std::string
ValidatorKeys::sign (std::string const& data)
{
    return strHex(blocmatrix::sign (publicKey_, secretKey_, makeSlice (data)));
}

} // blocmatrix

max_stars_repo_name: ReddyArunreddy/validator-keys-tool

max_issues_repo_name: ReddyArunreddy/validator-keys-tool

max_forks_repo_name: ReddyArunreddy/validator-keys-tool


text:
/**
 * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved
 *
 * This file is part of GeoDa.
 *
 * GeoDa is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * GeoDa is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <boost/foreach.hpp>
#include "VarGroup.h"

VarGroup::VarGroup() : displayed_decimals(-1)
{
}

VarGroup::VarGroup(const VarGroup& e) : name(e.name), vars(e.vars),
displayed_decimals(e.displayed_decimals)
{
}

VarGroup::VarGroup(const wxString& _name, int _displayed_decimals)
: name(_name), displayed_decimals(_displayed_decimals)
{
}

VarGroup::VarGroup(const wxString& _name, std::vector<wxString> _vars,
				   int _displayed_decimals)
:  name(_name), vars(_vars), displayed_decimals(_displayed_decimals)
{
	if (vars.size() == 1) vars.clear();
}

bool VarGroup::operator<(const VarGroup& e) const
{
	return name < e.name;
}

VarGroup& VarGroup::operator=(const VarGroup& e)
{
	name = e.name;
	vars = e.vars;
	return *this;
}

void VarGroup::Append(const VarGroup& e)
{
	if (e.vars.size() == 0 && !e.name.IsEmpty()) {
		vars.push_back(e.name);
	} else {
		for (int i=0; i<e.vars.size(); ++i) vars.push_back(e.vars[i]);
	}
}

void VarGroup::AppendPlaceholder()
{
	vars.push_back("");
}

bool VarGroup::IsAllPlaceholders() const
{
	if (IsEmpty()) return true;
	if (IsSimple()) return false;
	BOOST_FOREACH(const wxString& v, vars) if (!v.IsEmpty()) return false;
	return true;
}

int VarGroup::GetNumTms() const
{
	if (IsEmpty()) return 0;
	return vars.size() == 0 ? 1 : vars.size();
}

/**
 * If IsSimple() true, then return just group name, otherwise
 * return vars.
 */
void VarGroup::GetVarNames(std::vector<wxString>& var_nms) const
{
	if (IsEmpty()) return;
	if (IsSimple()) {
		var_nms.resize(1);
		var_nms[0] = GetGroupName();
	} else {
		var_nms = vars;
	}
}

wxString VarGroup::GetNameByTime(int time) const
{
	if ( vars.size() == 0 ) return name;
	if ( time >= 0 && time < vars.size() ) return vars[time];
	return "";
}

wxString VarGroup::GetGroupName() const
{
	return name;
}

void VarGroup::SetGroupName(const wxString& new_name)
{
	name = new_name;
}

void VarGroup::SetVarName(const wxString& new_name, int time)
{
	if (time < 0 || vars.size() >= time) return;
	vars[time] = new_name;
}

bool VarGroup::IsSimple() const
{
	return vars.size() == 0;
}

/** If name is empty, then VarGroup is considered to be empty.  An empty
 VarGroup should only be used as a temporary return value to indicate
 that a VarGroup wasn't found. */
bool VarGroup::IsEmpty() const
{
	return name.IsEmpty();
}

wxString VarGroup::ToStr() const
{
	wxString ss;
	if (vars.size() == 0) {
		ss << "VarGroup name: " << name;
	} else {
		ss << "VarGroup name: " << name << "\n";
		ss << "      vars: ";
		BOOST_FOREACH(const wxString& v, vars) {
			if (v.empty()) { // a placeholder
				ss << "placeholder ";
			} else {
				ss << v << " ";
			}
		}
	}
	ss << "\n";
	return ss;
}

int VarGroup::GetDispDecs() const
{
	return displayed_decimals;
}

void VarGroup::SetDispDecs(int _displayed_decimals)
{
	displayed_decimals = _displayed_decimals;
}

max_stars_repo_name: chenyoujie/GeoDa

max_issues_repo_name: chenyoujie/GeoDa

max_forks_repo_name: chenyoujie/GeoDa


text:
/*
 * (C) Copyright 2014 Kurento (http://kurento.org/)
 *
 * 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 <gst/gst.h>
#include "Processor.hpp"
#include "WebSocketTransport.hpp"
#include "WebSocketEventHandler.hpp"
#include "WebSocketRegistrar.hpp"
#include <jsonrpc/JsonRpcUtils.hpp>
#include <jsonrpc/JsonRpcConstants.hpp>
#include <KurentoException.hpp>
#include <MediaSet.hpp>

#include <UUIDGenerator.hpp>

#include <boost/filesystem.hpp>

#include <type_traits>

#define GST_CAT_DEFAULT kurento_websocket_transport
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoWebSocketTransport"

typedef websocketpp::lib::shared_ptr<boost::asio::ssl::context> context_ptr;

namespace kurento
{

const std::string DEFAULT_LOCAL_ADDRESS = "localhost";

/* Default config values */
const ushort WEBSOCKET_PORT_DEFAULT = 8888;
const std::string WEBSOCKET_PATH_DEFAULT = "kurento";
const int WEBSOCKET_THREADS_DEFAULT = 10;

class configuration_exception : public std::exception
{
public:
  configuration_exception (std::string message)
  {
    this->message = message;
  }

  virtual const char *what() const _GLIBCXX_USE_NOEXCEPT
  {
    return message.c_str();
  }

private:
  std::string message;
};

WebSocketTransport::WebSocketTransport (const boost::property_tree::ptree
                                        &config,
                                        std::shared_ptr<Processor> processor) :
  processor (processor)
{
  ushort port;
  ushort securePort;
  std::string registrarAddress;
  std::string localAddress;

  port = config.get<ushort> ("mediaServer.net.websocket.port",
                             WEBSOCKET_PORT_DEFAULT);
  securePort = config.get<ushort> ("mediaServer.net.websocket.secure.port", 0);

  path = config.get<std::string> ("mediaServer.net.websocket.path",
                                  WEBSOCKET_PATH_DEFAULT);

  try {
    n_threads = config.get<uint> ("mediaServer.net.websocket.threads");

    if (n_threads < 1) {
      throw boost::property_tree::ptree_bad_data ("Invalid threads number",
          n_threads);
    }
  } catch (const boost::property_tree::ptree_error &err) {
    GST_WARNING ("Setting default listener threads %d to websocket",
                 WEBSOCKET_THREADS_DEFAULT);
    n_threads = WEBSOCKET_THREADS_DEFAULT;
  }

  processor->setEventSubscriptionHandler (std::bind (
      &WebSocketTransport::processSubscription, this, std::placeholders::_1,
      std::placeholders::_2, std::placeholders::_3, std::placeholders::_4) );

  /* Configure server */
  server.clear_access_channels (websocketpp::log::alevel::all);
  server.clear_error_channels (websocketpp::log::alevel::all);

  server.init_asio (&ios);
  server.set_reuse_addr (true);
  server.set_open_handler (std::bind ( (void (WebSocketTransport::*) (
                                          WebSocketServer *, websocketpp::connection_hdl) )
                                       &WebSocketTransport::openHandler, this,
                                       &server, std::placeholders::_1) );
  server.set_close_handler (std::bind (&WebSocketTransport::closeHandler, this,
                                       std::placeholders::_1) );
  server.set_message_handler (std::bind ( (void (WebSocketTransport::*) (
      WebSocketServer *, websocketpp::connection_hdl,
      WebSocketServer::message_ptr) ) &WebSocketTransport::processMessage,
                                          this, &server, std::placeholders::_1,
                                          std::placeholders::_2) );

  try {
    server.listen (port);
  } catch (websocketpp::exception &e) {
    GST_ERROR ("Error starting listen for websocket transport on port %d: %s", port,
               e.what() );
    exit (1);
  }

  /* Configure secure server if enabled */
  if (securePort != 0) {
    try {
      std::string password;
      boost::filesystem::path certificateFile;

      try {
        password =
          config.get<std::string> ("mediaServer.net.websocket.secure.password");
      } catch (const boost::property_tree::ptree_error &err) {
        throw configuration_exception ("Cannot get password for secure websocket");
      }

      try {
        certificateFile = boost::filesystem::path (
                            config.get<std::string> ("mediaServer.net.websocket.secure.certificate") );

        if (certificateFile.is_relative() ) {
          certificateFile = boost::filesystem::path (
                              config.get<std::string> ("configPath") ) / certificateFile;
        }

        if (!boost::filesystem::exists (certificateFile) ) {
          throw configuration_exception ("Cannot get cerfificate file for secure websocket, configured file "
                                         + certificateFile.string() + " does not exist");
        }
      } catch (const boost::property_tree::ptree_error &err) {
        throw configuration_exception ("Cannot get cerfificate file for secure websocket");
      }

      secureServer.clear_access_channels (websocketpp::log::alevel::all);
      secureServer.clear_error_channels (websocketpp::log::alevel::all);

      secureServer.init_asio (&ios);
      secureServer.set_reuse_addr (true);

      secureServer.set_open_handler (std::bind ( (void (WebSocketTransport::*) (
                                       SecureWebSocketServer *,
                                       websocketpp::connection_hdl) ) &WebSocketTransport::openHandler, this,
                                     &secureServer, std::placeholders::_1) );
      secureServer.set_close_handler (std::bind (&WebSocketTransport::closeHandler,
                                      this,
                                      std::placeholders::_1) );
      secureServer.set_message_handler (std::bind ( (void (WebSocketTransport::*) (
                                          SecureWebSocketServer *, websocketpp::connection_hdl,
                                          SecureWebSocketServer::message_ptr) ) &WebSocketTransport::processMessage,
                                        this, &secureServer, std::placeholders::_1,
                                        std::placeholders::_2) );

      secureServer.set_tls_init_handler ( [password, certificateFile] (
      websocketpp::connection_hdl hdl) -> context_ptr {
        context_ptr context (new boost::asio::ssl::context (boost::asio::ssl::context::tlsv1) );

        try {
          context->set_options (boost::asio::ssl::context::default_workarounds |
          boost::asio::ssl::context::no_sslv2 |
          boost::asio::ssl::context::single_dh_use);
          context->set_password_callback (std::bind ([password] (void) -> std::string {
            GST_INFO ("password");
            return password;
          }) );
          context->use_certificate_chain_file (certificateFile.string() );
          context->use_private_key_file (certificateFile.string(), boost::asio::ssl::context::pem);
        } catch (std::exception &e)
        {
          GST_ERROR ("Error while setting up tls %s", e.what() );
        }

        return context;
      });

      try {
        secureServer.listen (securePort);
        hasSecureServer = true;
      } catch (websocketpp::exception &e) {
        throw configuration_exception ("Error listening on port" + securePort);
      }
    } catch (const configuration_exception &err) {
      GST_WARNING ("Secure websocket server not enabled: %s", err.what() );
    }
  } else {
    GST_INFO ("Secure websocket server not enabled");
  }

  registrarAddress =
    config.get<std::string> ("mediaServer.net.websocket.registrar.address", "");
  localAddress =
    config.get<std::string> ("mediaServer.net.websocket.registrar.localAddress",
                             DEFAULT_LOCAL_ADDRESS);

  if (!registrarAddress.empty () && !localAddress.empty () ) {
    registrar = std::shared_ptr<WebSocketRegistrar> (new WebSocketRegistrar (
                  registrarAddress, localAddress, port, securePort, path) );
  }
}

WebSocketTransport::~WebSocketTransport()
{
}

void WebSocketTransport::run()
{
  bool running = true;

  while (running) {
    try {
      ios.run();
      running = false;
    } catch (std::exception &e) {
      GST_ERROR ("Unexpected error while running the server: %s", e.what() );
    } catch (...) {
      GST_ERROR ("Unexpected error while running the server");
    }
  }
}

void WebSocketTransport::keepAliveSessions()
{
  std::unique_lock<std::recursive_mutex> lock (mutex);

  while (isRunning() ) {
    std::list<std::string> conns;

    for (auto c : connections) {
      conns.push_back (c.first);
    }

    lock.unlock ();

    for (auto c : conns) {
      GST_INFO ("Keep alive %s", c.c_str() );

      try {
        processor->keepAliveSession (c);
      } catch (KurentoException &e) {
        if (e.getCode() == INVALID_SESSION) {
          GST_INFO ("Session should be removed %s", c.c_str() );
          // TODO: Remove session
        } else {
          throw e;
        }
      }
    }

    lock.lock();
    cond.wait_for (lock, MediaSet::getCollectorInterval() / 4);
  }
}

void WebSocketTransport::start ()
{
  server.start_accept();

  if (hasSecureServer) {
    secureServer.start_accept();
  }

  for (int i = 0; i < n_threads; i++) {
    threads.push_back (std::thread (std::bind (&WebSocketTransport::run, this) ) );
  }

  std::unique_lock<std::recursive_mutex> lock (mutex);
  running = true;
  keepAliveThread = std::thread (std::bind (
                                   &WebSocketTransport::keepAliveSessions, this) );

  if (registrar) {
    registrar->start();
  }
}

void WebSocketTransport::stop ()
{
  std::unique_lock<std::recursive_mutex> lock (mutex);
  running = false;
  cond.notify_all();
  lock.unlock();

  GST_DEBUG ("stop transport");
  server.stop();

  for (int i = 0; i < n_threads; i++) {
    threads[i].join();
  }

  if (registrar) {
    registrar->stop();
  }

  keepAliveThread.join();
}

websocketpp::connection_hdl
WebSocketTransport::getConnection (const std::string &sessionId)
{
  try {
    std::unique_lock<std::recursive_mutex> lock (mutex);
    return connections.at (sessionId);
  } catch (std::out_of_range &e) {
    throw std::out_of_range ("Connection not found for sessionId: " + sessionId);
  }
}

void WebSocketTransport::storeConnection (const std::string &request,
    const std::string &response, websocketpp::connection_hdl connection,
    bool secure, std::string &sessionId)
{
  if (!sessionId.empty() ) {
    std::unique_lock<std::recursive_mutex> lock (mutex);
    bool needsWrite = false;

    try {
      websocketpp::connection_hdl conn = connections.at (sessionId);

      if (conn.lock() != connection.lock() ) {
        GST_WARNING ("Erasing old connection associated with: %s",
                     sessionId.c_str() );
        connectionsReverse.erase (conn);
        connections.erase (sessionId);
        secureConnections.erase (sessionId);
        needsWrite = true;
      }
    } catch (std::out_of_range &e) {
      /* Ignore */
      needsWrite = true;
    }

    try {
      std::string oldSession = connectionsReverse.at (connection);

      if (oldSession != sessionId) {
        GST_WARNING ("Erasing old sessionId %s associated with current connection",
                     oldSession.c_str() );
        connectionsReverse.erase (connection);
        connections.erase (oldSession);
        needsWrite = true;
      }

    } catch (std::out_of_range &e) {
      needsWrite = true;
    }

    if (needsWrite) {
      GST_DEBUG ("Asociating session %s", sessionId.c_str() );
      connections[sessionId] = connection;
      connectionsReverse[connection] = sessionId;

      try {
        processor->keepAliveSession (sessionId);
      } catch (KurentoException &e) {
        if (e.getCode () != INVALID_SESSION) {
          throw e;
        }
      }
    }

    secureConnections[sessionId] = secure;
  }
}

void
WebSocketTransport::send (const std::string &sessionId,
                          const std::string &message)
{
  std::unique_lock <std::recursive_mutex> lock (mutex);
  websocketpp::connection_hdl hdl = getConnection (sessionId);

  try {
    if (secureConnections[sessionId]) {
      lock.unlock();
      secureServer.send (hdl, message, websocketpp::frame::opcode::TEXT);
    } else {
      lock.unlock();
      server.send (hdl, message, websocketpp::frame::opcode::TEXT);
    }
  } catch (std::exception &e) {
    GST_ERROR ("Error sending event: %s", e.what() );
  }
}

template <typename ServerType>
void WebSocketTransport::processMessage (ServerType *s,
    websocketpp::connection_hdl hdl, typename ServerType::message_ptr msg)
{
  std::string request = msg->get_payload();
  std::string response;
  std::string sessionId;

  try {
    sessionId = connectionsReverse.at (hdl);
  } catch (std::out_of_range &e) {
    /* Ignore, there is no previous sessionId */
  }

  GST_DEBUG ("Message: >%s<", request.c_str() );
  sessionId = processor->process (request, response, sessionId);
  GST_DEBUG ("Response: >%s<", response.c_str() );

  storeConnection (request, response, hdl,
                   std::is_same<ServerType, SecureWebSocketServer>::value, sessionId);

  try {
    s->send (hdl, response, websocketpp::frame::opcode::TEXT);
  } catch (websocketpp::exception &e) {
    GST_ERROR ("Could not send response to client: %s",
               e.code().message().c_str() );
  }
}

template <typename ServerType>
void WebSocketTransport::openHandler (ServerType *s,
                                      websocketpp::connection_hdl hdl)
{
  auto connection = s->get_con_from_hdl (hdl);
  std::string resource = connection->get_resource();

  GST_DEBUG ("Client connected from %s", connection->get_origin().c_str() );

  if (resource.size() >= 1 && resource[0] == '/') {
    resource = resource.substr (1);
  }

  resource = resource.substr (0, resource.find_first_of ('?') );

  if (resource != path) {
    try {
      GST_ERROR ("Invalid path \"%s\", closing connection",
                 connection->get_resource().c_str() );
      s->close (hdl, websocketpp::close::status::protocol_error, "Invalid path");
    } catch (websocketpp::exception &e) {
      GST_ERROR ("Error: %s", e.code().message().c_str() );
    }
  }
}

std::string
WebSocketTransport::processSubscription (std::shared_ptr< MediaObjectImpl > obj,
    const std::string &sessionId,
    const std::string &eventType,
    const Json::Value &params)
{
  std::string subscriptionId;
  std::string eventId = sessionId + "|" + obj->getId() + "|" + eventType;
  std::shared_ptr <EventHandler> handler;
  std::unique_lock<std::recursive_mutex> lock (mutex);

  if (handlers.find (eventId) != handlers.end() ) {
    handler = handlers[eventId].lock();
  }

  if (!handler) {
    handler = std::shared_ptr <EventHandler> (new WebSocketEventHandler (obj,
              shared_from_this(), sessionId) );

    subscriptionId = processor->connectEventHandler (obj, sessionId, eventType,
                     handler);
    handlers[eventId] = std::weak_ptr <EventHandler> (handler);
  } else {
    subscriptionId = generateUUID();
    processor->registerEventHandler (obj, sessionId, subscriptionId, handler);
  }

  return subscriptionId;
}

void WebSocketTransport::closeHandler (websocketpp::connection_hdl hdl)
{
  GST_DEBUG ("Connection closed");

  try {
    std::unique_lock<std::recursive_mutex> lock (mutex);
    std::string sessionId = connectionsReverse.at (hdl);

    GST_DEBUG ("Erasing connection associated with: %s", sessionId.c_str() );
    connections.erase (sessionId);
    connectionsReverse.erase (hdl);
    secureConnections.erase (sessionId);
  } catch (std::out_of_range &e) {
    /* Ignore */
  }
}

WebSocketTransport::StaticConstructor WebSocketTransport::staticConstructor;

WebSocketTransport::StaticConstructor::StaticConstructor()
{
  GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
                           GST_DEFAULT_NAME);
}

} /* kurento */

max_stars_repo_name: gortazar/kurento-media-server

max_issues_repo_name: gortazar/kurento-media-server

max_forks_repo_name: gortazar/kurento-media-server


text:
#include <Eigen/Dense>
#include <iostream>

Eigen::MatrixXd StrassenMultiply(const Eigen::MatrixXd& A, const Eigen::MatrixXd& B) {
    if (A.rows() > 128) {
        return A * B;
    }

    unsigned int rows = A.rows() / 2;
    unsigned int cols = A.cols() / 2;

    Eigen::MatrixXd a = A.topLeftCorner(rows, cols);
    Eigen::MatrixXd b = A.topRightCorner(rows, cols);
    Eigen::MatrixXd c = A.bottomLeftCorner(rows, cols);
    Eigen::MatrixXd d = A.bottomRightCorner(rows, cols);
    Eigen::MatrixXd e = B.topLeftCorner(rows, cols);
    Eigen::MatrixXd f = B.topRightCorner(rows, cols);
    Eigen::MatrixXd g = B.bottomLeftCorner(rows, cols);
    Eigen::MatrixXd h = B.bottomRightCorner(rows, cols);

    Eigen::MatrixXd P1 = StrassenMultiply(a, f - h);
    Eigen::MatrixXd P2 = StrassenMultiply(a + b, h);
    Eigen::MatrixXd P3 = StrassenMultiply(c + d, e);
    Eigen::MatrixXd P4 = StrassenMultiply(d, g - e);
    Eigen::MatrixXd P5 = StrassenMultiply(a + d, e + h);
    Eigen::MatrixXd P6 = StrassenMultiply(b - d, g + h);
    Eigen::MatrixXd P7 = StrassenMultiply(a - c, e + f);

    Eigen::MatrixXd r = P5 + P4 - P2 + P6;
    Eigen::MatrixXd s = P1 + P2;
    Eigen::MatrixXd t = P3 + P4;
    Eigen::MatrixXd u = P1 + P5 - P3 - P7;

    Eigen::MatrixXd result = Eigen::MatrixXd::Zero(r.cols() + s.cols(), r.cols() + s.cols());
    result.topLeftCorner(rows, cols) = r;
    result.topRightCorner(rows, cols) = s;
    result.bottomLeftCorner(rows, cols) = t;
    result.bottomRightCorner(rows, cols) = h;

    return result;
}

int main(int argc, char const *argv[]) {
    Eigen::MatrixXd A = Eigen::MatrixXd::Random(2, 2);
    Eigen::MatrixXd B = Eigen::MatrixXd::Random(2, 2);

    Eigen::MatrixXd result = StrassenMultiply(A, B);
    std::cout << "Multiplication done !" << std::endl;

    return 0;
}

max_stars_repo_name: guillaume-haerinck/imac-c

max_issues_repo_name: guillaume-haerinck/imac-c

max_forks_repo_name: guillaume-haerinck/imac-c


text:
/** @file */
#ifndef __STL_CONCEPT_FORWARD_ITERATOR_HPP__
#define __STL_CONCEPT_FORWARD_ITERATOR_HPP__

#include "concept/convertible_to.hpp"
#include "concept/derived_from.hpp"
#include "concept/input_iterator.hpp"
#include "concept/incrementable.hpp"
#include <boost/concept/assert.hpp>
#include <boost/concept/usage.hpp>
#include <boost/concept/detail/concept_def.hpp>
#include "concept/detail/iterator_traits.hpp"

#if (defined _MSC_VER)
#pragma warning(push)
#pragma warning(disable : 4197) // topmost volatile ignored
#pragma warning(disable : 4510) // default constructor could not be generated
#pragma warning(disable : 4610) // object 'class' can never be instantiated - user-defined constructor required
#endif

namespace stl_concept {

/**
 * @addtogroup iterator_group Iterator Requirements
 * @struct ForwardIterator
 * @brief A ForwardIterator is an Iterator that can read data from the pointed-to element.
 *
 *

 * Unlike InputIterator and OutputIterator, it can be used in multipass algorithms.

 * Requirements
 *

 * The type It satisfies ForwardIterator if
 *

 *
The type It satisfies InputIterator

 *
The type It satisfies DefaultConstructible

 *
Objects of the type It provide multipass guarantee described below

 *
The type boost::iterator_reference<It>::type must be convertible to const T&, where T is the type denoted by
 *       boost::iterator_value<It>::type

 *

 *

 * And, given
 *

 *
i, dereferenceable iterator of type It

 *
reference, the type denoted by boost::iterator_reference<It>::type

 *

 * The following expressions must be valid and have their specified effects
 *

 *
ExpressionReturn typeEquivalent expression
 *
i++       It         It ip = i;
++i;
return ip;
 *
*i++      reference
 *

 *

 * @tparam It - type to be checked
 * @see https://en.cppreference.com/w/cpp/named_req/ForwardIterator
 * @see https://en.cppreference.com/w/cpp/experimental/ranges/iterator/ForwardIterator
 */
#ifdef DOXYGEN_WORKING
template <typename It>
struct ForwardIterator
    : InputIterator<It>
    , Incrementable<It> {};
#else // DOXYGEN_WORKING
BOOST_concept(ForwardIterator, (It))
    : InputIterator<It>
    , Incrementable<It>
{
    BOOST_CONCEPT_USAGE(ForwardIterator)
    {
        using __ValueType = __detail::__iterator_value_t<It>;
        using __ReferenceType = __detail::__iterator_reference_t<It>;
        using __CategoryType = __detail::__iterator_category_t<It>;
        // According to C++ named requirements for ForwardIterator,
        // if It satisfies OutputIterator as well, __ReferenceType should be exactly __ValueType&,
        // otherwise, it should be exactly const __ValueType&.
        // However, it is not possible for boost concept to be applied to enable_if for static dispatch.
        // The only way to check if It satisfies OutputIterator is to use BOOST_CONCEPT_ASSERT macro,
        // which will cause compile failure if it does not meet the requirement.
        // So the compromising requirement for __ReferenceType is to check if it can be converted to const __ValueType&.
        // And add another concept called MutableForwardIterator, which set strict requirements on it.
        BOOST_CONCEPT_ASSERT((ConvertibleTo<__ReferenceType, const __ValueType&>));
        BOOST_CONCEPT_ASSERT((DerivedFrom<__CategoryType, std::forward_iterator_tag>));
    }
};
#endif // DOXYGEN_WORKING

} // namespace stl_concept

#if (defined _MSC_VER)
#pragma warning(pop)
#endif

#include <boost/concept/detail/concept_undef.hpp>

#endif  // __STL_CONCEPT_FORWARD_ITERATOR_HPP__

max_stars_repo_name: matrixjoeq/concepts

max_issues_repo_name: matrixjoeq/concepts

max_forks_repo_name: matrixjoeq/concepts


text:
//==================================================================================================
/*!
  @file

  @copyright 2016 NumScale SAS
  @copyright 2016 J.T. Lapreste

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

#include <boost/simd/function/scalar/log2.hpp>
#include <boost/simd/arch/common/generic/function/autodispatcher.hpp>
#include <boost/simd/arch/common/simd/function/log2.hpp>

#endif


text:
// Base-2 logarithm bithack.

#ifndef _AFJDFJSDFSD_PYOPENCL_HEADER_SEEN_BITLOG_HPP
#define _AFJDFJSDFSD_PYOPENCL_HEADER_SEEN_BITLOG_HPP

#include <climits>
#include <boost/cstdint.hpp>

namespace pyopencl
{
  extern const char log_table_8[];

  inline unsigned bitlog2_16(boost::uint16_t v)
  {
    if (unsigned long t = v >> 8)
      return 8+log_table_8[t];
    else
      return log_table_8[v];
  }

  inline unsigned bitlog2_32(boost::uint32_t v)
  {
    if (boost::uint16_t t = v >> 16)
      return 16+bitlog2_16(t);
    else
      return bitlog2_16(v);
  }

  inline unsigned bitlog2(unsigned long v)
  {
#if (ULONG_MAX != 4294967295)
    if (boost::uint32_t t = v >> 32)
      return 32+bitlog2_32(t);
    else
#endif
      return bitlog2_32(v);
  }
}

#endif

max_stars_repo_name: bmerry/pyopencl

max_issues_repo_name: bmerry/pyopencl

max_forks_repo_name: bmerry/pyopencl


text:
/*
 * FlipEnumerator.hpp
 *
 *  Created on: Aug 26, 2009
 *      Author: stewie
 */

#ifndef FLIPENUMERATOR_HPP_
#define FLIPENUMERATOR_HPP_

#include <cstddef>

#include <boost/type_traits/is_convertible.hpp>
#include <boost/iterator/iterator_traits.hpp>
#include <boost/iterator/iterator_adaptor.hpp>
#include <boost/range/iterator.hpp>
#include <boost/range/iterator_range.hpp>

#include "../core/BooleanNetwork_fwd.hpp"

namespace bn {

namespace gen {

namespace detail {

template<class StateIt> class FlipIterator;

template<class StateIt> struct FlipIteratorBase {
	typedef typename boost::iterator_value<StateIt>::type value_type;
	typedef boost::iterator_adaptor<FlipIterator<StateIt> , StateIt,
			value_type, boost::use_default, const value_type> base;
};

/**
 * ForwardTraversal Readable Iterator.
 */
template<class StateIt> class FlipIterator : public FlipIteratorBase<StateIt>::base {
private:
	friend class boost::iterator_core_access;

	typedef typename FlipIteratorBase<StateIt>::value_type value_t;

	StateIt end;
	value_t current;
	typename value_t::size_type i;

	value_t dereference() const {
		return value_t(current).flip(i);
	}

	bool equal(const FlipIterator& other) const {
		return i == other.i && this->base_reference() == other.base_reference();
	}

	void increment() {
		if ((++i) == current.size()) {
			ensureNotEmpty();
			i = 0;
		}
	}

	void ensureNotEmpty() {
		if (++this->base_reference() != end)
			current = *(this->base_reference());
	}

public:

	FlipIterator() {
	}

	FlipIterator(const StateIt first, const StateIt last) :
		FlipIterator::iterator_adaptor_(first), end(last), i(0) {
		if (this->base_reference() != end)
			current = *(this->base_reference());
	}
};

}

/**
 * @ingroup generator
 *
 * Forward Traversal Readable range.
 */
template<class SinglePassRange> class FlipEnumerator : public boost::iterator_range<
		detail::FlipIterator<
				typename boost::range_iterator<SinglePassRange>::type> > {
private:
	typedef detail::FlipIterator<
			typename boost::range_iterator<SinglePassRange>::type> iter;
	typedef boost::iterator_range<iter> base;

public:

	FlipEnumerator() {
	}

	FlipEnumerator(SinglePassRange& gen) :
		base(iter(boost::begin(gen), boost::end(gen)), iter(boost::end(gen),
				boost::end(gen))) {
	}

	template<class OtherRange> FlipEnumerator(
			const FlipEnumerator<OtherRange>& other) :
		base(other) {
	}
};

namespace tag {

struct enumerate_flips {

	template<class SinglePassRange> struct apply {
		typedef FlipEnumerator<SinglePassRange> type;
	};
};

} // namespace tag

struct enumerate_flips {
};

template<class SinglePassRange> FlipEnumerator<SinglePassRange> operator|(
		SinglePassRange& sr, const enumerate_flips&) {
	return FlipEnumerator<SinglePassRange> (sr);
}

template<class SinglePassRange> FlipEnumerator<const SinglePassRange> operator|(
		const SinglePassRange& sr, const enumerate_flips&) {
	return FlipEnumerator<const SinglePassRange> (sr);
}

} // namespace gen

} // namespace bn

#endif /* FLIPENUMERATOR_HPP_ */

max_stars_repo_name: Markfrancisrogers/BooleanNetwork

max_issues_repo_name: Markfrancisrogers/BooleanNetwork

max_forks_repo_name: Markfrancisrogers/BooleanNetwork


text:
#include <boost/regex.hpp>
#include <cstdlib>

#include "eval_add/eval_add.h"

using namespace boost;

const regex re(R"(\s*(\d+)\s*\+\s*(\d+)\s*)");

bool eval_add(const char *str, int *out) {
  cmatch match;
  if (regex_match(str, match, re)) {
    *out = stoi(match[1].str()) + stoi(match[2].str());
    return true;
  } else {
    return false;
  }
}

max_stars_repo_name: melonedo/cmake-lecture

max_issues_repo_name: melonedo/cmake-lecture

max_forks_repo_name: melonedo/cmake-lecture


text:
/*
 * Copyright (C) 2009-2013, Computing Systems Laboratory (CSLab), NTUA.
 * Copyright (C) 2009-2011, Kornilios Kourtis
 * Copyright (C) 2011,      Vasileios Karakasis
 * Copyright (C) 2011,      Theodoros Gkountouvas
 * Copyright (C) 2012-2013, Athena Elafrou
 * All rights reserved.
 *
 * This file is distributed under the BSD License. See LICENSE.txt for details.
 */

/**
 * \file Mmf.hpp
 * \brief Matrix Market Format utilities
 *
 * \author Computing Systems Laboratory (CSLab), NTUA
 * \date 2011–2014
 * \copyright This file is distributed under the BSD License. See LICENSE.txt
 * for details.
 */

#ifndef SPARSEX_INTERNALS_MMF_HPP
#define SPARSEX_INTERNALS_MMF_HPP

#include <sparsex/internals/Element.hpp>
#include <sparsex/internals/logger/Logger.hpp>
#include <fstream>
#include <iterator>
#include <vector>
#include <algorithm>
#include <string>
#include <boost/algorithm/string.hpp>
#include <boost/assign/list_of.hpp>
#include <boost/bind/bind.hpp>
#include <boost/container/vector.hpp>
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/unordered_map.hpp>

using namespace std;
using namespace sparsex::csx;

namespace sparsex {
  namespace io {

    // For testing purposes; to be removed
    void ReadMmfSizeLine(const char *mmf_file, size_t& nr_rows, size_t& nr_cols,
			 size_t& nr_nzeros);

    // Returns false at EOF
    bool DoRead(ifstream &in, vector<string> &arguments);

    template<typename IndexType, typename ValueType>
    void ParseElement(vector<string> &arguments, IndexType &y, IndexType &x,
		      ValueType &v);

    template<typename IndexType, typename ValueType>
    class MMF
    {
    public:
      typedef IndexType idx_t;
      typedef ValueType val_t;

      MMF(const char *filename);
      MMF(IndexType *rowptr, IndexType *colind, ValueType *values,
	  size_t nr_rows, size_t nr_cols, bool zero_based) {} //Dummy
      ~MMF()
      {
        if (in.is_open())
	  in.close();
      }

      size_t GetNrRows() const
      {
        return nr_rows_;
      }

      size_t GetNrCols() const
      {
        return nr_cols_;
      }

      size_t GetNrNonzeros() const
      {
        if (symmetric_ || col_wise_)
	  return matrix_.size();
        else
	  return nr_nzeros_;
      }

      bool IsSymmetric() const
      {
        return symmetric_;
      }

      bool IsColWise() const
      {
        return col_wise_;
      }

      bool IsZeroBased() const
      {
        return zero_based_;
      }

      bool IsReordered() const
      {
        return reordered_;
      }

      pair<IndexType, IndexType> GetCoordinates(IndexType idx) const
      {
        return matrix_[idx].GetCoordinates();
      }

      void SetCoordinates(IndexType idx, IndexType row, IndexType col)
      {
        matrix_[idx] = Element<IndexType, ValueType>(row, col,
                                                     matrix_[idx].GetValue());
      }

      void Sort()
      {
        sort(matrix_.begin(), matrix_.end());
      }

      // void Print(std::ostream &os) const
      // {
      //     os << "Elements of Matrix" << endl;
      //     os << "------------------" << endl;
      //     if (symmetric_ || col_wise_) {
      //         for (size_t i = 0; i < matrix_.size(); i++) {
      //             os << matrix_[i] << endl;
      //         }
      //     } else {
      //         // iterator iter = begin();
      //         // iterator iter_end = end();
      //         // for (;iter != iter_end; ++iter) {
      //         //     cout << (*iter).row << " " << (*iter).col << " "
      //         //          << (*iter).val << endl;
      //         // }
      //     }
      //     os << endl;
      // }

      void InitMatrix(size_t size)
      {
        matrix_.reserve(size);
      }

      void ResetStream();

      void InsertElement(const Element<IndexType, ValueType> &elem)
      {
        matrix_.push_back(elem);
      }

      void SetReordered(bool flag)
      {
        reordered_ = flag;
      }

      class iterator;
      iterator begin();
      iterator end();

    private:
      size_t nr_rows_, nr_cols_, nr_nzeros_;
      ifstream in;
      bool symmetric_, col_wise_, zero_based_, reordered_;
      int file_mode_;     // 0 for MMF files, 1 for regular files
      boost::container::vector<Element<IndexType, ValueType> > matrix_;

      enum MmfInfo {
        Banner,
        Matrix,
        Coordinate,
        Real,
        Double,
        Integer,
        General,
        Symmetric,
        Indexing0,
        Indexing1,
        ColumnWise,
        RowWise
      };

      static boost::unordered_map<MmfInfo, const string> names_;

      void ParseMmfHeaderLine(vector<string> &arguments);
      void ParseMmfSizeLine(vector<string> &arguments);
      void DoLoadMmfMatrix();
      bool GetNext(IndexType &r, IndexType &c, ValueType &v);
    };

    template<typename IndexType, typename ValueType>
    class MMF<IndexType, ValueType>::iterator
      : public std::iterator<forward_iterator_tag,
			     Element<IndexType, ValueType> >
    {
    public:
      ~iterator() {
        if (!mmf_->reordered_)
	  mmf_->matrix_.clear();
        // In case subsequent calls to DoLoadMatrix() are made
        // mmf_->ResetStream();
      }

      iterator(MMF *mmf, size_t cnt)
	: mmf_(mmf),
	  cnt_(cnt),
	  elem_(Element<IndexType, ValueType>(0, 0, 0)),
	  valid_(false),
	  row_prev_(1),
	  col_prev_(1)
      {
        if (mmf_->symmetric_ || mmf_->col_wise_ || mmf_->reordered_)
	  return;

        // this is the initializer
        if (cnt_ == 0)
	  DoSet();
      }

      bool operator==(const iterator &i)
      {
        //cout << "me: " << mmf_ << " " << cnt_
        //     << " i: " << i.mmf << " " << i.cnt << "\n";
        return (mmf_ == i.mmf_) && (cnt_ == i.cnt_);
      }

      bool operator!=(const iterator &i)
      {
        return !(*this == i);
      }

      void operator++()
      {
        ++cnt_;
        if (mmf_->symmetric_ || mmf_->col_wise_ || mmf_->reordered_) {
	  return;
        }

        DoSet();
      }

      Element<IndexType, ValueType> &operator*()
      {
        if (mmf_->symmetric_ || mmf_->col_wise_ || mmf_->reordered_) {
	  return mmf_->matrix_[cnt_];
        } else {
	  if (!valid_) {
	    LOG_ERROR << "Requesting dereference, but mmf ended (cnt: "
		      << cnt_ << "/" << mmf_->nr_nzeros_ << ").\n";
	    exit(1);
	  }

	  if (elem_.GetRow() < row_prev_ || (elem_.GetRow() == row_prev_
					     && elem_.GetCol() < col_prev_)) {
	    LOG_ERROR << "indices are not sorted in MMF file\n";
	    exit(1);
	  }

	  if (elem_.GetRow() == row_prev_) {
	    col_prev_ = elem_.GetCol();
	  } else {
	    col_prev_ = 1;
	  }

	  row_prev_ = elem_.GetRow();
	  return elem_;
        }
      }

    private:
      void DoSet()
      {
        IndexType row, col;
        ValueType val;
        valid_ = mmf_->GetNext(row, col, val);
        elem_ = Element<IndexType, ValueType>(row, col, val);
      }

      MMF *mmf_;
      size_t cnt_;
      Element<IndexType, ValueType> elem_;
      bool valid_;
      IndexType row_prev_, col_prev_;
    };

    template<typename IndexType, typename ValueType>
    typename MMF<IndexType, ValueType>::iterator MMF<IndexType, ValueType>::
    begin()
    {
      return iterator(this, 0);
    }

    template<typename IndexType, typename ValueType>
    typename MMF<IndexType, ValueType>::iterator MMF<IndexType, ValueType>::
    end()
    {
      if (this->symmetric_ || this->col_wise_ || this->reordered_) {
        return iterator(this, matrix_.size());
      } else {
        return iterator(this, nr_nzeros_);
      }
    }

    /*
     * Implementation of class MMF
     */
    template<typename IndexType, typename ValueType>
    boost::unordered_map<typename MMF<IndexType, ValueType>::MmfInfo,
			 const string>
    MMF<IndexType, ValueType>::names_ =
				 boost::assign::map_list_of
				 (Banner, "%%MatrixMarket")
				 (Matrix, "matrix")
				 (Coordinate, "coordinate")
				 (Real, "real")
				 (Double, "double")
				 (Integer, "integer")
				 (General, "general")
				 (Symmetric, "symmetric")
				 (Indexing0, "0-base")
				 (Indexing1, "1-base")
				 (ColumnWise, "column")
				 (RowWise, "row");

    template<typename IndexType, typename ValueType>
    MMF<IndexType, ValueType>::
    MMF(const char* filename)
      :
      nr_rows_(0),
      nr_cols_(0),
      nr_nzeros_(0),
      symmetric_(false),
      col_wise_(true),
      zero_based_(false),
      reordered_(false),
      file_mode_(0)
    {
      try {
        in.open(filename);
        if (!in.is_open()) {
	  throw ios_base::failure("");
        }
      } catch (ios_base::failure &e) {
        LOG_ERROR << "MMF file error\n";
        exit(1);
      }

      vector<string> arguments;
      DoRead(in, arguments);
      ParseMmfHeaderLine(arguments);
      ParseMmfSizeLine(arguments);

      if (symmetric_ || col_wise_) {
        DoLoadMmfMatrix();
      }
    }

    template<typename IndexType, typename ValueType>
    void MMF<IndexType, ValueType>::
    ParseMmfHeaderLine(vector<string> &arguments)
    {
      // Check if header line exists
      if (arguments[0] != names_[Banner]) {
        if (arguments[0].length() > 2 && arguments[0][0] == '%'&&
            arguments[0][1] == '%') {
	  // Header exists but is erroneous so exit
	  LOG_ERROR << "invalid header line in MMF file\n";
	  exit(1);
        } else {
	  // Parse as size line
	  file_mode_ = 1;
	  col_wise_ = false;
	  return;
        }
      }

      size_t length;
      if ((length = arguments.size()) < 5) {
        LOG_ERROR << "less arguments in header line of MMF file\n";
        exit(1);
      }

      // Convert to lowercase just in case
      BOOST_FOREACH(string &t, arguments) {
        boost::algorithm::to_lower(t);
      }

      if (arguments[1] != names_[Matrix]) {
        LOG_ERROR << "unsupported object in header line of MMF file\n";
        exit(1);
      }

      if (arguments[2] != names_[Coordinate]) {
        LOG_ERROR << "unsupported matrix format in header line of MMF file\n";
        exit(1);
      }

      if (arguments[4] == names_[General]) {
        symmetric_ = false;
      } else if (arguments[4] == names_[Symmetric]) {
        symmetric_ = true;
      } else {
        LOG_ERROR << "unsupported symmetry in header line of MMF file\n";
        exit(1);
      }

      if (length > 5) {
        for (size_t i = 5; i < length; i++) {
	  if (arguments[i] == names_[Indexing0]) zero_based_ = true;
	  else if (arguments[i] == names_[Indexing1]) zero_based_ = false;
	  else if (arguments[i] == names_[ColumnWise]) col_wise_ = true;
	  else if (arguments[i] == names_[RowWise]) col_wise_ = false;
        }
      }
    }

    template<typename IndexType, typename ValueType>
    void MMF<IndexType, ValueType>::
    ParseMmfSizeLine(vector<string> &arguments)
    {
      bool ignore_comments = false;

      if (file_mode_ && arguments[0][0] == '%') {
        ignore_comments = true;
      }

      if (!file_mode_ || ignore_comments) {
        while (in.peek() == '%') {
	  in.ignore(numeric_limits<streamsize>::max(), '\n');
        }
        if (!DoRead(in, arguments)) {
	  LOG_ERROR << "size line error in MMF file\n";
	  exit(1);
        }
      }
      ParseElement(arguments, nr_rows_, nr_cols_, nr_nzeros_);
    }

    template<typename IndexType, typename ValueType>
    void MMF<IndexType, ValueType>::
    DoLoadMmfMatrix()
    {
      IndexType row, col;
      ValueType val;

      if (symmetric_) {
        matrix_.reserve(nr_nzeros_ << 1);
        for (size_t i = 0; i < nr_nzeros_; i++) {
	  if (!MMF::GetNext(row, col, val)) {
	    LOG_ERROR << "Requesting dereference, but mmf ended.\n";
	    exit(1);
	  }

	  matrix_.emplace_back(row, col, val);
	  if (row != col)
	    // Emplace also the symmetric element
	    matrix_.emplace_back(col, row, val);
        }
      } else {
        matrix_.reserve(nr_nzeros_);
        for (size_t i = 0; i < nr_nzeros_; i++) {
	  if (!MMF::GetNext(row, col, val)) {
	    LOG_ERROR << "Requesting dereference, but mmf ended.\n";
	    exit(1);
	  }

	  matrix_.emplace_back(row, col, val);
        }
      }

      sort(matrix_.begin(), matrix_.end());
    }

    template<typename IndexType, typename ValueType>
    bool MMF<IndexType, ValueType>::
    GetNext(IndexType &r, IndexType &c, ValueType &v)
    {
      vector<string> arguments;

      if (!DoRead(in, arguments)) {
        return false;
      }

      ParseElement(arguments, r, c, v);
      if (zero_based_) {
        r++;
        c++;
      }

      return true;
    }

    template<typename IndexType, typename ValueType>
    void MMF<IndexType, ValueType>::
    ResetStream()
    {
      in.clear();
      in.seekg(0, ios::beg);
      while (in.peek() == '%') {
        in.ignore(numeric_limits<streamsize>::max(), '\n');
      }
      in.ignore(numeric_limits<streamsize>::max(), '\n');
    }

    template<typename IndexType, typename ValueType>
    void ParseElement(vector<string> &arguments, IndexType &y, IndexType &x,
		      ValueType &v)
    {
      if (arguments.size() == 3) {
        y = boost::lexical_cast<IndexType,string>(arguments[0]);
        x = boost::lexical_cast<IndexType,string>(arguments[1]);
        v = boost::lexical_cast<ValueType,string>(arguments[2]);
      } else {
        LOG_ERROR << "bad input, less arguments in line of MMF file\n";
        exit(1);
      }
    }

  } // end of namespace io
} // end of namespace sparsex

#endif  // SPARSEX_INTERNALS_MMF_HPP

max_stars_repo_name: Baltoli/sparsex

max_issues_repo_name: Baltoli/sparsex

max_forks_repo_name: Baltoli/sparsex


text:
// (C) Copyright 2002-4 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)

//  See http://www.boost.org for updates, documentation, and revision history.
// text_warchive
#include <boost/archive/text_woarchive.hpp>
typedef boost::archive::text_woarchive test_oarchive;
typedef std::wofstream test_ostream;
#include <boost/archive/text_wiarchive.hpp>
typedef boost::archive::text_wiarchive test_iarchive;
typedef std::wifstream test_istream;
#define TEST_STREAM_FLAGS (std::ios_base::openmode)0


text:
// Author(s): Wieger Wesselink
// Copyright: see the accompanying file COPYING or copy at
// https://github.com/mCRL2org/mCRL2/blob/master/COPYING
//
// 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)
//
/// \file specification_test.cpp
/// \brief Add your file description here.

#define BOOST_TEST_MODULE specification_test
#include "mcrl2/lps/detail/test_input.h"
#include "mcrl2/lps/find.h"
#include "mcrl2/lps/linearise.h"
#include "mcrl2/lps/parse.h"
#include "mcrl2/lps/print.h"

#include <boost/test/included/unit_test_framework.hpp>

using namespace mcrl2;
using namespace mcrl2::data;
using namespace mcrl2::lps;

void test_find_sort_expressions()
{
  specification spec=remove_stochastic_operators(linearise(lps::detail::ABP_SPECIFICATION()));
  std::set<sort_expression> s;
  lps::find_sort_expressions(spec, std::inserter(s, s.end()));
  std::cout << core::detail::print_set(s) << std::endl;
}

void test_system_defined_sorts()
{
  const std::string SPEC(
    "act a;\n\n"
    "proc X(i,j: Nat)   = (i == 5) -> a. X(i,j);\n\n"
    "init X(0,1);\n");

  specification spec=remove_stochastic_operators(linearise(SPEC));
  function_symbol_vector r = spec.data().constructors(data::sort_nat::nat());
  BOOST_CHECK(r.size() != 0);
}

// This test is added to demonstrate that context sorts need to be added to
// the data specification of an LPS. If this is not done, the resulting
// LPS is not well typed.
void test_context_sorts()
{
  std::string text =
    "proc P = sum x:Real.(x==x) -> tau.P;\n"
    "init P;\n"
    ;

  specification spec = parse_linear_process_specification(text);
  std::cout << "spec = " << spec << std::endl;
  BOOST_CHECK(check_well_typedness(spec));

  stochastic_specification sspec;
  parse_lps(text, sspec);
  std::cout << "sspec = " << sspec << std::endl;
  BOOST_CHECK(check_well_typedness(sspec));
}

BOOST_AUTO_TEST_CASE(test_main)
{
  test_find_sort_expressions();
  test_system_defined_sorts();
  test_context_sorts();
}


text:
// Copyright 2005 The Trustees of Indiana University.

// 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)

//  Authors: Douglas Gregor
//           Andrew Lumsdaine
#ifndef BOOST_PARALLEL_GRAPH_PYTHON_ITERATOR_HPP
#define BOOST_PARALLEL_GRAPH_PYTHON_ITERATOR_HPP

#include <string>
#include <boost/python.hpp>
#include <iterator>

namespace boost { namespace graph { namespace python {

namespace detail {
  template<typename T> bool type_already_registered()
  {
    using boost::python::objects::registered_class_object;
    using boost::python::type_id;

    return registered_class_object(type_id<T>()).get() != 0;
  }
} // end namespace detail

template<typename Iterator>
class simple_python_iterator
{
public:
  typedef typename std::iterator_traits<Iterator>::difference_type
  difference_type;

  simple_python_iterator(std::pair<Iterator, Iterator> p)
    : orig_first(p.first), first(p.first), last(p.second), n(-1) { }

  typename std::iterator_traits<Iterator>::value_type next()
  {
    using boost::python::objects::stop_iteration_error;

    if (first == last) stop_iteration_error();
    return *first++;
  }

  difference_type len()
  {
    if (n == -1) n = std::distance(first, last);
    return n;
  }

  static void declare(const char* name, const char* docstring = 0)
  {
    using boost::python::class_;
    using boost::python::no_init;
    using boost::python::objects::identity_function;
    if (!detail::type_already_registered<simple_python_iterator>())
      class_<simple_python_iterator<Iterator> >(name, docstring, no_init)
        .def("__iter__", identity_function())
        .def("__len__", &simple_python_iterator<Iterator>::len)
        .def("next", &simple_python_iterator<Iterator>::next)
      ;
  }

private:
  Iterator orig_first;
  Iterator first;
  Iterator last;
  difference_type n;
};

} } } // end namespace boost::graph::python

#endif // BOOST_PARALLEL_GRAPH_PYTHON_ITERATOR_HPP

max_stars_repo_name: erwinvaneijk/bgl-python

max_issues_repo_name: erwinvaneijk/bgl-python

max_forks_repo_name: erwinvaneijk/bgl-python


text:
#include "MultiPartUploader.h"
#include "Tools.h"

#include <aws/core/utils/HashingUtils.h>
#include <aws/s3/model/CreateMultipartUploadRequest.h>
#include <aws/s3/model/GetObjectRequest.h>
#include <aws/s3/model/Object.h>
#include <aws/s3/model/UploadPartRequest.h>

#include <boost/interprocess/streams/bufferstream.hpp>

namespace comm {
namespace network {

MultiPartUploader::MultiPartUploader(
    std::shared_ptr<Aws::S3::S3Client> client,
    const std::string bucketName,
    const std::string objectName)
    : client(client), bucketName(bucketName), objectName(objectName) {
  this->completeMultipartUploadRequest.SetBucket(this->bucketName);
  this->completeMultipartUploadRequest.SetKey(this->objectName);

  Aws::S3::Model::CreateMultipartUploadRequest createRequest;
  createRequest.SetBucket(this->bucketName);
  createRequest.SetKey(this->objectName);
  createRequest.SetContentType("text/plain");

  Aws::S3::Model::CreateMultipartUploadOutcome createOutcome =
      this->client->CreateMultipartUpload(createRequest);

  if (!createOutcome.IsSuccess()) {
    throw std::runtime_error(createOutcome.GetError().GetMessage());
  }
  this->uploadId = createOutcome.GetResult().GetUploadId();
  this->completeMultipartUploadRequest.SetUploadId(this->uploadId);
}

void MultiPartUploader::addPart(const std::string &part) {
  Aws::S3::Model::UploadPartRequest uploadRequest;
  uploadRequest.SetBucket(this->bucketName);
  uploadRequest.SetKey(this->objectName);
  uploadRequest.SetPartNumber(this->partNumber);
  uploadRequest.SetUploadId(this->uploadId);

  std::shared_ptr<Aws::IOStream> body = std::shared_ptr<Aws::IOStream>(
      new boost::interprocess::bufferstream((char *)part.data(), part.size()));

  uploadRequest.SetBody(body);

  Aws::Utils::ByteBuffer partMd5(Aws::Utils::HashingUtils::CalculateMD5(*body));
  uploadRequest.SetContentMD5(Aws::Utils::HashingUtils::Base64Encode(partMd5));

  uploadRequest.SetContentLength(part.size());

  Aws::S3::Model::UploadPartOutcome uploadPartOutcome =
      this->client->UploadPart(uploadRequest);
  Aws::S3::Model::CompletedPart completedPart;
  completedPart.SetPartNumber(this->partNumber);
  std::string eTag = uploadPartOutcome.GetResult().GetETag();
  if (eTag.empty()) {
    throw std::runtime_error("etag empty");
  }
  completedPart.SetETag(eTag);
  completedMultipartUpload.AddParts(completedPart);
  ++this->partNumber;
}

void MultiPartUploader::finishUpload() {
  this->completeMultipartUploadRequest.SetMultipartUpload(
      this->completedMultipartUpload);

  Aws::S3::Model::CompleteMultipartUploadOutcome completeUploadOutcome =
      this->client->CompleteMultipartUpload(
          this->completeMultipartUploadRequest);

  if (!completeUploadOutcome.IsSuccess()) {
    throw std::runtime_error(completeUploadOutcome.GetError().GetMessage());
  }
}

} // namespace network
} // namespace comm

max_stars_repo_name: jonringer-comm/comm

max_issues_repo_name: jonringer-comm/comm

max_forks_repo_name: jonringer-comm/comm


text:
//          Copyright Oliver Kowalke 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)

#ifndef BOOST_COROUTINES2_DETAIL_CONFIG_H
#define BOOST_COROUTINES2_DETAIL_CONFIG_H

#include <boost/config.hpp>
#include <boost/context/detail/config.hpp>
#include <boost/detail/workaround.hpp>

#ifdef BOOST_COROUTINES2_DECL
# undef BOOST_COROUTINES2_DECL
#endif

#if (defined(BOOST_ALL_DYN_LINK) || defined(BOOST_COROUTINES2_DYN_LINK) ) && ! defined(BOOST_COROUTINES2_STATIC_LINK)
# if defined(BOOST_COROUTINES2_SOURCE)
#  define BOOST_COROUTINES2_DECL BOOST_SYMBOL_EXPORT
#  define BOOST_COROUTINES2_BUILD_DLL
# else
#  define BOOST_COROUTINES2_DECL BOOST_SYMBOL_IMPORT
# endif
#endif

#if ! defined(BOOST_COROUTINES2_DECL)
# define BOOST_COROUTINES2_DECL
#endif

#if ! defined(BOOST_COROUTINES2_SOURCE) && ! defined(BOOST_ALL_NO_LIB) && ! defined(BOOST_COROUTINES2_NO_LIB)
# define BOOST_LIB_NAME boost_coroutine
# if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_COROUTINES2_DYN_LINK)
#  define BOOST_DYN_LINK
# endif
# include <boost/config/auto_link.hpp>
#endif

#if defined(BOOST_USE_SEGMENTED_STACKS)
# if ! ( (defined(__GNUC__) && __GNUC__ > 3 && __GNUC_MINOR__ > 6) || \
         (defined(__clang__) && __clang_major__ > 2 && __clang_minor__ > 3) )
#  error "compiler does not support segmented_stack stacks"
# endif
# define BOOST_COROUTINES2_SEGMENTS 10
#endif

#if defined(BOOST_CONTEXT_NO_EXECUTION_CONTEXT)
# error "execution_context from boost.context not supported"
#endif

#endif // BOOST_COROUTINES2_DETAIL_CONFIG_H

max_stars_repo_name: BruceNUAA/gaze-detection-android-app

max_issues_repo_name: BruceNUAA/gaze-detection-android-app

max_forks_repo_name: BruceNUAA/gaze-detection-android-app