text:
/*=============================================================================
    Copyright (c) 2001-2011 Hartmut Kaiser

    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)
==============================================================================*/
#if !defined(BOOST_SPIRIT_STREAM_MAY_05_2007_1228PM)
#define BOOST_SPIRIT_STREAM_MAY_05_2007_1228PM

#if defined(_MSC_VER)
#pragma once
#endif

#include <boost/spirit/home/qi/detail/string_parse.hpp>
#include <boost/spirit/home/qi/stream/detail/match_manip.hpp>
#include <boost/spirit/home/support/detail/hold_any.hpp>
#include <boost/proto/traits.hpp>
#include <istream>

///////////////////////////////////////////////////////////////////////////////
namespace boost { namespace spirit
{
    ///////////////////////////////////////////////////////////////////////////
    // Enablers
    ///////////////////////////////////////////////////////////////////////////
    template <>
    struct use_terminal<qi::domain, tag::stream> // enables stream
      : mpl::true_ {};

    template <>
    struct use_terminal<qi::domain, tag::wstream> // enables wstream
      : mpl::true_ {};
}}

///////////////////////////////////////////////////////////////////////////////
namespace boost { namespace spirit { namespace qi
{
#ifndef BOOST_SPIRIT_NO_PREDEFINED_TERMINALS
    using spirit::stream;
    using spirit::wstream;
#endif
    using spirit::stream_type;
    using spirit::wstream_type;

namespace detail
{
    template <typename Iterator>
    struct psbuf
      : std::basic_streambuf<typename std::iterator_traits<Iterator>::value_type>
    {
        psbuf(Iterator first_, Iterator const& last_)
          : first(first_), last(last_) {}

        // silence MSVC warning C4512: assignment operator could not be generated
        BOOST_DELETED_FUNCTION(psbuf& operator=(psbuf const&))

    protected:
        typename psbuf::int_type underflow() BOOST_OVERRIDE
        {
            return first == last ? psbuf::traits_type::eof()
                                 : psbuf::traits_type::to_int_type(*first);
        }

        typename psbuf::int_type uflow() BOOST_OVERRIDE
        {
            return first == last ? psbuf::traits_type::eof()
                                 : psbuf::traits_type::to_int_type(*first++);
        }

    public:
        Iterator first;
        Iterator const& last;
    };
}

    template <typename Char = char, typename T = spirit::basic_hold_any<char> >
    struct stream_parser
      : primitive_parser<stream_parser<Char, T> >
    {
        template <typename Context, typename Iterator>
        struct attribute
        {
            typedef T type;
        };

        template <typename Iterator, typename Context
          , typename Skipper, typename Attribute>
        bool parse(Iterator& first, Iterator const& last
          , Context& /*context*/, Skipper const& skipper
          , Attribute& attr_) const
        {
            qi::skip_over(first, last, skipper);

            detail::psbuf<Iterator> pseudobuf(first, last);
            std::basic_istream<Char> in(&pseudobuf);
            in >> attr_;                        // use existing operator>>()

            // advance the iterator if everything is ok
            if (in) {
                first = pseudobuf.first;
                return true;
            }

            return false;
        }

        template <typename Context>
        info what(Context& /*context*/) const
        {
            return info("stream");
        }
    };

    template <typename T, typename Char = char>
    struct typed_stream
      : proto::terminal<stream_parser<Char, T> >::type
    {
    };

    ///////////////////////////////////////////////////////////////////////////
    // Parser generators: make_xxx function (objects)
    ///////////////////////////////////////////////////////////////////////////
    template <typename Char>
    struct make_stream
    {
        typedef stream_parser<Char> result_type;
        result_type operator()(unused_type, unused_type) const
        {
            return result_type();
        }
    };

    template <typename Modifiers>
    struct make_primitive<tag::stream, Modifiers> : make_stream<char> {};

    template <typename Modifiers>
    struct make_primitive<tag::wstream, Modifiers> : make_stream<wchar_t> {};
}}}

#endif


text:
#include "IndexBundleActivator.h"
#include <bundles/mining/MiningSearchService.h>

#include <common/SFLogger.h>
#include <common/Utilities.h>
#include <index-manager/InvertedIndexManager.h>
#include <index-manager/ZambeziIndexManager.h>
#include <index-manager/zambezi-manager/ZambeziManager.h>
#include <search-manager/SearchFactory.h>
#include <search-manager/SearchManager.h>
#include <search-manager/QueryPruneFactory.h>
#include <ranking-manager/RankingManager.h>
#include <document-manager/DocumentManager.h>
#include <la-manager/LAManager.h>
#include <la-manager/LAPool.h>
#include <la-manager/AttrTokenizeWrapper.h>
#include <la-manager/TitlePCAWrapper.h>
#include <aggregator-manager/SearchMerger.h>
#include <aggregator-manager/SearchWorker.h>
#include <aggregator-manager/IndexWorker.h>
#include <node-manager/MasterManagerBase.h>
#include <node-manager/Sf1rTopology.h>
#include <node-manager/RecoveryChecker.h>
#include <util/singleton.h>

#include <boost/filesystem.hpp>

#include <memory> // for auto_ptr

namespace bfs = boost::filesystem;
using namespace izenelib::util;

namespace sf1r
{

using namespace izenelib::osgi;
IndexBundleActivator::IndexBundleActivator()
    : miningSearchTracker_(0)
    , miningTaskTracker_(0)
    , context_(0)
    , searchService_(0)
    , searchServiceReg_(0)
    , taskService_(0)
    , taskServiceReg_(0)
    , config_(0)
    , zambeziManager_(NULL)
{
}

IndexBundleActivator::~IndexBundleActivator()
{
}

void IndexBundleActivator::start( IBundleContext::ConstPtr context )
{
    context_ = context;

    boost::shared_ptr<BundleConfiguration> bundleConfigPtr = context->getBundleConfig();
    config_ = static_cast<IndexBundleConfiguration*>(bundleConfigPtr.get());
    init_();

    Properties props;
    props.put( "collection", config_->collectionName_);
    searchServiceReg_ = context->registerService( "IndexSearchService", searchService_, props );
    taskServiceReg_ = context->registerService( "IndexTaskService", taskService_, props );
    miningSearchTracker_ = new ServiceTracker( context, "MiningSearchService", this );
    miningSearchTracker_->startTracking();
    miningTaskTracker_ = new ServiceTracker( context, "MiningTaskService", this );
    miningTaskTracker_->startTracking();
}

void IndexBundleActivator::stop( IBundleContext::ConstPtr context )
{
    if (config_->isNormalSchemaEnable_)
    {
        invertedIndexManager_->flush(false);
    }

    if (config_->isZambeziSchemaEnable_)
    {
        zambeziIndexManager_->postProcessForAPI();
    }

    if(miningSearchTracker_)
    {
        miningSearchTracker_->stopTracking();
        delete miningSearchTracker_;
        miningSearchTracker_ = 0;
    }
    if(miningTaskTracker_)
    {
        miningTaskTracker_->stopTracking();
        delete miningTaskTracker_;
        miningTaskTracker_ = 0;
    }

    if(searchServiceReg_)
    {
        searchServiceReg_->unregister();
        delete searchServiceReg_;
        delete searchService_;
        searchServiceReg_ = 0;
        searchService_ = 0;
    }
    if(taskServiceReg_)
    {
        taskServiceReg_->unregister();
        delete taskServiceReg_;
        delete taskService_;
        taskServiceReg_ = 0;
        taskService_ = 0;
    }

    MasterManagerBase::get()->unregisterAggregator(searchAggregator_);
    MasterManagerBase::get()->unregisterAggregator(ro_searchAggregator_, true);
    MasterManagerBase::get()->unregisterAggregator(indexAggregator_);

    if (zambeziManager_)
    {
        delete zambeziManager_;
    }
    // TODO flush and delete
}

bool IndexBundleActivator::addingService( const ServiceReference& ref )
{
    if ( ref.getServiceName() == "MiningSearchService" )
    {
        Properties props = ref.getServiceProperties();
        if ( props.get( "collection" ) == config_->collectionName_)
        {
            MiningSearchService* service = reinterpret_cast<MiningSearchService*> ( const_cast<IService*>(ref.getService()) );
            cout << "[IndexBundleActivator#addingService] Calling MiningSearchService..." << endl;
            searchService_->searchWorker_->miningManager_ = service->GetMiningManager();
            searchService_->searchMerger_->miningManager_ = service->GetMiningManager();

            searchService_->searchWorker_->queryPruneFactory_->init(searchService_->searchWorker_->miningManager_);

            searchManager_->setMiningManager(service->GetMiningManager());
            return true;
        }
        else
        {
            return false;
        }
    }
    else if ( ref.getServiceName() == "MiningTaskService" )
    {
        Properties props = ref.getServiceProperties();
        if ( props.get( "collection" ) == config_->collectionName_)
        {
            MiningTaskService* service = reinterpret_cast<MiningTaskService*> ( const_cast<IService*>(ref.getService()) );
            cout << "[IndexBundleActivator#addingService] Calling MiningTaskService..." << endl;
            taskService_->indexWorker_->miningTaskService_= service;
            return true;
        }
        else
        {
            return false;
        }
    }
    else if ( ref.getServiceName() == "ProductSearchService" )
    {
        Properties props = ref.getServiceProperties();
        if ( props.get( "collection" ) == config_->collectionName_)
        {
//             ProductSearchService* service = reinterpret_cast<ProductSearchService*> ( const_cast<IService*>(ref.getService()) );
            cout << "[IndexBundleActivator#addingService] Calling ProductSearchService..." << endl;
            // product index hook set in Product Bundle

            return true;
        }
        else
        {
            return false;
        }
    }
    else if ( ref.getServiceName() == "ProductTaskService" )
    {
        Properties props = ref.getServiceProperties();
        if ( props.get( "collection" ) == config_->collectionName_)
        {
            //ProductTaskService* service = reinterpret_cast<ProductTaskService*> ( const_cast<IService*>(ref.getService()) );
            cout << "[IndexBundleActivator#addingService] Calling ProductTaskService..." << endl;
            ///TODO
            return true;
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }
}

void IndexBundleActivator::removedService( const ServiceReference& ref )
{

}

bool IndexBundleActivator::init_()
{
    std::cout<<"["<<config_->collectionName_<<"]"<<"[IndexBundleActivator] open data directories.."<<std::endl;
    bool bOpenDataDir = openDataDirectories_();
    SF1R_ENSURE_INIT(bOpenDataDir);
    LOG(INFO)<<"["<<config_->collectionName_<<"]"<<"[IndexBundleActivator] working directory "<<currentCollectionDataName_<<std::endl;
    std::cout<<"["<<config_->collectionName_<<"]"<<"[IndexBundleActivator] open id manager.."<<std::endl;

    idManager_ = createIDManager_();
    SF1R_ENSURE_INIT(idManager_);

    laManager_ = createLAManager_();
    SF1R_ENSURE_INIT(laManager_);

    SF1R_ENSURE_INIT(initializeQueryManager_());

    std::cout<<"["<<config_->collectionName_<<"]"<<"[IndexBundleActivator] open document manager.."<<std::endl;
    documentManager_ = createDocumentManager_();
    SF1R_ENSURE_INIT(documentManager_);
    documentManager_->setZambeziConfig(config_->zambeziConfig_);

    /*
    Here, the NormalSchemaEnable must be true now, because the Schema must be used as a filter in documentSearch;
    Zambezi search now not support condition(filter) 2013.10.24;
    */
    if(config_->isNormalSchemaEnable_)
    {
        std::cout<<"["<<config_->collectionName_<<"]"<<"[IndexBundleActivator] open normal index manager.."<<std::endl;
        invertedIndexManager_ = createInvertedIndexManager_();
        SF1R_ENSURE_INIT(invertedIndexManager_);
    }

    std::cout<<"["<<config_->collectionName_<<"]"<<"[IndexBundleActivator] open ranking manager.."<<std::endl;
    rankingManager_ = createRankingManager_();
    SF1R_ENSURE_INIT(rankingManager_);

    if (config_->isZambeziSchemaEnable_)
    {
        if (!config_->zambeziConfig_.isEnable)
            return false;
        std::cout<<"["<<config_->collectionName_<<"]"<<"[IndexBundleActivator] open zambezi index manager.."<<std::endl;

        if (!createZambeziManager_())
            return false;
        zambeziIndexManager_ = createZambeziIndexManager_();
        SF1R_ENSURE_INIT(zambeziIndexManager_);
    }

    std::cout<<"["<<config_->collectionName_<<"]"<<"[IndexBundleActivator] open search manager.."<<std::endl;
    searchManager_ = createSearchManager_();
    SF1R_ENSURE_INIT(searchManager_);

    searchWorker_ = createSearchWorker_();
    SF1R_ENSURE_INIT(searchWorker_);

    searchAggregator_ = createSearchAggregator_(false);
    SF1R_ENSURE_INIT(searchAggregator_);

    if (MasterManagerBase::get()->isMasterEnabled())
    {
        ro_searchAggregator_ = createSearchAggregator_(true);
        SF1R_ENSURE_INIT(ro_searchAggregator_);
    }

    indexWorker_ = createIndexWorker_();
    SF1R_ENSURE_INIT(indexWorker_);

    std::cout<<"["<<config_->collectionName_<<"]"<<"[IndexBundleActivator] open index worker.."<<std::endl;
    // add all kinds of index that will support increment build.
    if (config_->isNormalSchemaEnable_)
        indexWorker_->getIncSupportedIndexManager().addIndex(invertedIndexManager_);

    indexWorker_->getIncSupportedIndexManager().setDocumentManager(documentManager_);

    if (config_->isZambeziSchemaEnable_)
        indexWorker_->getIncSupportedIndexManager().addIndex(zambeziIndexManager_);

    indexAggregator_ = createIndexAggregator_();
    SF1R_ENSURE_INIT(indexAggregator_);

    searchService_ = new IndexSearchService(config_);

    searchService_->searchAggregator_ = searchAggregator_;
    //if (MasterManagerBase::get()->isOnlyMaster())
    {
        searchService_->ro_searchAggregator_ = ro_searchAggregator_;
    }
    //else
    //{
    //    searchService_->ro_searchAggregator_ = searchAggregator_;
    //}
    searchService_->searchMerger_ = searchMerger_.get();
    searchService_->searchWorker_ = searchWorker_;
    searchService_->searchWorker_->laManager_ = laManager_;
    searchService_->searchWorker_->idManager_ = idManager_;
    searchService_->searchWorker_->documentManager_ = documentManager_;
    searchService_->searchWorker_->invertedIndexManager_ = invertedIndexManager_;
    //searchService_->searchWorker_->rankingManager_ = rankingManager_;
    searchService_->searchWorker_->searchManager_ = searchManager_;

    taskService_ = new IndexTaskService(config_);
    indexWorker_->sharding_strategy_ = taskService_->sharding_strategy_;
    searchMerger_->sharding_strategy_ = taskService_->sharding_strategy_;

    taskService_->indexAggregator_ = indexAggregator_;
    taskService_->indexWorker_ = indexWorker_;
    taskService_->indexWorker_->idManager_ = idManager_;
    //taskService_->indexWorker_->laManager_ = laManager_;
    taskService_->indexWorker_->documentManager_ = documentManager_;
    taskService_->indexWorker_->searchWorker_= searchWorker_;
    taskService_->indexWorker_->summarizer_.init(LAPool::getInstance()->getLangId(), idManager_);

    return true;
}

std::string IndexBundleActivator::getCurrentCollectionDataPath_() const
{
    return config_->collPath_.getCollectionDataPath()+"/"+currentCollectionDataName_;
}

std::string IndexBundleActivator::getCollectionDataPath_() const
{
    return config_->collPath_.getCollectionDataPath();
}

std::string IndexBundleActivator::getQueryDataPath_() const
{
    return config_->collPath_.getQueryDataPath();
}

bool IndexBundleActivator::openDataDirectories_()
{
    bfs::create_directories(config_->indexSCDPath());
    bfs::create_directories(config_->masterIndexSCDPath());
    bfs::create_directories(config_->rebuildIndexSCDPath());
    bfs::create_directories(config_->logSCDPath());

    std::vector<std::string>& directories = config_->collectionDataDirectories_;
    if( directories.size() == 0 )
    {
        LOG(ERROR)<<"no data dir config"<<std::endl;
        return false;
    }
    directoryRotator_.setCapacity(directories.size());
    std::vector<bfs::path> dirtyDirectories;
    typedef std::vector<std::string>::const_iterator iterator;
    for (iterator it = directories.begin(); it != directories.end(); ++it)
    {
        bfs::path dataDir = bfs::path( getCollectionDataPath_() ) / *it;
        if (!directoryRotator_.appendDirectory(dataDir))
        {
            std::string msg = dataDir.string() + " corrupted, delete it!";
            LOG(ERROR) <<msg <<endl;
            //clean the corrupt dir
            boost::filesystem::remove_all( dataDir );
            dirtyDirectories.push_back(dataDir);
            if (MasterManagerBase::get()->isDistributed())
            {
                RecoveryChecker::get()->setRollbackFlag(0);
                RecoveryChecker::forceExit("exit for corrupted collection data. please restart to start auto rollback.");
            }
        }
    }

    directoryRotator_.rotateToNewest();
    boost::shared_ptr<Directory> newest = directoryRotator_.currentDirectory();
    if (newest)
    {
        bfs::path p = newest->path();
        currentCollectionDataName_ = p.filename().string();
        config_->collPath_.setCurrCollectionDir(currentCollectionDataName_);
        std::vector<bfs::path>::iterator it = dirtyDirectories.begin();
        for( ; it != dirtyDirectories.end(); ++it)
            directoryRotator_.appendDirectory(*it);
        return true;
    }
    else
    {
        std::vector<bfs::path>::iterator it = dirtyDirectories.begin();
        for( ; it != dirtyDirectories.end(); ++it)
            directoryRotator_.appendDirectory(*it);

        directoryRotator_.rotateToNewest();
        boost::shared_ptr<Directory> dir = directoryRotator_.currentDirectory();
        if(dir)
        {
            currentCollectionDataName_ = dir->path().filename().string();
            config_->collPath_.setCurrCollectionDir(currentCollectionDataName_);
            return true;
        }
    }

    return false;
}

boost::shared_ptr<IDManager>
IndexBundleActivator::createIDManager_() const
{
    std::string dir = getCurrentCollectionDataPath_()+"/id/";
    boost::filesystem::create_directories(dir);

    boost::shared_ptr<IDManager> ret(
        new IDManager(dir)
    );

    return ret;
}

boost::shared_ptr<DocumentManager>
IndexBundleActivator::createDocumentManager_() const
{
    std::string dir = getCurrentCollectionDataPath_()+"/dm/";
    boost::filesystem::create_directories(dir);
    boost::shared_ptr<DocumentManager> ret(
        new DocumentManager(
            dir,
            config_->indexSchema_,
            config_->encoding_,
            config_->documentCacheNum_
        )
    );

    return ret;
}

boost::shared_ptr<InvertedIndexManager>
IndexBundleActivator::createInvertedIndexManager_() const
{
    std::string dir = getCurrentCollectionDataPath_()+"/index/";
    boost::filesystem::create_directories(dir);
    boost::shared_ptr<InvertedIndexManager> ret;

    ret.reset(new InvertedIndexManager(config_));
    if (ret)
    {
        IndexManagerConfig config(config_->indexConfig_);
        config.indexStrategy_.indexLocation_ = dir;

        IndexerCollectionMeta indexCollectionMeta;
        indexCollectionMeta.setName(config_->collectionName_);

        const IndexBundleSchema& indexSchema = config_->indexSchema_;
        for (IndexBundleSchema::const_iterator iter = indexSchema.begin(), iterEnd = indexSchema.end();
            iter != iterEnd; ++iter)
        {
            IndexerPropertyConfig indexerPropertyConfig(
                iter->getPropertyId(),
                iter->getName(),
                iter->isIndex(),
                iter->isAnalyzed(),
                iter->getusePerFilter()
            );
            indexerPropertyConfig.setIsFilter(iter->getIsFilter());
            indexerPropertyConfig.setIsMultiValue(iter->getIsMultiValue());
            indexerPropertyConfig.setIsStoreDocLen(iter->getIsStoreDocLen());
            PropertyDataType sf1r_type = iter->getType();
//             LOG(INFO)<<"Find property "<<iter->getName()<<","<<sf1r_type<<std::endl;
            izenelib::ir::indexmanager::PropertyType type;
            if(Utilities::convertPropertyDataType(iter->getName(), sf1r_type, type))
            {
//                 LOG(INFO)<<"Index get property "<<iter->getName()<<","<<type.which()<<std::endl;
                indexerPropertyConfig.setType(type);
            }
            indexCollectionMeta.addPropertyConfig(indexerPropertyConfig);
        }

        config.addCollectionMeta(indexCollectionMeta);

        std::map<std::string, unsigned int> collectionIdMapping;
        collectionIdMapping[config_->collectionName_] = 1;

        ret->setIndexManagerConfig(config, collectionIdMapping);
        ret->idManager_ = idManager_;
        ret->laManager_ = laManager_;
        ret->documentManager_ = documentManager_;
    }
    return ret;
}

boost::shared_ptr<RankingManager>
IndexBundleActivator::createRankingManager_() const
{
    boost::shared_ptr<RankingManager> ret(new RankingManager);
    ret->init(config_->rankingManagerConfig_.rankingConfigUnit_);

    typedef std::map<std::string, float>::const_iterator weight_map_iterator;
    PropertyConfig propertyConfigOut;
    for (weight_map_iterator it = config_->rankingManagerConfig_.propertyWeightMapByProperty_.begin(),
                                        itEnd = config_->rankingManagerConfig_.propertyWeightMapByProperty_.end();
          it != itEnd; ++it)
    {
        if (config_->getPropertyConfig(it->first, propertyConfigOut))
        {
            ret->setPropertyWeight(propertyConfigOut.getPropertyId(), it->second);
        }
    }
    return ret;
}

bool IndexBundleActivator::createZambeziManager_()
{
    if (config_->zambeziConfig_.hasAttrtoken &&
        !AttrTokenizeWrapper::get()->loadDictFiles(config_->zambeziConfig_.system_resource_path_ + "/dict/" + config_->zambeziConfig_.tokenPath))
    {
        LOG(ERROR) << "failed in AttrTokenizeWrapper load";
        return false;
    }

    if (!TitlePCAWrapper::get()->loadDictFiles(config_->zambeziConfig_.system_resource_path_ + "/dict/title_pca/"))
    {
        LOG(ERROR) << "failed in TitlePCAWrapper load";
        return false;
    }

    std::string dir = getCurrentCollectionDataPath_()+"/zambezi/";
    const bfs::path zambeziDir(dir);

    config_->zambeziConfig_.indexFilePath = dir + "index_bin";
    bfs::create_directories(zambeziDir);

    if (zambeziManager_) delete zambeziManager_;
    zambeziManager_ = new ZambeziManager(config_->zambeziConfig_);

    if (!zambeziManager_->open())
        return false;

    return true;
}

boost::shared_ptr<IIncSupportedIndex>
IndexBundleActivator::createZambeziIndexManager_() const
{
    boost::shared_ptr<IIncSupportedIndex> ret(new ZambeziIndexManager
                                             (config_->zambeziConfig_,
                                              zambeziManager_->getProperties(),
                                              zambeziManager_->getIndexMap(),
                                              zambeziManager_->getTokenizer(),
                                              documentManager_));
    return ret;
}

boost::shared_ptr<SearchManager>
IndexBundleActivator::createSearchManager_() const
{
    boost::shared_ptr<SearchManager> ret;

    if (documentManager_ && rankingManager_ && (invertedIndexManager_ || zambeziManager_))
    {

        SearchFactory factory(*config_,
                          documentManager_,
                          invertedIndexManager_,
                          rankingManager_,
                          zambeziManager_);
        ret.reset(new SearchManager(*config_, factory));
    }
    return ret;
}

boost::shared_ptr<LAManager>
IndexBundleActivator::createLAManager_() const
{
    boost::shared_ptr<LAManager> ret(new LAManager());
    std::string kma_path;
    LAPool::getInstance()->get_kma_path(kma_path);
    string temp = kma_path + "/stopword.txt";
    ret->loadStopDict( temp );
    return ret;
}

boost::shared_ptr<SearchWorker>
IndexBundleActivator::createSearchWorker_()
{
    boost::shared_ptr<SearchWorker> ret(new SearchWorker(config_));
    return ret;
}

boost::shared_ptr<SearchAggregator>
IndexBundleActivator::createSearchAggregator_(bool readonly)
{
    if (!searchMerger_)
        searchMerger_.reset(new SearchMerger());

    std::auto_ptr<SearchMergerProxy> mergerProxy(new SearchMergerProxy(searchMerger_.get()));
    searchMerger_->bindCallProxy(*mergerProxy);

    std::auto_ptr<SearchWorkerProxy> localWorkerProxy(new SearchWorkerProxy(searchWorker_.get()));
    searchWorker_->bindCallProxy(*localWorkerProxy);

    boost::shared_ptr<SearchAggregator> ret(
        new SearchAggregator(mergerProxy.get(), localWorkerProxy.get(),
            Sf1rTopology::getServiceName(Sf1rTopology::SearchService), config_->collectionName_));

    mergerProxy.release();
    localWorkerProxy.release();

    // workers will be detected and set by master node manager
    MasterManagerBase::get()->registerAggregator(ret, readonly);
    return ret;
}

boost::shared_ptr<IndexWorker>
IndexBundleActivator::createIndexWorker_()
{
    boost::shared_ptr<IndexWorker> ret(new IndexWorker(config_, directoryRotator_));
    return ret;
}

boost::shared_ptr<IndexAggregator>
IndexBundleActivator::createIndexAggregator_()
{
    indexMerger_.reset(new IndexMerger);

    std::auto_ptr<IndexMergerProxy> mergerProxy(new IndexMergerProxy(indexMerger_.get()));
    indexMerger_->bindCallProxy(*mergerProxy);

    std::auto_ptr<IndexWorkerProxy> localWorkerProxy(new IndexWorkerProxy(indexWorker_.get()));
    indexWorker_->bindCallProxy(*localWorkerProxy);

    boost::shared_ptr<IndexAggregator> ret(
        new IndexAggregator(mergerProxy.get(), localWorkerProxy.get(),
            Sf1rTopology::getServiceName(Sf1rTopology::SearchService), config_->collectionName_));

    mergerProxy.release();
    localWorkerProxy.release();

    MasterManagerBase::get()->registerAggregator(ret);
    return ret;
}

bool IndexBundleActivator::initializeQueryManager_() const
{
    // initialize Query Parser
    QueryParser::initOnlyOnce();

    std::string kma_path;
    LAPool::getInstance()->get_kma_path(kma_path);
    std::string restrictDictPath = kma_path + "/restrict.txt";
    QueryUtility::buildRestrictTermDictionary( restrictDictPath, idManager_);

    return true;
}

}

ext: cpp


text:
/**
Recaius Library

Copyright (c) 2016 Hironori Ogawa

This software is released under the MIT License.
http://opensource.org/licenses/mit-license.php
*/

#include <string>
#include <iostream>
#include <vector>
using namespace std;

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/foreach.hpp>
using namespace boost::property_tree;

#include <curl/curl.h>

#include <jsoncpp/json/json.h>
#include <jsoncpp/json/writer.h>
#include <jsoncpp/json/reader.h>

#include "librecaius.h"

namespace
{
  string cmd_login = "login";
  string cmd_logout = "logout";
  string cmd_voice = "voice";
  string cmd_result = "result";

  string cmd_text2wave = "plaintext2speechwave";
  string cmd_getsplist = "get_speaker_list";

  enum HTTP_RES {
    HTTP_RES_OK = 200
  };

  size_t callbackWrite(char *ptr, size_t size, size_t nmemb, string *stream)
  {
    int dataLength = size * nmemb;
    stream->append(ptr, dataLength);
    return dataLength;
  }
  size_t callbackWriteRaw(char *ptr, size_t size, size_t nmemb, vector<unsigned char> *stream)
  {
    int dataLength = size * nmemb;
    // stream->resize(dataLength);
    // memcpy(&stream[0], ptr, dataLength);
    for(int i=0;i<dataLength;i++){
      stream->push_back(ptr[i]);
    }
    return dataLength;
  }
}

CRecaiusRecognition::CRecaiusRecognition()
{
  id = "";
  password = "";
  uuid = "";
  model_id = 0;

  curl_verbose = 0;

  orig_url = "https://try-api.recaius.jp/asr/v1/";
  base_url = orig_url;
}

CRecaiusRecognition::~CRecaiusRecognition()
{
  Logout();
}

int CRecaiusRecognition::LoadConfigFile(string fname)
{
  return 0;
}

int CRecaiusRecognition::SetID(string _id)
{
  id = _id;
  return 0;
}

int CRecaiusRecognition::SetPassword(string _password)
{
  password = _password;
  return 0;
}

int CRecaiusRecognition::SetModelID(int _model_id)
{
  model_id = _model_id;
  return 0;
}

int CRecaiusRecognition::Login()
{
  //とりあえずログアウト
  Logout();

  //ログインデータ準備
  string header = "Content-Type:application/json";
  string url = base_url + cmd_login;

  // JSON形式のデータ用意
  Json::Value root;
  root["id"] = id;
  root["password"] = password;
  Json::Value model;
  model["model_id"] = model_id;
  model["resulttype"] = "nbest";
  root["model"] = model;
  Json::FastWriter writer;
  string json_string = writer.write(root);

  cout << url << endl;
  cout << header << endl;
  cout << json_string;

  //ログイン処理
  CURLcode ret;
  CURL *hnd;
  struct curl_slist *slist1;

  string chunk;

  slist1 = NULL;
  slist1 = curl_slist_append(slist1, header.c_str());

  hnd = curl_easy_init();
  curl_easy_setopt(hnd, CURLOPT_URL, url.c_str());
  curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, json_string.c_str());
  curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, slist1);
  curl_easy_setopt(hnd, CURLOPT_MAXREDIRS, 50L);
  curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYPEER, 0L);
  curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYHOST, 0L);
  curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST");
  curl_easy_setopt(hnd, CURLOPT_VERBOSE, curl_verbose);
  curl_easy_setopt(hnd, CURLOPT_TCP_KEEPALIVE, 1L);

  curl_easy_setopt(hnd, CURLOPT_WRITEFUNCTION, callbackWrite);
  curl_easy_setopt(hnd, CURLOPT_WRITEDATA, &chunk);

  ret = curl_easy_perform(hnd);

  if(ret == CURLE_OK)
  {
    long res_code;
    curl_easy_getinfo(hnd, CURLINFO_RESPONSE_CODE, &res_code);
    cout << "Responce Code: " << res_code << endl;
    string content_type;

    switch(res_code)
    {
    case HTTP_RES_OK:
      char* ct;
      curl_easy_getinfo(hnd, CURLINFO_CONTENT_TYPE, &ct);
      if(ct == NULL)
        content_type = "NULL";
      else
        content_type = ct;

      cout << "Content Type: "<< content_type << endl;

      uuid = chunk;
      base_url = orig_url + uuid + "/";

      break;
    }
  }

  curl_easy_cleanup(hnd);
  hnd = NULL;
  curl_slist_free_all(slist1);
  slist1 = NULL;

  return ret;
}

int CRecaiusRecognition::Logout()
{
  if(uuid == ""){
    return 0;
  }

  //ログインデータ準備
  string url = base_url + cmd_logout;
  cout << url << endl;
  //
  // //Recaius APIアクセス
  CURLcode ret;
  CURL *hnd;

  hnd = curl_easy_init();
  curl_easy_setopt(hnd, CURLOPT_URL, url.c_str());
  curl_easy_setopt(hnd, CURLOPT_MAXREDIRS, 50L);
  curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYPEER, 0L);
  curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYHOST, 0L);
  curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST");
  curl_easy_setopt(hnd, CURLOPT_VERBOSE, curl_verbose);
  curl_easy_setopt(hnd, CURLOPT_TCP_KEEPALIVE, 1L);

  ret = curl_easy_perform(hnd);

  if(ret == CURLE_OK)
  {
    long res_code;
    curl_easy_getinfo(hnd, CURLINFO_RESPONSE_CODE, &res_code);
    cout << "Responce Code: " << res_code << endl;
    string content_type;

    switch(res_code)
    {
    case HTTP_RES_OK:
      char* ct;
      curl_easy_getinfo(hnd, CURLINFO_CONTENT_TYPE, &ct);
      if(ct == NULL)
        content_type = "NULL";
      else
        content_type = ct;

      cout << "Content Type: "<< content_type << endl;

      break;
    }
  }

  curl_easy_cleanup(hnd);
  hnd = NULL;

  uuid = "";
  base_url = orig_url;

  return (int)ret;
}

string CRecaiusRecognition::SendVoice(int voice_id, vector<unsigned char> data)
{
  CURLcode ret;
  CURL *hnd;
  struct curl_httppost *post1;
  struct curl_httppost *postend;
  struct curl_slist *slist1;

  string chunk;

  cout << data.size() << endl;

  post1 = NULL;
  postend = NULL;
  stringstream stream;
  stream << voice_id;
  curl_formadd(&post1, &postend,
               CURLFORM_COPYNAME, "voiceid",
               CURLFORM_COPYCONTENTS, stream.str().c_str(),
               CURLFORM_END);
  if(data.size())
  {
    curl_formadd(&post1, &postend,
                 CURLFORM_COPYNAME, "voice",
                 CURLFORM_COPYCONTENTS, &data[0],
                 CURLFORM_CONTENTSLENGTH, data.size(),
                 CURLFORM_CONTENTTYPE, "application/octet-stream",
                 CURLFORM_END);
  }
  else
  {
    curl_formadd(&post1, &postend,
                 CURLFORM_COPYNAME, "voice",
                 CURLFORM_COPYCONTENTS, "",
                 CURLFORM_CONTENTTYPE, "application/octet-stream",
                 CURLFORM_END);
  }
  slist1 = NULL;
  slist1 = curl_slist_append(slist1, "Content-Type:multipart/form-data");

  string url = base_url + cmd_voice;
  cout << url << endl;

  hnd = curl_easy_init();
  curl_easy_setopt(hnd, CURLOPT_URL, url.c_str());
  curl_easy_setopt(hnd, CURLOPT_HTTPPOST, post1);
  curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, slist1);
  curl_easy_setopt(hnd, CURLOPT_MAXREDIRS, 50L);
  curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYPEER, 0L);
  curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYHOST, 0L);
  curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "PUT");
  curl_easy_setopt(hnd, CURLOPT_VERBOSE, curl_verbose);
  curl_easy_setopt(hnd, CURLOPT_TCP_KEEPALIVE, 1L);
  curl_easy_setopt(hnd, CURLOPT_WRITEFUNCTION, callbackWrite);
  curl_easy_setopt(hnd, CURLOPT_WRITEDATA, &chunk);

  ret = curl_easy_perform(hnd);

  if(ret == CURLE_OK)
  {
    long res_code;
    curl_easy_getinfo(hnd, CURLINFO_RESPONSE_CODE, &res_code);
    cout << "Responce Code: " << res_code << endl;
    string content_type;

    switch(res_code)
    {
    case HTTP_RES_OK:
      char* ct;
      curl_easy_getinfo(hnd, CURLINFO_CONTENT_TYPE, &ct);
      if(ct == NULL)
        content_type = "NULL";
      else
        content_type = ct;

      cout << "Content Type: "<< content_type << endl;

      break;
    }
  }

  curl_easy_cleanup(hnd);
  curl_formfree(post1);
  curl_slist_free_all(slist1);

  return chunk;
}

string CRecaiusRecognition::SendWaveFile(string fname)
{
  vector<unsigned char> wave_data;

  //バイナリファイル読み込み
  ifstream ifs((const char*)fname.c_str(), ios::in | ios::binary);
  ifs.seekg(0, fstream::end);
  unsigned int eofPos = ifs.tellg();
  ifs.clear();
  ifs.seekg(0, fstream::beg);
  unsigned int begPos = ifs.tellg();
  unsigned int size = eofPos - begPos;

  wave_data.resize(size);
  ifs.read((char*)&wave_data[0], wave_data.size());

  // cout << wave_data.size() << endl;
  // cout << wave_data.size()/44100 << endl;
  // cout << wave_data.size()%44100 << endl;

  string chunk;
  chunk += SendVoice(1, wave_data);
  vector<unsigned char> wave_null(0);
  chunk += SendVoice(2, wave_null);

  return chunk;
}

string CRecaiusRecognition::GetResult()
{
  CURLcode ret;
  CURL *hnd;

  string chunk;

  string url = base_url +  cmd_result;
  cout << url << endl;

  hnd = curl_easy_init();
  curl_easy_setopt(hnd, CURLOPT_URL, url.c_str());
  curl_easy_setopt(hnd, CURLOPT_MAXREDIRS, 50L);
  curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYPEER, 0L);
  curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYHOST, 0L);
  curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "GET");
  curl_easy_setopt(hnd, CURLOPT_VERBOSE, curl_verbose);
  curl_easy_setopt(hnd, CURLOPT_TCP_KEEPALIVE, 1L);

  curl_easy_setopt(hnd, CURLOPT_WRITEFUNCTION, callbackWrite);
  curl_easy_setopt(hnd, CURLOPT_WRITEDATA, &chunk);

  ret = curl_easy_perform(hnd);

  long res_code;
  if(ret == CURLE_OK)
  {
    curl_easy_getinfo(hnd, CURLINFO_RESPONSE_CODE, &res_code);
    cout << "Responce Code: " << res_code << endl;
    string content_type;

    switch(res_code)
    {
    case HTTP_RES_OK:
      char* ct;
      curl_easy_getinfo(hnd, CURLINFO_CONTENT_TYPE, &ct);
      if(ct == NULL)
        content_type = "NULL";
      else
        content_type = ct;

      cout << "Content Type: "<< content_type << endl;

      break;
    }
  }

  curl_easy_cleanup(hnd);
  hnd = NULL;

  if(res_code == HTTP_RES_OK)
  {
    // cout << chunk << endl;

    // JSON形式のデータ用意
    Json::Value root;
    Json::Reader reader;
    bool success = reader.parse(chunk, root);

    return chunk;
  }

  return ("");
}

// 音声合成

namespace{
}

CSynth::CSynth()
{
  id = "";
  password = "";
  lang = "";
  speaker_id = "";

  curl_verbose = 0;

  speakers.clear();

  orig_url = "https://try-api.recaius.jp/tts/v1/";
  base_url = orig_url;
}

CSynth::~CSynth()
{

}

int CSynth::SetID(string _id)
{
  id = _id;
  return 0;
}

int CSynth::SetPassword(string _password)
{
  password = _password;
  return 0;
}

int CSynth::SetSpeaker(int speaker_id)
{
  SetLang(speakers[speaker_id].lang);
  SetSpeakerID(speakers[speaker_id].speaker_id);
  return 0;
}

int CSynth::SetLang(string _lang)
{
  lang = _lang;
  return 0;
}

int CSynth::SetSpeakerID(string _id)
{
  speaker_id = _id;
  return 0;
}

vector<unsigned char> CSynth::GetSpeechWaveFromPlainText(string text)
{
  // JSON形式のデータ用意
  Json::Value json_value;
  json_value["id"] = id;
  json_value["password"] = password;
  json_value["plain_text"] = text;
  json_value["lang"] = lang;
  json_value["speaker_id"] = speaker_id;
  Json::FastWriter writer;
  string json_string = writer.write(json_value);

  //recaiusにアクセス
  CURLcode ret;
  CURL *hnd;
  struct curl_slist *slist1;

  slist1 = NULL;
  slist1 = curl_slist_append(slist1, "Content-Type:application/json");

  string url = base_url + cmd_text2wave;

  cout << url << endl;
  cout << json_string << endl;

  hnd = curl_easy_init();
  curl_easy_setopt(hnd, CURLOPT_URL, url.c_str());
  curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, json_string.c_str());
  curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, slist1);
  curl_easy_setopt(hnd, CURLOPT_MAXREDIRS, 50L);
  curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYPEER, 0L);
  curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYHOST, 0L);
  curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST");
  curl_easy_setopt(hnd, CURLOPT_VERBOSE, curl_verbose);
  curl_easy_setopt(hnd, CURLOPT_TCP_KEEPALIVE, 1L);

  vector<unsigned char> raw;
  curl_easy_setopt(hnd, CURLOPT_WRITEFUNCTION, callbackWriteRaw);
  curl_easy_setopt(hnd, CURLOPT_WRITEDATA, &raw);

  ret = curl_easy_perform(hnd);

  long res_code;
  curl_easy_getinfo(hnd, CURLINFO_RESPONSE_CODE, &res_code);
  cout << "Responce Code: " << res_code << endl;
  string content_type;
  char* ct;
  curl_easy_getinfo(hnd, CURLINFO_CONTENT_TYPE, &ct);
  if(ct == NULL)
    content_type = "NULL";
  else
    content_type = ct;
  cout << "Content Type: "<< content_type << endl;

  curl_easy_cleanup(hnd);
  hnd = NULL;
  curl_slist_free_all(slist1);
  slist1 = NULL;

  // cout << chunk << endl;

  return raw;
}

//  文字列を置換する
std::string Replace( std::string String1, std::string String2, std::string String3 )
{
    std::string::size_type  Pos( String1.find( String2 ) );

    while( Pos != std::string::npos )
    {
        String1.replace( Pos, String2.length(), String3 );
        Pos = String1.find( String2, Pos + String3.length() );
    }

    return String1;
}

int CSynth::GetSpeakerList()
{
  // JSON形式のデータ用意
  Json::Value json_value;
  json_value["id"] = id;
  json_value["password"] = password;
  Json::FastWriter writer;
  string json_string = writer.write(json_value);
  // json_string.pop_back();
  cout << json_string << endl;

  //recaiusにアクセス
  CURLcode ret;
  CURL *hnd;
  struct curl_slist *slist1;

  slist1 = NULL;
  slist1 = curl_slist_append(slist1, "Content-Type:application/json");

  string url = base_url + cmd_getsplist;
  cout << url << endl;

  hnd = curl_easy_init();
  curl_easy_setopt(hnd, CURLOPT_URL, url.c_str());
  curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, json_string.c_str());
  curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, slist1);
  curl_easy_setopt(hnd, CURLOPT_MAXREDIRS, 50L);
  curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYPEER, 0L);
  curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYHOST, 0L);
  curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST");
  curl_easy_setopt(hnd, CURLOPT_VERBOSE, curl_verbose);
  curl_easy_setopt(hnd, CURLOPT_TCP_KEEPALIVE, 1L);

  string chunk;
  curl_easy_setopt(hnd, CURLOPT_WRITEFUNCTION, callbackWrite);
  curl_easy_setopt(hnd, CURLOPT_WRITEDATA, &chunk);

  ret = curl_easy_perform(hnd);

  curl_easy_cleanup(hnd);
  hnd = NULL;
  curl_slist_free_all(slist1);
  slist1 = NULL;

  // cout << chunk << endl;

  ptree pt;
  istringstream is1(chunk);
  read_xml(is1, pt);
  string body = pt.get<string>("response.body");

  istringstream is2(body);
  read_xml(is2, pt);

  //ひとりずつ処理
  speakers.clear();
  BOOST_FOREACH(ptree::value_type &v, pt.get_child("speaker_group"))
  {
    speaker sp;
    sp.speaker_id = v.second.get<string>("speaker_id");
    sp.lang = v.second.get<string>("lang");
    sp.style = v.second.get<string>("style");
    sp.description = v.second.get<string>("description");
    sp.emotion = v.second.get<string>("emotion");
    sp.tts_type = v.second.get<string>("tts_type");
    sp.dic_type = v.second.get<string>("dic_type");

    sp.lang = Replace(sp.lang, ",", "-");

    // cout << v.second.get<string>("alias") << endl;
    speakers.push_back(sp);
  }

  return (int)ret;
}

max_stars_repo_name: hiro-ogawa/librecaius

max_issues_repo_name: hiro-ogawa/librecaius

max_forks_repo_name: hiro-ogawa/librecaius


text:
/*
  Lua module to provide shared memory IPC
*/

#include <boost/utility/binary.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
//#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/exceptions.hpp>
#include <vector>
#include <string>
#include <lua.hpp>
#include <iostream>

using namespace boost::interprocess;

// Typedefs of allocators and containers
typedef double value_t;
//typedef boost::variant<double, std::string> value_t;

static managed_shared_memory * lua_checkshm(lua_State *L, int narg) {
  void *ud = luaL_checkudata(L, narg, "shm_mt");
  luaL_argcheck(L, *(managed_shared_memory **)ud != NULL, narg, "invalid shm");
  return *(managed_shared_memory **)ud;
}

static int lua_shm_create(lua_State *L) {
  const char *name = luaL_checkstring(L, 1);
  int size = luaL_optinteger(L, 2, 65536);

	/*
	// TODO: Even if using root, allow the segment to be unrestricted
	// http://www.boost.org/doc/libs/1_46_1/boost/interprocess/managed_shared_memory.hpp
	// http://stackoverflow.com/questions/8758896/setting-permission-for-shared-memory-created-by-boost
	boost::interprocess::permissions perm;
	perm.set_unrestricted();
	*/

  managed_shared_memory **ud = (managed_shared_memory **)
    lua_newuserdata(L, sizeof(managed_shared_memory *));
	try {
		*ud = new managed_shared_memory(open_or_create, name, size);
	}
	catch (boost::interprocess::bad_alloc &ex) {
		std::cerr << ex.what() << std::endl;
	}

  luaL_getmetatable(L, "shm_mt");
  lua_setmetatable(L, -2);
  return 1;
}

static int lua_shm_open(lua_State *L) {
  const char *name = luaL_checkstring(L, 1);

  managed_shared_memory **ud = (managed_shared_memory **)
    lua_newuserdata(L, sizeof(managed_shared_memory *));
	try {
		*ud = new managed_shared_memory(open_only, name);
	}
	catch (boost::interprocess::bad_alloc &ex) {
		std::cerr << ex.what() << std::endl;
	}
  luaL_getmetatable(L, "shm_mt");
  lua_setmetatable(L, -2);
  return 1;
}

static int lua_shm_destroy(lua_State *L) {
  const char *name = luaL_checkstring(L, 1);
  shared_memory_object::remove(name);
  return 0;
}

static int lua_shm_delete(lua_State *L) {
  managed_shared_memory *shm = lua_checkshm(L, 1);
  delete shm;
  return 0;
}

static int lua_shm_create_empty_variable(lua_State *L) {
  managed_shared_memory *shm = lua_checkshm(L, 1);

  const char *key = luaL_checkstring(L, 2);
  std::vector<value_t> val(1);

  // get the number of bytes
  int nbytes = lua_tointeger(L, 3);
  // calculate size of the shm array (based on sizeof(value_t)
  int nval = nbytes >> 3;
  if (nbytes & BOOST_BINARY(111)) {
    // if the data does not fit evenly into the value_t types
    nval++;
  }

  // Find key in shm
  std::pair<value_t*, std::size_t> ret;
  ret = shm->find<value_t>(key);
  value_t *pr = ret.first;
  int n = ret.second;

  if (pr == NULL) {
    // construct the shm key if it doesn't exist
    //printf("Size of memory segment: %u bytes\n", shm->get_size());
    //printf("Size of value_t: %u bytes\n", sizeof(value_t) );
    pr = shm->construct<value_t>(key)[nval]();
  } else if (n != nval) {
    // if it exists but is not the correct size
    // create a new key with the correct size
//    printf("WARNING: Input size %d != current block size %d. Resizing %s block.\n", nval, n, key);
    shm->destroy_ptr(pr);
    pr = shm->construct<value_t>(key)[nval]();
  }

  return 0;
}

static int lua_shm_set(lua_State *L) {
  managed_shared_memory *shm = lua_checkshm(L, 1);

  const char *key = luaL_checkstring(L, 2);
  int nval = 0;
  std::vector<value_t> val(1);

  const void* light_ptr = NULL;
  unsigned int light_bytes = 0;

  if (lua_isnumber(L, 3)) {
    nval = 1;
    val[0] = lua_tonumber(L, 3);
  } else if (lua_istable(L, 3)) {
#if LUA_VERSION_NUM == 502
    nval = lua_rawlen(L, 3);
#else
    nval = lua_objlen(L, 3);
#endif
    val.resize(nval);
    for (int i = 0; i < nval; i++) {
      lua_rawgeti(L, 3, i+1);
      val[i] = lua_tonumber(L, -1);
      lua_pop(L, 1);
    }
  } else if (lua_islightuserdata(L, 3)) {
    // if the input is a pointer then use memcpy
    light_ptr = lua_topointer(L, 3);
    // get the number of bytes to copy
    light_bytes = lua_tointeger(L, 4);
    // calculate size of the shm array (based on sizeof(value_t)
    nval = light_bytes >> 3;
    if (light_bytes & BOOST_BINARY(111)) {
      // if the data does not fit evenly into the value_t types
      nval++;
    }
  } else if (lua_isstring(L, 3)) {
    size_t len;
    // if the input is a string then use memcpy
    light_ptr = (const void*)lua_tolstring(L, 3, &len);
    // get the number of bytes to copy
    light_bytes = (unsigned int)len;
    // calculate size of the shm array (based on sizeof(value_t)
    nval = light_bytes >> 3;
    if (light_bytes & BOOST_BINARY(111)) {
      // if the data does not fit evenly into the value_t types
      nval++;
    }
  }

  // Find key in shm
  std::pair<value_t*, std::size_t> ret;
  ret = shm->find<value_t>(key);
  value_t *pr = ret.first;
  int n = ret.second;

  if (pr == NULL) {
    // construct the shm key if it doesn't exist
    //printf("Size of memory segment: %u bytes\n", shm->get_size());
    //printf("Size of value_t: %u bytes\n", sizeof(value_t) );
    pr = shm->construct<value_t>(key)[nval]();
  } else if (n != nval) {
    // if it exists but is not the correct size
    // create a new key with the correct size
//    printf("WARNING: Input size %d != current block size %d. Resizing %s block.\n", nval, n, key);
    shm->destroy_ptr(pr);
    pr = shm->construct<value_t>(key)[nval]();
  }

  if (light_ptr != NULL) {
    // use memcpy if the input is a pointer
    memcpy( pr, light_ptr, light_bytes );
  } else {
    //int start = luaL_optint(L, 4, 1)-1;
    // otherwise copy the array data
    for (int i = 0; i < nval; i++) {
      pr[i] = val[i];
    }
  }

  return 0;
}

static int lua_shm_get(lua_State *L) {
  managed_shared_memory *shm = lua_checkshm(L, 1);
  const char *key = luaL_checkstring(L, 2);

  std::pair<value_t*, std::size_t> ret;
  ret = shm->find<value_t>(key);
  value_t *pr = ret.first;
  int n = ret.second;
  if ((pr == NULL) || (n == 0)) {
    // key does not exist in the shm segment
    lua_pushnil(L);
  } else if (n == 1) {
    lua_pushnumber(L, *pr);
  } else {
    lua_createtable(L, n, 0);
    for (int i = 0; i < n; i++) {
      lua_pushnumber(L, pr[i]);
      lua_rawseti(L, -2, i+1);
    }
  }

  return 1;
}

static int lua_shm_size(lua_State *L) {
  managed_shared_memory *shm = lua_checkshm(L, 1);
  const char *key = luaL_checkstring(L, 2);

  std::pair<value_t*, std::size_t> ret;
  ret = shm->find<value_t>(key);
  value_t *pr = ret.first;
  int n = ret.second;
  if ((pr == NULL) || (n == 0)) {
    // key does not exist in the shm segment
    lua_pushnumber(L, 0);
  } else {
    lua_pushnumber(L, n);
  }

  return 1;
}

static int lua_shm_pointer(lua_State *L) {
  managed_shared_memory *shm = lua_checkshm(L, 1);
  const char *key = luaL_checkstring(L, 2);

  // Find key
  std::pair<value_t*, std::size_t> ret;
  ret = shm->find<value_t>(key);
  value_t *pr = ret.first;
  int n = ret.second;

  lua_pushlightuserdata(L, pr);
  lua_pushstring(L, "double");
  lua_pushinteger(L, n);
  return 3;
}

static int lua_shm_next(lua_State *L) {
  managed_shared_memory *shm = lua_checkshm(L, 1);

  typedef managed_shared_memory::const_named_iterator const_named_it;
  const_named_it named_beg = shm->named_begin();
  const_named_it named_end = shm->named_end();

  if (lua_isnil(L, 2) || lua_isnone(L, 2)) {
    // if it is not empty return the first
    if (named_beg != named_end) {
      lua_pushstring(L, named_beg->name());
      lua_pushlightuserdata(L, (void *)named_beg->value());
      return 2;
    } else {
      lua_pushnil(L);
      return 1;
    }
  }

  const char *key = luaL_checkstring(L, 2);
  bool find = false;
  do {
    if (find) {
      lua_pushstring(L, named_beg->name());
      lua_pushlightuserdata(L, (void *)named_beg->value());
      return 2;
    } else {
      const managed_shared_memory::char_type *name = named_beg->name();
      //std::size_t name_len = named_beg->name_length();
      if (std::string(key) == std::string(name)) { find = true; }
    }
  } while (++named_beg != named_end);

  lua_pushnil(L);
  return 1;
}

static int lua_shm_tostring(lua_State *L) {
  managed_shared_memory *shm = lua_checkshm(L, 1);
  lua_pushfstring(L, "shm(%p): %d bytes, %d free, %d named, %d unique",
                    shm, shm->get_size(), shm->get_free_memory(),
                    shm->get_num_named_objects(), shm->get_num_unique_objects());
  return 1;
}

static const struct luaL_Reg shm_functions[] = {
  {"new", lua_shm_create},
  {"open", lua_shm_open},
  {"destroy", lua_shm_destroy},
  {NULL, NULL}
};

static const struct luaL_Reg shm_methods[] = {
  {"empty", lua_shm_create_empty_variable},
  {"set", lua_shm_set},
  {"get", lua_shm_get},
  {"pointer", lua_shm_pointer},
  {"next", lua_shm_next},
  {"size", lua_shm_size},
  {"__gc", lua_shm_delete},
  {"__newindex", lua_shm_set},
  {"__tostring", lua_shm_tostring},
  {NULL, NULL}
};

#ifdef __cplusplus
extern "C"
#endif
int luaopen_shm (lua_State *L) {
  luaL_newmetatable(L, "shm_mt");

  // OO access: mt.__index = mt
  // Not compatible with array access
  lua_pushvalue(L, -1);
  lua_setfield(L, -2, "__index");

  /*
  // Array access: mt.__index = get(); mt.__newindex = set()
  // Not compatible with OO access
  lua_pushstring(L, "__index");
  lua_pushcfunction(L, lua_shm_get);
  lua_settable(L, -3);
  */

#if LUA_VERSION_NUM == 502
  // TODO: why 0 for nup? Any use for nup?
  luaL_setfuncs( L, shm_methods, 0 );
  luaL_newlib( L, shm_functions );
#else
  /*
   * I put this into the methods array
  // Implement index method:
  lua_pushstring(L, "__index");
  lua_pushcfunction(L, lua_carray_index);
  lua_settable(L, -3);
  */
  luaL_register(L, NULL, shm_methods);
  luaL_register(L, "shm", shm_functions);
#endif

  return 1;
}

max_stars_repo_name: ToyotaResearchInstitute/rad-robot

max_issues_repo_name: ToyotaResearchInstitute/rad-robot

max_forks_repo_name: SJ-YI/HSRDEV


text:
#pragma once
#include <Eigen/Dense>
#include "../Ray.hpp"

class Camera
{
public:
    Camera(float aspect_radio) : Camera({0.0f, 0.0f, 0.0f}, aspect_radio){};

    Camera(Eigen::Vector3f position, float aspect_radio) : position(position), aspect_radio(aspect_radio){};

    virtual ~Camera(){};

    virtual Ray generate_primary_ray(float x, float y) const = 0;

protected:
    Eigen::Vector3f position;

    double aspect_radio;
};

ext: hpp


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

// Copyright (c) 2010 Alfredo Correa
// Copyright (c) 2010-2012 Barend Gehrels, Amsterdam, the Netherlands.

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

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#include <iostream>

#include <geometry_test_common.hpp>

#include <boost/geometry/algorithms/distance.hpp>
#include <boost/geometry/geometries/adapted/boost_array.hpp>
#include <boost/geometry/geometries/adapted/boost_tuple.hpp>
#include <boost/geometry/geometries/adapted/c_array.hpp>
#include <boost/geometry/geometries/adapted/std_array.hpp>
#include <boost/geometry/geometries/point.hpp>

BOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian)
BOOST_GEOMETRY_REGISTER_BOOST_ARRAY_CS(cs::cartesian)
BOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)
BOOST_GEOMETRY_REGISTER_STD_ARRAY_CS(cs::cartesian)

int test_main(int, char* [])
{
    bg::model::point<double, 3, bg::cs::cartesian> p1(1,2,3);
    double p2[3] = {4,5,6};
    boost::tuple<double, double, double> p3(7,8,9);
    boost::array<double, 3> p4 = {{10,11,12}};
    std::array<double, 3> p5 = {{13,14,15}};

    std::clog << bg::distance(p1, p2) << std::endl;
    std::clog << bg::distance(p2, p3) << std::endl;
    std::clog << bg::distance(p3, p4) << std::endl;
    std::clog << bg::distance(p4, p5) << std::endl;

    return 0;
}


text:
//Copyright (c) 2008-2016 Emil Dotchevski and Reverge Studios, Inc.

//Distributed under the Boost Software License, Version 1.0. (See accompanying

//file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef UUID_6D6B1EE2119A11E291554FEE6188709B

#define UUID_6D6B1EE2119A11E291554FEE6188709B

#include <boost/qvm/inline.hpp>

#include <boost/qvm/deduce_quat.hpp>

#include <boost/qvm/detail/remove_const.hpp>

#include <boost/qvm/assert.hpp>

namespace

boost

    {

    namespace

    qvm

        {

        template <class T,int D>

        struct

        quat_traits<T[D]>

            {

            typedef void scalar_type;

            };

        template <class T,int D>

        struct

        quat_traits<T[D][4]>

            {

            typedef void scalar_type;

            };

        template <class T,int D>

        struct

        quat_traits<T[4][D]>

            {

            typedef void scalar_type;

            };

        template <class T>

        struct

        quat_traits<T[4][4]>

            {

            typedef void scalar_type;

            };

        template <class T,int M,int N>

        struct

        quat_traits<T[M][N]>

            {

            typedef void scalar_type;

            };

        template <class T>

        struct

        quat_traits<T[4]>

            {

            typedef T this_quaternion[4];

            typedef typename qvm_detail::remove_const<T>::type scalar_type;

            template <int I>

            static

            BOOST_QVM_INLINE_CRITICAL

            scalar_type

            read_element( this_quaternion const & x )

                {

                BOOST_QVM_STATIC_ASSERT(I>=0);

                BOOST_QVM_STATIC_ASSERT(I<4);

                return x[I];

                }

            template <int I>

            static

            BOOST_QVM_INLINE_CRITICAL

            scalar_type &

            write_element( this_quaternion & x )

                {

                BOOST_QVM_STATIC_ASSERT(I>=0);

                BOOST_QVM_STATIC_ASSERT(I<4);

                return x[I];

                }

            static

            BOOST_QVM_INLINE_CRITICAL

            scalar_type

            read_element_idx( int i, this_quaternion const & x )

                {

                BOOST_QVM_ASSERT(i>=0);

                BOOST_QVM_ASSERT(i<4);

                return x[i];

                }

            static

            BOOST_QVM_INLINE_CRITICAL

            scalar_type &

            write_element_idx( int i, this_quaternion & x )

                {

                BOOST_QVM_ASSERT(i>=0);

                BOOST_QVM_ASSERT(i<4);

                return x[i];

                }

            };

        template <class T>

        struct

        deduce_quat<T[4]>

            {

            typedef quat<T> type;

            };

        template <class T>

        struct

        deduce_quat<T const[4]>

            {

            typedef quat<T> type;

            };

        template <class T1,class T2>

        struct

        deduce_quat2<T1[4],T2[4]>

            {

            typedef quat<typename deduce_scalar<T1,T2>::type> type;

            };

        template <class T>

        T (&ptr_qref( T * ptr ))[4]

            {

            return *reinterpret_cast<T (*)[4]>(ptr);

            }

        }

    }

#endif

max_stars_repo_name: newtondev/drachtio-server

max_issues_repo_name: newtondev/drachtio-server

max_forks_repo_name: newtondev/drachtio-server


text: #include <boost/mpl/vector/aux_/preprocessed/plain/vector40.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/*
 * configuration.cpp
 *
 *  Created on: Dec 5, 2011
 *      Author: Maurice Fallon
 *      Author: Hordur Johannsson
 */

#include "voconfig.hpp"
#include <iostream>
#include <boost/lexical_cast.hpp>
#include <Eigen/Dense>

#include <path_util/path_util.h>

namespace voconfig
{

BotParamConfiguration::BotParamConfiguration(lcm_t* bot_param_lcm,
  BotParam* bot_param,
  const std::string & key_prefix) : bot_param_lcm_(bot_param_lcm),
                                    bot_param_(bot_param),
                                    key_prefix_(key_prefix)
{
}

BotParamConfiguration::~BotParamConfiguration() {}

bool BotParamConfiguration::has_key(const std::string & key)
{
  return bot_param_has_key(bot_param_, (key_prefix_+"."+key).c_str());
}

bool BotParamConfiguration::get(const std::string & key, bool default_value)
{
  int bval;
  if (bot_param_get_boolean(bot_param_, (key_prefix_+"."+key).c_str(), &bval) != 0) bval = default_value;
  return bval;
}

int BotParamConfiguration::get(const std::string & key, int default_value)
{
  int ival;
  if (bot_param_get_int(bot_param_, (key_prefix_+"."+key).c_str(), &ival) != 0) ival = default_value;
  return ival;
}

double BotParamConfiguration::get(const std::string & key, double default_value)
{
  double dval;
  if (bot_param_get_double(bot_param_, (key_prefix_+"."+key).c_str(), &dval) != 0) dval = default_value;
  return dval;
}

std::string BotParamConfiguration::get(const std::string & key, const std::string & default_value)
{
  std::string val;
  char * sval = NULL;
  if (bot_param_get_str(bot_param_, (key_prefix_+"."+key).c_str(), &sval) == 0) val = std::string(sval);
  else val = default_value;
  if (sval) free(sval);
  return val;
}

KmclConfiguration::KmclConfiguration(BotParam* botparam,
                            const std::string & depth_source_name)
    : depth_source_type_(UNKNOWN)
{
  init(botparam, depth_source_name);
}

Configuration::Ptr KmclConfiguration::get_section(const std::string & key_prefix) const
{
  return BotParamConfiguration::Ptr(new BotParamConfiguration(bot_param_lcm_, bot_param_, key_prefix));
}

void KmclConfiguration::init(BotParam* bot_param,
                            const std::string & depth_source_name) {
  bot_param_lcm_ = lcm_create(NULL);

//  bot_param_ = bot_param_new_from_file(config_name.c_str());
  bot_param_ = bot_param;
  if (bot_param_ == NULL) {
    std::cerr << "Couldn't get bot param" << std::endl;
    exit(-1);
  }

  /*
  // proposal
  char * loop_proposal_str = bot_param_get_str_or_fail(bot_param_, "vision_slam.loop_proposal.loop_proposal");
  char * vocabulary_str = bot_param_get_str_or_fail(bot_param_, "vision_slam.loop_proposal.vocabulary");
  char * vocabulary_weights_str = bot_param_get_str_or_fail(bot_param_, "vision_slam.loop_proposal.vocabulary_weights");
  char * vocabulary_descriptor_str = bot_param_get_str_or_fail(bot_param_, "vision_slam.loop_proposal.vocabulary_descriptor");
  char * builder_descriptor_str = bot_param_get_str_or_fail(bot_param_, "vision_slam.vocabulary_builder.descriptor");
  loop_proposal_ = loop_proposal_str;
  //vocabulary_ = std::string(getConfigPath()) + "/" + std::string(vocabulary_str);
  //vocabulary_weights_ = std::string(getConfigPath()) + "/" + std::string(vocabulary_weights_str);
  vocabulary_descriptor_ = std::string(vocabulary_descriptor_str);
  builder_descriptor_ = std::string(builder_descriptor_str);
  free(loop_proposal_str);
  free(vocabulary_str);
  free(vocabulary_weights_str);
  free(vocabulary_descriptor_str);
  free(builder_descriptor_str);
  min_time_ = bot_param_get_int_or_fail(bot_param_, "vision_slam.loop_proposal.min_time");
  min_score_ = bot_param_get_double_or_fail(bot_param_, "vision_slam.loop_proposal.min_score");
  max_num_proposals_ = bot_param_get_int_or_fail(bot_param_, "vision_slam.loop_proposal.max_num_proposals");

  // closure
  char * alignment_descriptor_str = bot_param_get_str_or_fail(bot_param_, "vision_slam.loop_closure.alignment_descriptor");
  alignment_descriptor_ = std::string(alignment_descriptor_str);
  free(alignment_descriptor_str);
  min_inliers_ = bot_param_get_int_or_fail(bot_param_, "vision_slam.loop_closure.min_inliers");
  */

  // cameras
  key_prefix_ = "cameras." + depth_source_name;

  char * depth_source_type_str = bot_param_get_str_or_fail(bot_param_, (key_prefix_ + ".type").c_str());
  if (depth_source_type_str == std::string("stereo")) {
    depth_source_type_ = STEREO;
  } else if (depth_source_type_str == std::string("openni")) {
    depth_source_type_ = OPENNI;
  } else if (depth_source_type_str == std::string("primesense")) {
    depth_source_type_ = PRIMESENSE;
  } else {
    std::cerr << "Unknown depth source type: '" << depth_source_type_str
              << "'. Should be 'stereo' or 'primesense'\n";
    exit(-1);
  }
  free (depth_source_type_str);

  char * lcm_channel_str = bot_param_get_str_or_fail(bot_param_, (key_prefix_ + ".lcm_channel").c_str());
  lcm_channel_ = lcm_channel_str;
  free(lcm_channel_str);
}

KmclConfiguration::~KmclConfiguration()
{
  bot_param_destroy(bot_param_);
}

boost::shared_ptr<fovis::PrimeSenseCalibration>
KmclConfiguration::load_primesense_calibration() const {
  assert (depth_source_type_==PRIMESENSE || depth_source_type_==OPENNI);
  if (depth_source_type_ != PRIMESENSE && depth_source_type_ != OPENNI) {
    return boost::shared_ptr<fovis::PrimeSenseCalibration>();
  }
  std::string key_prefix_str;
  fovis::PrimeSenseCalibrationParameters kparams;
  for (int i=0; i < 2; ++i) {
    fovis::CameraIntrinsicsParameters* params;

    if (i == 0) {
      key_prefix_str = std::string(key_prefix_) + ".rgb";
      params = &(kparams.rgb_params);
    } else {
      key_prefix_str = std::string(key_prefix_) + ".depth";
      params = &(kparams.depth_params);
    }
    params->width = bot_param_get_int_or_fail(bot_param_, (key_prefix_str+".width").c_str());
    params->height = bot_param_get_int_or_fail(bot_param_,(key_prefix_str+".height").c_str());
    params->fx = bot_param_get_double_or_fail(bot_param_, (key_prefix_str+".fx").c_str());
    params->fy = bot_param_get_double_or_fail(bot_param_, (key_prefix_str+".fy").c_str());
    params->cx = bot_param_get_double_or_fail(bot_param_, (key_prefix_str+".cx").c_str());
    params->cy = bot_param_get_double_or_fail(bot_param_, (key_prefix_str+".cy").c_str());
  }

  kparams.width = kparams.rgb_params.width;
  kparams.height = kparams.rgb_params.width;
  kparams.shift_offset = bot_param_get_double_or_fail(
      bot_param_, (key_prefix_+".shift_offset").c_str());
  kparams.projector_depth_baseline = bot_param_get_double_or_fail(
      bot_param_, (key_prefix_+".projector_depth_baseline").c_str());

  Eigen::Matrix3d R;
  R << 0.999999, -0.000796, 0.001256, 0.000739, 0.998970, 0.045368, -0.001291, -0.045367, 0.998970;
  kparams.depth_to_rgb_translation[0] = -0.015756;
  kparams.depth_to_rgb_translation[1] = -0.000923;
  kparams.depth_to_rgb_translation[2] =  0.002316;
  Eigen::Quaterniond Q(R);
  kparams.depth_to_rgb_quaternion[0] = Q.w();
  kparams.depth_to_rgb_quaternion[1] = Q.x();
  kparams.depth_to_rgb_quaternion[2] = Q.y();
  kparams.depth_to_rgb_quaternion[3] = Q.z();

  // We assume rotation is a rotation matrix
  double rotation[9], translation[3];
  bot_param_get_double_array_or_fail(bot_param_,
                                     (key_prefix_str+".rotation").c_str(),
                                     &rotation[0],
                                     9);
  bot_param_get_double_array_or_fail(bot_param_,
                                     (key_prefix_str+".translation").c_str(),
                                     &translation[0],
                                     3);

  bot_matrix_to_quat(rotation, kparams.depth_to_rgb_quaternion);
  std::copy(translation, translation+3, kparams.depth_to_rgb_translation);

  return boost::shared_ptr<fovis::PrimeSenseCalibration>(new fovis::PrimeSenseCalibration(kparams));
}

boost::shared_ptr<fovis::StereoCalibration>
KmclConfiguration::load_stereo_calibration() const {
  assert (depth_source_type_==STEREO);

  if (depth_source_type_ != STEREO) {
    return boost::shared_ptr<fovis::StereoCalibration>();
  }
  fovis::StereoCalibrationParameters stereo_params;
  std::string key_prefix_str;
  fovis::CameraIntrinsicsParameters* params;

  for (int i=0; i < 2; ++i) {
    if (i == 0) {
      key_prefix_str = std::string(key_prefix_) + "_LEFT"; // change mfallon april 2014 was .left
      params = &(stereo_params.left_parameters);
    } else {
      key_prefix_str = std::string(key_prefix_) + "_RIGHT"; // change mfallon april 2014 was .left
      params = &(stereo_params.right_parameters);
    }
    params->width = bot_param_get_int_or_fail(bot_param_, (key_prefix_str+".intrinsic_cal.width").c_str());
    params->height = bot_param_get_int_or_fail(bot_param_,(key_prefix_str+".intrinsic_cal.height").c_str());

    double vals[5];
    bot_param_get_double_array_or_fail(bot_param_, (key_prefix_str+".intrinsic_cal.pinhole").c_str(), vals, 5);
    params->fx = vals[0];
    params->fy = vals[1];
    params->cx = vals[3];
    params->cy = vals[4];

    if (3 == bot_param_get_double_array(bot_param_, (key_prefix_str+".intrinsic_cal.distortion_k").c_str(), vals, 3)) {
      params->k1 = vals[0];
      params->k2 = vals[1];
      params->k3 = vals[2];
    }
    if (2 == bot_param_get_double_array(bot_param_, (key_prefix_str+".intrinsic_cal.distortion_p").c_str(), vals, 2)) {
      params->p1 = vals[0];
      params->p2 = vals[1];
    }

  }

  // We assume rotation is a rotation matrix
  std::string main_key_prefix_str = std::string(key_prefix_);
  double rotation[9], translation[3];
  bot_param_get_double_array_or_fail(bot_param_,
                                     (main_key_prefix_str+".rotation").c_str(),
                                     &rotation[0],
                                     9);
  bot_param_get_double_array_or_fail(bot_param_,
                                     (main_key_prefix_str+".translation").c_str(),
                                     &translation[0],
                                     3);

  bot_matrix_to_quat(rotation, stereo_params.right_to_left_rotation);
  std::copy(translation, translation+3, stereo_params.right_to_left_translation);
  return boost::shared_ptr<fovis::StereoCalibration>(new fovis::StereoCalibration(stereo_params));
}

void KmclConfiguration::set_vo_option_int(fovis::VisualOdometryOptions & vo_opts,
    const std::string & option) const
{
  int ival;
  std::string param = std::string("fovis.") + option;
  if (bot_param_get_int(bot_param_, param.c_str(), &ival) == 0)
    vo_opts[option] = boost::lexical_cast<std::string>(ival);
}

void KmclConfiguration::set_vo_option_double(fovis::VisualOdometryOptions & vo_opts,
    const std::string & option) const
{
  double dval;
  std::string param = std::string("fovis.") + option;
  if (bot_param_get_double(bot_param_, param.c_str(), &dval) == 0)
    vo_opts[option] = boost::lexical_cast<std::string>(dval);
}

void KmclConfiguration::set_vo_option_boolean(fovis::VisualOdometryOptions & vo_opts,
    const std::string & option) const
{
  int bval;
  std::string param = std::string("fovis.") + option;
  if (bot_param_get_boolean(bot_param_, param.c_str(), &bval) == 0)
    vo_opts[option] = boost::lexical_cast<std::string>((bval?"true":"false"));
}

fovis::VisualOdometryOptions KmclConfiguration::visual_odometry_options() const {
  fovis::VisualOdometryOptions vo_opts = fovis::VisualOdometry::getDefaultOptions();

  set_vo_option_int(vo_opts, "feature-window-size");
  set_vo_option_int(vo_opts, "max-pyramid-level");
  set_vo_option_int(vo_opts, "min-pyramid-level");
  set_vo_option_int(vo_opts, "target-pixels-per-feature");
  set_vo_option_int(vo_opts, "fast-threshold");
  set_vo_option_double(vo_opts, "fast-threshold-adaptive-gain");
  set_vo_option_boolean(vo_opts, "use-adaptive-threshold");
  set_vo_option_boolean(vo_opts, "use-homography-initialization");
  set_vo_option_int(vo_opts, "ref-frame-change-threshold");

  // OdometryFrame
  set_vo_option_boolean(vo_opts, "use-bucketing");
  set_vo_option_int(vo_opts, "bucket-width");
  set_vo_option_int(vo_opts, "bucket-height");
  set_vo_option_int(vo_opts, "max-keypoints-per-bucket");
  set_vo_option_boolean(vo_opts, "use-image-normalization");

  // MotionEstimator
  set_vo_option_double(vo_opts, "inlier-max-reprojection-error");
  set_vo_option_double(vo_opts, "clique-inlier-threshold");
  set_vo_option_int(vo_opts, "min-features-for-estimate");
  set_vo_option_double(vo_opts, "max-mean-reprojection-error");
  set_vo_option_boolean(vo_opts, "use-subpixel-refinement");
  set_vo_option_int(vo_opts, "feature-search-window");
  set_vo_option_boolean(vo_opts, "update-target-features-with-refined");

  // StereoDepth
  set_vo_option_boolean(vo_opts, "stereo-require-mutual-match");
  set_vo_option_double(vo_opts, "stereo-max-dist-epipolar-line");
  set_vo_option_double(vo_opts, "stereo-max-refinement-displacement");
  set_vo_option_int(vo_opts, "stereo-max-disparity");

  return vo_opts;
}

} // namespace vs

max_stars_repo_name: liangfok/oh-distro

max_issues_repo_name: liangfok/oh-distro

max_forks_repo_name: liangfok/oh-distro


text:
/*
	A test program for futures and active object classes

	Author: Frank Hess <frank.hess@nist.gov>
	Begin: 2004-11
*/
//  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)

#include <boost/thread.hpp>
#include <poet/active_object.hpp>
#include <poet/future.hpp>
#include <iostream>
#include <vector>

class ActiveIncrementer
{
public:
	poet::future<int> increment(poet::future<int> value)
	{
		poet::promise<int> returnValue;
		boost::shared_ptr<IncrementRequest> request(new IncrementRequest(&_servant,
			value, returnValue));
		_scheduler.post_method_request(request);
		return returnValue;
	}
private:
	class Servant
	{
	public:
		int increment(int value) {boost::this_thread::sleep(boost::posix_time::seconds(1)); return ++value;}
	};
	class IncrementRequest: public poet::method_request_base
	{
	public:
		IncrementRequest(Servant *servant, poet::future<int> inputValue, poet::promise<int> returnValue):
			_servant(servant), _inputValue(inputValue), _returnValue(returnValue)
		{
		}
		virtual void run() {_returnValue.fulfill(_servant->increment(_inputValue));}
		virtual poet::future<void> scheduling_guard() const
		{
			return _inputValue;
		}
	private:
		Servant *_servant;
		poet::future<int> _inputValue;
		poet::promise<int> _returnValue;
	};

	Servant _servant;
	poet::scheduler _scheduler;

};

int main()
{
	ActiveIncrementer inc1;
	ActiveIncrementer inc2;
	std::vector<poet::future<int> > results(10);
	unsigned i;
	std::cerr << "getting Futures..." << std::endl;
	for(i = 0; i < 2; ++i)
	{
		poet::future<int> temp = inc1.increment(i);
		results.at(i) = inc2.increment(temp);
	}
	std::cerr << "converting Futures to values..." << std::endl;
	for(i = 0; i < 2; ++i)
	{
		int value = results.at(i);
		std::cerr << "value from results[" << i << "] is " << value << std::endl;
	}
	return 0;
}

max_stars_repo_name: fmhess/libpoet

max_issues_repo_name: fmhess/libpoet

max_forks_repo_name: fmhess/libpoet


text:
#include "vnl/vnl_matrix.h"

#include <boost/algorithm/string.hpp>

#include <boost/make_shared.hpp>

#include <boost/program_options.hpp>
namespace po = boost::program_options;
#include <boost/locale/encoding_utf.hpp>
using boost::locale::conv::utf_to_utf;

//Filetype
#include "itkVectorImage.h"

#include <iostream>
#include <fstream>

//IO
#include "itkImageFileWriter.h"
#include "itkImageFileReader.h"

#include "../../Utils/cmReconstructor.h"
#include "../../Utils/cmReconstructorRootSumOfSquares.h"

#include "itkImageRegionConstIterator.h"

#include "../../Utils/cmISMRMRDToITKImageFilter.h"

#include "../../Utils/cmClasses.h"

#include <iostream>   // std::cout
#include <string>     // std::string, std::stoi

#include "../../Utils/cm.h"
#include "../../Utils/mropt.h"

int main(int argc, char *argv[]) {

	/** Signal file name. */
	std::string SFN;
	/** Noise file name. */
	std::string NFN;

	/** Noise file name. */
	std::string OFN;

	/**Noise typee. */
	std::string NType="noiseFile";

	/**Reconstruciton type. */
    std::string RECONTYPE="Reconstruction";

	/**Reconstruciton type. */
	std::string RECON="RSS";

	/**Noise Bandwidth evaluation method. */
	std::string NBWType="readfromnoise";
	bool NBW=true;
	float NBWv= std::nanf("1");

	bool UCM=false;

	/** Body coil. */
	std::string BC="no";

	/**noise typee. */
	std::string SENS="inner";

	// acceleration
	int frequencyAcceleration=1;
	int phase0Acceleration=1;
	int phase1Acceleration=std::nanf("1");//this part will be usefull for the 3D acceleration

	//autocalibrations
	int frequencyAutocalibrationLines=1;
	int phase0AutocalibrationLines=1;
	int phase1AutocalibrationLines=std::nanf("1"); //this part will be usefull for the 3D acceleration

	/** The options */
	po::options_description desc("The software calculates 2D SNR or reconstruciton from two ismrmrd file, noise and signal: Allowed options");
	desc.add_options()("help,h", "Produce HELP message")
																	("signalfilename,s",po::value<std::string>(&SFN), " Signal Filename (H5)")
																	("noiselfilename,n",po::value<std::string>(&NFN), " Noise Filename (H5)")
																	("function,f",po::value<std::string>(&RECONTYPE), " Reconstruction or SNR")

																	("noisetype,t",po::value<std::string>(&NType), " Noise Type (noiseFile,selfMulti,selfSingle)")
																	("outputimage,o",po::value<std::string>(&OFN), " OUTPUTIMAGE file")
																	("noisebandwidthvalue,b",po::value<float>(&NBWv), " noise BW value")
																	("noisebandwidthmethod,t",po::value<std::string>(&NBWType), " How do you want your bandwidth to be evaluated? (readfromnoise,calculatefromnoise,setvalue,no)")
//																	("usecovariancematrix,U",po::value<bool>(&UCM), " use noisecovariance matrix (false)")
																	("reconstructiontype,r",po::value<std::string>(&RECON), " Reconstruction type (RSS)")
																	("coilsensitivitymethod,S", po::value<std::string>(&SENS), "coilsensitivitymethod (INNER)")
																	//  														    ("bc,B", po::value<std::string>(&BC), " the BC id s set the sensemethod is set to BC")
																	("frequencyacceleration,A",po::value<int>(&frequencyAcceleration), " frequency acceleration (1)")
																	("phaseacceleration,B",po::value<int>(&phase0Acceleration), " phase acceleration (1) ");
																	("frequencyautocalibrationlines,L",po::value<int>(&frequencyAutocalibrationLines), " frequency acceleration (1)");
	   																("phaseautocalibration,M",po::value<int>(&phase0AutocalibrationLines), " phase acceleration (0) ");

	;

	po::options_description myerror("test main class SNR array combining\n Eros Montin, PhD");

	po::variables_map vm;

	if (argc < 1) {
		std::cout << myerror << "\n";
		return 1;
	}
	try {
		po::store(po::parse_command_line(argc, argv, desc), vm);
		po::notify(vm);

		if (vm.count("help")) {
			std::cout << desc << "\n";
			return 1;
		}

	}

	catch (po::error& e) {
		std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
		std::cerr << desc << std::endl;
		return -1;

	}

//check if the reconstructor type is set correctly

	const std::string R = boost::algorithm::to_lower_copy(RECONTYPE);
	std::cout<<R<<"\n"<<"\n\n"<<std::endl;

	if (boost::iequals(R,"reconstruction") || (boost::iequals(R,"snr")))
		{
			std::cout<<R<<std::endl;

		}
		else
		{		std::cout << "Choose between to reconstruct the image (-f reconstruction) or to calculate the snr (-f snr) "<<"\n"<<myerror << "\n";
		return 1;
		}

	// let's read the image
	mroptimum::H5ReaderType ::Pointer rs=mroptimum::H5ReaderType::New();
	rs->SetIsmrmrdFileName(SFN);
	rs->SetaverageImageThroughAverages(true);
	rs->SetremoveFrequencyOversampling(true);
	rs->Update();

	mroptimum::H5ReaderType::Pointer rn=mroptimum::H5ReaderType::New();

	if (boost::iequals(NType,"noiseFile"))
	{
		rn->SetIsmrmrdFileName(NFN);
		rn->SetremoveFrequencyOversampling(false);
		rn->SetaverageImageThroughAverages(false);
		rn->Update();
	}

	//Filter Area
	mroptimum::ReconstructorType::Pointer filter;

	if (boost::iequals(R,"reconstruction")){
	filter=mroptimum::selectReconstructor(RECON);
	}

	if (boost::iequals(R,"snr")){
	filter=mroptimum::selectSNRUnitsReconstructor(RECON);
	}

	filter->SetInput(rs->GetOutput());
	filter->SetKSpaceDimension(rs->GetKSpaceDimension());
	filter->SetNoiseKSpace(rn->GetOutput());
	filter->SetNoiseBandWidthCorrection(true);

	//	Noise Bandwidth area
	if (boost::iequals(NBWType,"readfromnoise")){
		filter->SetNoiseBandWidth(rn->getRelativeReceiverBandwidth());
	}

	if (boost::iequals(NBWType,"calculatefromnoise")){
		//nothing to do already done in the class
	}
	if (boost::iequals(NBWType,"setvalue"))
	{filter->SetNoiseBandWidth(NBWv);}

	if (boost::iequals(NBWType,"no")){
		filter->SetNoiseBandWidthCorrection(false);
		filter->SetNoiseBandWidth(1.00);
	}

	//Sensitivity area

	if(filter->GetHasSensitivity())
	{
		if (boost::iequals(SENS,"INNER"))
		{

			filter->SetSensitivityMapCalculationMode(cm::SensitivityMapCalculation::INNER);

		}
		//		if(boost::iequals(SENS,"BC") || vm.count("bc"))
		//		{
		//
		//
		//			filter->SetSensitivityMapCalculationMode(cm::SensitivityMapCalculation::BODYCOIL);
		//
		//
		//			if (vm.count("bc")) {
		//
		//
		//				filter->SetBodyCoilSource(rb->GetOutput());
		//
		//			}
		//
		//		}
	}

	//Aceleration
	if(filter->GetHasAcceleration())
	{

		cm::VectorImageType::IndexType ACL={frequencyAutocalibrationLines, phase0AutocalibrationLines, phase1AutocalibrationLines};
		cm::VectorImageType::IndexType ACC={frequencyAutocalibrationLines, phase0AutocalibrationLines, phase1AutocalibrationLines};

		filter->SetAcceleration(ACC);
		filter->SetAutocalibrationLines(ACL);
	}

	filter->Update();

	if(vm.count("outputimage"))
	{

		typedef itk::ImageFileWriter<cm::ScalarImageType >  W3Type;
		typename W3Type::Pointer w3 = W3Type::New();
		w3->SetInput(filter->GetOutput());
		w3->SetFileName(OFN);
		w3->Update();

	}

	return EXIT_SUCCESS;
}

ext: cxx

max_stars_repo_name: cloudmrhub-com/CMRCode

max_issues_repo_name: cloudmrhub-com/CMRCode

max_forks_repo_name: cloudmrhub-com/CMRCode


text:
//  (C) Copyright John Maddock 2006.
//  Use, modification and distribution are subject to the
//  Boost Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_MATH_SF_CBRT_HPP
#define BOOST_MATH_SF_CBRT_HPP

#ifdef _MSC_VER
#pragma once
#endif

#include <boost/math/tools/roots.hpp>
#include <boost/math/special_functions/math_fwd.hpp>

namespace boost{ namespace math{

namespace detail
{

   template <class T>
   struct cbrt_functor
   {
       cbrt_functor(T const& target) : a(target){}
       std::tr1::tuple<T, T, T> operator()(T const& z)
       {
         T sqr = z * z;
         return std::tr1::make_tuple(sqr * z - a, 3 * sqr, 6 * z);
       }
   private:
       T a;
   };

template <class T, class Policy>
T cbrt_imp(T z, const Policy&)
{
   BOOST_MATH_STD_USING
   int i_exp, sign(1);
   if(z < 0)
   {
      z = -z;
      sign = -sign;
   }
   if(z == 0)
      return 0;

   frexp(z, &i_exp);
   T min = static_cast<T>(ldexp(0.5, i_exp/3));
   T max = static_cast<T>(ldexp(2.0, i_exp/3));
   T guess = static_cast<T>(ldexp(1.0, i_exp/3));
   int digits = (policies::digits<T, Policy>()) / 2;
   return sign * tools::halley_iterate(detail::cbrt_functor<T>(z), guess, min, max, digits);
}

} // namespace detail

template <class T, class Policy>
inline typename tools::promote_args<T>::type cbrt(T z, const Policy& pol)
{
   typedef typename tools::promote_args<T>::type result_type;
   return detail::cbrt_imp(result_type(z), pol);
}

template <class T>
inline typename tools::promote_args<T>::type cbrt(T z)
{
   return cbrt(z, policies::policy<>());
}

} // namespace math
} // namespace boost

#endif // BOOST_MATH_SF_CBRT_HPP

max_issues_repo_name: mrfarhadi/BinClone

max_forks_repo_name: mrfarhadi/BinClone


text:
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2014 MaidSafe.net Limited
//
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)
//
///////////////////////////////////////////////////////////////////////////////

#ifndef MAIDSAFE_CRUX_ACCEPTOR_HPP
#define MAIDSAFE_CRUX_ACCEPTOR_HPP

#include <memory>
#include <boost/asio/io_service.hpp>
#include <maidsafe/crux/detail/service.hpp>
#include <maidsafe/crux/endpoint.hpp>
#include <maidsafe/crux/socket.hpp>

namespace maidsafe
{
namespace crux
{

class acceptor
    : public boost::asio::basic_io_object<detail::service>
{
public:
    using endpoint_type = crux::endpoint;
    using socket_type = crux::socket;

    acceptor(boost::asio::io_service& io,
             endpoint_type local_endpoint);

    template <typename AcceptHandler>
    void async_accept(socket_type& socket,
                      AcceptHandler&& handler);

    endpoint_type local_endpoint() const;

private:
    template <typename AcceptHandler>
    void process_accept(const boost::system::error_code& error,
                        socket_type& socket,
                        AcceptHandler&& handler);

private:
    std::shared_ptr<detail::multiplexer> multiplexer;
};

} // namespace crux
} // namespace maidsafe

#include <cassert>
#include <utility>
#include <functional>

namespace maidsafe
{
namespace crux
{

inline acceptor::acceptor(boost::asio::io_service& io,
                          endpoint_type local_endpoint)
    : boost::asio::basic_io_object<detail::service>(io),
      multiplexer(get_service().add(local_endpoint))
{
}

template <typename AcceptHandler>
void acceptor::async_accept(socket_type& socket,
                            AcceptHandler&& handler)
{
    assert(multiplexer);

    multiplexer->async_accept
        (socket,
         [this, &socket, handler]
         (const boost::system::error_code& error)
         {
             this->process_accept(error, socket, handler);
         });
}

template <typename AcceptHandler>
void acceptor::process_accept(const boost::system::error_code& error,
                              socket_type& socket,
                              AcceptHandler&& handler)
{
    switch (error.value())
    {
    case 0:
        {
            // FIXME: set local_endpoint?
            socket.set_multiplexer(multiplexer);
            multiplexer->add(&socket);
            boost::system::error_code success;
            handler(success);
        }
        break;

    case boost::asio::error::operation_aborted:
    default:
        handler(error);
        break;
    }
}

acceptor::endpoint_type acceptor::local_endpoint() const
{
    assert(multiplexer);

    return multiplexer->next_layer().local_endpoint();
}

} // namespace crux
} // namespace maidsafe

#endif // MAIDSAFE_CRUX_ACCEPTOR_HPP

max_stars_repo_name: chandraprakash/MaidSafe-CRUX

max_issues_repo_name: chandraprakash/MaidSafe-CRUX

max_forks_repo_name: chandraprakash/MaidSafe-CRUX