<commit_before>#include "kfold.h"
#include <vector>
#include <stdlib.h>
#include <time.h>
#include <iostream>
using std::vector;
using std::cout;
using std::endl;
/**
Class to generate the vectors from a dataset for kfold cross validation.
data is the whole dataset
numGenes is the number of rows
classSizes is a vector containing the 2 classSizes
k is the number of folds
**/
kfold::kfold( vector<double> & data, int numGenes, vector<int> & classSizes, int k){
    this->nGenes = numGenes;
    this->orig_data = &data;
    this->class1size = classSizes[0];
    this->class2size = classSizes[1];
    this->k = k;
    this->it = 0;
    this->samp_vector = generateSampleVector();
    this->next_fold = 0;
    this->generated_data = NULL;
    this->generated_test = NULL;
    this->curr_class = -1;
    this->curr_classSizes = classSizes;
}

kfold::~kfold(){
    delete generated_data;
    delete generated_test;
    orig_data = NULL;
}
/**
Generates a vector containing [0,...,n-1] that has been shuffled.
**/
vector<int> kfold::generateSampleVector(){

    srand(time(NULL));
    if (k > class1size + class2size){
        k = class1size + class2size;
        //k is bigger than our sample size, so lets do loocv
    }
    vector<int> samples(class1size+class2size);
    for(int i = 0;i<class1size+class2size;i++){
        samples[i] = i;
    }
    for(int i=class1size+class2size-1;i>0;i--){//fisher-yates shuffle
        int j = rand() % i;
        int temp = samples[i];
        samples[i] = samples[j];
        samples[j] = temp;
    }

    if (checkFoldsGood(samples)){
        return samples;
    } else {
        //all our pigeons are in the same hole.
        //shuffle shuffle
        return generateSampleVector();
    }

}
/**
Checks that we will not have a training set without any samples for a class.

**/
bool kfold::checkFoldsGood( vector<int> & sample){
    int fsize = getFoldSize();

    bool good = true;

    if (class1size > fsize && class2size > fsize) return good;//shortcircuit pigeon
    int class1counter, class2counter;
    for( int i = 0; i < sample.size();i++ ){
        //the only way for this to happen is if all of one class ends up in a
        //fold
        if (i%fsize == 0){//new fold
           class1counter = 0;
           class2counter = 0;
        }
        //size of class[1||2] in this fold
        if(sample.at(i) < class1size){//class1sample
            class1counter++;
        } else {//class2sample
            class2counter++;
        }
        if ((class1counter == class1size)
            || (class2counter == class2size)){
            //Oh noes!!!!All our eggs are in one basket.
            good = false;
            break;
        }
     }
     return good;
}
/**
Returns a vector that contains the training set for the next set of learners
Returns null if there are no more training sets to be generated.

NOTE: on each call to this function the previous training set is deleted!!
You will need to copy the vector if you want to keep it.
**/
vector<double> * kfold::getNextTrainingSet(){
    next_fold = next_fold + getFoldSize();
    curr_classSizes[0] = 0;
    curr_classSizes[1] = 0;

    if (next_fold > samp_vector.size()) next_fold = samp_vector.size();
    if (samp_vector.size() == it) return NULL;

    delete generated_data;
    generated_data = new vector<double>();
    for(int base_i = 0; base_i<class1size+class2size;base_i++){
        if(trainingData(base_i) ){
            curr_classSizes[base_i >= class1size]++;
            for(int j=0; j<nGenes;j++){
                generated_data->push_back(orig_data->at(base_i*nGenes + j));
            }
        }

    }
    return generated_data;
}
/**
Returns the current test vector.
Returns null if their are no more test vectors for the current training set

NOTE: on each call to this function the previous test vector is deleted!!
You will need to copy the vector if you want to keep it.
**/
vector<double> * kfold::getNextTestVector(){
    delete generated_test;
    if(it == next_fold){
        curr_class = -1;
        generated_test = NULL;
        return NULL;
    }
    generated_test = new vector<double>();
    int next_sample = samp_vector[it];
    if (next_sample < class1size){
        curr_class = 0;
    } else {
        curr_class = 1;
    }
    int col = nGenes*next_sample;

    for(int i = 0; i<nGenes; i++){
        generated_test->push_back(orig_data->at(col + i));
    }
    it++;
   return generated_test;
}
vector<int> kfold::getClassSizes(){
    return curr_classSizes;
}

int kfold::getTestVectorClass(){
    return curr_class;
}
/**
Given a sample number
return true if sample is in training set
return false is sample is to be used for crossvalidation
**/
bool kfold::trainingData(int sample){
    int ksize = getFoldSize();
    int temp_it = it;
    for(int i=it; i < next_fold;i++){
        if(samp_vector[i] == sample){
            return false;
        }
    }
    return true;
}
int kfold::getFoldSize(){
    int ksize = (class1size+class2size)/k;
    if((class1size+class2size)%k > 0){
        ksize++;
    }
    return ksize;
}
void printVect(vector<double> a, int rows){
    for(int i=0;i<a.size();i++){
        if (i%rows == 0){cout << endl;}
        cout << a.at(i) << " ";
    }
    cout << endl;
}
/**
int main(){

    vector<double> data;
    vector<int> cs;

    int c1=5;
    int c2 = 5;
    int nGenes = 10;
    float base = 0.0;
    for (int i=0; i<c1;i++){
        for(int j=0;j<nGenes;j++){
                base = 0.0;
            data.push_back(i*nGenes + j + base);
        }

    }
    for (int i=c1; i<c1+c2;i++){
        for(int j=0;j<nGenes;j++){
                base = 0.5;
            data.push_back(i*nGenes + j + base);
        }

    }
    cs.push_back(c1);
    cs.push_back(c2);
    kfold k(data,nGenes, cs, 3);
    vector<double> * ts;
    vector<double> * ls;
    ts = k.getNextTrainingSet();
    int counter = 0;
    while(ts != NULL){
    counter++;
    cout <<endl<< "ts" << endl;
        printVect((*ts), nGenes);
        ls = k.getNextTestVector();
        while(ls != NULL){
            cout <<  endl<< "ls" << endl;
            printVect((*ls), nGenes);
            cout << "class=" << k.getTestVectorClass()<<endl;
            cout << "cs1=" <<k.getClassSizes()[0];
            cout << "cs2=" <<k.getClassSizes()[1];
            k.getTestVectorClass();
            ls = k.getNextTestVector();
        }
        ts = k.getNextTrainingSet();
    }

    cout << "times ran = " << counter << endl;
}**/
<commit_msg>Cleanup<commit_after>#include "kfold.h"
#include <vector>
#include <stdlib.h>
#include <time.h>
#include <iostream>
using std::vector;
using std::cout;
using std::endl;
/**
Class to generate the vectors from a dataset for kfold cross validation.
data is the whole dataset
numGenes is the number of rows
classSizes is a vector containing the 2 classSizes
k is the number of folds
**/
kfold::kfold( vector<double> & data, int numGenes, vector<int> & classSizes, int k){
    this->nGenes = numGenes;
    this->orig_data = &data;
    this->class1size = classSizes[0];
    this->class2size = classSizes[1];
    this->k = k;
    this->it = 0;
    this->samp_vector = generateSampleVector();
    this->next_fold = 0;
    this->generated_data = NULL;
    this->generated_test = NULL;
    this->curr_class = -1;
    this->curr_classSizes = classSizes;
}

kfold::~kfold(){
    delete generated_data;
    delete generated_test;
    orig_data = NULL;
}
/**
Generates a vector containing [0,...,n-1] that has been shuffled.
**/
vector<int> kfold::generateSampleVector(){

    srand(time(NULL));
    if (k > class1size + class2size){
        k = class1size + class2size;
        //k is bigger than our sample size, so lets do loocv
    }
    vector<int> samples(class1size+class2size);
    for(int i = 0;i<class1size+class2size;i++){
        samples[i] = i;
    }
    for(int i=class1size+class2size-1;i>0;i--){//fisher-yates shuffle
        int j = rand() % i;
        int temp = samples[i];
        samples[i] = samples[j];
        samples[j] = temp;
    }

    if (checkFoldsGood(samples)){
        return samples;
    } else {
        //all our pigeons are in the same hole.
        //shuffle shuffle
        return generateSampleVector();
    }

}
/**
Checks that we will not have a training set without any samples for a class.

**/
bool kfold::checkFoldsGood( vector<int> & sample){
    int fsize = getFoldSize();

    bool good = true;

    if (class1size > fsize && class2size > fsize) return good;//shortcircuit pigeon
    int class1counter=0;
    int class2counter=0;
    for(unsigned int i = 0; i < sample.size();i++ ){
        //the only way for this to happen is if all of one class ends up in a
        //fold
        if (i%fsize == 0){//new fold
           class1counter = 0;
           class2counter = 0;
        }
        //size of class[1||2] in this fold
        if(sample.at(i) < class1size){//class1sample
            class1counter++;
        } else {//class2sample
            class2counter++;
        }
        if ((class1counter == class1size)
            || (class2counter == class2size)){
            //Oh noes!!!!All our eggs are in one basket.
            good = false;
            break;
        }
     }
     return good;
}
/**
Returns a vector that contains the training set for the next set of learners
Returns null if there are no more training sets to be generated.

NOTE: on each call to this function the previous training set is deleted!!
You will need to copy the vector if you want to keep it.
**/
vector<double> * kfold::getNextTrainingSet(){
    next_fold = next_fold + getFoldSize();
    curr_classSizes[0] = 0;
    curr_classSizes[1] = 0;

    if (next_fold > (int)samp_vector.size()) next_fold = (int)samp_vector.size();
    if ((int)samp_vector.size() == it) return NULL;

    delete generated_data;
    generated_data = new vector<double>();
    for(int base_i = 0; base_i<class1size+class2size;base_i++){
        if(trainingData(base_i) ){
            curr_classSizes[base_i >= class1size]++;
            for(int j=0; j<nGenes;j++){
                generated_data->push_back(orig_data->at(base_i*nGenes + j));
            }
        }

    }
    return generated_data;
}
/**
Returns the current test vector.
Returns null if their are no more test vectors for the current training set

NOTE: on each call to this function the previous test vector is deleted!!
You will need to copy the vector if you want to keep it.
**/
vector<double> * kfold::getNextTestVector(){
    delete generated_test;
    if(it == next_fold){
        curr_class = -1;
        generated_test = NULL;
        return NULL;
    }
    generated_test = new vector<double>();
    int next_sample = samp_vector[it];
    if (next_sample < class1size){
        curr_class = 0;
    } else {
        curr_class = 1;
    }
    int col = nGenes*next_sample;

    for(int i = 0; i<nGenes; i++){
        generated_test->push_back(orig_data->at(col + i));
    }
    it++;
   return generated_test;
}
vector<int> kfold::getClassSizes(){
    return curr_classSizes;
}

int kfold::getTestVectorClass(){
    return curr_class;
}
/**
Given a sample number
return true if sample is in training set
return false is sample is to be used for crossvalidation
**/
bool kfold::trainingData(int sample){
    for(int i=it; i < next_fold;i++){
        if(samp_vector[i] == sample){
            return false;
        }
    }
    return true;
}
int kfold::getFoldSize(){
    int ksize = (class1size+class2size)/k;
    if((class1size+class2size)%k > 0){
        ksize++;
    }
    return ksize;
}
void printVect(vector<double> a, int rows){
    for(unsigned int i=0;i<a.size();i++){
        if (i%rows == 0){cout << endl;}
        cout << a.at(i) << " ";
    }
    cout << endl;
}
/**
int main(){

    vector<double> data;
    vector<int> cs;

    int c1=5;
    int c2 = 5;
    int nGenes = 10;
    float base = 0.0;
    for (int i=0; i<c1;i++){
        for(int j=0;j<nGenes;j++){
                base = 0.0;
            data.push_back(i*nGenes + j + base);
        }

    }
    for (int i=c1; i<c1+c2;i++){
        for(int j=0;j<nGenes;j++){
                base = 0.5;
            data.push_back(i*nGenes + j + base);
        }

    }
    cs.push_back(c1);
    cs.push_back(c2);
    kfold k(data,nGenes, cs, 3);
    vector<double> * ts;
    vector<double> * ls;
    ts = k.getNextTrainingSet();
    int counter = 0;
    while(ts != NULL){
    counter++;
    cout <<endl<< "ts" << endl;
        printVect((*ts), nGenes);
        ls = k.getNextTestVector();
        while(ls != NULL){
            cout <<  endl<< "ls" << endl;
            printVect((*ls), nGenes);
            cout << "class=" << k.getTestVectorClass()<<endl;
            cout << "cs1=" <<k.getClassSizes()[0];
            cout << "cs2=" <<k.getClassSizes()[1];
            k.getTestVectorClass();
            ls = k.getNextTestVector();
        }
        ts = k.getNextTrainingSet();
    }

    cout << "times ran = " << counter << endl;
}**/
<|endoftext|>


<commit_before>#include "MatrixTransform.h"
#include "Group.h"

#include <osg/Notify>

#include <osgDB/FileNameUtils>
#include <osgDB/Registry>

using namespace osg;
using namespace osgDB;

class IVEReaderWriter : public ReaderWriter
{
    public:
        virtual const char* className() { return "IVE Reader/Writer"; }

        virtual bool acceptsExtension(const std::string& extension)
        {
            return equalCaseInsensitive(extension,"ive");
        }

        virtual ReadResult readNode(const std::string& fileName, const Options* options)
        {
            std::string ext = getFileExtension(fileName);
            if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;

            std::ifstream istream(fileName.c_str(), std::ios::in | std::ios::binary);
            return readNode(istream,options);
        }

        virtual ReadResult readNode(std::istream& fin, const Options*)
        {
	    try{
                // Create datainputstream.
                ive::DataInputStream in(&fin);

                return in.readNode();
	    }
	    catch(ive::Exception e)
            {
	        std::cout<<"Error reading file: "<< e.getError()<<std::endl;
	        return ReadResult::FILE_NOT_HANDLED;
	    }
            return 0;
        }

        virtual WriteResult writeNode(const Node& node,const std::string& fileName, const osgDB::ReaderWriter::Options* options)
        {
            std::string ext = getFileExtension(fileName);
            if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED;

            std::ofstream fout(fileName.c_str(), std::ios::out | std::ios::binary);
            WriteResult result = writeNode(node, fout, options);
            fout.close();
            return result;
        }

        virtual WriteResult writeNode(const Node& node,std::ostream& fout, const osgDB::ReaderWriter::Options*)
        {
            try
            {
                ive::DataOutputStream out(&fout);

                out.writeNode(const_cast<osg::Node*>(&node));
                return WriteResult::FILE_SAVED;
            }
            catch(ive::Exception e)
            {
	        osg::notify(osg::WARN)<<"Error parsing OSG file: "<< e.getError() << std::endl;
            }
            return WriteResult::FILE_NOT_HANDLED;

        }

};

// now register with Registry to instantiate the above
// reader/writer.
RegisterReaderWriterProxy<IVEReaderWriter> g_IVEReaderWriterProxy;
<commit_msg>Added #ifdef IVE_CATCH_EXCEPTIONS to allow catching of exceptions to be turned off for debugging purposes.<commit_after>#include "MatrixTransform.h"
#include "Group.h"

#include <osg/Notify>

#include <osgDB/FileNameUtils>
#include <osgDB/Registry>

using namespace osg;
using namespace osgDB;

class IVEReaderWriter : public ReaderWriter
{
    public:
        virtual const char* className() { return "IVE Reader/Writer"; }

        virtual bool acceptsExtension(const std::string& extension)
        {
            return equalCaseInsensitive(extension,"ive");
        }

        virtual ReadResult readNode(const std::string& fileName, const Options* options)
        {
            std::string ext = getFileExtension(fileName);
            if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;

            std::ifstream istream(fileName.c_str(), std::ios::in | std::ios::binary);
            return readNode(istream,options);
        }

        virtual ReadResult readNode(std::istream& fin, const Options*)
        {
        #define IVE_CATCH_EXCEPTIONS
        #ifdef IVE_CATCH_EXCEPTIONS
	    try{
        #endif
                // Create datainputstream.
                ive::DataInputStream in(&fin);

                return in.readNode();
        #ifdef IVE_CATCH_EXCEPTIONS
	    }
	    catch(ive::Exception e)
            {
	        std::cout<<"Error reading file: "<< e.getError()<<std::endl;
	        return ReadResult::FILE_NOT_HANDLED;
	    }
            return 0;
        #endif
        }

        virtual WriteResult writeNode(const Node& node,const std::string& fileName, const osgDB::ReaderWriter::Options* options)
        {
            std::string ext = getFileExtension(fileName);
            if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED;

            std::ofstream fout(fileName.c_str(), std::ios::out | std::ios::binary);
            WriteResult result = writeNode(node, fout, options);
            fout.close();
            return result;
        }

        virtual WriteResult writeNode(const Node& node,std::ostream& fout, const osgDB::ReaderWriter::Options*)
        {
            try
            {
                ive::DataOutputStream out(&fout);

                out.writeNode(const_cast<osg::Node*>(&node));
                return WriteResult::FILE_SAVED;
            }
            catch(ive::Exception e)
            {
	        osg::notify(osg::WARN)<<"Error parsing OSG file: "<< e.getError() << std::endl;
            }
            return WriteResult::FILE_NOT_HANDLED;

        }

};

// now register with Registry to instantiate the above
// reader/writer.
RegisterReaderWriterProxy<IVEReaderWriter> g_IVEReaderWriterProxy;
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <sstream>

#include <osg/Notify>

#include <osgDB/Input>
#include <osgDB/Registry>
#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgDB/FileUtils>
#include <osgDB/Archive>
#include <osg/MatrixTransform>
#include <osg/Group>
#include <osg/Timer>
#include "sockinet.h"

 /*
  *  Semantics:
  *    Two methods for using the .net loader.
  *      1) Add a hostname prefix and a '.net' suffix on a model when passing
  *          to osgDB::readNodeFile()
  *          e.g:    osgDB::readNodeFile( "openscenegraph.org:cow.osg.net" );
  *
  *     2) Explicitely load the .net plugin and pass the plugin options including
  *           hostname=<hostname>
  *
  *    Method #1 takes precedence.  SO, if the hostname option is passed the
  *    plugin, but the name also contains a hostname prefix, the hostname
  *    prefix on the file name will override the option
  *
  *  Plugin options:
  *           hostname=<hostname>     - Specify the host where the data file is to
  *                                     be fetched from.
  *
  *           prefix=<prefix>         - Specify a server directory to prefix the
  *                                     file name with.
  *
  *           local_cache_dir=<dir>   - Specify a directory in which to cache files
  *                                     on the local machine once they've been fetched.
  *                                     This directory is also searched before fetching
  *                                     the file from the server when Read mode is
  *                                     enabled on the cache.
  *
  *           cache_mode=<mode>       - Set the mode for the local cache if local_cache
  *                                     was specified.  If local_cache was not specified
  *                                     this directive is ignored.  <mode> may
  *                                     be specified with ReadOnly, WriteOnly, or
  *                                     ReadWrite.  Behavior for the different modes is
  *                                     defined as:
  *
  *                                       ReadOnly   - When retrieving files, cache is
  *                                                    searched first, and if the file is
  *                                                    not present, it is fetched from the
  *                                                    server.  If it is fetched from the
  *                                                    server it is not stored in local cache
  *
  *                                       WriteOnly  - When retrieving files, cache is not
  *                                                    searched, file is always retrieved
  *                                                    from the server and always written to
  *                                                    cache.
  *
  *                                       ReadWrite  - (the default).  When retrieving files
  *                                                    cache is searched first, if file is
  *                                                    not present in cache, it is fetched from
  *                                                    the server.  If fetched, it is written
  *                                                    to cache.
  *
  */

class NetReader : public osgDB::ReaderWriter
{
    public:
        NetReader() {}

        virtual const char* className() const { return "HTTP Protocol Model Reader"; }

        virtual bool acceptsExtension(const std::string& extension) const
        {
            return osgDB::equalCaseInsensitive(extension,"net");
        }

        enum ObjectType
        {
            OBJECT,
            ARCHIVE,
            IMAGE,
            HEIGHTFIELD,
            NODE
        };

        virtual ReadResult openArchive(const std::string& fileName,ArchiveStatus status, unsigned int , const Options* options) const
        {
            if (status!=READ) return ReadResult(ReadResult::FILE_NOT_HANDLED);
            else return readFile(ARCHIVE,fileName,options);
        }

        virtual ReadResult readObject(const std::string& fileName, const Options* options) const
        {
            return readFile(OBJECT,fileName,options);
        }

        virtual ReadResult readImage(const std::string& fileName, const Options *options) const
        {
            return readFile(IMAGE,fileName,options);
        }

        virtual ReadResult readHeightField(const std::string& fileName, const Options *options) const
        {
            return readFile(HEIGHTFIELD,fileName,options);
        }

        virtual ReadResult readNode(const std::string& fileName, const Options *options) const
        {
            return readFile(NODE,fileName,options);
        }

        ReadResult readFile(ObjectType objectType, ReaderWriter* rw, std::istream& fin, const Options *options) const
        {
            switch(objectType)
            {
            case(OBJECT): return rw->readObject(fin,options);
            case(ARCHIVE): return rw->openArchive(fin,options);
            case(IMAGE): return rw->readImage(fin,options);
            case(HEIGHTFIELD): return rw->readHeightField(fin,options);
            case(NODE): return rw->readNode(fin,options);
            default: break;
            }
            return ReadResult::FILE_NOT_HANDLED;
        }

        virtual ReadResult readFile(ObjectType objectType, const std::string& inFileName, const Options *options) const
        {
            osg::Timer_t start = osg::Timer::instance()->tick();

            osg::notify(osg::NOTICE) << "osgPlugin .net: start load" << inFileName << std::endl;

            std::string hostname;
            std::string serverPrefix;
            std::string localCacheDir;
            int port = 80;

            enum CacheMode {
                Read      = 1,
                Write     = 2,
                ReadWrite = 3
            };

            CacheMode cacheMode = ReadWrite;

            if (options)
            {
                std::istringstream iss(options->getOptionString());
                std::string opt;
                while (iss >> opt)
                {
                    int index = opt.find( "=" );
                    if( opt.substr( 0, index ) == "hostname" ||
                        opt.substr( 0, index ) == "HOSTNAME" )
                    {
                        hostname = opt.substr( index+1 );
                    }
                    else if( opt.substr( 0, index ) == "port" ||
                             opt.substr( 0, index ) == "PORT" )
                    {
                        port = atoi( opt.substr(index+1).c_str() );
                    }
                    else if( opt.substr( 0, index ) == "server_prefix" ||
                             opt.substr( 0, index ) == "SERVER_PREFIX" ||
                             opt.substr( 0, index ) == "prefix" ||
                             opt.substr( 0, index ) == "PREFIX" )
                    {
                        serverPrefix = opt.substr(index+1);
                    }
                    else if( opt.substr( 0, index ) == "local_cache_dir" ||
                             opt.substr( 0, index ) == "LOCAL_CACHE_DIR" )
                    {
                        localCacheDir = opt.substr(index+1);
                    }
                    else if( opt.substr( 0, index ) == "cache_mode" ||
                             opt.substr( 0, index ) == "CACHE_MODE" )
                    {
                        if( opt.substr(index+1) == "ReadOnly" )
                            cacheMode = Read;
                        else if(  opt.substr(index+1) == "WriteOnly" )
                            cacheMode = Write;
                        else if(  opt.substr(index+1) == "ReadWrite" )
                            cacheMode = ReadWrite;
                        else
                            osg::notify(osg::WARN) <<
                                "NET plug-in warning:  cache_mode " << opt.substr(index+1) <<
                                " not understood.  Defaulting to ReadWrite." << std::endl;
                    }
                }
            }

            ReadResult readResult = ReadResult::FILE_NOT_HANDLED;

            /* * we accept all extensions
            std::string ext = osgDB::getFileExtension(inFileName);
            if (!acceptsExtension(ext))
                return ReadResult::FILE_NOT_HANDLED;
                */

            std::string fileName;
            int index = inFileName.find(":");
            // If we haven't been given a hostname as an option
            // and it hasn't been prefixed to the name, we fail
            if( index != -1 )
            {
                hostname = inFileName.substr( 0, index);
                // need to strip the inFileName of the hostname prefix
                fileName = inFileName.substr( index+1 );
            }
            else
            {
                if( hostname.empty() )
                    return ReadResult::FILE_NOT_HANDLED;
                else
                    fileName = inFileName;
            }

            // Let's also strip the possible .net extension
            if( osgDB::getFileExtension( fileName ) == "net" )
            {
                int rindex = fileName.rfind( "." );
                fileName = fileName.substr( 0, rindex );
            }

            if( !serverPrefix.empty() )
                fileName = serverPrefix + '/' + fileName;

            osg::notify(osg::WARN) << "hostname " << hostname << std::endl;
            osg::notify(osg::WARN) << "filename " << fileName << std::endl;

            // Invoke the reader corresponding to the extension
            osgDB::ReaderWriter *reader =
                    osgDB::Registry::instance()->getReaderWriterForExtension( osgDB::getFileExtension(fileName));
            if( reader == 0L )
                return ReadResult::FILE_NOT_HANDLED;

            // Before we go to the network, lets see if it is in local cache, if cache
            // was specified and Read bit is set
            if( !localCacheDir.empty() && (cacheMode & Read) )
            {
                std::string cacheFile = localCacheDir + '/' + fileName;
                if( osgDB::fileExists( cacheFile ))
                {
                    std::ifstream  in(cacheFile.c_str());
                    readResult = readFile(objectType, reader, in, options );

                    in.close();
                    osg::notify(osg::DEBUG_INFO) << "osgPlugin .net: " << fileName <<
                                         " fetched from local cache." << std::endl;
                    return readResult;
                }
            }

            // Fetch from the network
            osg::ref_ptr<iosockinet> sio = new iosockinet(sockbuf::sock_stream);
            try {
                sio->rdbuf()->connect( hostname.c_str(), port );
            }
            catch( sockerr e )
            {
                osg::notify(osg::WARN) << "osgPlugin .net reader: Unable to connect to host " << hostname << std::endl;
                return ReadResult::FILE_NOT_FOUND;
            }

            *sio << "GET /" << fileName << " HTTP/1.1\n" << "Host: " << hostname << "\n\n";
            sio->flush();

            char linebuff[256];
            do
            {
                sio->getline( linebuff, sizeof( linebuff ));

                std::istringstream iss(linebuff);
                std::string directive;
                iss >> directive;
                if( directive.substr(0,4) == "HTTP" )
                {
                    iss >> directive;
                    // Code 200.  We be ok.
                    if( directive == "200" )
                        ;
                    // Code 400 Bad Request
                    else if( directive == "400" )
                    {
                        osg::notify(osg::WARN) <<
                            "osgPlugin .net: http server response 400 - Bad Request" << std::endl;
                        return ReadResult::FILE_NOT_FOUND;
                    }
                    // Code 401 Bad Request
                    else if( directive == "401" )
                    {
                        osg::notify(osg::WARN) <<
                            "osgPlugin .net: http server response 401 - Unauthorized Access" << std::endl;
                        return ReadResult::FILE_NOT_FOUND;
                    }
                    // Code 403 Bad Request
                    else if( directive == "403" )
                    {
                        osg::notify(osg::WARN) <<
                            "osgPlugin .net: http server response 403 - Access Forbidden" << std::endl;
                        return ReadResult::FILE_NOT_FOUND;
                    }
                    // Code 404 File not found
                    else if( directive == "404" )
                    {
                        osg::notify(osg::WARN) <<
                            "osgPlugin .net: http server response 404 - File Not Found" << std::endl;
                        return ReadResult::FILE_NOT_FOUND;
                    }
                    // Code 405 Method not allowed
                    else if( directive == "405" )
                    {
                        osg::notify(osg::WARN) <<
                            "osgPlugin .net: http server response 405 - Method Not Allowed" << std::endl;
                        return ReadResult::FILE_NOT_FOUND;
                    }
                    // There's more....
                }

            } while( linebuff[0] != '\r' );

            // code for setting up the database path so that any paged
            // databases can be automatically located.
            osg::ref_ptr<Options> local_opt = const_cast<Options*>(options);
            if (!local_opt) local_opt = new Options;

            if (local_opt.valid() && local_opt->getDatabasePathList().empty())
            {
                local_opt->setDatabasePath(osgDB::getFilePath(inFileName));
            }

            if( reader != 0L )
                readResult = readFile(objectType, reader, *sio, local_opt.get() );

            double ms = osg::Timer::instance()->delta_m(start,osg::Timer::instance()->tick());

            osg::notify(osg::DEBUG_INFO) << "osgPlugin .net: " << fileName <<
                                         " fetched from server. in" << ms <<" ms"<< std::endl;

            if (objectType==ARCHIVE && readResult.validArchive())
            {
                // attach the socket istream to the archive to keep it alive.
                osgDB::Archive* archive = readResult.getArchive();
                archive->setUserData(sio.get());
            }

            if( !localCacheDir.empty() && cacheMode & Write )
            {
                std::string cacheFile = localCacheDir + '/' + fileName;
                if( osgDB::makeDirectoryForFile( cacheFile ) )
                {

                    switch(objectType)
                    {
                    case(OBJECT): osgDB::writeObjectFile( *(readResult.getObject()), cacheFile );
                    case(IMAGE): osgDB::writeImageFile( *(readResult.getImage()), cacheFile );
                    case(HEIGHTFIELD): osgDB::writeHeightFieldFile( *(readResult.getHeightField()), cacheFile );
                    case(NODE): osgDB::writeNodeFile( *(readResult.getNode()), cacheFile );;
                    default: break;
                    }

                    osg::notify(osg::DEBUG_INFO) << "osgPlugin .net: " << fileName <<
                                         " stored to local cache." << std::endl;
                }
            }

            return readResult;
        }

};

osgDB::RegisterReaderWriterProxy<NetReader> g_netReader_Proxy;

<commit_msg>Fixed osgDB:: prefix for Windows build<commit_after>#include <iostream>
#include <fstream>
#include <sstream>

#include <osg/Notify>

#include <osgDB/Input>
#include <osgDB/Registry>
#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgDB/FileUtils>
#include <osgDB/Archive>
#include <osg/MatrixTransform>
#include <osg/Group>
#include <osg/Timer>
#include "sockinet.h"

 /*
  *  Semantics:
  *    Two methods for using the .net loader.
  *      1) Add a hostname prefix and a '.net' suffix on a model when passing
  *          to osgDB::readNodeFile()
  *          e.g:    osgDB::readNodeFile( "openscenegraph.org:cow.osg.net" );
  *
  *     2) Explicitely load the .net plugin and pass the plugin options including
  *           hostname=<hostname>
  *
  *    Method #1 takes precedence.  SO, if the hostname option is passed the
  *    plugin, but the name also contains a hostname prefix, the hostname
  *    prefix on the file name will override the option
  *
  *  Plugin options:
  *           hostname=<hostname>     - Specify the host where the data file is to
  *                                     be fetched from.
  *
  *           prefix=<prefix>         - Specify a server directory to prefix the
  *                                     file name with.
  *
  *           local_cache_dir=<dir>   - Specify a directory in which to cache files
  *                                     on the local machine once they've been fetched.
  *                                     This directory is also searched before fetching
  *                                     the file from the server when Read mode is
  *                                     enabled on the cache.
  *
  *           cache_mode=<mode>       - Set the mode for the local cache if local_cache
  *                                     was specified.  If local_cache was not specified
  *                                     this directive is ignored.  <mode> may
  *                                     be specified with ReadOnly, WriteOnly, or
  *                                     ReadWrite.  Behavior for the different modes is
  *                                     defined as:
  *
  *                                       ReadOnly   - When retrieving files, cache is
  *                                                    searched first, and if the file is
  *                                                    not present, it is fetched from the
  *                                                    server.  If it is fetched from the
  *                                                    server it is not stored in local cache
  *
  *                                       WriteOnly  - When retrieving files, cache is not
  *                                                    searched, file is always retrieved
  *                                                    from the server and always written to
  *                                                    cache.
  *
  *                                       ReadWrite  - (the default).  When retrieving files
  *                                                    cache is searched first, if file is
  *                                                    not present in cache, it is fetched from
  *                                                    the server.  If fetched, it is written
  *                                                    to cache.
  *
  */

class NetReader : public osgDB::ReaderWriter
{
    public:
        NetReader() {}

        virtual const char* className() const { return "HTTP Protocol Model Reader"; }

        virtual bool acceptsExtension(const std::string& extension) const
        {
            return osgDB::equalCaseInsensitive(extension,"net");
        }

        enum ObjectType
        {
            OBJECT,
            ARCHIVE,
            IMAGE,
            HEIGHTFIELD,
            NODE
        };

        virtual ReadResult openArchive(const std::string& fileName,ArchiveStatus status, unsigned int , const Options* options) const
        {
            if (status!=READ) return ReadResult(ReadResult::FILE_NOT_HANDLED);
            else return readFile(ARCHIVE,fileName,options);
        }

        virtual ReadResult readObject(const std::string& fileName, const Options* options) const
        {
            return readFile(OBJECT,fileName,options);
        }

        virtual ReadResult readImage(const std::string& fileName, const Options *options) const
        {
            return readFile(IMAGE,fileName,options);
        }

        virtual ReadResult readHeightField(const std::string& fileName, const Options *options) const
        {
            return readFile(HEIGHTFIELD,fileName,options);
        }

        virtual ReadResult readNode(const std::string& fileName, const Options *options) const
        {
            return readFile(NODE,fileName,options);
        }

        ReadResult readFile(ObjectType objectType, osgDB::ReaderWriter* rw, std::istream& fin, const Options *options) const
        {
            switch(objectType)
            {
            case(OBJECT): return rw->readObject(fin,options);
            case(ARCHIVE): return rw->openArchive(fin,options);
            case(IMAGE): return rw->readImage(fin,options);
            case(HEIGHTFIELD): return rw->readHeightField(fin,options);
            case(NODE): return rw->readNode(fin,options);
            default: break;
            }
            return ReadResult::FILE_NOT_HANDLED;
        }

        virtual ReadResult readFile(ObjectType objectType, const std::string& inFileName, const Options *options) const
        {
            osg::Timer_t start = osg::Timer::instance()->tick();

            osg::notify(osg::NOTICE) << "osgPlugin .net: start load" << inFileName << std::endl;

            std::string hostname;
            std::string serverPrefix;
            std::string localCacheDir;
            int port = 80;

            enum CacheMode {
                Read      = 1,
                Write     = 2,
                ReadWrite = 3
            };

            CacheMode cacheMode = ReadWrite;

            if (options)
            {
                std::istringstream iss(options->getOptionString());
                std::string opt;
                while (iss >> opt)
                {
                    int index = opt.find( "=" );
                    if( opt.substr( 0, index ) == "hostname" ||
                        opt.substr( 0, index ) == "HOSTNAME" )
                    {
                        hostname = opt.substr( index+1 );
                    }
                    else if( opt.substr( 0, index ) == "port" ||
                             opt.substr( 0, index ) == "PORT" )
                    {
                        port = atoi( opt.substr(index+1).c_str() );
                    }
                    else if( opt.substr( 0, index ) == "server_prefix" ||
                             opt.substr( 0, index ) == "SERVER_PREFIX" ||
                             opt.substr( 0, index ) == "prefix" ||
                             opt.substr( 0, index ) == "PREFIX" )
                    {
                        serverPrefix = opt.substr(index+1);
                    }
                    else if( opt.substr( 0, index ) == "local_cache_dir" ||
                             opt.substr( 0, index ) == "LOCAL_CACHE_DIR" )
                    {
                        localCacheDir = opt.substr(index+1);
                    }
                    else if( opt.substr( 0, index ) == "cache_mode" ||
                             opt.substr( 0, index ) == "CACHE_MODE" )
                    {
                        if( opt.substr(index+1) == "ReadOnly" )
                            cacheMode = Read;
                        else if(  opt.substr(index+1) == "WriteOnly" )
                            cacheMode = Write;
                        else if(  opt.substr(index+1) == "ReadWrite" )
                            cacheMode = ReadWrite;
                        else
                            osg::notify(osg::WARN) <<
                                "NET plug-in warning:  cache_mode " << opt.substr(index+1) <<
                                " not understood.  Defaulting to ReadWrite." << std::endl;
                    }
                }
            }

            ReadResult readResult = ReadResult::FILE_NOT_HANDLED;

            /* * we accept all extensions
            std::string ext = osgDB::getFileExtension(inFileName);
            if (!acceptsExtension(ext))
                return ReadResult::FILE_NOT_HANDLED;
                */

            std::string fileName;
            int index = inFileName.find(":");
            // If we haven't been given a hostname as an option
            // and it hasn't been prefixed to the name, we fail
            if( index != -1 )
            {
                hostname = inFileName.substr( 0, index);
                // need to strip the inFileName of the hostname prefix
                fileName = inFileName.substr( index+1 );
            }
            else
            {
                if( hostname.empty() )
                    return ReadResult::FILE_NOT_HANDLED;
                else
                    fileName = inFileName;
            }

            // Let's also strip the possible .net extension
            if( osgDB::getFileExtension( fileName ) == "net" )
            {
                int rindex = fileName.rfind( "." );
                fileName = fileName.substr( 0, rindex );
            }

            if( !serverPrefix.empty() )
                fileName = serverPrefix + '/' + fileName;

            osg::notify(osg::WARN) << "hostname " << hostname << std::endl;
            osg::notify(osg::WARN) << "filename " << fileName << std::endl;

            // Invoke the reader corresponding to the extension
            osgDB::ReaderWriter *reader =
                    osgDB::Registry::instance()->getReaderWriterForExtension( osgDB::getFileExtension(fileName));
            if( reader == 0L )
                return ReadResult::FILE_NOT_HANDLED;

            // Before we go to the network, lets see if it is in local cache, if cache
            // was specified and Read bit is set
            if( !localCacheDir.empty() && (cacheMode & Read) )
            {
                std::string cacheFile = localCacheDir + '/' + fileName;
                if( osgDB::fileExists( cacheFile ))
                {
                    std::ifstream  in(cacheFile.c_str());
                    readResult = readFile(objectType, reader, in, options );

                    in.close();
                    osg::notify(osg::DEBUG_INFO) << "osgPlugin .net: " << fileName <<
                                         " fetched from local cache." << std::endl;
                    return readResult;
                }
            }

            // Fetch from the network
            osg::ref_ptr<iosockinet> sio = new iosockinet(sockbuf::sock_stream);
            try {
                sio->rdbuf()->connect( hostname.c_str(), port );
            }
            catch( sockerr e )
            {
                osg::notify(osg::WARN) << "osgPlugin .net reader: Unable to connect to host " << hostname << std::endl;
                return ReadResult::FILE_NOT_FOUND;
            }

            *sio << "GET /" << fileName << " HTTP/1.1\n" << "Host: " << hostname << "\n\n";
            sio->flush();

            char linebuff[256];
            do
            {
                sio->getline( linebuff, sizeof( linebuff ));

                std::istringstream iss(linebuff);
                std::string directive;
                iss >> directive;
                if( directive.substr(0,4) == "HTTP" )
                {
                    iss >> directive;
                    // Code 200.  We be ok.
                    if( directive == "200" )
                        ;
                    // Code 400 Bad Request
                    else if( directive == "400" )
                    {
                        osg::notify(osg::WARN) <<
                            "osgPlugin .net: http server response 400 - Bad Request" << std::endl;
                        return ReadResult::FILE_NOT_FOUND;
                    }
                    // Code 401 Bad Request
                    else if( directive == "401" )
                    {
                        osg::notify(osg::WARN) <<
                            "osgPlugin .net: http server response 401 - Unauthorized Access" << std::endl;
                        return ReadResult::FILE_NOT_FOUND;
                    }
                    // Code 403 Bad Request
                    else if( directive == "403" )
                    {
                        osg::notify(osg::WARN) <<
                            "osgPlugin .net: http server response 403 - Access Forbidden" << std::endl;
                        return ReadResult::FILE_NOT_FOUND;
                    }
                    // Code 404 File not found
                    else if( directive == "404" )
                    {
                        osg::notify(osg::WARN) <<
                            "osgPlugin .net: http server response 404 - File Not Found" << std::endl;
                        return ReadResult::FILE_NOT_FOUND;
                    }
                    // Code 405 Method not allowed
                    else if( directive == "405" )
                    {
                        osg::notify(osg::WARN) <<
                            "osgPlugin .net: http server response 405 - Method Not Allowed" << std::endl;
                        return ReadResult::FILE_NOT_FOUND;
                    }
                    // There's more....
                }

            } while( linebuff[0] != '\r' );

            // code for setting up the database path so that any paged
            // databases can be automatically located.
            osg::ref_ptr<Options> local_opt = const_cast<Options*>(options);
            if (!local_opt) local_opt = new Options;

            if (local_opt.valid() && local_opt->getDatabasePathList().empty())
            {
                local_opt->setDatabasePath(osgDB::getFilePath(inFileName));
            }

            if( reader != 0L )
                readResult = readFile(objectType, reader, *sio, local_opt.get() );

            double ms = osg::Timer::instance()->delta_m(start,osg::Timer::instance()->tick());

            osg::notify(osg::DEBUG_INFO) << "osgPlugin .net: " << fileName <<
                                         " fetched from server. in" << ms <<" ms"<< std::endl;

            if (objectType==ARCHIVE && readResult.validArchive())
            {
                // attach the socket istream to the archive to keep it alive.
                osgDB::Archive* archive = readResult.getArchive();
                archive->setUserData(sio.get());
            }

            if( !localCacheDir.empty() && cacheMode & Write )
            {
                std::string cacheFile = localCacheDir + '/' + fileName;
                if( osgDB::makeDirectoryForFile( cacheFile ) )
                {

                    switch(objectType)
                    {
                    case(OBJECT): osgDB::writeObjectFile( *(readResult.getObject()), cacheFile );
                    case(IMAGE): osgDB::writeImageFile( *(readResult.getImage()), cacheFile );
                    case(HEIGHTFIELD): osgDB::writeHeightFieldFile( *(readResult.getHeightField()), cacheFile );
                    case(NODE): osgDB::writeNodeFile( *(readResult.getNode()), cacheFile );;
                    default: break;
                    }

                    osg::notify(osg::DEBUG_INFO) << "osgPlugin .net: " << fileName <<
                                         " stored to local cache." << std::endl;
                }
            }

            return readResult;
        }

};

osgDB::RegisterReaderWriterProxy<NetReader> g_netReader_Proxy;

<|endoftext|>


<commit_before>/*
 * File:   main.cpp
 * Author: RedSpiderMkV
 *
 * Created on 11 November 2015, 21:38
 */

#include <iostream>
#include <string>
#include "Converter/DecimalConverter.h"
#include "Converter/HexadecimalConverter.h"
#include "Converter/BinaryConverter.h"

using namespace std;
using namespace NumberBaseConverter;
/*
 *
 */
int main(int argc, char* argv[])
{
    cout << "Hello world!" << endl;

    DecimalConverter newConverter;
    HexadecimalConverter hexConverter;
    BinaryConverter binConverter;

    string input = "0";
    while(input != "-1")
    {
        cin >> input;
        //cout << newConverter.ConvertToBinary(input) << "\t";
        //cout << newConverter.ConvertToHexadecimal(input) << endl;

        //cout << hexConverter.ConvertToBinary(input) << "\t";
        //cout << hexConverter.ConvertToDecimal(input) << endl;

        cout << binConverter.ConvertToDecimal(input) << "\t";
        cout << binConverter.ConvertToHexadecimal(input) << endl;
    }

    return 0;
} // end method

<commit_msg>main - taking input from command line<commit_after>/*
 * File:   main.cpp
 * Author: RedSpiderMkV
 *
 * Created on 11 November 2015, 21:38
 */

#include <iostream>
#include <string>
#include "Converter/DecimalConverter.h"
#include "Converter/HexadecimalConverter.h"
#include "Converter/BinaryConverter.h"

using namespace std;
using namespace NumberBaseConverter;

bool argumentCountValid(int argc)
{
    if(argc != 4)
    {
        cout << "Incorrect usage.  Usage:" << endl;
        cout << "bindechexconverter dec hex 10" << endl << endl;

        return false;
    } // end if

    return true;
} // end method

bool inputBaseValid(string inputBase)
{
    if(inputBase != "dec" && inputBase != "hex" && inputBase != "bin")
    {
        cout << "Specified input base is unrecognised: " << inputBase << endl;
        cout << "Can be dec, hex or bin" << endl << endl;

        return false;
    } // end if

    return true;
} // end method

bool outputBaseValid(string outputBase)
{
    if(outputBase != "dec" && outputBase != "hex" && outputBase != "bin")
    {
        cout << "Specified output base is unrecognised: " << outputBase << endl;
        cout << "Can be dec, hex or bin" << endl << endl;

        return false;
    } // end if

    return true;
} // end method

int main(int argc, char* argv[])
{
    if(!argumentCountValid(argc)
            || !inputBaseValid(string(argv[1]))
            || !outputBaseValid(string(argv[2])))
    {
        cout << "Conversion failed, exiting" << endl;

        return -1;
    } // end if

    DecimalConverter newConverter;
    HexadecimalConverter hexConverter;
    BinaryConverter binConverter;

    return 0;
} // end method

<|endoftext|>


<commit_before>#include "CommandRequest.h"

using namespace opencog;

CommandRequest::~CommandRequest() {
}

CommandRequest::CommandRequest(CallBackInterface *callBack, std::string &command, std::queue<std::string> &args) {
    this->callBackRequestor = callBack;
    this->command = command;
    this->args = args;
}

std::string CommandRequest::getType() {
    return "COMMAND_LINE";
}

void CommandRequest::setAnswer(std::string &commandOutput) {
    answer = commandOutput;
}

std::string CommandRequest::getCommand() {
    return command;
}

std::queue<std::string> CommandRequest::getArgs() {
    return args;
}

void CommandRequest::callBack() {
    callBackRequestor->callBack(answer);
}
<commit_msg>wrap long lines to fit 80 columns<commit_after>#include "CommandRequest.h"

using namespace opencog;

CommandRequest::~CommandRequest() {
}

CommandRequest::CommandRequest(CallBackInterface *callBack,
                               std::string &command,
                               std::queue<std::string> &args)
{
    this->callBackRequestor = callBack;
    this->command = command;
    this->args = args;
}

std::string CommandRequest::getType() {
    return "COMMAND_LINE";
}

void CommandRequest::setAnswer(std::string &commandOutput) {
    answer = commandOutput;
}

std::string CommandRequest::getCommand() {
    return command;
}

std::queue<std::string> CommandRequest::getArgs() {
    return args;
}

void CommandRequest::callBack() {
    callBackRequestor->callBack(answer);
}
<|endoftext|>


<commit_before><commit_msg>Updated max line length<commit_after><|endoftext|>


<commit_before>#pragma once

#include <gtest/gtest.h>
#include "twosum.hxx"

namespace {
  class TwoSumTest : public testing::Test
  {
  protected:
    TwoSumTest(void) {}
    virtual ~TwoSumTest(void) {}
    virtual void SetUp(void) {}
    virtual void TearDown(void) {}
  };

  TEST(TwoSumTest, TwoSum1)
  {
    auto actual = 0/*Solution{}.numTrees(1)*/;
    decltype(actual) expected = 1;

    EXPECT_EQ(expected, actual);
  }
}
<commit_msg>first unit test for twosum<commit_after>#pragma once

#include <vector>
#include <gtest/gtest.h>

#include "../../../../include/cpp/gtest-array.hxx"
#include "twosum.hxx"

using std::vector;

namespace {
  class TwoSumTest : public testing::Test
  {
  protected:
    TwoSumTest(void) {}
    virtual ~TwoSumTest(void) {}
    virtual void SetUp(void) {}
    virtual void TearDown(void) {}
  };

  TEST(TwoSumTest, TwoSum1)
  {
    vector<int> input{2, 7, 11, 15};
    auto actual = Solution{}.twoSum(input, 9);
    vector<int> expected{1, 2};

    EXPECT_TRUE(arrayMatch(expected, actual));
  }
}
<|endoftext|>


<commit_before>#include "process_based_isolation_module.hpp"

#include "foreach.hpp"

using std::cerr;
using std::cout;
using std::endl;
using std::list;
using std::make_pair;
using std::ostringstream;
using std::pair;
using std::queue;
using std::string;
using std::vector;

using boost::lexical_cast;
using boost::unordered_map;
using boost::unordered_set;

using namespace nexus;
using namespace nexus::internal;
using namespace nexus::internal::slave;

ProcessBasedIsolationModule::ProcessBasedIsolationModule(Slave* slave)
{
  this->slave = slave;
  reaper = new Reaper(this);
  Process::spawn(reaper);
}

ProcessBasedIsolationModule::~ProcessBasedIsolationModule()
{
  // We want to wait until the reaper has completed because it
  // accesses 'this' in order to make callbacks ... deleting 'this'
  // could thus lead to a seg fault!
  Process::post(reaper->getPID(), SHUTDOWN_REAPER);
  Process::wait(reaper);
  delete reaper;
}

void ProcessBasedIsolationModule::frameworkAdded(Framework* framework)
{
  pgids[framework->id] = -1;
  framework->executorStatus = "No executor running";
}

void ProcessBasedIsolationModule::frameworkRemoved(Framework* framework)
{
  pgids.erase(framework->id);
}

void ProcessBasedIsolationModule::startExecutor(Framework* framework)
{
  LOG(INFO) << "Starting executor for framework " << framework->id << ": "
            << framework->executorInfo.uri;
  CHECK(pgids[framework->id] == -1);

  pid_t pid;
  if ((pid = fork()) == -1)
    PLOG(FATAL) << "Failed to fork to launch new executor";

  if (pid) {
    // In parent process, record the pgid for killpg later.
    LOG(INFO) << "Started executor, OS pid = " << pid;
    pgids[framework->id] = pid;
    framework->executorStatus = "PID: " + lexical_cast<string>(pid);
  } else {
    // In child process, make cleanup easier.
    if (setpgid(0, 0) < 0)
      PLOG(FATAL) << "Failed to put executor in own process group";
//     if ((pid = setsid()) == -1)
//       PLOG(FATAL) << "Failed to put executor in own session";

    createExecutorLauncher(framework)->run();
  }
}

void ProcessBasedIsolationModule::killExecutor(Framework* fw)
{
  if (pgids[fw->id] != -1) {
    // TODO(benh): Consider sending a SIGTERM, then after so much time
    // if it still hasn't exited do a SIGKILL (can use a libprocess
    // process for this).
    LOG(INFO) << "Sending SIGKILL to gpid " << pgids[fw->id];
    killpg(pgids[fw->id], SIGKILL);
    pgids[fw->id] = -1;
    fw->executorStatus = "No executor running";
    // TODO(benh): Kill all of the process's descendants? Perhaps
    // create a new libprocess process that continually tries to kill
    // all the processes that are a descendant of the executor, trying
    // to kill the executor last ... maybe this is just too much of a
    // burden?
  }
}

void ProcessBasedIsolationModule::resourcesChanged(Framework* fw)
{
  // Do nothing; subclasses may override this.
}

ExecutorLauncher* ProcessBasedIsolationModule::createExecutorLauncher(Framework* fw)
{
  return new ExecutorLauncher(fw->id, fw->executorInfo.uri, fw->user,
			      slave->getWorkDirectory(fw->id),
			      slave->self(), !slave->local);
}

ProcessBasedIsolationModule::Reaper::Reaper(ProcessBasedIsolationModule* m)
  : module(m)
{}

void ProcessBasedIsolationModule::Reaper::operator () ()
{
  link(module->slave->getPID());
  while (true) {
    switch (receive(1)) {
    case PROCESS_TIMEOUT: {
      // Check whether any child process has exited
      pid_t pid;
      int status;
      if ((pid = waitpid((pid_t) -1, &status, WNOHANG)) > 0) {
	foreachpair (FrameworkID fid, pid_t& pgid, module->pgids) {
	  if (pgid == pid) {
	    // Kill the process group to clean up the tasks.
	    LOG(INFO) << "Sending SIGKILL to gpid " << pgid;
	    killpg(pgid, SIGKILL);
	    module->pgids[fid] = -1;
	    LOG(INFO) << "Telling slave of lost framework " << fid;
	    // TODO(benh): This is broken if/when libprocess is parallel!
	    module->slave->executorExited(fid, status);
	    break;
	  }
	}
      }
      break;
    }
    case SHUTDOWN_REAPER:
    case PROCESS_EXIT:
      return;
    }
  }
}

<commit_msg>Using sessions instead of process groups.<commit_after>#include "process_based_isolation_module.hpp"

#include "foreach.hpp"

using std::cerr;
using std::cout;
using std::endl;
using std::list;
using std::make_pair;
using std::ostringstream;
using std::pair;
using std::queue;
using std::string;
using std::vector;

using boost::lexical_cast;
using boost::unordered_map;
using boost::unordered_set;

using namespace nexus;
using namespace nexus::internal;
using namespace nexus::internal::slave;

ProcessBasedIsolationModule::ProcessBasedIsolationModule(Slave* slave)
{
  this->slave = slave;
  reaper = new Reaper(this);
  Process::spawn(reaper);
}

ProcessBasedIsolationModule::~ProcessBasedIsolationModule()
{
  // We want to wait until the reaper has completed because it
  // accesses 'this' in order to make callbacks ... deleting 'this'
  // could thus lead to a seg fault!
  Process::post(reaper->getPID(), SHUTDOWN_REAPER);
  Process::wait(reaper);
  delete reaper;
}

void ProcessBasedIsolationModule::frameworkAdded(Framework* framework)
{
  pgids[framework->id] = -1;
  framework->executorStatus = "No executor running";
}

void ProcessBasedIsolationModule::frameworkRemoved(Framework* framework)
{
  pgids.erase(framework->id);
}

void ProcessBasedIsolationModule::startExecutor(Framework* framework)
{
  LOG(INFO) << "Starting executor for framework " << framework->id << ": "
            << framework->executorInfo.uri;
  CHECK(pgids[framework->id] == -1);

  pid_t pid;
  if ((pid = fork()) == -1)
    PLOG(FATAL) << "Failed to fork to launch new executor";

  if (pid) {
    // In parent process, record the pgid for killpg later.
    LOG(INFO) << "Started executor, OS pid = " << pid;
    pgids[framework->id] = pid;
    framework->executorStatus = "PID: " + lexical_cast<string>(pid);
  } else {
    // In child process, make cleanup easier.
//     if (setpgid(0, 0) < 0)
//       PLOG(FATAL) << "Failed to put executor in own process group";
    if ((pid = setsid()) == -1)
      PLOG(FATAL) << "Failed to put executor in own session";

    createExecutorLauncher(framework)->run();
  }
}

void ProcessBasedIsolationModule::killExecutor(Framework* fw)
{
  if (pgids[fw->id] != -1) {
    // TODO(benh): Consider sending a SIGTERM, then after so much time
    // if it still hasn't exited do a SIGKILL (can use a libprocess
    // process for this).
    LOG(INFO) << "Sending SIGKILL to gpid " << pgids[fw->id];
    killpg(pgids[fw->id], SIGKILL);
    pgids[fw->id] = -1;
    fw->executorStatus = "No executor running";
    // TODO(benh): Kill all of the process's descendants? Perhaps
    // create a new libprocess process that continually tries to kill
    // all the processes that are a descendant of the executor, trying
    // to kill the executor last ... maybe this is just too much of a
    // burden?
  }
}

void ProcessBasedIsolationModule::resourcesChanged(Framework* fw)
{
  // Do nothing; subclasses may override this.
}

ExecutorLauncher* ProcessBasedIsolationModule::createExecutorLauncher(Framework* fw)
{
  return new ExecutorLauncher(fw->id, fw->executorInfo.uri, fw->user,
			      slave->getWorkDirectory(fw->id),
			      slave->self(), !slave->local);
}

ProcessBasedIsolationModule::Reaper::Reaper(ProcessBasedIsolationModule* m)
  : module(m)
{}

void ProcessBasedIsolationModule::Reaper::operator () ()
{
  link(module->slave->getPID());
  while (true) {
    switch (receive(1)) {
    case PROCESS_TIMEOUT: {
      // Check whether any child process has exited
      pid_t pid;
      int status;
      if ((pid = waitpid((pid_t) -1, &status, WNOHANG)) > 0) {
	foreachpair (FrameworkID fid, pid_t& pgid, module->pgids) {
	  if (pgid == pid) {
	    // Kill the process group to clean up the tasks.
	    LOG(INFO) << "Sending SIGKILL to gpid " << pgid;
	    killpg(pgid, SIGKILL);
	    module->pgids[fid] = -1;
	    LOG(INFO) << "Telling slave of lost framework " << fid;
	    // TODO(benh): This is broken if/when libprocess is parallel!
	    module->slave->executorExited(fid, status);
	    break;
	  }
	}
      }
      break;
    }
    case SHUTDOWN_REAPER:
    case PROCESS_EXIT:
      return;
    }
  }
}

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013-2016 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt)
 *
 * This file is part of vanillacoin.
 *
 * vanillacoin is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef COIN_INVENTORY_VECTOR_HPP
#define COIN_INVENTORY_VECTOR_HPP

#include <cstdint>

#include <coin/protocol.hpp>
#include <coin/sha256.hpp>

namespace coin {

    class data_buffer;
    class db_tx;

    /**
     * The inventory vector structure.
     * type uint32_t Identifies the object type linked to this inventory.
     * hash char[32] Hash of the object.
     */
    class inventory_vector
    {
        public:

            /**
             * The types.
             * @param type_error Any data of with this number may be ignored.
             * @param type_msg_tx Hash is related to a transaction.
             * @param type_msg_block Hash is related to a data block.
             * @param type_msg_ztlock Hash is related to a zerotime lock.
             * @param type_msg_ztvote Hash is related to zerotime vote.
             * @param type_msg_ivote Hash is related to incentive vote.
             */
            typedef enum
            {
                type_error,
                type_msg_tx,
                type_msg_block,
                type_msg_ztlock,
                type_msg_ztvote,
                type_msg_ivote,
            } type_t;

            /**
             * Constructor
             */
            inventory_vector();

            /**
             * Constructor
             */
            inventory_vector(const type_t & type, const sha256 & hash);

            /**
             * Constructor
             */
            inventory_vector(
                const std::string & type, const sha256 & hash
            );

            /**
             * Encodes
             * buffer The data_buffer.
             */
            bool encode(data_buffer & buffer);

            /**
             * Decodes
             * buffer The data_buffer.
             */
            bool decode(data_buffer & buffer);

            /**
             * The type.
             */
            const type_t & type() const;

            /**
             * The hash.
             */
            const sha256 & hash() const;

            /**
             * If true it is of a known type.
             */
            bool is_know_type() const;

            /**
             * The command.
             */
            const std::string command() const;

            /**
             * Returns the string representation.
             */
            const std::string to_string() const;

            /**
             * Checks if we already have the transaction.
             * @param tx_db The transaction database.
             * @param inv The inventory_vector.
             */
            static bool already_have(
                db_tx & tx_db, const inventory_vector & inv
            );

            /**
             * operator ==
             */
            friend bool operator == (
                const inventory_vector & a, const inventory_vector & b
                )
            {
                return a.m_type == b.m_type && a.m_hash == b.m_hash;
            }

            /**
             * operator <
             */
            friend bool operator < (
                const inventory_vector & a, const inventory_vector & b
                )
            {
                return
                    a.m_type < b.m_type ||
                    (a.m_type == b.m_type && a.m_hash < b.m_hash)
                ;
            }

        private:

            /**
             * The type.
             */
            type_t m_type;

            /**
             * The hash.
             */
            sha256 m_hash;

        protected:

            // ...
    };

} // namespace coin

#endif // COIN_INVENTORY_VECTOR_HPP
<commit_msg>0.4.5 partial merge<commit_after>/*
 * Copyright (c) 2013-2016 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt)
 *
 * This file is part of vanillacoin.
 *
 * vanillacoin is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef COIN_INVENTORY_VECTOR_HPP
#define COIN_INVENTORY_VECTOR_HPP

#include <cstdint>

#include <coin/protocol.hpp>
#include <coin/sha256.hpp>

namespace coin {

    class data_buffer;
    class db_tx;

    /**
     * The inventory vector structure.
     * type uint32_t Identifies the object type linked to this inventory.
     * hash char[32] Hash of the object.
     */
    class inventory_vector
    {
        public:

            /**
             * The types.
             * @param type_error Any data of with this number may be ignored.
             * @param type_msg_tx Hash is related to a transaction.
             * @param type_msg_block Hash is related to a data block.
             * @param type_msg_filtered_block Hash is related to a filtered
             * block.
             * @param type_msg_ztlock Hash is related to a zerotime lock.
             * @param type_msg_ztvote Hash is related to zerotime vote.
             * @param type_msg_ivote Hash is related to incentive vote.
             */
            typedef enum
            {
                type_error,
                type_msg_tx,
                type_msg_block,
#if 0 /* BIP-0037 */
                type_msg_filtered_block,
#endif
                type_msg_ztlock,
                type_msg_ztvote,
                type_msg_ivote,
            } type_t;

            /**
             * Constructor
             */
            inventory_vector();

            /**
             * Constructor
             */
            inventory_vector(const type_t & type, const sha256 & hash);

            /**
             * Constructor
             */
            inventory_vector(
                const std::string & type, const sha256 & hash
            );

            /**
             * Encodes
             * buffer The data_buffer.
             */
            bool encode(data_buffer & buffer);

            /**
             * Decodes
             * buffer The data_buffer.
             */
            bool decode(data_buffer & buffer);

            /**
             * The type.
             */
            const type_t & type() const;

            /**
             * The hash.
             */
            const sha256 & hash() const;

            /**
             * If true it is of a known type.
             */
            bool is_know_type() const;

            /**
             * The command.
             */
            const std::string command() const;

            /**
             * Returns the string representation.
             */
            const std::string to_string() const;

            /**
             * Checks if we already have the transaction.
             * @param tx_db The transaction database.
             * @param inv The inventory_vector.
             */
            static bool already_have(
                db_tx & tx_db, const inventory_vector & inv
            );

            /**
             * operator ==
             */
            friend bool operator == (
                const inventory_vector & a, const inventory_vector & b
                )
            {
                return a.m_type == b.m_type && a.m_hash == b.m_hash;
            }

            /**
             * operator <
             */
            friend bool operator < (
                const inventory_vector & a, const inventory_vector & b
                )
            {
                return
                    a.m_type < b.m_type ||
                    (a.m_type == b.m_type && a.m_hash < b.m_hash)
                ;
            }

        private:

            /**
             * The type.
             */
            type_t m_type;

            /**
             * The hash.
             */
            sha256 m_hash;

        protected:

            // ...
    };

} // namespace coin

#endif // COIN_INVENTORY_VECTOR_HPP
<|endoftext|>


<commit_before>#pragma once

/*
   A generic forward checker for properties
 */

#include <crab/common/types.hpp>
#include <crab/common/stats.hpp>
#include <crab/checkers/base_property.hpp>
#include <crab/analysis/fwd_analyzer.hpp>
#include <crab/analysis/inter_fwd_analyzer.hpp>

namespace crab {

  namespace checker {

  template<typename Analyzer>
  class checker {
    /*
      The checker propagates the invariants that hold at the entry of
      each block (assume forward analysis) to each program point while
      checking for the properties. The analysis results are shared by
      all the property checkers so the analysis needs to be run only
      once.
     */

    checker(const checker<Analyzer>& other); // non construction copyable
    checker<Analyzer>& operator=(const checker<Analyzer>& other); // non-copyable

   public:

    typedef boost::shared_ptr<property_checker<Analyzer>> prop_checker_ptr;
    typedef std::vector<prop_checker_ptr> prop_checker_vector;

   protected:

    prop_checker_vector m_checkers;

   public:

    checker(prop_checker_vector checkers): m_checkers(checkers) { }

    virtual ~checker(){ }

    virtual void run() = 0;

    virtual void show(crab_os& o) {
      for (auto prop_checker: m_checkers) {
        prop_checker->write(o);
      }
    }

    // merge all the databases in one: useful for crab clients
    virtual checks_db get_all_checks() const {
      checks_db res;
      for (auto prop_checker: m_checkers) {
        res += prop_checker->get_db();
      }
      return res;
    }

  };

  template<typename Analyzer>
  class intra_checker: public checker<Analyzer> {
   public:

    typedef checker<Analyzer> base_checker_t;
    using typename base_checker_t::prop_checker_ptr;
    using typename base_checker_t::prop_checker_vector;

   private:

    typedef typename Analyzer::cfg_t cfg_t;
    typedef typename cfg_t::statement_t statement_t;
    typedef typename Analyzer::abs_dom_t abs_dom_t;
    typedef typename Analyzer::abs_tr_t abs_tr_t;

    Analyzer& m_analyzer;

   public:

    intra_checker(Analyzer& analyzer, prop_checker_vector checkers)
      : base_checker_t(checkers)
      , m_analyzer(analyzer) { }

    virtual void run() override {
      CRAB_VERBOSE_IF(1, crab::outs() << "Started property checker.\n";);
      crab::ScopedCrabStats __st__("Checker");
      cfg_t cfg = m_analyzer.get_cfg();

      // In some cases, the analyzer might know that an assertion is
      // safe but it cannot be proven by propagating only
      // invariants. This is common if the analyzer is based on a
      // forward/backward refinement loop.
      std::set<const statement_t*> safe_assertions;
      m_analyzer.get_safe_assertions(safe_assertions);

      for (auto &bb: cfg) {
        for (auto checker: this->m_checkers) {
          crab::ScopedCrabStats __st__("Checker." + checker->get_property_name());
          abs_dom_t inv = m_analyzer[bb.label()];
	  boost::shared_ptr<abs_tr_t> abs_tr = m_analyzer.get_abs_transformer(&inv);
          // propagate forward the invariants from the block entry
          // while checking the property
          checker->set(&*abs_tr, safe_assertions);
          for (auto &stmt: bb) {
	    stmt.accept(&*checker);
	  }
        }
      }
      CRAB_VERBOSE_IF(1, crab::outs() << "Finished property checker.\n";);
    }
  };

  template< typename Analyzer>
  class inter_checker: public checker<Analyzer> {
   public:

    typedef checker<Analyzer> base_checker_t;
    using typename base_checker_t::prop_checker_ptr;
    using typename base_checker_t::prop_checker_vector;

   private:

    typedef typename Analyzer::cg_t cg_t;
    typedef typename Analyzer::cfg_t cfg_t;
    typedef typename Analyzer::abs_dom_t abs_dom_t;
    typedef typename Analyzer::abs_tr_t abs_tr_t;

    Analyzer& m_analyzer;

   public:

    inter_checker(Analyzer& analyzer, prop_checker_vector checkers)
        : base_checker_t(checkers), m_analyzer(analyzer) { }

    virtual void run() override {
      CRAB_VERBOSE_IF(1, crab::outs() << "Started property checker.\n";);
      crab::ScopedCrabStats __st__("Checker");
      cg_t& cg = m_analyzer.get_call_graph();
      for (auto &v: boost::make_iterator_range(vertices(cg))) {
        cfg_t cfg = v.get_cfg();

        for (auto &bb: cfg) {
          for (auto checker: this->m_checkers) {
            crab::ScopedCrabStats __st__("Checker." + checker->get_property_name());
            abs_dom_t inv = m_analyzer.get_pre(cfg, bb.label());
	    boost::shared_ptr<abs_tr_t> abs_tr = m_analyzer.get_abs_transformer(&inv);
            // propagate forward the invariants from the block entry
            // while checking the property
            checker->set(&*abs_tr);
            for (auto &stmt: bb) {
              stmt.accept(&*checker);
	    }
          }
        }
      }
      CRAB_VERBOSE_IF(1, crab::outs() << "Finished property checker.";);

    }
  };

  } // end namespace
} // end namespace
<commit_msg>Forgot from last commit<commit_after>#pragma once

/*
   A generic forward checker for properties
 */

#include <crab/common/types.hpp>
#include <crab/common/stats.hpp>
#include <crab/checkers/base_property.hpp>
#include <crab/analysis/fwd_analyzer.hpp>
#include <crab/analysis/inter_fwd_analyzer.hpp>

namespace crab {

  namespace checker {

  template<typename Analyzer>
  class checker {
    /*
      The checker propagates the invariants that hold at the entry of
      each block (assume forward analysis) to each program point while
      checking for the properties. The analysis results are shared by
      all the property checkers so the analysis needs to be run only
      once.
     */

    checker(const checker<Analyzer>& other); // non construction copyable
    checker<Analyzer>& operator=(const checker<Analyzer>& other); // non-copyable

   public:

    typedef boost::shared_ptr<property_checker<Analyzer>> prop_checker_ptr;
    typedef std::vector<prop_checker_ptr> prop_checker_vector;

   protected:

    prop_checker_vector m_checkers;

   public:

    checker(prop_checker_vector checkers): m_checkers(checkers) {}

    virtual ~checker() {}

    virtual void run() = 0;

    virtual void show(crab_os& o) {
      for (auto prop_checker: m_checkers) {
        prop_checker->write(o);
      }
    }

    // merge all the databases in one: useful for crab clients
    virtual checks_db get_all_checks() const {
      checks_db res;
      for (auto prop_checker: m_checkers) {
        res += prop_checker->get_db();
      }
      return res;
    }

  };

  template<typename Analyzer>
  class intra_checker: public checker<Analyzer> {
   public:

    typedef checker<Analyzer> base_checker_t;
    using typename base_checker_t::prop_checker_ptr;
    using typename base_checker_t::prop_checker_vector;

   private:

    typedef typename Analyzer::cfg_t cfg_t;
    typedef typename cfg_t::statement_t statement_t;
    typedef typename Analyzer::abs_dom_t abs_dom_t;
    typedef typename Analyzer::abs_tr_t abs_tr_t;

    Analyzer& m_analyzer;

   public:

    intra_checker(Analyzer& analyzer, prop_checker_vector checkers)
      : base_checker_t(checkers)
      , m_analyzer(analyzer) { }

    virtual void run() override {
      CRAB_VERBOSE_IF(1, crab::outs() << "Started property checker.\n";);
      crab::ScopedCrabStats __st__("Checker");
      cfg_t cfg = m_analyzer.get_cfg();

      // In some cases, the analyzer might know that an assertion is
      // safe but it cannot be proven by propagating only
      // invariants. This is possible if the analyzer is based on a
      // forward/backward refinement loop.
      std::set<const statement_t*> safe_assertions;
      m_analyzer.get_safe_assertions(safe_assertions);

      for (auto &bb: cfg) {
        for (auto checker: this->m_checkers) {
          crab::ScopedCrabStats __st__("Checker." + checker->get_property_name());
          abs_dom_t inv = m_analyzer[bb.label()];
	  boost::shared_ptr<abs_tr_t> abs_tr = m_analyzer.get_abs_transformer(&inv);
          // propagate forward the invariants from the block entry
          // while checking the property
          checker->set(&*abs_tr, safe_assertions);
          for (auto &stmt: bb) {
	    stmt.accept(&*checker);
	  }
        }
      }
      CRAB_VERBOSE_IF(1, crab::outs() << "Finished property checker.\n";);
    }
  };

  template< typename Analyzer>
  class inter_checker: public checker<Analyzer> {
   public:

    typedef checker<Analyzer> base_checker_t;
    using typename base_checker_t::prop_checker_ptr;
    using typename base_checker_t::prop_checker_vector;

   private:

    typedef typename Analyzer::cg_t cg_t;
    typedef typename Analyzer::cfg_t cfg_t;
    typedef typename cfg_t::statement_t statement_t;
    typedef typename Analyzer::abs_dom_t abs_dom_t;
    typedef typename Analyzer::abs_tr_t abs_tr_t;

    Analyzer& m_analyzer;

   public:

    inter_checker(Analyzer& analyzer, prop_checker_vector checkers)
        : base_checker_t(checkers), m_analyzer(analyzer) { }

    virtual void run() override {
      CRAB_VERBOSE_IF(1, crab::outs() << "Started property checker.\n";);
      crab::ScopedCrabStats __st__("Checker");
      cg_t& cg = m_analyzer.get_call_graph();
      for (auto &v: boost::make_iterator_range(vertices(cg))) {
        cfg_t cfg = v.get_cfg();

        for (auto &bb: cfg) {
	  // the forward+backward analyzer only works for
	  // intra-procedural analysis.
	  std::set<const statement_t*> safe_assertions;
          for (auto checker: this->m_checkers) {
            crab::ScopedCrabStats __st__("Checker." + checker->get_property_name());
            abs_dom_t inv = m_analyzer.get_pre(cfg, bb.label());
	    boost::shared_ptr<abs_tr_t> abs_tr = m_analyzer.get_abs_transformer(&inv);
            // propagate forward the invariants from the block entry
            // while checking the property
            checker->set(&*abs_tr, safe_assertions);
            for (auto &stmt: bb) {
              stmt.accept(&*checker);
	    }
          }
        }
      }
      CRAB_VERBOSE_IF(1, crab::outs() << "Finished property checker.";);

    }
  };

  } // end namespace
} // end namespace
<|endoftext|>