text:
#include "calibration_manager.h"
#include <boost/lexical_cast.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/tokenizer.hpp>
#include <boost/math/special_functions/round.hpp>

#include <opencv2/flann/miniflann.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <scan_calculator.h>

#include <fstream>
#include <graycode.h>

CalibrationManager::CalibrationManager()
{
    m_calibParams.resize(2);
    m_detectionResult.resize(2);

    m_calibDescription.ReadFromIni("C:/Users/yildirim/Dropbox/Vision/myOCV/images/hosteo1/Calib.ini");
}

CalibrationManager::~CalibrationManager()
{

}

bool CalibrationManager::StereoCalibrate()
{
    if(!IsReadyToGo())
        return false;

    std::vector<std::vector<std::vector<cv::Point2f> > > ring_markers_image_wrapper;
    ring_markers_image_wrapper.resize(2);
    ring_markers_image_wrapper[0].resize(1);
    ring_markers_image_wrapper[1].resize(1);

    for(int cam_idx = 0; cam_idx < 2; cam_idx++)
    {
        //calculate initial guess for Ps
        m_stereoResult.P[cam_idx] = DLT(m_detectionResult[cam_idx].id_markers_world[0], m_detectionResult[cam_idx].id_markers_image[0]);

        //decompose Ps
        cv::decomposeProjectionMatrix(m_stereoResult.P[cam_idx], m_stereoResult.K[cam_idx], m_stereoResult.rvecs[cam_idx][0], m_stereoResult.tvecs[cam_idx][0]);
        m_stereoResult.K[cam_idx] = m_stereoResult.K[cam_idx] / m_stereoResult.K[cam_idx].at<float>(2,2);
        m_stereoResult.K[cam_idx].at<float>(0,1) = 0.0;
        m_stereoResult.K[cam_idx].at<float>(1,0) = 0.0;

        cv::Mat dummy;
        if(!MatchMarkers(m_calibDescription, m_stereoResult.P[cam_idx], m_detectionResult[cam_idx], cam_idx, dummy))
            return false;

        //Tum noktalari buraya dose, bu Levenberg-Marquard kullaniyor guya
        m_stereoResult.RMS[cam_idx] = cv::calibrateCamera(
                                        m_detectionResult[cam_idx].ring_markers_world,
                                        m_detectionResult[cam_idx].ring_markers_image,
                                        m_detectionResult[cam_idx].img_size,
                                        m_stereoResult.K[cam_idx],
                                        m_stereoResult.D[cam_idx],
                                        m_stereoResult.rvecs[cam_idx],
                                        m_stereoResult.tvecs[cam_idx],
                                        CV_CALIB_USE_INTRINSIC_GUESS); //| CV_CALIB_FIX_K1|CV_CALIB_FIX_K2|CV_CALIB_FIX_K3|CV_CALIB_FIX_K4|CV_CALIB_FIX_K5);

        cv::projectPoints(m_calibDescription.calib_points,
                          m_stereoResult.rvecs[cam_idx][0],
                          m_stereoResult.tvecs[cam_idx][0],
                          m_stereoResult.K[cam_idx],
                          m_stereoResult.D[cam_idx],
                          ring_markers_image_wrapper[cam_idx][0]);
    }

    //stereo calibration
    std::vector<std::vector<cv::Point3f> > calib_points_wrapper;
    calib_points_wrapper.push_back(m_calibDescription.calib_points);

    m_stereoResult.stereoRMS = cv::stereoCalibrate(calib_points_wrapper,
                                     ring_markers_image_wrapper[0],
                                     ring_markers_image_wrapper[1],
                                     m_stereoResult.K[0],
                                     m_stereoResult.D[0],
                                     m_stereoResult.K[1],
                                     m_stereoResult.D[1],
                                     m_detectionResult[0].img_size,
                                     m_stereoResult.R,
                                     m_stereoResult.T,
                                     m_stereoResult.E,
                                     m_stereoResult.F,
                                     cv::TermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 50, 1e-5),
                                     CV_CALIB_USE_INTRINSIC_GUESS );
    return true;
}

void CalibrationManager::WriteRawCal(const char* filename, std::vector<std::vector<cv::Mat> >& sequence)
{
	int height = sequence[0][0].rows;
	int width = sequence[0][0].cols;

	ScanCalculator sc;
	sc.CalculateAbsPhase(sequence);
	cv::Mat absL = cv::Mat(height, width, CV_16S);
	cv::Mat absR = cv::Mat(height, width, CV_16S);
	LoadAbsolutePhase("absL.tiff", absL);
	LoadAbsolutePhase("absR.tiff", absR);

	int i = 0;
	boost::property_tree::ptree pt;
	char bufferHeader[32];
	char bufferData[256];
	pt.put("Cam1.NP", m_detectionResult[0].ring_markers_image[0].size());
	for(; i < m_detectionResult[0].ring_markers_image[0].size(); i++)
	{
		double imgX = m_detectionResult[0].ring_markers_image[0][i].x;
		double imgY = m_detectionResult[0].ring_markers_image[0][i].y;
		double wrdX = m_detectionResult[0].ring_markers_world[0][i].x;
		double wrdY = m_detectionResult[0].ring_markers_world[0][i].y;
		double wrdZ = m_detectionResult[0].ring_markers_world[0][i].z;
		double srcW = BLInterpolate(imgX, imgY, absL);

		sprintf(bufferHeader, "Cam1.Mark_%.3i", i);
		sprintf(bufferData, "%f %f %f %f %f %f", wrdX, wrdY, wrdZ, imgX, imgY, srcW);
		pt.put(bufferHeader, bufferData);
	}

	i = 0;
	pt.put("Cam2.NP", m_detectionResult[1].ring_markers_image[0].size());
	for(; i < m_detectionResult[1].ring_markers_image[0].size(); i++)
	{
		double imgX = m_detectionResult[1].ring_markers_image[0][i].x;
		double imgY = m_detectionResult[1].ring_markers_image[0][i].y;
		double wrdX = m_detectionResult[1].ring_markers_world[0][i].x;
		double wrdY = m_detectionResult[1].ring_markers_world[0][i].y;
		double wrdZ = m_detectionResult[1].ring_markers_world[0][i].z;
		double srcW = BLInterpolate(imgX, imgY, absR);

		sprintf(bufferHeader, "Cam2.Mark_%.3i", i);
		sprintf(bufferData, "%f %f %f %f %f %f", wrdX, wrdY, wrdZ, imgX, imgY, srcW);
		pt.put(bufferHeader, bufferData);
	}
	boost::property_tree::write_ini(filename, pt);
}

bool CalibrationManager::DetectMarkers(cv::Mat& camImg, int idxCam)
{
    m_detectionResult[idxCam].amount_id_markers = 0;
    m_detectionResult[idxCam].img_size = cv::Size(camImg.cols, camImg.rows);

    std::map<int, int> id_markers_index;
    std::vector<cv::Point3f> id_markers_world;
    std::vector<cv::Point2f> id_markers_image;
    std::vector<cv::Point2f> all_markers_image;

    //convert source image to gray
    cv::Mat src_gray;
    cv::cvtColor(camImg, src_gray, CV_BGR2GRAY);

    cv::GaussianBlur( src_gray, src_gray, cv::Size(m_calibParams[idxCam].kernel_size, m_calibParams[idxCam].kernel_size), 2, 2 );

    //binarize image
    cv::RNG rng(12345);
    cv::threshold( src_gray, src_gray, m_calibParams[idxCam].binary_threshold, 255, CV_THRESH_BINARY);

    cv::Mat src_binary;
    src_gray.copyTo(src_binary);

    std::vector<std::vector<cv::Point> > contours;
    std::vector<cv::Vec4i> hierarchy;
    cv::findContours( src_gray, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0) );

    //Find the rotated rectangles and ellipses for each contour
    std::vector<cv::RotatedRect> minRect( contours.size() );
    std::vector<cv::RotatedRect> minEllipse( contours.size() );

    for( int i = 0; i < contours.size(); i++ )
    {
        minRect[i] = cv::minAreaRect( cv::Mat(contours[i]) );
        if( contours[i].size() > 5 )
        {
            minEllipse[i] = cv::fitEllipse( cv::Mat(contours[i]) );
        }
    }

    //Draw contours + rotated rects + ellipses
    for( int i = 0; i< contours.size(); i++ )
    {
        if(minEllipse[i].size.width < 20 || minEllipse[i].size.width > 100)continue;
        if(minEllipse[i].size.height < 20 || minEllipse[i].size.height > 100)continue;
        if(minEllipse[i].size.area() < 1500 || minEllipse[i].size.area() > 5000)continue;
        if( abs((minEllipse[i].size.width / (double)minEllipse[i].size.height)-1.0) > 0.15 )continue;

        cv::Scalar color = cv::Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
        // contour
        //cv::drawContours( camImg, contours, i, cv::Scalar(255,255,0), 1, 8, std::vector<cv::Vec4i>(), 0, cv::Point() );
        // ellipse

        // rotated rectangle
        cv::Point2f rect_points[4]; minRect[i].points( rect_points );
        //for( int j = 0; j < 4; j++ )
          //cv::line( camImg, rect_points[j], rect_points[(j+1)%4], color, 1, 8 );

        //detected_img_points.push_back(minEllipse[i].center);
        //m_detectionResult[idxCam].all_markers_image[0].push_back(minEllipse[i].center);

        cv::Point2f p = cv::Point2f(minEllipse[i].size.width/2-m_calibParams[idxCam].id_marker_position_offset);
        cv::Point2f image_coord = minEllipse[i].center + p;
        int prev_val = src_binary.at<uchar>(image_coord);
        int tooth_counter = 0;

        double step_size = M_PI * 2 / m_calibParams[idxCam].radial_step_amount;
        for(int j = 0; j < m_calibParams[idxCam].radial_step_amount; j++)
        {
            cv::Point2f newp;
            newp.x = (p.x*std::cos(step_size*j) - p.y*std::sin(step_size*j));
            newp.y = (p.x*std::sin(step_size*j) + p.y*std::cos(step_size*j));
            image_coord = minEllipse[i].center + newp;
            //cv::circle( camImg, image_coord, 2,cv::Scalar(255,255,255));

            //analyze this value to detect teeth
            uchar val = src_binary.at<uchar>(image_coord);
            if(abs(val - prev_val) == 255)
                tooth_counter++;
                prev_val = val;
        }

        if(tooth_counter>2){
            m_detectionResult[idxCam].amount_id_markers++;
            id_markers_index[std::ceil(tooth_counter/2.0)] = i;
            cv::circle( camImg, minEllipse[i].center, 20,cv::Scalar(255,0,0), 5);
            std::ostringstream oss;
            oss << std::ceil(tooth_counter/2.0);
            cv::putText(camImg, oss.str(), minEllipse[i].center-cv::Point2f(15,0), cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar(255, 255, 0), 3);
        }
        else
        {
            cv::ellipse( camImg, minEllipse[i], cv::Scalar(0,255,255), 2, 8 );
            all_markers_image.push_back(minEllipse[i].center);
        }
    }

    //find id markers
    for(std::map<int, int>::const_iterator it = id_markers_index.begin(); it != id_markers_index.end();it++)
    {
        id_markers_world.push_back(m_calibDescription.id_markers_pos[(*it).first]);
        id_markers_image.push_back(minEllipse[id_markers_index[(*it).first]].center);
        //std::cout << "id: " << (*it).first << " pos: " << (*it).second << std::endl;
    }
    m_detectionResult[idxCam].id_markers_world[0].swap(id_markers_world);
    m_detectionResult[idxCam].id_markers_image[0].swap(id_markers_image);
    m_detectionResult[idxCam].all_markers_image[0].swap(all_markers_image);

    return true;
}

bool CalibrationManager::MatchMarkers(const CalibrationDescription& desc, const cv::Mat& P, DetectionResult& detectionResult, int idxCam, cv::Mat& camImg)
{
    std::vector<cv::Point3f> ring_markers_world;
    std::vector<cv::Point2f> ring_markers_image;

    cv::flann::KDTreeIndexParams indexParams;
    cv::flann::Index kdtree(cv::Mat(detectionResult.all_markers_image[0]).reshape(1), indexParams);
    for(int i = 0; i < desc.calib_points.size(); i++)
    {
        cv::Mat cp(4,1,CV_32F);
        cp.at<float>(cv::Point2i(0,0)) = desc.calib_points[i].x;
        cp.at<float>(cv::Point2i(0,1)) = desc.calib_points[i].y;
        cp.at<float>(cv::Point2i(0,2)) = desc.calib_points[i].z;
        cp.at<float>(cv::Point2i(0,3)) = 1;

        cv::Mat projected = P*cp;
        projected /= projected.at<float>(2);
        cv::Point2f proj(projected.at<float>(0), projected.at<float>(1));

        cv::circle( camImg, proj, 3,cv::Scalar(0,0,255));
        std::ostringstream oss;
        oss << i;
        cv::putText(camImg, oss.str(), cv::Point2f(proj.x - 25, proj.y), cv::FONT_HERSHEY_SIMPLEX, .5, cv::Scalar(0, 255, 255));

        std::vector<float> query;
        query.push_back(proj.x); //Insert the 2D point we need to find neighbours to the query
        query.push_back(proj.y); //Insert the 2D point we need to find neighbours to the query
        std::vector<int> indices;
        std::vector<float> dists;
        bool result = (bool)kdtree.radiusSearch(query, indices, dists, m_calibParams[idxCam].marker_search_radius, 1);

        if(!result)
            continue;

        //item found
        ring_markers_world.push_back(desc.calib_points[i]);
        ring_markers_image.push_back(detectionResult.all_markers_image[0][indices[0]]);
    }

    m_detectionResult[idxCam].ring_markers_world[0].swap(ring_markers_world);
    m_detectionResult[idxCam].ring_markers_image[0].swap(ring_markers_image);

    return true;
}

DetectionResult& CalibrationManager::GetDetectionResult(const int idx_cam)
{
    return m_detectionResult[idx_cam];
}

CalibrationParameters& CalibrationManager::GetCalibrationParameters(int idxCam)
{
    return m_calibParams[idxCam];
}

CalibrationDescription& CalibrationManager::GetCalibrationDescription()
{
    return m_calibDescription;
}

cv::Mat CalibrationManager::Calculate2DConditioning(std::vector<cv::Point2f> in)const
{
    //translation x ve y lerin ortalamasi t
    cv::Scalar t = cv::mean(in);

    //transform olmus hallerinin abs li ortalamasi s
    for(int i = 0; i < in.size(); i++)
    {
        in[i].x = abs(in[i].x - t[0]);
        in[i].y = abs(in[i].y - t[1]);
    }

    cv::Scalar s = cv::mean(in);

    cv::Mat S = cv::Mat::eye(3,3, CV_32F);
    S.at<float>(cv::Point2i(0,0)) = 1.0/s[0];
    S.at<float>(cv::Point2i(1,1)) = 1.0/s[1];

    cv::Mat Tr = cv::Mat::eye(3,3, CV_32F);
    Tr.at<float>(cv::Point2i(2,0)) = -t[0];
    Tr.at<float>(cv::Point2i(2,1)) = -t[1];

    cv::Mat T;
    T = S*Tr;
    return T;
}

cv::Mat CalibrationManager::Calculate3DConditioning(std::vector<cv::Point3f> in)const
{
    //translation x ve y lerin ortalamasi t
    cv::Scalar t = cv::mean(in);

    //transform olmus hallerinin abs li ortalamasi s
    for(int i = 0; i < in.size(); i++)
    {
        in[i].x = abs(in[i].x - t[0]);
        in[i].y = abs(in[i].y - t[1]);
        in[i].z = abs(in[i].z - t[2]);
    }

    cv::Scalar s = cv::mean(in);

    cv::Mat S = cv::Mat::eye(4,4, CV_32F);
    if(s[0])S.at<float>(cv::Point2i(0,0)) = 1.0/s[0];
    if(s[1])S.at<float>(cv::Point2i(1,1)) = 1.0/s[1];
    if(s[2])S.at<float>(cv::Point2i(2,2)) = 1.0/s[2];

    cv::Mat Tr = cv::Mat::eye(4,4, CV_32F);
    Tr.at<float>(cv::Point2i(3,0)) = -t[0];
    Tr.at<float>(cv::Point2i(3,1)) = -t[1];
    Tr.at<float>(cv::Point2i(3,2)) = -t[2];

    cv::Mat T;
    T = S*Tr;
    return T;
}

cv::Mat CalibrationManager::DLT(const std::vector<cv::Point3f>& ptsObject, const std::vector<cv::Point2f>& ptsImage)const
{
    cv::Mat P = cv::Mat::zeros(3,4,CV_32F);

    if(!ptsObject.size() || !ptsImage.size())
        return P;

    //conditioning
    cv::Mat To = Calculate3DConditioning(ptsObject);
    cv::Mat Ti = Calculate2DConditioning(ptsImage);
    //std::cout <<"To: "<< To << "\n\n";
    //std::cout <<"Ti: "<< Ti << "\n\n";

    std::vector<cv::Mat> conObjPts;
    std::vector<cv::Mat> conImgPts;

    for(int i = 0; i < 6;i++)
    {
        //object points
        cv::Mat om(4,1,CV_32F);
        om.at<float>(cv::Point2i(0,0)) = ptsObject[i].x;
        om.at<float>(cv::Point2i(0,1)) = ptsObject[i].y;
        om.at<float>(cv::Point2i(0,2)) = ptsObject[i].z;
        om.at<float>(cv::Point2i(0,3)) = 1;
        conObjPts.push_back(To*om);
     }

    for(int i = 0; i < 6;i++)
    {
        //image points
        cv::Mat im(3,1,CV_32F);
        im.at<float>(cv::Point2i(0,0)) = ptsImage[i].x;
        im.at<float>(cv::Point2i(0,1)) = ptsImage[i].y;
        im.at<float>(cv::Point2i(0,2)) = 1;
        conImgPts.push_back(Ti*im);
    }

    //Direct Linear Transformation
    //Prepare design(A) matrix
    cv::Mat A(12, 12, CV_32F);
    for(int i = 0; i < conObjPts.size(); i++ )
    {
        A.at<float>(cv::Point2i(0,i*2)) = -conImgPts[i].at<float>(2)*conObjPts[i].at<float>(0);
        A.at<float>(cv::Point2i(1,i*2)) = -conImgPts[i].at<float>(2)*conObjPts[i].at<float>(1);
        A.at<float>(cv::Point2i(2,i*2)) = -conImgPts[i].at<float>(2)*conObjPts[i].at<float>(2);
        A.at<float>(cv::Point2i(3,i*2)) = -conImgPts[i].at<float>(2)*conObjPts[i].at<float>(3);
        A.at<float>(cv::Point2i(4,i*2)) = 0.0;
        A.at<float>(cv::Point2i(5,i*2)) = 0.0;
        A.at<float>(cv::Point2i(6,i*2)) = 0.0;
        A.at<float>(cv::Point2i(7,i*2)) = 0.0;
        A.at<float>(cv::Point2i(8,i*2)) = conImgPts[i].at<float>(0)*conObjPts[i].at<float>(0);
        A.at<float>(cv::Point2i(9,i*2)) = conImgPts[i].at<float>(0)*conObjPts[i].at<float>(1);
        A.at<float>(cv::Point2i(10,i*2)) = conImgPts[i].at<float>(0)*conObjPts[i].at<float>(2);
        A.at<float>(cv::Point2i(11,i*2)) = conImgPts[i].at<float>(0)*conObjPts[i].at<float>(3);

        A.at<float>(cv::Point2i(0,i*2+1)) = 0.0;
        A.at<float>(cv::Point2i(1,i*2+1)) = 0.0;
        A.at<float>(cv::Point2i(2,i*2+1)) = 0.0;
        A.at<float>(cv::Point2i(3,i*2+1)) = 0.0;
        A.at<float>(cv::Point2i(4,i*2+1)) = -conImgPts[i].at<float>(2)*conObjPts[i].at<float>(0);
        A.at<float>(cv::Point2i(5,i*2+1)) = -conImgPts[i].at<float>(2)*conObjPts[i].at<float>(1);
        A.at<float>(cv::Point2i(6,i*2+1)) = -conImgPts[i].at<float>(2)*conObjPts[i].at<float>(2);
        A.at<float>(cv::Point2i(7,i*2+1)) = -conImgPts[i].at<float>(2)*conObjPts[i].at<float>(3);
        A.at<float>(cv::Point2i(8,i*2+1)) = conImgPts[i].at<float>(1)*conObjPts[i].at<float>(0);
        A.at<float>(cv::Point2i(9,i*2+1)) = conImgPts[i].at<float>(1)*conObjPts[i].at<float>(1);
        A.at<float>(cv::Point2i(10,i*2+1)) = conImgPts[i].at<float>(1)*conObjPts[i].at<float>(2);
        A.at<float>(cv::Point2i(11,i*2+1)) = conImgPts[i].at<float>(1)*conObjPts[i].at<float>(3);
    }

    //std::cout << A << std::endl;

    //prepare parameter space
    cv::Mat p(12,1,CV_32F);

    //Solve for 12 parameters
    cv::SVD::solveZ(A, p);

    //Reshape P
    P.at<float>(cv::Point2i(0,0)) = p.at<float>(0);
    P.at<float>(cv::Point2i(1,0)) = p.at<float>(1);
    P.at<float>(cv::Point2i(2,0)) = p.at<float>(2);
    P.at<float>(cv::Point2i(3,0)) = p.at<float>(3);
    P.at<float>(cv::Point2i(0,1)) = p.at<float>(4);
    P.at<float>(cv::Point2i(1,1)) = p.at<float>(5);
    P.at<float>(cv::Point2i(2,1)) = p.at<float>(6);
    P.at<float>(cv::Point2i(3,1)) = p.at<float>(7);
    P.at<float>(cv::Point2i(0,2)) = p.at<float>(8);
    P.at<float>(cv::Point2i(1,2)) = p.at<float>(9);
    P.at<float>(cv::Point2i(2,2)) = p.at<float>(10);
    P.at<float>(cv::Point2i(3,2)) = p.at<float>(11);

    //Reverse condition
    P = Ti.inv()*P*To;
    P = P/P.at<float>(2,3); //make homogenous
    //std::cout << "P " << P << "\n";

    return P;
}

bool CalibrationManager::IsReadyToGo() const
{
    if(m_detectionResult[0].amount_id_markers < 6 || m_detectionResult[1].amount_id_markers < 6 )
        return false;

    if(m_detectionResult[0].ring_markers_world.size() != m_detectionResult[0].ring_markers_image.size())
        return false;

    if(m_detectionResult[1].ring_markers_world.size() != m_detectionResult[1].ring_markers_image.size())
        return false;

    return true;
}

DetectionResult::DetectionResult()
{
    amount_points = 0;
    amount_id_markers = 0;
    img_size = cv::Size(0,0);
    id_markers_world.resize(1);
    id_markers_image.resize(1);
    ring_markers_world.resize(1);
    ring_markers_image.resize(1);
    all_markers_image.resize(1);
}

CalibrationResult& CalibrationManager::GetCalibrationResult()
{
    return m_stereoResult;
}

CalibrationDescription::CalibrationDescription(){
    amount_points = 0;
    amount_id_markers = 0;
}

void CalibrationDescription::ReadFromIni(const char* filename)
{
    //todo: add if file exist condition, this implementation is error prone

    amount_id_markers = 0;
    boost::property_tree::ptree pt;
    boost::property_tree::ini_parser::read_ini(filename, pt);

    int amount_points = pt.get<int>("CalibInfo.MarkCount");
    (*this).amount_points = amount_points;
    char buffer[32];
    typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
    boost::char_separator<char> sep(" ");

    for(int i = 0; i < amount_points; i++)
    {
        sprintf(buffer, "Marks.Mark_%.3i", i);
        std::string line = pt.get<std::string>(buffer);
        tokenizer tokens(line, sep);
        cv::Point3f calib_p;
        tokenizer::iterator tok_iter = tokens.begin();
        calib_p.x = ::atof(std::string(*tok_iter++).c_str());
        calib_p.y = ::atof(std::string(*tok_iter++).c_str());
        calib_p.z = ::atof(std::string(*tok_iter).c_str());

        sprintf(buffer, "Marks.Mark_%.3i_ID", i);
        boost::optional<int> id = pt.get_optional<int>(buffer);

        if(id.is_initialized())
        {
            amount_id_markers++;
            id_markers_pos[id.get()] = calib_p;
            continue;
        }

        calib_points.push_back(calib_p);
    }
}

CalibrationParameters::CalibrationParameters()
{
    binary_threshold = 30;
    kernel_size = 9;
    id_marker_position_offset = 3;
    radial_step_amount = 72;
    marker_search_radius = 500;
}


text:
/////////////////////////////////////////////////////////////
//                                                         //
// Copyright (c) 2003-2017 by The University of Queensland //
// Centre for Geoscience Computing                         //
// http://earth.uq.edu.au/centre-geoscience-computing      //
//                                                         //
// Primary Business: Brisbane, Queensland, Australia       //
// Licensed under the Open Software License version 3.0    //
// http://www.apache.org/licenses/LICENSE-2.0              //
//                                                         //
/////////////////////////////////////////////////////////////

#include <boost/version.hpp>
#include <boost/python.hpp>
#include "Python/esys/lsm/RunnablePy.h"

namespace esys
{
  namespace lsm
  {
    void RunnablePy::run()
    {
      boost::python::override overrideMethod = this->get_override("run");
      if (overrideMethod)
      {
        overrideMethod();
      }
      else
      {
        defaultRun();
      }
    }

    void RunnablePy::defaultRun()
    {
      PyErr_SetString(
        PyExc_NotImplementedError,
        "run method needs to be implemented in derived class"
      );
      boost::python::throw_error_already_set();
    }

    void exportRunnable()
    {
      // Disable autogeneration of C++ signatures (Boost 1.34.0 and higher)
      // for Epydoc which stumbles over indentation in the automatically generated strings.
      boost::python::docstring_options no_autogen(true,false);

      boost::python::class_<
        RunnablePy,
        boost::noncopyable
      >(
        "Runnable",
        "Base class with overridable C{run} method, that is subclassed to implement user-defined subroutines called each timestep of a simulation.\n"
      )
      .def(
        "run",
        &Runnable::run,
        "Method called each timestep, overridden by subclasses of the Runnable base class.",
        &RunnablePy::defaultRun
      )
      ;
    }
  }
}

ext: cpp

max_stars_repo_name: danielfrascarelli/esys-particle

max_issues_repo_name: danielfrascarelli/esys-particle

max_forks_repo_name: danielfrascarelli/esys-particle


text:
/*
 * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.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 <iostream>
#include <fstream>
#include <boost/program_options.hpp>
#include <votca/csg/version.h>
#include "csg_stat_imc.h"
#include <stdlib.h>
#include <votca/csg/csgapplication.h>

//using namespace votca::tools;
using namespace std;
using namespace votca::csg;

class CsgStatApp
    : public CsgApplication
{
public:
    string ProgramName() { return "csg_stat"; }
    void HelpText(ostream &out);

    bool DoTrajectory() {return true;}
    bool DoMapping() {return true;}
    bool DoMappingDefault(void) { return false; }
    bool DoThreaded() {return true; }
    bool SynchronizeThreads() {return true;}
    void Initialize();
    bool EvaluateOptions();

    void BeginEvaluate(Topology *top, Topology *top_ref);
    void EndEvaluate();

    CsgApplication::Worker *ForkWorker() {
        return _imc.ForkWorker();
    }

    void MergeWorker(CsgApplication::Worker *worker) {
        _imc.MergeWorker(worker);
    }

public:
    Imc _imc;
    int _block_length;
    string _extension;
};

void CsgStatApp::HelpText(ostream &out)
{
    out << "Calculate all distributions (bonded and non-bonded) specified in options file.\n"
            "Optionally calculates update matrix for invere Monte Carlo. This program\n"
            "is called inside the inverse scripts. Unlike csg_boltzmann, big systems\n"
            "can be treated as well as non-bonded interactions can be evaluated.";
}

void CsgStatApp::Initialize()
{
    CsgApplication::Initialize();
    AddProgramOptions("Specific options")
            ("options", boost::program_options::value<string>(), "  options file for coarse graining")
            ("do-imc", "  write out additional Inverse Monte Carlo data")
            ("block-length", boost::program_options::value<int>(), "  write blocks of this length, the averages are cleared after every write")
            ("ext", boost::program_options::value<string>(&_extension)->default_value("dist.new"), "Extension of the output");
}

bool CsgStatApp::EvaluateOptions()
{
    CsgApplication::EvaluateOptions();
    CheckRequired("options");
    CheckRequired("trj", "no trajectory file specified");

    _imc.LoadOptions(OptionsMap()["options"].as<string>());

    if(OptionsMap().count("block-length")){
       _imc.BlockLength(OptionsMap()["block-length"].as<int>());
    } else {
      _imc.BlockLength(0);
    }

    if(OptionsMap().count("do-imc"))
    _imc.DoImc(true);

    _imc.Extension(_extension);

    _imc.Initialize();
    return true;
}

void CsgStatApp::BeginEvaluate(Topology *top, Topology *top_ref)
{
    _imc.BeginEvaluate(top, top_ref);
}

void CsgStatApp::EndEvaluate()
{
    _imc.EndEvaluate();
}

int main(int argc, char** argv)
{
    CsgStatApp app;
    return app.Exec(argc, argv);
}

ext: cc


text:
//-----------------------------------------------------------------------------
// Copyright (c) 2015-2018 Benjamin Buch
//
// https://github.com/bebuch/disposer
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
//-----------------------------------------------------------------------------
#ifndef _disposer__core__exec_output__hpp_INCLUDED_
#define _disposer__core__exec_output__hpp_INCLUDED_

#include "exec_output_base.hpp"
#include "output_map_type.hpp"
#include "output.hpp"

#include "../tool/input_data.hpp"
#include "../tool/to_std_string_view.hpp"

#include <io_tools/make_string.hpp>

#include <logsys/log_base.hpp>

#include <boost/hana/tuple.hpp>

#include <functional>
#include <variant>

namespace disposer{

	/// \brief The output type while exec
	template < typename T >
	class unnamed_exec_output
		: public exec_output_base
		, public logsys::log_base{
	public:
		/// \brief The actual type
		using type = T;

		/// \brief Constructor
		unnamed_exec_output(
			std::size_t const id,
			std::string&& log_prefix,
			std::string_view name,
			std::size_t use_count
		)noexcept
			: exec_output_base(use_count)
			, logsys::log_base(io_tools::make_string("id(", id, ") ",
				std::move(log_prefix), "output(", name, ") ")) {}

		/// \brief Add given data to \ref data_
		template < typename ... Args >
		void emplace(Args&& ... args){
			data_.emplace_back(static_cast< Args&& >(args) ...);
		}

		/// \brief Add given data to \ref data_
		template < typename Arg >
		void push(Arg&& value){
			data_.push_back(static_cast< Arg&& >(value));
		}

		/// \brief Get a view to the data
		input_data_r< T > references()const{
			return data_;
		}

		/// \brief Get a reference to the data
		input_data_v< T > values()const{
			if(is_last_use()){
				return std::move(data_);
			}else{
				return data_;
			}
		}

		/// \brief Remove data on last cleanup call
		void cleanup()noexcept{
			if(is_cleanup()){
				log(
					[](logsys::stdlogb& os){
						os << "cleanup";
					},
					[this]{
						data_.clear();
					});
			}
		}

	private:
		/// \brief Putted data of the output
		std::vector< T > data_;
	};

	template < typename Name, typename T >
	struct exec_output_init_data{
		exec_output_init_data(
			disposer::output< Name, T >& output,
			output_map_type& output_map,
			std::size_t const id,
			std::string&& module_log_prefix
		)noexcept
			: output(output)
			, output_map(output_map)
			, id(id)
			, module_log_prefix(std::move(module_log_prefix)) {}

		disposer::output< Name, T >& output;
		output_map_type& output_map;
		std::size_t id;
		std::string module_log_prefix;
	};

	/// \brief The output type while exec
	template < typename Name, typename T >
	class exec_output: public unnamed_exec_output< T >{
	public:
		/// \brief Constructor
		exec_output(exec_output_init_data< Name, T >&& data)noexcept
			: unnamed_exec_output< T >(
				std::move(data.id),
				std::move(data.module_log_prefix),
				detail::to_std_string_view(name),
				data.output.use_count()
			)
		{
			data.output_map.emplace(&data.output, this);
		}

		/// \brief Compile time name of the output
		using name_type = Name;

		/// \brief Name object
		static constexpr auto name = name_type{};

		using unnamed_exec_output< T >::unnamed_exec_output;
	};

}

#endif

ext: hpp

max_stars_repo_name: bebuch/disposer

max_issues_repo_name: bebuch/disposer

max_forks_repo_name: bebuch/disposer


text:
#include "material.hpp"

#include <OgreMaterialManager.h>
#include <OgreTechnique.h>
#include <OgrePass.h>

#include <boost/functional/hash.hpp>

#if TERRAIN_USE_SHADER
#include <extern/shiny/Main/Factory.hpp>
#endif

namespace
{

int getBlendmapIndexForLayer (int layerIndex)
{
    return std::floor((layerIndex-1)/4.f);
}

std::string getBlendmapComponentForLayer (int layerIndex)
{
    int n = (layerIndex-1)%4;
    if (n == 0)
        return "x";
    if (n == 1)
        return "y";
    if (n == 2)
        return "z";
    else
        return "w";
}

}

namespace Terrain
{

    MaterialGenerator::MaterialGenerator()
        : mShaders(true)
        , mShadows(false)
        , mSplitShadows(false)
        , mNormalMapping(true)
        , mParallaxMapping(true)
    {

    }

    Ogre::MaterialPtr MaterialGenerator::generate()
    {
        assert(!mLayerList.empty() && "Can't create material with no layers");

        return create(false, false);
    }

    Ogre::MaterialPtr MaterialGenerator::generateForCompositeMapRTT()
    {
        assert(!mLayerList.empty() && "Can't create material with no layers");

        return create(true, false);
    }

    Ogre::MaterialPtr MaterialGenerator::generateForCompositeMap()
    {
        return create(false, true);
    }

    Ogre::MaterialPtr MaterialGenerator::create(bool renderCompositeMap, bool displayCompositeMap)
    {
        assert(!renderCompositeMap || !displayCompositeMap);

        static int count = 0;
        std::stringstream name;
        name << "terrain/mat" << count++;

        if (!mShaders)
        {
            Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().create(name.str(),
                                                               Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
            Ogre::Technique* technique = mat->getTechnique(0);
            technique->removeAllPasses();

            if (displayCompositeMap)
            {
                Ogre::Pass* pass = technique->createPass();
                pass->setVertexColourTracking(Ogre::TVC_AMBIENT|Ogre::TVC_DIFFUSE);
                pass->createTextureUnitState(mCompositeMap)->setTextureAddressingMode(Ogre::TextureUnitState::TAM_CLAMP);
            }
            else
            {
                assert(mLayerList.size() == mBlendmapList.size()+1);
                std::vector<Ogre::TexturePtr>::iterator blend = mBlendmapList.begin();
                for (std::vector<LayerInfo>::iterator layer = mLayerList.begin(); layer != mLayerList.end(); ++layer)
                {
                    Ogre::Pass* pass = technique->createPass();
                    pass->setLightingEnabled(false);
                    pass->setVertexColourTracking(Ogre::TVC_NONE);
                    // TODO: How to handle fog?
                    pass->setFog(true, Ogre::FOG_NONE);

                    bool first = (layer == mLayerList.begin());

                    Ogre::TextureUnitState* tus;

                    if (!first)
                    {
                        pass->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);
                        pass->setDepthFunction(Ogre::CMPF_EQUAL);

                        tus = pass->createTextureUnitState((*blend)->getName());
                        tus->setAlphaOperation(Ogre::LBX_BLEND_TEXTURE_ALPHA,
                                               Ogre::LBS_TEXTURE,
                                               Ogre::LBS_TEXTURE);
                        tus->setColourOperationEx(Ogre::LBX_BLEND_DIFFUSE_ALPHA,
                                                  Ogre::LBS_TEXTURE,
                                                  Ogre::LBS_TEXTURE);
                        tus->setIsAlpha(true);
                        tus->setTextureAddressingMode(Ogre::TextureUnitState::TAM_CLAMP);

                        float scale = (16/(16.f+1.f));
                        tus->setTextureScale(1.f/scale,1.f/scale);
                    }

                    // Add the actual layer texture on top of the alpha map.
                    tus = pass->createTextureUnitState(layer->mDiffuseMap);
                    if (!first)
                        tus->setColourOperationEx(Ogre::LBX_BLEND_DIFFUSE_ALPHA,
                                                  Ogre::LBS_TEXTURE,
                                                  Ogre::LBS_CURRENT);

                    tus->setTextureScale(1/16.f,1/16.f);

                    if (!first)
                        ++blend;
                }

                if (!renderCompositeMap)
                {
                    Ogre::Pass* lightingPass = technique->createPass();
                    lightingPass->setSceneBlending(Ogre::SBT_MODULATE);
                    lightingPass->setVertexColourTracking(Ogre::TVC_AMBIENT|Ogre::TVC_DIFFUSE);
                    lightingPass->setFog(true, Ogre::FOG_NONE);
                }
            }

            return mat;
        }
#if TERRAIN_USE_SHADER
        else
        {
            sh::MaterialInstance* material = sh::Factory::getInstance().createMaterialInstance (name.str());
            material->setProperty ("allow_fixed_function", sh::makeProperty<sh::BooleanValue>(new sh::BooleanValue(false)));

            if (displayCompositeMap)
            {
                sh::MaterialInstancePass* p = material->createPass ();

                p->setProperty ("vertex_program", sh::makeProperty<sh::StringValue>(new sh::StringValue("terrain_vertex")));
                p->setProperty ("fragment_program", sh::makeProperty<sh::StringValue>(new sh::StringValue("terrain_fragment")));
                p->mShaderProperties.setProperty ("is_first_pass", sh::makeProperty(new sh::BooleanValue(true)));
                p->mShaderProperties.setProperty ("render_composite_map", sh::makeProperty(new sh::BooleanValue(false)));
                p->mShaderProperties.setProperty ("display_composite_map", sh::makeProperty(new sh::BooleanValue(true)));
                p->mShaderProperties.setProperty ("num_layers", sh::makeProperty (new sh::StringValue("0")));
                p->mShaderProperties.setProperty ("num_blendmaps", sh::makeProperty (new sh::StringValue("0")));
                p->mShaderProperties.setProperty ("normal_map_enabled", sh::makeProperty (new sh::BooleanValue(false)));
                p->mShaderProperties.setProperty ("parallax_enabled", sh::makeProperty (new sh::BooleanValue(false)));
                p->mShaderProperties.setProperty ("normal_maps",
                                                  sh::makeProperty (new sh::IntValue(0)));

                sh::MaterialInstanceTextureUnit* tex = p->createTextureUnit ("compositeMap");
                tex->setProperty ("direct_texture", sh::makeProperty (new sh::StringValue(mCompositeMap)));
                tex->setProperty ("tex_address_mode", sh::makeProperty (new sh::StringValue("clamp")));

                // shadow. TODO: repeated, put in function
                if (mShadows)
                {
                    for (int i = 0; i < (mSplitShadows ? 3 : 1); ++i)
                    {
                        sh::MaterialInstanceTextureUnit* shadowTex = p->createTextureUnit ("shadowMap" + Ogre::StringConverter::toString(i));
                        shadowTex->setProperty ("content_type", sh::makeProperty<sh::StringValue> (new sh::StringValue("shadow")));
                    }
                }
                p->mShaderProperties.setProperty ("shadowtexture_offset", sh::makeProperty (new sh::StringValue(
                    Ogre::StringConverter::toString(1))));

                p->mShaderProperties.setProperty ("pass_index", sh::makeProperty(new sh::IntValue(0)));
            }
            else
            {

                bool shadows = mShadows && !renderCompositeMap;

                int layerOffset = 0;
                while (layerOffset < (int)mLayerList.size())
                {
                    int blendmapOffset = (layerOffset == 0) ? 1 : 0; // the first layer of the first pass is the base layer and does not need a blend map

                    // Check how many layers we can fit in this pass
                    int numLayersInThisPass = 0;
                    int numBlendTextures = 0;
                    std::vector<std::string> blendTextures;
                    int remainingTextureUnits = OGRE_MAX_TEXTURE_LAYERS;
                    if (shadows)
                        remainingTextureUnits -= (mSplitShadows ? 3 : 1);
                    while (remainingTextureUnits && layerOffset + numLayersInThisPass < (int)mLayerList.size())
                    {
                        int layerIndex = numLayersInThisPass + layerOffset;

                        int neededTextureUnits=0;
                        int neededBlendTextures=0;

                        if (layerIndex != 0)
                        {
                            std::string blendTextureName = mBlendmapList[getBlendmapIndexForLayer(layerIndex)]->getName();
                            if (std::find(blendTextures.begin(), blendTextures.end(), blendTextureName) == blendTextures.end())
                            {
                                blendTextures.push_back(blendTextureName);
                                ++neededBlendTextures;
                                ++neededTextureUnits; // blend texture
                            }
                        }
                        ++neededTextureUnits; // layer texture

                        // Check if this layer has a normal map
                        if (mNormalMapping && !mLayerList[layerIndex].mNormalMap.empty() && !renderCompositeMap)
                            ++neededTextureUnits; // normal map
                        if (neededTextureUnits <= remainingTextureUnits)
                        {
                            // We can fit another!
                            remainingTextureUnits -= neededTextureUnits;
                            numBlendTextures += neededBlendTextures;
                            ++numLayersInThisPass;
                        }
                        else
                            break; // We're full
                    }

                    sh::MaterialInstancePass* p = material->createPass ();
                    p->setProperty ("vertex_program", sh::makeProperty<sh::StringValue>(new sh::StringValue("terrain_vertex")));
                    p->setProperty ("fragment_program", sh::makeProperty<sh::StringValue>(new sh::StringValue("terrain_fragment")));
                    if (layerOffset != 0)
                    {
                        p->setProperty ("scene_blend", sh::makeProperty(new sh::StringValue("alpha_blend")));
                        // Only write if depth is equal to the depth value written by the previous pass.
                        p->setProperty ("depth_func", sh::makeProperty(new sh::StringValue("equal")));
                    }

                    p->mShaderProperties.setProperty ("render_composite_map", sh::makeProperty(new sh::BooleanValue(renderCompositeMap)));
                    p->mShaderProperties.setProperty ("display_composite_map", sh::makeProperty(new sh::BooleanValue(displayCompositeMap)));

                    p->mShaderProperties.setProperty ("num_layers", sh::makeProperty (new sh::StringValue(Ogre::StringConverter::toString(numLayersInThisPass))));
                    p->mShaderProperties.setProperty ("num_blendmaps", sh::makeProperty (new sh::StringValue(Ogre::StringConverter::toString(numBlendTextures))));
                    p->mShaderProperties.setProperty ("normal_map_enabled",
                                                      sh::makeProperty (new sh::BooleanValue(false)));

                    // blend maps
                    // the index of the first blend map used in this pass
                    int blendmapStart;
                    if (mLayerList.size() == 1) // special case. if there's only one layer, we don't need blend maps at all
                        blendmapStart = 0;
                    else
                        blendmapStart = getBlendmapIndexForLayer(layerOffset+blendmapOffset);
                    for (int i = 0; i < numBlendTextures; ++i)
                    {
                        sh::MaterialInstanceTextureUnit* blendTex = p->createTextureUnit ("blendMap" + Ogre::StringConverter::toString(i));
                        blendTex->setProperty ("direct_texture", sh::makeProperty (new sh::StringValue(mBlendmapList[blendmapStart+i]->getName())));
                        blendTex->setProperty ("tex_address_mode", sh::makeProperty (new sh::StringValue("clamp")));
                    }

                    // layer maps
                    bool anyNormalMaps = false;
                    bool anyParallax = false;
                    size_t normalMaps = 0;
                    for (int i = 0; i < numLayersInThisPass; ++i)
                    {
                        const LayerInfo& layer = mLayerList[layerOffset+i];
                        // diffuse map
                        sh::MaterialInstanceTextureUnit* diffuseTex = p->createTextureUnit ("diffuseMap" + Ogre::StringConverter::toString(i));
                        diffuseTex->setProperty ("direct_texture", sh::makeProperty (new sh::StringValue(layer.mDiffuseMap)));

                        // normal map (optional)
                        bool useNormalMap = mNormalMapping && !mLayerList[layerOffset+i].mNormalMap.empty() && !renderCompositeMap;
                        bool useParallax = useNormalMap && mParallaxMapping && layer.mParallax;
                        bool useSpecular = layer.mSpecular;
                        if (useNormalMap)
                        {
                            anyNormalMaps = true;
                            anyParallax = anyParallax || useParallax;
                            sh::MaterialInstanceTextureUnit* normalTex = p->createTextureUnit ("normalMap" + Ogre::StringConverter::toString(i));
                            normalTex->setProperty ("direct_texture", sh::makeProperty (new sh::StringValue(layer.mNormalMap)));
                        }
                        p->mShaderProperties.setProperty ("use_normal_map_" + Ogre::StringConverter::toString(i),
                                                          sh::makeProperty (new sh::BooleanValue(useNormalMap)));
                        p->mShaderProperties.setProperty ("use_parallax_" + Ogre::StringConverter::toString(i),
                                                          sh::makeProperty (new sh::BooleanValue(useParallax)));
                        p->mShaderProperties.setProperty ("use_specular_" + Ogre::StringConverter::toString(i),
                                                          sh::makeProperty (new sh::BooleanValue(useSpecular)));
                        boost::hash_combine(normalMaps, useNormalMap);
                        boost::hash_combine(normalMaps, useNormalMap && layer.mParallax);
                        boost::hash_combine(normalMaps, useSpecular);

                        if (i+layerOffset > 0)
                        {
                            int blendTextureIndex = getBlendmapIndexForLayer(layerOffset+i);
                            std::string blendTextureComponent = getBlendmapComponentForLayer(layerOffset+i);
                            p->mShaderProperties.setProperty ("blendmap_component_" + Ogre::StringConverter::toString(i),
                                                              sh::makeProperty (new sh::StringValue(Ogre::StringConverter::toString(blendTextureIndex-blendmapStart) + "." + blendTextureComponent)));
                        }
                        else
                        {
                            // just to make it shut up about blendmap_component_0 not existing in the first pass.
                            // it might be retrieved, but will never survive the preprocessing step.
                            p->mShaderProperties.setProperty ("blendmap_component_" + Ogre::StringConverter::toString(i),
                                sh::makeProperty (new sh::StringValue("")));
                        }
                    }
                    p->mShaderProperties.setProperty ("normal_map_enabled",
                                                      sh::makeProperty (new sh::BooleanValue(anyNormalMaps)));
                    p->mShaderProperties.setProperty ("parallax_enabled",
                                                      sh::makeProperty (new sh::BooleanValue(anyParallax)));
                    // Since the permutation handler can't handle dynamic property names,
                    // combine normal map settings for all layers into one value
                    p->mShaderProperties.setProperty ("normal_maps",
                                                      sh::makeProperty (new sh::IntValue(normalMaps)));

                    // shadow
                    if (shadows)
                    {
                        for (int i = 0; i < (mSplitShadows ? 3 : 1); ++i)
                        {
                            sh::MaterialInstanceTextureUnit* shadowTex = p->createTextureUnit ("shadowMap" + Ogre::StringConverter::toString(i));
                            shadowTex->setProperty ("content_type", sh::makeProperty<sh::StringValue> (new sh::StringValue("shadow")));
                        }
                    }
                    p->mShaderProperties.setProperty ("shadowtexture_offset", sh::makeProperty (new sh::StringValue(
                        Ogre::StringConverter::toString(numBlendTextures + numLayersInThisPass))));

                    // Make sure the pass index is fed to the permutation handler, because blendmap components may be different
                    p->mShaderProperties.setProperty ("pass_index", sh::makeProperty(new sh::IntValue(layerOffset)));

                    assert ((int)p->mTexUnits.size() == OGRE_MAX_TEXTURE_LAYERS - remainingTextureUnits);

                    layerOffset += numLayersInThisPass;
                }
            }
        }
#endif
        return Ogre::MaterialManager::getSingleton().getByName(name.str());
    }

}

max_stars_repo_name: Bodillium/openmw

max_issues_repo_name: Bodillium/openmw

max_forks_repo_name: Bodillium/openmw


text:
/**
 * @file llfasttimer.cpp
 * @brief Implementation of the fast timer.
 *
 * $LicenseInfo:firstyear=2004&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */
#include "linden_common.h"

#include "llfasttimer.h"

#include "llmemory.h"
#include "llprocessor.h"
#include "llsingleton.h"
#include "lltreeiterators.h"
#include "llsdserialize.h"
#include "llunits.h"
#include "llsd.h"
#include "lltracerecording.h"
#include "lltracethreadrecorder.h"

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

#if LL_WINDOWS
#include "lltimer.h"
#elif LL_LINUX || LL_SOLARIS
#include <sys/time.h>
#include <sched.h>
#include "lltimer.h"
#elif LL_DARWIN
#include <sys/time.h>
#include "lltimer.h"	// get_clock_count()
#include <mach/mach_time.h>
#else
#error "architecture not supported"
#endif

namespace LLTrace
{

//////////////////////////////////////////////////////////////////////////////
// statics

bool        BlockTimer::sLog		     = false;
std::string BlockTimer::sLogName         = "";
bool        BlockTimer::sMetricLog       = false;

#ifdef LL_DARWIN
//AO: Added ability to test this separately from other OS's
#define USE_RDTSC 0
#else
#endif
#if LL_LINUX || LL_SOLARIS || LL_DARWIN // AO: Add LL_DARWIN to this list now
U64         BlockTimer::sClockResolution = 1000000000; // Nanosecond resolution
#else
U64         BlockTimer::sClockResolution = 1000000; // Microsecond resolution
#endif

static LLMutex*			sLogLock = NULL;
static std::queue<LLSD> sLogQueue;

block_timer_tree_df_iterator_t begin_block_timer_tree_df(BlockTimerStatHandle& id)
{
	return block_timer_tree_df_iterator_t(&id,
		boost::bind(boost::mem_fn(&BlockTimerStatHandle::beginChildren), _1),
		boost::bind(boost::mem_fn(&BlockTimerStatHandle::endChildren), _1));
}

block_timer_tree_df_iterator_t end_block_timer_tree_df()
{
	return block_timer_tree_df_iterator_t();
}

block_timer_tree_df_post_iterator_t begin_block_timer_tree_df_post(BlockTimerStatHandle& id)
{
	return block_timer_tree_df_post_iterator_t(&id,
							boost::bind(boost::mem_fn(&BlockTimerStatHandle::beginChildren), _1),
							boost::bind(boost::mem_fn(&BlockTimerStatHandle::endChildren), _1));
}

block_timer_tree_df_post_iterator_t end_block_timer_tree_df_post()
{
	return block_timer_tree_df_post_iterator_t();
}

block_timer_tree_bf_iterator_t begin_block_timer_tree_bf(BlockTimerStatHandle& id)
{
	return block_timer_tree_bf_iterator_t(&id,
		boost::bind(boost::mem_fn(&BlockTimerStatHandle::beginChildren), _1),
		boost::bind(boost::mem_fn(&BlockTimerStatHandle::endChildren), _1));
}

block_timer_tree_bf_iterator_t end_block_timer_tree_bf()
	{
	return block_timer_tree_bf_iterator_t();
	}

block_timer_tree_df_iterator_t begin_timer_tree(BlockTimerStatHandle& id)
	{
	return block_timer_tree_df_iterator_t(&id,
		boost::bind(boost::mem_fn(&BlockTimerStatHandle::beginChildren), _1),
							boost::bind(boost::mem_fn(&BlockTimerStatHandle::endChildren), _1));
	}

block_timer_tree_df_iterator_t end_timer_tree()
	{
	return block_timer_tree_df_iterator_t();
}

// sort child timers by name
struct SortTimerByName
	{
	bool operator()(const BlockTimerStatHandle* i1, const BlockTimerStatHandle* i2)
		{
		return i1->getName() < i2->getName();
		}
};

static BlockTimerStatHandle sRootTimer("root", NULL);
BlockTimerStatHandle& BlockTimer::getRootTimeBlock()
{
	return sRootTimer;
	}

void BlockTimer::pushLog(LLSD log)
{
	LLMutexLock lock(sLogLock);

	sLogQueue.push(log);
}

void BlockTimer::setLogLock(LLMutex* lock)
{
	sLogLock = lock;
}

//static
#if (LL_DARWIN || LL_LINUX || LL_SOLARIS) && !(defined(__i386__) || defined(__amd64__))
U64 BlockTimer::countsPerSecond()
{
	return sClockResolution;
}
#else // windows or x86-mac or x86-linux or x86-solaris
U64 BlockTimer::countsPerSecond()
{
#if LL_FASTTIMER_USE_RDTSC || !LL_WINDOWS
	//getCPUFrequency returns MHz and sCPUClockFrequency wants to be in Hz
	static LLUnit<U64, LLUnits::Hertz> sCPUClockFrequency = LLProcessorInfo().getCPUFrequency();
	return sCPUClockFrequency.value();
#else
	// If we're not using RDTSC, each fasttimer tick is just a performance counter tick.
	// Not redefining the clock frequency itself (in llprocessor.cpp/calculate_cpu_frequency())
	// since that would change displayed MHz stats for CPUs
	static bool firstcall = true;
	static U64 sCPUClockFrequency;
	if (firstcall)
	{
		QueryPerformanceFrequency((LARGE_INTEGER*)&sCPUClockFrequency);
		firstcall = false;
	}
	return sCPUClockFrequency.value();
#endif
}
#endif

BlockTimerStatHandle::BlockTimerStatHandle(const char* name, const char* description)
:	StatType<TimeBlockAccumulator>(name, description)
{}

TimeBlockTreeNode& BlockTimerStatHandle::getTreeNode() const
{
	TimeBlockTreeNode* nodep = LLTrace::get_thread_recorder()->getTimeBlockTreeNode(getIndex());
	llassert(nodep);
	return *nodep;
}

void BlockTimer::bootstrapTimerTree()
{
	for (auto& base : BlockTimerStatHandle::instance_snapshot())
	{
		// because of indirect derivation from LLInstanceTracker, have to downcast
		BlockTimerStatHandle& timer = static_cast<BlockTimerStatHandle&>(base);
		if (&timer == &BlockTimer::getRootTimeBlock()) continue;

		// bootstrap tree construction by attaching to last timer to be on stack
		// when this timer was called
		if (timer.getParent() == &BlockTimer::getRootTimeBlock())
		{
			TimeBlockAccumulator& accumulator = timer.getCurrentAccumulator();

			if (accumulator.mLastCaller)
			{
				timer.setParent(accumulator.mLastCaller);
				accumulator.mParent = accumulator.mLastCaller;
			}
			// no need to push up tree on first use, flag can be set spuriously
			accumulator.mMoveUpTree = false;
		}
	}
}

// bump timers up tree if they have been flagged as being in the wrong place
// do this in a bottom up order to promote descendants first before promoting ancestors
// this preserves partial order derived from current frame's observations
void BlockTimer::incrementalUpdateTimerTree()
{
	for(block_timer_tree_df_post_iterator_t it = begin_block_timer_tree_df_post(BlockTimer::getRootTimeBlock());
		it != end_block_timer_tree_df_post();
		++it)
	{
		BlockTimerStatHandle* timerp = *it;

		// sort timers by time last called, so call graph makes sense
		TimeBlockTreeNode& tree_node = timerp->getTreeNode();
		if (tree_node.mNeedsSorting)
{
			std::sort(tree_node.mChildren.begin(), tree_node.mChildren.end(), SortTimerByName());
}

		// skip root timer
		if (timerp != &BlockTimer::getRootTimeBlock())
{
			TimeBlockAccumulator& accumulator = timerp->getCurrentAccumulator();

			if (accumulator.mMoveUpTree)
{
				// since ancestors have already been visited, re-parenting won't affect tree traversal
			//step up tree, bringing our descendants with us
			LL_DEBUGS("FastTimers") << "Moving " << timerp->getName() << " from child of " << timerp->getParent()->getName() <<
				" to child of " << timerp->getParent()->getParent()->getName() << LL_ENDL;
			timerp->setParent(timerp->getParent()->getParent());
				accumulator.mParent = timerp->getParent();
				accumulator.mMoveUpTree = false;

			// don't bubble up any ancestors until descendants are done bubbling up
				// as ancestors may call this timer only on certain paths, so we want to resolve
				// child-most block locations before their parents
			it.skipAncestors();
		}
	}
	}
}

void BlockTimer::updateTimes()
	{
	// walk up stack of active timers and accumulate current time while leaving timing structures active
	BlockTimerStackRecord* stack_record	= LLThreadLocalSingletonPointer<BlockTimerStackRecord>::getInstance();
	if (!stack_record) return;

	U64 cur_time = getCPUClockCount64();
	BlockTimer* cur_timer				= stack_record->mActiveTimer;
	TimeBlockAccumulator* accumulator	= &stack_record->mTimeBlock->getCurrentAccumulator();

	while(cur_timer
		&& cur_timer->mParentTimerData.mActiveTimer != cur_timer) // root defined by parent pointing to self
		{
		U64 cumulative_time_delta = cur_time - cur_timer->mStartTime;
		cur_timer->mStartTime = cur_time;

		accumulator->mTotalTimeCounter += cumulative_time_delta;
		accumulator->mSelfTimeCounter += cumulative_time_delta - stack_record->mChildTime;
		stack_record->mChildTime = 0;

		stack_record = &cur_timer->mParentTimerData;
		accumulator  = &stack_record->mTimeBlock->getCurrentAccumulator();
		cur_timer    = stack_record->mActiveTimer;

		stack_record->mChildTime += cumulative_time_delta;
	}
}

static LLTrace::BlockTimerStatHandle FTM_PROCESS_TIMES("Process FastTimer Times");

// not thread safe, so only call on main thread
//static
void BlockTimer::processTimes()
{
#if LL_TRACE_ENABLED
	LL_RECORD_BLOCK_TIME(FTM_PROCESS_TIMES);
	get_clock_count(); // good place to calculate clock frequency

	// set up initial tree
	bootstrapTimerTree();

	incrementalUpdateTimerTree();

	updateTimes();

	// reset for next frame
	for (auto& base : BlockTimerStatHandle::instance_snapshot())
	{
		// because of indirect derivation from LLInstanceTracker, have to downcast
		BlockTimerStatHandle& timer = static_cast<BlockTimerStatHandle&>(base);
		TimeBlockAccumulator& accumulator = timer.getCurrentAccumulator();

		accumulator.mLastCaller = NULL;
		accumulator.mMoveUpTree = false;
	}
#endif
}

std::vector<BlockTimerStatHandle*>::iterator BlockTimerStatHandle::beginChildren()
		{
	return getTreeNode().mChildren.begin();
		}

std::vector<BlockTimerStatHandle*>::iterator BlockTimerStatHandle::endChildren()
		{
	return getTreeNode().mChildren.end();
}

std::vector<BlockTimerStatHandle*>& BlockTimerStatHandle::getChildren()
{
	return getTreeNode().mChildren;
	}

bool BlockTimerStatHandle::hasChildren()
{
	return ! getTreeNode().mChildren.empty();
}

// static
void BlockTimer::logStats()
{
	// get ready for next frame
	if (sLog)
	{ //output current frame counts to performance log

		static S32 call_count = 0;
		if (call_count % 100 == 0)
		{
			LL_DEBUGS("FastTimers") << "countsPerSecond: " << countsPerSecond() << LL_ENDL;
			LL_DEBUGS("FastTimers") << "LLProcessorInfo().getCPUFrequency() " << LLProcessorInfo().getCPUFrequency() << LL_ENDL;
			LL_DEBUGS("FastTimers") << "getCPUClockCount32() " << getCPUClockCount32() << LL_ENDL;
			LL_DEBUGS("FastTimers") << "getCPUClockCount64() " << getCPUClockCount64() << LL_ENDL;
			LL_DEBUGS("FastTimers") << "elapsed sec " << ((F64)getCPUClockCount64() / (F64HertzImplicit)LLProcessorInfo().getCPUFrequency()) << LL_ENDL;
		}
		call_count++;

		F64Seconds total_time(0);
		LLSD sd;

		{
			for (auto& base : BlockTimerStatHandle::instance_snapshot())
			{
				// because of indirect derivation from LLInstanceTracker, have to downcast
				BlockTimerStatHandle& timer = static_cast<BlockTimerStatHandle&>(base);
				LLTrace::PeriodicRecording& frame_recording = LLTrace::get_frame_recording();
				sd[timer.getName()]["Time"] = (LLSD::Real) (frame_recording.getLastRecording().getSum(timer).value());
				sd[timer.getName()]["Calls"] = (LLSD::Integer) (frame_recording.getLastRecording().getSum(timer.callCount()));

				// computing total time here because getting the root timer's getCountHistory
				// doesn't work correctly on the first frame
				total_time += frame_recording.getLastRecording().getSum(timer);
			}
		}

		sd["Total"]["Time"] = (LLSD::Real) total_time.value();
		sd["Total"]["Calls"] = (LLSD::Integer) 1;

		{
			LLMutexLock lock(sLogLock);
			sLogQueue.push(sd);
		}
	}

}

//static
void BlockTimer::dumpCurTimes()
{
	LLTrace::PeriodicRecording& frame_recording = LLTrace::get_frame_recording();
	LLTrace::Recording& last_frame_recording = frame_recording.getLastRecording();

	// walk over timers in depth order and output timings
	for(block_timer_tree_df_iterator_t it = begin_timer_tree(BlockTimer::getRootTimeBlock());
		it != end_timer_tree();
		++it)
	{
		BlockTimerStatHandle* timerp = (*it);
		F64Seconds total_time = last_frame_recording.getSum(*timerp);
		U32 num_calls = last_frame_recording.getSum(timerp->callCount());

		// Don't bother with really brief times, keep output concise
		if (total_time < F32Milliseconds(0.1f)) continue;

		std::ostringstream out_str;
		BlockTimerStatHandle* parent_timerp = timerp;
		while(parent_timerp && parent_timerp != parent_timerp->getParent())
		{
			out_str << "\t";
			parent_timerp = parent_timerp->getParent();
		}

		out_str << timerp->getName() << " "
			<< std::setprecision(3) << total_time.valueInUnits<LLUnits::Milliseconds>() << " ms, "
			<< num_calls << " calls";

		LL_INFOS() << out_str.str() << LL_ENDL;
}
}

//static
void BlockTimer::writeLog(std::ostream& os)
{
	while (!sLogQueue.empty())
	{
		LLSD& sd = sLogQueue.front();
		LLSDSerialize::toXML(sd, os);
		LLMutexLock lock(sLogLock);
		sLogQueue.pop();
	}
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// TimeBlockAccumulator
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

TimeBlockAccumulator::TimeBlockAccumulator()
:	mTotalTimeCounter(0),
	mSelfTimeCounter(0),
	mCalls(0),
	mLastCaller(NULL),
	mActiveCount(0),
	mMoveUpTree(false),
	mParent(NULL)
{}

void TimeBlockAccumulator::addSamples( const TimeBlockAccumulator& other, EBufferAppendType append_type )
{
#if LL_TRACE_ENABLED
	// we can't merge two unrelated time block samples, as that will screw with the nested timings
	// due to the call hierarchy of each thread
	llassert(append_type == SEQUENTIAL);
	mTotalTimeCounter += other.mTotalTimeCounter;
	mSelfTimeCounter += other.mSelfTimeCounter;
	mCalls += other.mCalls;
	mLastCaller = other.mLastCaller;
	mActiveCount = other.mActiveCount;
	mMoveUpTree = other.mMoveUpTree;
	mParent = other.mParent;
#endif
}

void TimeBlockAccumulator::reset( const TimeBlockAccumulator* other )
{
	mCalls = 0;
	mSelfTimeCounter = 0;
	mTotalTimeCounter = 0;

	if (other)
{
		mLastCaller = other->mLastCaller;
		mActiveCount = other->mActiveCount;
		mMoveUpTree = other->mMoveUpTree;
		mParent = other->mParent;
	}
}

F64Seconds BlockTimer::getElapsedTime()
{
	U64 total_time = getCPUClockCount64() - mStartTime;

	return F64Seconds((F64)total_time / (F64)BlockTimer::countsPerSecond());
}

} // namespace LLTrace

max_stars_repo_name: SaladDais/LLUDP-Encryption

max_issues_repo_name: SaladDais/LLUDP-Encryption

max_forks_repo_name: SaladDais/LLUDP-Encryption


text: #include <boost/spirit/include/qi_bool.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include <certificate_handler.hpp>
#include <boost/container/flat_map.hpp>
#include <sdbusplus/asio/object_server.hpp>
#include <iostream>
#include <stdio.h>

using namespace std::string_literals;
namespace monitor_hostname
{
    void install_certificate(std::shared_ptr<sdbusplus::asio::connection> conn, const std::string& certPath)
    {
        if(access(certPath.c_str(), F_OK) == 0)
        {
            conn->async_method_call(
                [certPath](boost::system::error_code ec) {
                    if (ec)
                    {
                        std::cerr << "Replace Certificate Fail.." << std::endl;
                        return;
                    }

                    std::cerr << "Replace Certificate Success, remove temporary certificate file.." << std::endl;
                    remove(certPath.c_str());
                },
                "xyz.openbmc_project.Certs.Manager.Server.Https",
                "/xyz/openbmc_project/certs/server/https/1",
                "xyz.openbmc_project.Certs.Replace", "Replace",
                certPath);
        }
        else
        {
            std::cerr << "install_certificate Fail..file not exist" << std::endl;
        }
    }

    std::string parseSubject(const std::string& subject)
    {
        std::size_t cnPos = subject.find("CN=");
        if (cnPos != std::string::npos)
        {
            std::string cn = subject.substr(cnPos);
            cnPos = cn.find(",");
            if (cnPos != std::string::npos)
            {
                cn = cn.substr(0, cnPos);
            }

            cnPos = cn.find("=");
            std::string cnValue = cn.substr(cnPos+1);

            return cnValue;
        }
        std::cerr << "Can't find CN in subject" << std::endl;
        return "";
    }

    void monitor_hostname_signal(std::shared_ptr<sdbusplus::asio::connection> conn)
    {
        static std::unique_ptr<sdbusplus::bus::match::match> hostnameSignalMonitor;

        auto param = "type='signal',interface='org.freedesktop.DBus.Properties',"s +
                     "member='PropertiesChanged',"s +
                     "path='/xyz/openbmc_project/network/config',"s +
                     "arg0='xyz.openbmc_project.Network.SystemConfiguration'"s;

        hostnameSignalMonitor = std::make_unique<sdbusplus::bus::match::match>(
            *conn, param,
            [conn](sdbusplus::message::message& message) {
                // Callback when dbus signal occurs
                try
                {
                    std::string iface;
                    boost::container::flat_map<std::string, std::variant<std::string>>
                        changed_properties;
                    std::string hostname;

                    message.read(iface, changed_properties);

                    auto it = changed_properties.find("HostName");
                    if (it != changed_properties.end())
                    {
                        hostname = std::get<std::string>(it->second);
                        std::cerr << "Read hostname from signal: "<< hostname << std::endl;

                        conn->async_method_call(
                        [hostname, conn](boost::system::error_code ec,
                        const std::variant<std::string>& currentCertSubject) {
                            if (ec)
                            {
                                return;
                            }
                            const std::string* subject = std::get_if<std::string>(&currentCertSubject);
                            if (subject == nullptr)
                            {
                                std::cerr << "Unable to read subject" << std::endl;
                                return;
                            }

                            std::string cnValue = parseSubject(*subject);
                            if(!cnValue.empty())
                            {
                                std::cerr << "Current HTTPs Certificate Subject: "<< cnValue << ", New HostName: " << hostname << std::endl;
                                if(cnValue != hostname)
                                {
                                    certificate::CertHandler certHandler;
                                    certHandler.generateSslCertificate(hostname);
                                    install_certificate(conn, certificate::tmpCertPath);
                                }
                            }
                        },
                        "xyz.openbmc_project.Certs.Manager.Server.Https",
                        "/xyz/openbmc_project/certs/server/https/1",
                        "org.freedesktop.DBus.Properties", "Get",
                        "xyz.openbmc_project.Certs.Certificate", "Subject");
                    }
                }
                catch (std::exception& e)
                {
                    std::cerr << "Unable to read hostname" << std::endl;
                    return;
                }
            });
    }
} // namespace monitor_hostname

int main(int argc, char* argv[])
{
    boost::asio::io_service io;
    std::shared_ptr<sdbusplus::asio::connection> conn;

    std::cerr << "Start Monitor hostname service..." << std::endl;

    conn = std::make_shared<sdbusplus::asio::connection>(io);
    monitor_hostname::monitor_hostname_signal(conn);

    io.run();
    return 0;
}

max_stars_repo_name: quanta-bmc/phosphor-monitor-hostname

max_issues_repo_name: quanta-bmc/phosphor-monitor-hostname

max_forks_repo_name: quanta-bmc/phosphor-monitor-hostname


text:
//
// Copyright (c) 2019 Vinnie Falco (vinnie.falco@gmail.com)
// Copyright (c) 2022 Alan de Freitas (alandefreitas@gmail.com)
//
// 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)
//
// Official repository: https://github.com/CPPAlliance/url
//

#ifndef BOOST_URL_IMPL_PARAMS_ENCODED_VIEW_HPP
#define BOOST_URL_IMPL_PARAMS_ENCODED_VIEW_HPP

#include <boost/url/detail/except.hpp>
#include <boost/url/detail/params_encoded_iterator_impl.hpp>
#include <boost/assert.hpp>

namespace boost {
namespace urls {

//------------------------------------------------

class params_encoded_view::iterator
{
    detail::params_encoded_iterator_impl impl_;

    friend class params_encoded_view;

    iterator(
        string_view s) noexcept
        : impl_(s)
    {
    }

    // end
    iterator(
        string_view s,
        std::size_t nparam,
        int) noexcept
        : impl_(s, nparam, 0)
    {
    }

    string_view
    encoded_key() const noexcept
    {
        return impl_.encoded_key();
    }

public:
    using value_type = query_param;
    using reference = query_param_view;
    using pointer = void const*;
    using difference_type = std::ptrdiff_t;
    using iterator_category =
        std::forward_iterator_tag;

    iterator() = default;

    iterator&
    operator++() noexcept
    {
        impl_.increment();
        return *this;
    }

    iterator
    operator++(int) noexcept
    {
        auto tmp = *this;
        ++*this;
        return tmp;
    }

    reference
    operator*() const
    {
        return impl_.dereference();
    }

    friend
    bool
    operator==(
        iterator const& a,
        iterator const& b) noexcept
    {
        return a.impl_.equal(b.impl_);
    }

    friend
    bool
    operator!=(
        iterator const& a,
        iterator const& b) noexcept
    {
        return !a.impl_.equal(b.impl_);
    }
};

//------------------------------------------------
//
// Members
//
//------------------------------------------------

inline
params_encoded_view::
params_encoded_view(
    string_view s,
    std::size_t n) noexcept
    : s_(s)
    , n_(n)
{
}

template<class Allocator>
params_view
params_encoded_view::
decoded(Allocator const& alloc) const
{
    return params_view(s_, n_, alloc);
}

//------------------------------------------------
//
// Capacity
//
//------------------------------------------------

inline
bool
params_encoded_view::
empty() const noexcept
{
    return n_ == 0;
}

inline
std::size_t
params_encoded_view::
size() const noexcept
{
    return n_;
}

//------------------------------------------------
//
// Lookup
//
//------------------------------------------------

inline
auto
params_encoded_view::
find(string_view key) const noexcept ->
    iterator
{
    return find(begin(), key);
}

inline
bool
params_encoded_view::
contains(string_view key) const noexcept
{
    return find(key) != end();
}

} // urls
} // boost

#endif

max_stars_repo_name: abitmore/url

max_issues_repo_name: abitmore/url

max_forks_repo_name: abitmore/url


text:
/*
 * Temp.cpp
 *
 *  Created on: 21 Mar 2016
 *      Author: arjun
 */
/*
#include "Backend/Engine/Inotifier/Watch.h"
#include <csignal>
#include <iostream>
#include <iomanip>
#include <fstream>

#include <boost/atomic.hpp>
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>
#include <tbb/concurrent_queue.h>

using namespace std;
tbb::atomic<bool> stop (false);
tbb::atomic<bool> running (false);

tbb::concurrent_queue< boost::filesystem::path > fileQueue;

const char* root= "/home/arjun/Workspace/OpenCV/Images/2015 Aerial Images/Originals/Outputs/Targets";

void signalHandler( int signum )
{
    cout << "Interrupt signal (" << signum << ") received.\n";
    // cleanup and close up stuff here
    // terminate program
    fstream dummy;
    stop = true;
    string directory(root);
    remove((directory+"/"+"dummy").c_str());
    dummy.open((directory+"/"+"dummy").c_str(),ios::out);
    dummy<<flush;

    dummy.close();
}

void consumer(tbb::concurrent_queue< boost::filesystem::path > fileQueue){
	while(!fileQueue.empty()){
		boost::filesystem::path filePath;
		fileQueue.try_pop(filePath);
		cout<<filePath.c_str()<<endl;
	}
	running = false;
}

void producer(){
	fileMonitor(root,stop,running,consumer,fileQueue);
}
int main(int argc , char* argv[]){
	signal(SIGINT, signalHandler);

	boost::thread producerThread(producer);

	producerThread.join();

	cout<<"Exiting main\nMay the OCR be with you.\n";

	return 0;
}*/


text:
#ifndef ALLOCGC_SYS_ALLOCATOR_HPP
#define ALLOCGC_SYS_ALLOCATOR_HPP

#include <cstddef>
#include <cstdint>
#include <cstdlib>

#include <sys/mman.h>

#include <boost/range/iterator_range.hpp>

#include <liballocgc/details/allocators/allocator_tag.hpp>
#include <liballocgc/details/logging.hpp>
#include <liballocgc/details/constants.hpp>
#include <liballocgc/gc_common.hpp>

namespace allocgc { namespace details { namespace allocators {

class sys_allocator
{
public:
    typedef byte* pointer_type;
    typedef stateless_alloc_tag alloc_tag;
    typedef boost::iterator_range<byte*> memory_range_type;

    static size_t align_size(size_t size)
    {
        return ((size + PAGE_SIZE - 1) / PAGE_SIZE) * PAGE_SIZE;
    }

    static byte* allocate(size_t size)
    {
        assert(size % PAGE_SIZE == 0);
        void* mem = mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
        if (mem == MAP_FAILED) {
            logging::warning() << "mmap failed: " << strerror(errno);
            assert(false);
        }
        return reinterpret_cast<byte*>(mem);
    }

    static void deallocate(byte* ptr, size_t size)
    {
        int ret = munmap(reinterpret_cast<void*>(ptr), size);
        if (ret == -1) {
            logging::error() << "munmap failed: " << strerror(errno);
        }
    }

    static size_t shrink()
    {
        return 0;
    }

    static memory_range_type memory_range()
    {
        return memory_range_type(nullptr, nullptr);
    }
};

}}}

#endif //ALLOCGC_SYS_ALLOCATOR_HPP

max_stars_repo_name: eucpp/allocgc

max_issues_repo_name: eucpp/allocgc

max_forks_repo_name: eucpp/allocgc


text:
#include <fstream>
#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/connect.hpp>
#include <boost/filesystem.hpp>
#include <boost/beast/core/error.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/exception/all.hpp>
#include <boost/program_options.hpp>
#include <regex>
#include <csignal>
#include "ClientData.h"
#include "WaitingAnimation.h"
#include "pwd.h"

namespace asio = boost::asio;
using asio::ip::tcp;
namespace beast = boost::beast;
namespace websocket = beast::websocket;

void parse_environment(ClientData &client_data) {
    Logger::debug("Parsing environment variables");

    struct passwd *pws;
    pws = getpwuid(getuid());
    if (pws == NULL) {
        throw std::runtime_error("Error get login name for client data!");
    }
    client_data.user_id = std::string(pws->pw_name);

    auto host = std::getenv("QUEUE_HOST");
    if (!host) {
        throw std::runtime_error("QUEUE_HOST not set!");
    }
    client_data.queue_host = std::string(host);
}

int main(int argc, char *argv[]) {
    asio::io_context io_context;
    websocket::stream<tcp::socket> queue_stream(io_context);

    try {
        ClientData client_data;

        parse_environment(client_data);

        WaitingAnimation wait_queue("Connecting to BuilderQueue");
        // Open a WebSocket stream to the queue
        tcp::resolver queue_resolver(io_context);
        asio::connect(queue_stream.next_layer(), queue_resolver.resolve({client_data.queue_host, "8080"}));
        queue_stream.handshake(client_data.queue_host + ":8080", "/");
        wait_queue.stop_success("Connected to queue: " + client_data.queue_host);

        // Request a build host from the queue
        WaitingAnimation wait_images("Requesting image list");

        Logger::debug("Writing image list request string");
        std::string request_string("image_list_request");
        queue_stream.write(asio::buffer(request_string));

        Logger::debug("Read image list string");
        std::string images_string;
        auto images_buffer = boost::asio::dynamic_buffer(images_string);
        queue_stream.read(images_buffer);

        wait_images.stop_success("Fetched");
        std::cout << images_string;

    } catch (const boost::exception &ex) {
        auto diagnostics = diagnostic_information(ex);
        Logger::error(std::string() + "Container Builder exception encountered: " + diagnostics);
    } catch (const std::exception &ex) {
        Logger::error(std::string() + "Container Builder exception encountered: " + ex.what());
    } catch (...) {
        Logger::error("Unknown exception caught!");
    }

    // Attempt to disconnect from builder and queue
    try {
        Logger::debug("Attempting normal close");
        queue_stream.close(websocket::close_code::normal);
    } catch (...) {
        Logger::debug("Failed to cleanly close the WebSockets");
    }

    return 0;
}

max_stars_repo_name: olcf/container-builder

max_issues_repo_name: olcf/container-builder

max_forks_repo_name: olcf/container-builder


text:
//Copyright (c) 2013 Singapore-MIT Alliance for Research and Technology
//Licensed under the terms of the MIT License, as described in the file:
//   license.txt   (http://opensource.org/licenses/MIT)

#include "XmlParseHelper.hpp"

#include <stdexcept>
#include <boost/lexical_cast.hpp>
#include <xercesc/dom/DOMNodeList.hpp>
#include <xercesc/dom/DOMNamedNodeMap.hpp>
#include <xercesc/util/XMLString.hpp>

#include "LangHelpers.hpp"
#include "logging/Log.hpp"

using namespace sim_mob;
using namespace xercesc;

namespace sim_mob
{

//Helper: turn a Xerces error message into a string.
std::string TranscodeString(const XMLCh *str)
{
    char *raw = XMLString::transcode(str);
    std::string res(raw);
    XMLString::release(&raw);
    return res;
}

//Helper: make sure we actually have an element
DOMElement* NodeToElement(DOMNode* node)
{
    DOMElement* res = dynamic_cast<DOMElement*>(node);

    if (node && !res)
    {
        std::stringstream msg;
        msg << "Failed to cast <" << TranscodeString(node->getLocalName())
            << "> from DOMNode to DOMElement";
        throw std::runtime_error(msg.str());
    }
    else if(!node)
    {
        std::stringstream msg;
        msg << "Null pointer encountered";
        throw std::runtime_error(msg.str());
    }

    return res;
}

//Helper: retrieve child elements without leaking memory
std::vector<DOMElement*> GetElementsByName(DOMElement* node, const std::string& key, bool required)
{
    XMLCh* keyX = XMLString::transcode(key.c_str());
    DOMNodeList* res = node->getElementsByTagName(keyX);
    XMLString::release(&keyX);

    if (res->getLength() == 0 && required)
    {
        std::stringstream msg;
        msg << "Mandatory configuration fields <" << key << "> not found.";
        throw std::runtime_error(msg.str());
    }

    std::vector<DOMElement*> resV;
    for (XMLSize_t i = 0; i < res->getLength(); i++)
    {
        try
        {
            resV.push_back(NodeToElement(res->item(i)));
        }
        catch (std::runtime_error &ex)
        {
            std::stringstream msg;
            msg << "Invalid <" << TranscodeString(node->getLocalName()) << "> element at position "
                << (i+1) << ". " << ex.what();
            throw std::runtime_error(msg.str());
        }
    }

    return resV;
}

//Helper: retrieve a single element; optionally required.
DOMElement* GetSingleElementByName(DOMElement* node, const std::string& key, bool required)
{
    XMLCh* keyX = XMLString::transcode(key.c_str());
    DOMNodeList* res = node->getElementsByTagName(keyX);
    XMLString::release(&keyX);

    //Check.
    if (res->getLength() > 1)
    {
        std::stringstream msg;
        msg << "Multiple occurrence of configuration field <" << key << "> found. Expected: single occurrence";
        throw std::runtime_error(msg.str());
    }
    else if (res->getLength() == 1)
    {
        try
        {
            return NodeToElement(res->item(0));
        }
        catch (std::runtime_error &ex)
        {
            std::stringstream msg;
            msg << "Invalid <" << TranscodeString(node->getLocalName()) << "> element at position 1. "
                << ex.what();
            throw std::runtime_error(msg.str());
        }
    }
    else if (required)
    {
        std::stringstream msg;
        msg << "Mandatory configuration field <" << key << "> not found.";
        throw std::runtime_error(msg.str());
    }

    return nullptr;
}

//Helper: retrieve an attribute
DOMAttr* GetNamedAttribute(DOMElement* node, const std::string& key, bool required)
{
    if (!node)
    {
        return nullptr;
    }

    XMLCh* keyX = XMLString::transcode(key.c_str());
    DOMNode* res = node->getAttributes()->getNamedItem(keyX);
    XMLString::release(&keyX);

    //Check.
    if (!res)
    {
        if (required)
        {
            std::stringstream msg;
            msg << "Mandatory attribute \"" << key << "\" in <" << TranscodeString(node->getLocalName())
                << "> not found.";
            throw std::runtime_error(msg.str());
        }
        else
        {
            return nullptr;
        }
    }

    DOMAttr* resAttr = dynamic_cast<DOMAttr*>(res);

    if (!resAttr)
    {
        std::stringstream msg;
        msg << "Failed to cast <" << TranscodeString(res->getLocalName())
            << "> from DOMNode to DOMAttr";
        throw std::runtime_error(msg.str());
    }

    return resAttr;
}

//Helper
const XMLCh* GetAttributeValue(const DOMAttr* attr)
{
    if (!attr)
    {
        return nullptr;
    }

    return attr->getNodeValue();
}

//Helper: Combined
const XMLCh* GetNamedAttributeValue(DOMElement* node, const std::string& key, bool required)
{
    return GetAttributeValue(GetNamedAttribute(node, key, required));
}

//Helper: boolean stuff
bool ParseBoolean(const XMLCh* srcX, bool* defValue)
{
    if (srcX)
    {
        std::string src = TranscodeString(srcX);
        std::transform(src.begin(), src.end(), src.begin(), ::tolower);
        if (src == "true" || src == "yes")
        {
            return true;
        }
        else if (src == "false" || src == "no")
        {
            return false;
        }

        std::stringstream msg;
        msg << "Invalid value \"" << src << "\". Expected: \"true\" or \"false\"";
        throw std::runtime_error(msg.str());
    }

    //Wasn't found.
    if (!defValue)
    {
        std::stringstream msg;
        msg << "No value provided for boolean attribute.";
        throw std::runtime_error(msg.str());
    }

    return *defValue;
}

int ParseInteger(const XMLCh* srcX, int* defValue)
{
    if (srcX)
    {
        int value = 0;
        std::string src = TranscodeString(srcX);

        try
        {
            value = boost::lexical_cast<int>(src);
        }
        catch (boost::bad_lexical_cast const&)
        {
            std::stringstream msg;
            msg << "Invalid value \"" << src << "\". Expected: Integer value";
            throw std::runtime_error(msg.str());
        }

        return value;
    }

    //Wasn't found.
    if (!defValue)
    {
        std::stringstream msg;
        msg << "No value provided for integer attribute.";
        throw std::runtime_error(msg.str());
    }

    return *defValue;
}

float ParseFloat(const XMLCh* srcX, float* defValue)
{
    if (srcX)
    {
        std::string src = TranscodeString(srcX);
        return boost::lexical_cast<float>(src);
    }

    //Wasn't found.
    if (!defValue)
    {
        std::stringstream msg;
        msg << "No value provided for float attribute.";
        throw std::runtime_error(msg.str());
    }

    return *defValue;
}

unsigned int ParseUnsignedInt(const XMLCh* srcX, unsigned int* defValue)
{
    if (srcX)
    {
        unsigned int value = 0;
        std::string src = TranscodeString(srcX);

        try
        {
            value = boost::lexical_cast<unsigned int>(src);
        }
        catch (boost::bad_lexical_cast const&)
        {
            std::stringstream msg;
            msg << "Invalid value \"" << src << "\". Expected: Unsigned integer value";
            throw std::runtime_error(msg.str());
        }

        return value;
    }

    //Wasn't found.
    if (!defValue)
    {
        std::stringstream msg;
        msg << "No value provided for unsigned int attribute.";
        throw std::runtime_error(msg.str());
    }

    return *defValue;
}

std::string ParseString(const XMLCh* srcX, std::string* defValue)
{
    if (srcX)
    {
        return TranscodeString(srcX);
    }

    //Wasn't found.
    if (!defValue)
    {
        std::stringstream msg;
        msg << "No value provided for string attribute.";
        throw std::runtime_error(msg.str());
    }

    return *defValue;
}

//Helper: amount+value for time granularity.
unsigned int GetValueInMs(double amount, std::string units, unsigned int* defValue)
{
    //Handle plural
    if (units == "second")
    {
        units = "seconds";
    }

    if (units == "minute")
    {
        units = "minutes";
    }

    //Detect errors
    if (units.empty() || (units != "minutes" && units != "seconds" && units != "ms"))
    {
        if (defValue)
        {
            return *defValue;
        }
        else
        {
            std::stringstream msg;
            msg << "Invalid units provided for granularity. Expected: \"seconds\" or \"minutes\" or \"ms\"";
            throw std::runtime_error(msg.str());
        }
    }

    //Reduce to ms
    if (units == "minutes")
    {
        amount *= 60 * 1000;
    }
    if (units == "seconds")
    {
        amount *= 1000;
    }

    //Check for overflow:
    unsigned int res = static_cast<unsigned int>(amount);

    if (static_cast<double>(res) != amount)
    {
        Warn() << "WARNING! Rounding granularity value in from " << amount << "ms to " << res << "ms\n";
    }

    return res;
}

unsigned int GetValueInSecond(double amount, std::string units, unsigned int* defValue)
{
    //Handle plural
    if (units == "second") { units = "seconds"; }
    if (units == "minute") { units = "minutes"; }
    if (units == "hour") { units = "hours"; }

    //Detect errors
    if (units.empty() || (units != "minutes" && units != "seconds" && units != "ms" && units!= "hours"))
    {
        if (defValue)
        {
            return *defValue;
        }
        else
        {
            std::stringstream msg;
            msg << "Invalid units provided for granularity. Expected: \"seconds\" or \"minutes\" or \"ms\"";
            throw std::runtime_error(msg.str());
        }
    }

    //Reduce to seconds
    if (units == "ms") { amount /= 1000; }
    if (units == "minutes") { amount *= 60; }
    if (units == "hours") { amount *= 3600; }

    //Check for overflow:
    unsigned int res = static_cast<unsigned int>(amount);

    if (static_cast<double>(res) != amount)
    {
        Warn() << "WARNING! Rounding granularity value in from " << amount << "ms to " << res << "ms\n";
    }

    return res;
}

//Helper: Time units such as "10", "seconds"
unsigned int ParseTimegranAsMs(const XMLCh* amountX, const XMLCh* unitsX, unsigned int* defValue)
{
    double amount = boost::lexical_cast<double>(TranscodeString(amountX));
    std::string units = TranscodeString(unitsX);

    return GetValueInMs(amount, units, defValue);
}

unsigned int ParseTimegranAsSeconds(const XMLCh* amountX, const XMLCh* unitsX, unsigned int* defValue)
{
    double amount = boost::lexical_cast<double>(TranscodeString(amountX));
    std::string units = TranscodeString(unitsX);
    return GetValueInSecond(amount, units, defValue);
}

DailyTime ParseDailyTime(const XMLCh* srcX, DailyTime* defValue)
{
    if (srcX)
    {
        return DailyTime(TranscodeString(srcX));
    }

    //Wasn't found.
    if (!defValue)
    {
        std::stringstream msg;
        msg << "No value provided for time attribute.";
        throw std::runtime_error(msg.str());
    }

    return *defValue;
}

std::string ParseNonemptyString(const XMLCh* srcX, std::string* defValue)
{
    std::string res = ParseString(srcX, defValue);

    if (!res.empty())
    {
        return res;
    }

    //Wasn't found.
    if (!defValue)
    {
        std::stringstream msg;
        msg << "No value provided for string attribute.";
        throw std::runtime_error(msg.str());
    }

    return *defValue;
}

//How to do defaults
bool ParseBoolean(const XMLCh* src, bool defValue)
{
    return ParseBoolean(src, &defValue);
}

bool ParseBoolean(const XMLCh* src)
{
    //No default
    return ParseBoolean(src, nullptr);
}

int ParseInteger(const XMLCh* src, int defValue)
{
    return ParseInteger(src, &defValue);
}

int ParseInteger(const XMLCh* src)
{
    //No default
    return ParseInteger(src, nullptr);
}

unsigned int ParseUnsignedInt(const XMLCh* src, unsigned int defValue)
{
    return ParseUnsignedInt(src, &defValue);
}

unsigned int ParseUnsignedInt(const XMLCh* src)
{
    //No default
    return ParseUnsignedInt(src, nullptr);
}

float ParseFloat(const XMLCh* src)
{
    return ParseFloat(src, nullptr);
}

float ParseFloat(const XMLCh* src, float defValue)
{
    return ParseFloat(src, &defValue);
}

DailyTime ParseDailyTime(const XMLCh* src, DailyTime defValue)
{
    return ParseDailyTime(src, &defValue);
}

DailyTime ParseDailyTime(const XMLCh* src)
{
    //No default
    return ParseDailyTime(src, nullptr);
}

std::string ParseString(const XMLCh* src, std::string defValue)
{
    return ParseString(src, &defValue);
}

std::string ParseString(const XMLCh* src)
{
    //No default
    return ParseString(src, nullptr);
}

std::string ParseNonemptyString(const XMLCh* src, std::string defValue)
{
    return ParseNonemptyString(src, &defValue);
}

std::string ParseNonemptyString(const XMLCh* src)
{
    //No default
    return ParseNonemptyString(src, nullptr);
}

unsigned int ParseTimegranAsMs(const XMLCh* amount, const XMLCh* units, unsigned int defValue)
{
    return ParseTimegranAsMs(amount, units, &defValue);
}

unsigned int ParseTimegranAsMs(const XMLCh* amount, const XMLCh* units)
{
    //No default
    return ParseTimegranAsMs(amount, units, nullptr);
}

unsigned int ParseTimegranAsSecond(const XMLCh* amount, const XMLCh* units, unsigned int defValue)
{
    return ParseTimegranAsSeconds(amount, units, &defValue);
}

//TODO: Same issue; needs to be easier access to these things.
std::string ProcessValueString(xercesc::DOMElement* node)
{
    return ParseString(GetNamedAttributeValue(node, "value"));
}

}


text:
/* ----------------------------------------------------------------------------

 * GTSAM Copyright 2010, Georgia Tech Research Corporation,
 * Atlanta, Georgia 30332-0415
 * All Rights Reserved
 * Authors: Frank Dellaert, et al. (see THANKS for the full author list)

 * See LICENSE for the license information

 * -------------------------------------------------------------------------- */

/**
 * @file    testParticleFactor.cpp
 * @brief   Unit tests for the Particle factor
 * @author  Frank Dellaert
 * @date    Dec 9, 2013
 */

#include <gtsam/linear/NoiseModel.h>
#include <boost/make_shared.hpp>

namespace gtsam {

/**
 * A factor approximating a density on a variable as a set of weighted particles
 */
template<class X>
class ParticleFactor {

public:
  typedef ParticleFactor This; ///< Typedef to this class
  typedef std::shared_ptr<This> shared_ptr; ///< shared_ptr to this class

};

/**
 * A particle filter class, styled on functional KalmanFilter
 * A state is created, which is functionally updates through [predict] and [update]
 */
template<class X>
class ParticleFilter {

public:

  /**
   * The Particle filter state is simply a ParticleFactor
   */
  typedef typename ParticleFactor<X>::shared_ptr State;

  /**
   * Create initial state, i.e., prior density at time k=0
   * In Bayes Filter notation, these are x_{0|0} and P_{0|0}
   * @param x0 estimate at time 0
   * @param P0 covariance at time 0, given as a diagonal Gaussian 'model'
   */
  State init(const Vector& x0, const SharedDiagonal& P0) {
    return std::make_shared<ParticleFactor<X> >();
  }

};
// ParticleFilter

}// namespace gtsam

#include <gtsam/slam/BetweenFactor.h>
#include <gtsam/linear/KalmanFilter.h>
#include <gtsam/geometry/Pose2.h>
#include <CppUnitLite/TestHarness.h>

using namespace std;
using namespace gtsam;

//******************************************************************************

TEST( particleFactor, constructor ) {
//  ParticleFactor<Pose2> pf;
  //CHECK(assert_equal(expected, actual));
}

//******************************************************************************
// Tests to do:
// Take two variables pf-x-*-y, eliminate x, multiply and sample then marginalize
TEST( particleFactor, eliminate) {
//  ParticleFactor<Pose2> fx;
  BetweenFactor<Pose2> fxy;

}

//******************************************************************************

/** Small 2D point class implemented as a Vector */
struct State: Vector {
  State(double x, double y) :
      Vector((Vector(2) << x, y).finished()) {
  }
};

//******************************************************************************
TEST( ParticleFilter, constructor) {

// Create a Kalman filter of dimension 2
  ParticleFilter<Pose2> pf1;

// Create inital mean/covariance
  State x_initial(0.0, 0.0);
  SharedDiagonal P1 = noiseModel::Isotropic::Sigma(2, 0.1);

// Get initial state by passing initial mean/covariance to the filter
  ParticleFilter<Pose2>::State p1 = pf1.init(x_initial, P1);

//  // Assert it has the correct mean, covariance and information
//  EXPECT(assert_equal(x_initial, p1->mean()));
//  Matrix Sigma = (Mat(2, 2) << 0.01, 0.0, 0.0, 0.01);
//  EXPECT(assert_equal(Sigma, p1->covariance()));
//  EXPECT(assert_equal(inverse(Sigma), p1->information()));
//
//  // Create one with a sharedGaussian
//  KalmanFilter::State p2 = pf1.init(x_initial, Sigma);
//  EXPECT(assert_equal(Sigma, p2->covariance()));
//
//  // Now make sure both agree
//  EXPECT(assert_equal(p1->covariance(), p2->covariance()));
}

//******************************************************************************
TEST( ParticleFilter, linear1 ) {

  // Create the controls and measurement properties for our example
  Matrix F = I_2x2;
  Matrix B = I_2x2;
  Vector u = Vector2(1.0, 0.0);
  SharedDiagonal modelQ = noiseModel::Isotropic::Sigma(2, 0.1);
  Matrix Q = 0.01 * I_2x2;
  Matrix H = I_2x2;
  State z1(1.0, 0.0);
  State z2(2.0, 0.0);
  State z3(3.0, 0.0);
  SharedDiagonal modelR = noiseModel::Isotropic::Sigma(2, 0.1);
  Matrix R = 0.01 * I_2x2;

// Create the set of expected output TestValues
  State expected0(0.0, 0.0);
  Matrix P00 = 0.01 * I_2x2;

  State expected1(1.0, 0.0);
  Matrix P01 = P00 + Q;
  Matrix I11 = P01.inverse() + R.inverse();

  State expected2(2.0, 0.0);
  Matrix P12 = I11.inverse() + Q;
  Matrix I22 = P12.inverse() + R.inverse();

  State expected3(3.0, 0.0);
  Matrix P23 = I22.inverse() + Q;
  Matrix I33 = P23.inverse() + R.inverse();

// Create a Kalman filter of dimension 2
  KalmanFilter kf(2);

// Create the Kalman Filter initialization point
  State x_initial(0.0, 0.0);
  SharedDiagonal P_initial = noiseModel::Isotropic::Sigma(2, 0.1);

// Create initial KalmanFilter object
  KalmanFilter::State p0 = kf.init(x_initial, P_initial);
  EXPECT(assert_equal(expected0, p0->mean()));
  EXPECT(assert_equal(P00, p0->covariance()));

// Run iteration 1
  KalmanFilter::State p1p = kf.predict(p0, F, B, u, modelQ);
  EXPECT(assert_equal(expected1, p1p->mean()));
  EXPECT(assert_equal(P01, p1p->covariance()));

  KalmanFilter::State p1 = kf.update(p1p, H, z1, modelR);
  EXPECT(assert_equal(expected1, p1->mean()));
  EXPECT(assert_equal(I11, p1->information()));

// Run iteration 2 (with full covariance)
  KalmanFilter::State p2p = kf.predictQ(p1, F, B, u, Q);
  EXPECT(assert_equal(expected2, p2p->mean()));

  KalmanFilter::State p2 = kf.update(p2p, H, z2, modelR);
  EXPECT(assert_equal(expected2, p2->mean()));

// Run iteration 3
  KalmanFilter::State p3p = kf.predict(p2, F, B, u, modelQ);
  EXPECT(assert_equal(expected3, p3p->mean()));
  LONGS_EQUAL(3, (long)KalmanFilter::step(p3p));

  KalmanFilter::State p3 = kf.update(p3p, H, z3, modelR);
  EXPECT(assert_equal(expected3, p3->mean()));
  LONGS_EQUAL(3, (long)KalmanFilter::step(p3));
}

//******************************************************************************
int main() {
  TestResult tr;
  return TestRegistry::runAllTests(tr);
}
//******************************************************************************

max_stars_repo_name: ProfFan/gtsam

max_issues_repo_name: ProfFan/gtsam

max_forks_repo_name: ProfFan/gtsam