text:
/* LICENSE:
Copyright (c) Members of the EGEE Collaboration. 2010.
See http://www.eu-egee.org/partners/ for details on the copyright
holders.

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

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

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

END LICENSE */

/**
 *
 * ICE Headers
 *
 */
#include "iceCommandUpdateStatus.h"
#include "emptyStatusNotification.h"
#include "normalStatusNotification.h"
#include "iceLBLogger.h"
#include "iceLBEventFactory.h"
#include "iceUtils.h"
#include "ice-core.h"
//#include "subscriptionManager.h"
#include "DNProxyManager.h"
#include "iceDb/GetJobByCid.h"
#include "iceDb/Transaction.h"
#include "iceDb/GetCreamURLUserDN.h"
#include "iceDb/GetFields.h"

// CREAM stuff
#include "glite/ce/cream-client-api-c/creamApiLogger.h"

// other gLite stuff
#include "classad_distribution.h"

// boost includes
#include <boost/scoped_ptr.hpp>
#include <boost/algorithm/string.hpp>

// System includes
#include <iostream>

// STL stuff
#include <set>
#include <list>

namespace api = glite::ce::cream_client_api;
using namespace glite::wms::ice::util;
using namespace std;

iceCommandUpdateStatus::iceCommandUpdateStatus( const vector<monitortypes__Event>& ev, const string& cemondn ) :
    iceAbsCommand( "iceCommandUpdateStatus", "" ),
    m_log_dev( api::util::creamApiLogger::instance()->getLogger() ),
    m_ev( ev ),
    m_cemondn( cemondn )
{
    static const char* method_name = "iceCommandUpdateStatus::iceCommandUpdateStatus() - ";
    if ( m_log_dev->isInfoEnabled() ) {
        // Dumps the content of the notification
        vector< monitortypes__Event >::const_iterator it;
        for ( it = m_ev.begin(); m_ev.end() != it; ++it ) {
            CREAM_SAFE_LOG(m_log_dev->debugStream()
                           << method_name
                           << "Message dump follows"
                           );

            vector< string >::const_iterator msg_it;
            for ( msg_it = it->Message.begin();
                  msg_it != it->Message.end(); msg_it++ ) {
                CREAM_SAFE_LOG(m_log_dev->debugStream()
                               << method_name
                               << "Got notification: "
                               << boost::replace_all_copy( *msg_it, "\n", " " )
                               );
            }
        }
    }
}

//____________________________________________________________________________
void iceCommandUpdateStatus::execute( const std::string& tid) throw( )
{
  //    jobCache *cache( jobCache::getInstance() );

  m_thread_id = tid;

    static const char* method_name = "iceCommandUpdateStatus::execute() - ";

    // We define two "sets" of operations which must be performed by
    // the status change notifications.

    set< string > subscription_set; // The set of subscription IDs for
                                    // which an empty status change
                                    // notification has been received

    list< absStatusNotification* > commands; // The set of commands
                                             // which will be executed
                                             // to update the jobs
                                             // according to the
                                             // content of each
                                             // notification received.

    //
    // This method operates in two passes.
    //
    // During pass 1. we scan the vector of monitortypes__Event. For
    // each event:
    //
    // 1a: if it is a "normal" (i.e., non-empty status notification),
    // we create an appropriate normalStatusNotification object which
    // will update the status of that specific job, and push that
    // object in the commands list.
    //
    // 1b: if it is an "empty" status notification, then we insert in
    // the subscription_set set the pair (subscription_id, cemondn),
    // so that each pair will appear only once in the set.
    //

      vector< monitortypes__Event >::const_iterator it;
      for ( it = m_ev.begin(); m_ev.end() != it; ++it ) {

        if( it->Message.empty() ) {
	  CREAM_SAFE_LOG( m_log_dev->warnStream()
			  << method_name
			  << "got a CEMon notification with no messages. Skipping."
			  );
            continue; // Skip to the next notification
        }

        CREAM_SAFE_LOG( m_log_dev->debugStream()
                        << method_name
                        << "processing notification, with "
                        << it->Message.size() << " events"
                        );

        string first_event( *(it->Message.begin()) );
        string printable_first_event( boost::replace_all_copy( first_event, "\n", " " ) );

	bool has_keep_alive;
	bool has_subid;
	bool keep_alive;
	string subs_id;
	{ // Classad-mutex protected region

	  boost::recursive_mutex::scoped_lock M_classad( util::CreamJob::s_classad_mutex );

	  classad::ClassAdParser parser;
	  classad::ClassAd *ad = parser.ParseClassAd( first_event );

	  if ( !ad ) {
	    CREAM_SAFE_LOG(m_log_dev->errorStream()
			   << method_name
			   << "Cannot parse notification classad "
			   << printable_first_event
			   );
	    continue; // Skip to the next notification
	  }

	  // Classad gets destroyed when exiting the scope
	  boost::scoped_ptr< classad::ClassAd > classad_safe_ptr( ad );

	  keep_alive = false;
	  //string subs_id;

	  // Check whether the current notification is an empty notification
	  has_keep_alive = classad_safe_ptr->EvaluateAttrBool( "KEEP_ALIVE", keep_alive );
	  has_subid      = classad_safe_ptr->EvaluateAttrString( "SUBSCRIPTION_ID", subs_id );
	} // end of Classad-mutex protected region

        if ( has_keep_alive && keep_alive && has_subid ) {
            // Push the subs_id into the set, which will be considered
            // after all the notifications have been examined.
            subscription_set.insert( subs_id );

        } else {
            // Push back a normalStatusNotification, which will update
            // the status of the job referenced in the monitor event
            normalStatusNotification* notif = 0;
            try {
                notif = new normalStatusNotification( *it, m_cemondn );
            } catch( ... ) {
                CREAM_SAFE_LOG( m_log_dev->errorStream()
                                << method_name
                                << "Unable to make normal status notification for notification "
                                << printable_first_event
                                << " Skipping to the next notification"
                                );
                continue;
            }

            commands.push_front( notif );

            // Gets the job which is mentioned in the notification
	    //            boost::recursive_mutex::scoped_lock L( jobCache::mutex );
	    //boost::recursive_mutex::scoped_lock L( CreamJob::globalICEMutex );

            //jobCache::iterator job_it( cache->lookupByCompleteCreamJobID( notif->get_complete_cream_job_id() ) );
	    CreamJob theJob;
	    {
	      db::GetJobByCid getter( notif->get_complete_cream_job_id(), "iceCommandUpdateStatus::execute" );
	      db::Transaction tnx(false, false);
	      //tnx.begin( );
	      tnx.execute( &getter );
	      if( !getter.found() )
		{
		  CREAM_SAFE_LOG( m_log_dev->warnStream()
				  << method_name
				  << "Job with CREAM job id ["
				  << notif->get_complete_cream_job_id()
				  << "] was not found in the cache. Cannot update "
				  << "the set of subscriptions the jobs belongs to"
				  );
		} else {
		theJob = getter.get_job();
		// Gets the subscription ID which is used to get
                // notifications associated with that job.

		iceSubscription subscription;
		string cemon_url;
		string proxy = DNProxyManager::getInstance()->getAnyBetterProxyByDN( theJob.get_user_dn() ).get<0>();
		//subscriptionManager::getInstance()->getCEMonURL(proxy, theJob.get_cream_address(), cemon_url);
		//subscriptionManager::getInstance()->getSubscriptionByDNCEMon( theJob.get_user_dn(), cemon_url, subscription );
                string subs_id( subscription.getSubscriptionID()/*job_it->getSubscriptionID()*/ );

                // Then, push the pair (subs_id, cemondn) into the
                // set.  This is necessary, as a normal status
                // notification should also update all the jobs of
                // that subs_id, in the exact same way as empty status
                // notifications do.
                CREAM_SAFE_LOG( m_log_dev->debugStream()
                                << method_name
                                << "Normal status notification for job "
                                << theJob.describe()
                                << " requires adding subscription id "
                                << subs_id
                                << " to the set of subscriptions whose jobs "
                                << "will be updated"
                                );

                subscription_set.insert( subs_id );
	      }
	    }

//             if ( cache->end() != job_it ) {

//                 // Gets the subscription ID which is used to get
//                 // notifications associated with that job.

// 		iceSubscription subscription;
// 		string cemon_url;
// 		string proxy = DNProxyManager::getInstance()->getAnyBetterProxyByDN( job_it->getUserDN() ).get<0>();
// 		subscriptionManager::getInstance()->getCEMonURL(proxy, job_it->getCreamURL(), cemon_url);
// 		subscriptionManager::getInstance()->getSubscriptionByDNCEMon( job_it->getUserDN(), cemon_url, subscription );
//                 string subs_id( subscription.getSubscriptionID()/*job_it->getSubscriptionID()*/ );

//                 // Then, push the pair (subs_id, cemondn) into the
//                 // set.  This is necessary, as a normal status
//                 // notification should also update all the jobs of
//                 // that subs_id, in the exact same way as empty status
//                 // notifications do.
//                 CREAM_SAFE_LOG( m_log_dev->debugStream()
//                                 << method_name
//                                 << "Normal status notification for job "
//                                 << job_it->describe()
//                                 << " requires adding subscription id "
//                                 << subs_id
//                                 << " to the set of subscriptions whose jobs "
//                                 << "will be updated"
//                                 );

//                 subscription_set.insert( subs_id );
//             } else {
//                 CREAM_SAFE_LOG( m_log_dev->warnStream()
//                                 << method_name
//                                 << "Job with CREAM job id ["
//                                 << notif->get_complete_cream_job_id()
//                                 << "] was not found in the cache. Cannot update the set of subscriptions the jobs belongs to"
//                                 );
//             }
        }
    }

    // At this point, we complete the list of commands to add also the
    // processing of empty status notifications. We do this by
    // checking al the jobs in the cache.
    {
      //boost::recursive_mutex::scoped_lock L( jobCache::mutex );
      //      boost::recursive_mutex::scoped_lock L( CreamJob::globalICEMutex );

      /**
	 SELECT DISTINCT creamurl,userdn FROM jobs;
      */

      list< pair<string, string> > list_creamurl_userdn, save;

      {
 	list<string> params;
	params.push_back( "creamurl" );
	params.push_back( "userdn" );
	list< vector<string> > result;
	db::GetFields getter( params, list<pair<string, string> >(), result, "iceCommandUpdateStatus::execute",true/* use DISTINCT = true */ );
        {
	  db::Transaction tnx(false, false);
	  tnx.execute( &getter );
	}

        for( list< vector<string> >::const_iterator it=result.begin();
             it != result.end();
	     ++it )
	{
	  string creamurl = it->at(0);
	  string userdn   = it->at(1);

	  list_creamurl_userdn.push_back( make_pair( creamurl, userdn ) );
	}

      }

      for( list< pair<string, string> >::const_iterator it=list_creamurl_userdn.begin();
	   it != list_creamurl_userdn.end();
	   ++it)
	{
	  string proxy = DNProxyManager::getInstance()->getAnyBetterProxyByDN( it->second ).get<0>();
	  iceSubscription subscription;
	  string cemon_url;
	  subscriptionManager::getInstance()->getCEMonURL(proxy, it->first, cemon_url);
	  subscriptionManager::getInstance()->getSubscriptionByDNCEMon( it->second, cemon_url, subscription );
	  string subs_id( subscription.getSubscriptionID() );

	  if ( subscription_set.end() !=  subscription_set.find( subs_id ) ) {
	    save.push_back( *it );
	  }
	}

      list<string> cids;
      for( list< pair<string, string> >::const_iterator it=save.begin();
	   it != save.end();
	   ++it)
	{
	  list<string> fields_to_retrieve;
	  fields_to_retrieve.push_back( "complete_cream_jobid" );
	  list<pair<string, string> > clause;
	  clause.push_back( make_pair("creamurl", it->first ) );
	  clause.push_back( make_pair("userdn", it->second ) );

	  //list<list<string> > result;
	  //db::GetCidByCreamURLUserDN getter( *it );
	  list< vector< string> > tmp;
	  db::GetFields getter( fields_to_retrieve, clause, tmp, "iceCommandUpdateStatus::execute" );
	  db::Transaction tnx(false, false);
	  tnx.execute( &getter );

	  //	  list< vector< string> > tmp = getter.get_values();
	  list< string > _tmp_cids;
	  for(list< vector< string> >::const_iterator it=tmp.begin();
	      it!=tmp.end();
	      ++it)
	      {
	        string thisCompleteCreamJobID = it->at(0);
	        _tmp_cids.push_back( thisCompleteCreamJobID );
	      }

	  cids.merge( _tmp_cids );
	}

      for( list<string>::const_iterator it=cids.begin();
	   it != cids.end();
	   ++it)
	{
	  commands.push_front( new emptyStatusNotification( *it ) );
	}

    } // end block, unlock global mutex

    // Now executes all the commands in the list
      while( ! commands.empty() ) {
        boost::scoped_ptr< absStatusNotification > elem( commands.front() );
        commands.pop_front();
        try {
	  elem->apply();
        } catch( ... ) {
	  // FIXME
        }
      }
    }

max_stars_repo_name: italiangrid/wms

max_issues_repo_name: italiangrid/wms

max_forks_repo_name: italiangrid/wms


text:
// portions of run() fall under:

// server.cpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#include <ctime>
#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>

#include <fstream>

#include "DeviceState.h"
#include "DeviceStateServer.h"
#include "devicestate_cs_common.h"

using namespace std;

using boost::asio::ip::tcp;

string
DeviceStateServer::
read_from_file(const string filename)
{
    string line;
    if (m_fin == 0)
        m_fin = new ifstream(filename.c_str());

    if (getline(*m_fin, line))
        return line;
    else
        return "";
}

void
DeviceStateServer::
updateState(DeviceState & deviceState)
{
    if ( ! m_currentState )
        m_currentState = new DeviceState(0, 0);

    *m_currentState = deviceState;
}

void
DeviceStateServer::
setInputFilename(const string filename)
{
    m_filename = filename;

    if (m_fin)
    {
        m_fin->close();
        m_fin = NULL;
    }
}

/** Keep serving connection attempts requesting the current state until
 * terminate() is called, or the input file giving the next state is exhausted.
 */
void
DeviceStateServer::
run()
{
    string message;

    try
    {
        boost::asio::io_service io_service;
        tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), SERVER_PORT));

        while (true)
        {
            tcp::socket socket(io_service);
            acceptor.accept(socket);

            if (m_inputSource == FILE_INPUT)
            {
                message = read_from_file(m_filename) + "\n";

                // Terminate once the end of the file has been reached.
                if (! m_fin->good())
                {
                    cout << "END OF FILE. Terminating server..." << endl;
                    return;
                }
            }

            else if (m_inputSource == MANUAL_INPUT)
            {
                message = m_currentState->serialize();
            }

            boost::system::error_code ignored_error;
            boost::asio::write(socket, boost::asio::buffer(message),
                               boost::asio::transfer_all(), ignored_error);
        }
    }
    catch (exception& e)
    {
        cerr << e.what() << endl;
    }
}

/*

void manuallyUpdateState(DeviceStateServer * server)
{
    DeviceState devState;
    string line;

    if (server == NULL)
        return;

    cout << "Please enter a line containing two numbers: x-position, y-position" << endl
         << "e.g.     .5  .5" << endl
         << "Note that the positions will be adapted to the dimensions at the" << endl
         << "client end, and must therefore be between 0 and 1." << endl;

    while ( getline(cin, line) )
    {
        devState.instantiate(line);
        server->updateState(devState);
    }
}

int main(int argc, char * argv[])
{
    DeviceStateServer server;
    string filename;
    bool configured = false;

    for ( int i = 1; i < argc; i++)
    {
        if      (!strcmp(argv[i], "-manual-input"))
        {
            configured = true;
            server.setInputSource( DeviceStateServer::MANUAL_INPUT );
            boost::thread second_thread( boost::bind( manuallyUpdateState, & server ) );
        }
        else if (!strcmp(argv[i], "-file-input"))
        {
            configured = true;
            server.setInputSource( DeviceStateServer::FILE_INPUT );
            server.setInputFilename(argv[++i]);
        }
    }

    if ( ! configured )
    {
        cerr << "usage: Run using either of the following methods:\n\n"
             << "  ./DeviceStateServer -manual-input\n"
             << "               # to allow manual control of position\n"
             << "  ./DeviceStateServer -file-input [INPUT_FILE]\n"
             << "               # automatic control based on given file\n"
             << "               # (see position_file.txt for an example)\n" << endl;
        return 1;
    }

    server.run();
}
*/

ext: cpp

max_stars_repo_name: jmlien/shepherding

max_issues_repo_name: jmlien/shepherding

max_forks_repo_name: jmlien/shepherding


text:
#include <Discregrid/All>
#include <Eigen/Dense>
#include <cxxopts/cxxopts.hpp>

#include <string>
#include <iostream>
#include <array>

#include "sph_kernel.hpp"
#include "gauss_quadrature.hpp"

using namespace Eigen;

std::istream& operator>>(std::istream& is, std::array<unsigned int, 3>& data)
{
	is >> data[0] >> data[1] >> data[2];
	return is;
}

std::istream& operator>>(std::istream& is, AlignedBox3d& data)
{
	is	>> data.min()[0] >> data.min()[1] >> data.min()[2]
		>> data.max()[0] >> data.max()[1] >> data.max()[2];
	return is;
}

int main(int argc, char* argv[])
{
	cxxopts::Options options(argv[0], "Generates a signed distance field from a closed two-manifold triangle mesh.");
	options.positional_help("[input OBJ file]");

	options.add_options()
	("h,help", "Prints this help text")
	("r,rest_density", "Rest density rho0 of the fluid", cxxopts::value<double>()->default_value("1000.0"))
	("i,invert", "Invert field")
	("s,smoothing_length", "Kernel smoothing length", cxxopts::value<double>()->default_value("0.1"))
	("o,output", "Ouput file in cdf format", cxxopts::value<std::string>()->default_value(""))
	("no-reduction", "Disables discarding of cells for sparse layout.")
	("input", "Discrete grid file containing input SDF in field 0", cxxopts::value<std::vector<std::string>>())
	;

	try
	{
		options.parse_positional("input");
		options.parse(argc, argv);
	}
	catch (cxxopts::OptionException const& e)
	{
		std::cout << "error parsing options: " << e.what() << std::endl;
		exit(1);
	}
	if (options.count("help"))
	{
		std::cout << options.help() << std::endl;
		std::cout << std::endl << std::endl << "Example: GenerateSDF -r \"50 50 50\" dragon.obj" << std::endl;
		exit(0);
	}
	if (!options.count("input"))
	{
		std::cout << "ERROR: No input SDF given." << std::endl;
		std::cout << options.help() << std::endl;
		std::cout << std::endl << std::endl << "Example: GenerateDensityMap -r \"50 50 50\" field.cdf" << std::endl;
		exit(1);
	}
	auto filename = options["input"].as<std::vector<std::string>>().front();

	if (!std::ifstream(filename).good())
	{
		std::cerr << "ERROR: Input file does not exist!" << std::endl;
		exit(1);
	}

	auto sdf = std::unique_ptr<Discregrid::DiscreteGrid>{};

	auto lastindex = filename.find_last_of(".");
	auto extension = filename.substr(lastindex+1, filename.length() - lastindex);

	std::cout << "Load SDF...";
	if (extension == "cdf")
	{
		sdf = std::make_unique<Discregrid::CubicLagrangeDiscreteGrid>(filename);
	}
	std::cout << "DONE" << std::endl;

	auto h = options["s"].as<double>();
	auto sph_kernel = CubicKernel{};
	sph_kernel.setRadius(h);
	auto gamma = [&](Vector3d const& x)
	{
		auto ar = sph_kernel.getRadius();
		auto dist = sdf->interpolate(0u, x);
		if (dist > ar)
			return 0.0;
		return 1.0 - dist / ar;
	};
	auto int_domain = AlignedBox3d(Vector3d::Constant(-h), Vector3d::Constant(h));
	auto rho0 = options["r"].as<double>();
	auto density_func = [&](Vector3d const& x)
	{
		auto dist = sdf->interpolate(0u, x);
		if (dist > 2.0 * sph_kernel.getRadius())
		{
			return 0.0;
		}

		auto integrand = [&sph_kernel, &gamma, &x](Vector3d const& xi)
		{
			auto res = gamma(x + xi) * sph_kernel.W(xi);
			return res;
		};

		auto res = GaussQuadrature::integrate(integrand, int_domain, 30);
		return rho0 * res;
	};

	auto no_reduction = options["no-reduction"].count() > 0u;

	auto cell_diag = sdf->cellSize().norm();
	std::cout << "Generate density map..." << std::endl;
	sdf->addFunction(density_func, true, [&](Vector3d const& x_)
	{
		if (no_reduction)
		{
			return true;
		}
		auto x = x_.cwiseMax(sdf->domain().min()).cwiseMin(sdf->domain().max());
		auto dist = sdf->interpolate(0u, x);
		if (dist == std::numeric_limits<double>::max())
		{
			return false;
		}

		return -6.0 * h < dist + cell_diag && dist -cell_diag < 2.0 * h;
	});

	if (options["no-reduction"].count() == 0u)
	{
		std::cout << "Reduce discrete fields...";
		sdf->reduceField(0u, [&](auto const&, double v)
		{
			return -6.0 * h < v + cell_diag && v -cell_diag  < 2.0 * h;
		});
		sdf->reduceField(1u, [&](auto const&, double v)
		{
			return 0.0 <= v && v <= 3.0 * rho0;
		});
		std::cout << "DONE" << std::endl;
	}

	std::cout << "Serialize discretization...";
	auto output_file = options["o"].as<std::string>();
	if (output_file == "")
	{
		output_file = filename;
		if (output_file.find(".") != std::string::npos)
		{
			auto lastindex = output_file.find_last_of(".");
			output_file = output_file.substr(0, lastindex);
		}
		output_file += ".cdm";
	}
	sdf->save(output_file);
	std::cout << "DONE" << std::endl;

	return 0;
}


text:
/*
 input.cpp

 Copyright (c) 2014, 2015, 2016 Terumasa Tadano

 This file is distributed under the terms of the MIT license.
 Please see the file 'LICENCE.txt' in the root directory
 or http://opensource.org/licenses/mit-license.php for information.
*/

#include "input.h"
#include <iostream>
#include <string>
#include "memory.h"
#include "files.h"
#include "interaction.h"
#include "system.h"
#include "symmetry.h"
#include "error.h"
#include "fitting.h"
#include "constraint.h"
#include "fcs.h"
#include "patterndisp.h"
#include <algorithm>
#include <map>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

using namespace ALM_NS;

Input::Input(ALM *alm, int narg, char **arg): Pointers(alm) {}

Input::~Input() {}

void Input::parce_input(int narg, char **arg)
{

    if (narg == 1) {

        from_stdin = true;

    } else {

        from_stdin = false;

        ifs_input.open(arg[1], std::ios::in);
        if (!ifs_input) {
            std::cout << "No such file or directory: " << arg[1] << std::endl;
            exit(EXIT_FAILURE);
        }
    }

    if (!locate_tag("&general")) {
        error->exit("parse_input", "&general entry not found in the input file");
    }
    parse_general_vars();

    if (!locate_tag("&cell")) {
        error->exit("parse_input", "&cell entry not found in the input file");
    }
    parse_cell_parameter();

    if (!locate_tag("&interaction")) {
        error->exit("parse_input", "&interaction entry not found in the input file");
    }
    parse_interaction_vars();

    if (!locate_tag("&cutoff")) {
        error->exit("parse_input", "&cutoff entry not found in the input file");
    }
    parse_cutoff_radii();

    if (alm->mode == "fitting") {
        if (!locate_tag("&fitting")) {
            error->exit("parse_input", "&fitting entry not found in the input file");
        }
        parse_fitting_vars();
    }

    if (!locate_tag("&position")) {
        error->exit("parse_input", "&position entry not found in the input file");
    }
    parse_atomic_positions();
}

void Input::parse_general_vars()
{
    int i, j;
    std::string prefix, mode, str_tmp, str_disp_basis;
    int nat, nkd, nsym;
    int is_printsymmetry, is_periodic[3];
    int icount, ncount;
    bool trim_dispsign_for_evenfunc;
    bool lspin;
    int noncollinear, trevsym;
    std::string *kdname;
    double **magmom, magmag;
    double tolerance;

    std::vector<std::string> kdname_v, periodic_v, magmom_v, str_split;
    std::string str_allowed_list = "PREFIX MODE NAT NKD NSYM KD PERIODIC PRINTSYM TOLERANCE DBASIS TRIMEVEN\
                                   MAGMOM NONCOLLINEAR TREVSYM";
    std::string str_no_defaults = "PREFIX MODE NAT NKD KD";
    std::vector<std::string> no_defaults;
    std::map<std::string, std::string> general_var_dict;

    if (from_stdin) {
        std::cin.ignore();
    } else {
        ifs_input.ignore();
    }

    get_var_dict(str_allowed_list, general_var_dict);

    boost::split(no_defaults, str_no_defaults, boost::is_space());

    for (std::vector<std::string>::iterator it = no_defaults.begin(); it != no_defaults.end(); ++it) {
        if (general_var_dict.find(*it) == general_var_dict.end()) {
            error->exit("parse_general_vars",
                "The following variable is not found in &general input region: ", (*it).c_str());
        }
    }

    prefix = general_var_dict["PREFIX"];
    mode = general_var_dict["MODE"];

    std::transform(mode.begin(), mode.end(), mode.begin(), tolower);
    if (mode != "fitting" && mode != "suggest") {
        error->exit("parse_general_vars", "Invalid MODE variable");
    }

    assign_val(nat, "NAT", general_var_dict);
    assign_val(nkd, "NKD", general_var_dict);

    if (general_var_dict["NSYM"].empty()) {
        nsym = 0;
    } else {
        assign_val(nsym, "NSYM", general_var_dict);
    }

    if (general_var_dict["PRINTSYM"].empty()) {
        is_printsymmetry = 0;
    } else {
        assign_val(is_printsymmetry, "PRINTSYM", general_var_dict);
    }

    split_str_by_space(general_var_dict["KD"], kdname_v);

    if (kdname_v.size() != nkd) {
        error->exit("parse_general_vars", "The number of entries for KD is inconsistent with NKD");
    } else {
        memory->allocate(kdname, nkd);
        for (i = 0; i < nkd; ++i){
            kdname[i] = kdname_v[i];
        }
    }

    split_str_by_space(general_var_dict["PERIODIC"], periodic_v);

    if (periodic_v.size() == 0) {
        for (i = 0; i < 3; ++i) {
            is_periodic[i] = 1;
        }
    } else if (periodic_v.size() == 3) {
        for (i = 0; i < 3; ++i) {
            try{
                is_periodic[i] = boost::lexical_cast<int>(periodic_v[i]);
            } catch (std::exception &e) {
                std::cout << e.what() << std::endl;
                error->exit("parse_general_vars", "The PERIODIC tag must be a set of integers.");
            }
        }
    } else {
        error->exit("parse_general_vars", "Invalid number of entries for PERIODIC");
    }

    if (general_var_dict["TOLERANCE"].empty()) {
        tolerance = 1.0e-8;
    } else {
        assign_val(tolerance, "TOLERANCE", general_var_dict);
    }

    // Convert MAGMOM input to array
    memory->allocate(magmom, nat, 3);
    lspin = false;

    for (i = 0; i < nat; ++i) {
        for (j = 0; j < 3; ++j) {
            magmom[i][j] = 0.0;
        }
    }

    if (general_var_dict["NONCOLLINEAR"].empty()) {
        noncollinear = 0;
    } else {
        assign_val(noncollinear, "NONCOLLINEAR", general_var_dict);
    }
    if (general_var_dict["TREVSYM"].empty()) {
        trevsym = 1;
    } else {
        assign_val(trevsym, "TREVSYM", general_var_dict);
    }

    if (!general_var_dict["MAGMOM"].empty()) {
        lspin = true;

        if (noncollinear) {
            icount = 0;
            split_str_by_space(general_var_dict["MAGMOM"], magmom_v);
            for (std::vector<std::string>::const_iterator it = magmom_v.begin(); it != magmom_v.end(); ++it) {
                if ((*it).find("*") != std::string::npos) {
                    error->exit("parse_general_vars", "Wild card '*' is not supported when NONCOLLINEAR = 1.");
                } else {
                    magmag = boost::lexical_cast<double>((*it));
                    if (icount/3 >= nat) {
                        error->exit("parse_general_vars", "Too many entries for MAGMOM.");
                    }
                    magmom[icount/3][icount%3] = magmag;
                    ++icount;
                }
            }

            if (icount != 3 * nat) {
                error->exit("parse_general_vars", "Number of entries for MAGMOM must be 3*NAT when NONCOLLINEAR = 1.");
            }
        } else {
            icount = 0;
            split_str_by_space(general_var_dict["MAGMOM"], magmom_v);
            for (std::vector<std::string>::const_iterator it = magmom_v.begin(); it != magmom_v.end(); ++it) {

                if ((*it).find("*") != std::string::npos) {
                    if ((*it) == "*") {
                        error->exit("parse_general_vars", "Please place '*' without space for the MAGMOM-tag.");
                    }
                    boost::split(str_split, (*it), boost::is_any_of("*"));
                    if (str_split.size() != 2) {
                        error->exit("parse_general_vars", "Invalid format for the MAGMOM-tag.");
                    } else {
                        if (str_split[0].empty() || str_split[1].empty()) {
                            error->exit("parse_general_vars", "Please place '*' without space for the MAGMOM-tag.");
                        }
                        try {
                             magmag = boost::lexical_cast<double>(str_split[1]);
                             ncount = static_cast<int>(boost::lexical_cast<double>(str_split[0]));
                        } catch (std::exception &e) {
                            error->exit("parse_general_vars", "Bad format for MAGMOM.");
                        }

                        for (i = icount; i < icount + ncount; ++i) {
                            magmom[i][2] = magmag;
                        }
                        icount += ncount;
                    }

                } else {
                    magmag = boost::lexical_cast<double>((*it));
                    magmom[icount++][2] = magmag;
                }
            }
            if (icount != nat) {
                error->exit("parse_general_vars", "Number of entries for MAGMOM must be NAT.");
            }
        }
    }

    if (mode == "suggest") {
        if (general_var_dict["DBASIS"].empty()) {
            str_disp_basis = "Cart";
        } else {
            str_disp_basis = general_var_dict["DBASIS"];
        }
        std::transform(str_disp_basis.begin(), str_disp_basis.end(), str_disp_basis.begin(), toupper);
        if (str_disp_basis[0] != 'C' && str_disp_basis[0] != 'F') {
            error->exit("parse_general_vars", "Invalid DBASIS");
        }

        if (general_var_dict["TRIMEVEN"].empty()) {
            trim_dispsign_for_evenfunc = true;
        } else {
            assign_val(trim_dispsign_for_evenfunc, "TRIMEVEN", general_var_dict);
        }

    }

    files->job_title = prefix;
    alm->mode = mode;
    system->nat = nat;
    system->nkd = nkd;
    symmetry->nsym = nsym;
    symmetry->is_printsymmetry = is_printsymmetry;
    symmetry->tolerance = tolerance;

    memory->allocate(system->kdname, nkd);
    memory->allocate(system->magmom, nat, 3);

    for (i = 0; i < nkd; ++i) {
        system->kdname[i] = kdname[i];
    }
    for (i = 0; i < 3; ++i) {
        interaction->is_periodic[i] = is_periodic[i];
    }
    for (i = 0; i < nat; ++i) {
        for (j = 0; j < 3; ++j) {
            system->magmom[i][j] = magmom[i][j];
        }
    }
    system->lspin = lspin;
    system->noncollinear = noncollinear;
    symmetry->trev_sym_mag = trevsym;

    if (mode == "suggest") {
        displace->disp_basis = str_disp_basis;
        displace->trim_dispsign_for_evenfunc = trim_dispsign_for_evenfunc;
    }

    memory->deallocate(kdname);
    memory->deallocate(magmom);

    kdname_v.clear();
    periodic_v.clear();
    no_defaults.clear();
    general_var_dict.clear();
}

void Input::parse_cell_parameter()
{
    int i, j;
    double a;
    double lavec_tmp[3][3];
    std::string line;
    std::string line_wo_comment, line_tmp;
    std::vector<std::string> line_vec, line_split;
    std::string::size_type pos_first_comment_tag;

    line_vec.clear();

    if (from_stdin) {

        while (std::getline(std::cin, line)) {

            // Ignore comment region
            pos_first_comment_tag = line.find_first_of('#');

            if (pos_first_comment_tag == std::string::npos) {
                line_wo_comment = line;
            } else {
                line_wo_comment = line.substr(0, pos_first_comment_tag);
            }

            boost::trim_if(line_wo_comment, boost::is_any_of("\t "));

            if (line_wo_comment.empty()) continue;
            if (is_endof_entry(line_wo_comment)) break;

            line_vec.push_back(line_wo_comment);
        }

    } else {
        while (std::getline(ifs_input, line)) {

            // Ignore comment region
            pos_first_comment_tag = line.find_first_of('#');

            if (pos_first_comment_tag == std::string::npos) {
                line_wo_comment = line;
            } else {
                line_wo_comment = line.substr(0, pos_first_comment_tag);
            }

            boost::trim_if(line_wo_comment, boost::is_any_of("\t "));

            if (line_wo_comment.empty()) continue;
            if (is_endof_entry(line_wo_comment)) break;

            line_vec.push_back(line_wo_comment);
        }
    }

    if (line_vec.size() != 4) {
        error->exit("parse_cell_parameter", "Too few or too much lines for the &cell field.\n \
                                            The number of valid lines for the &cell field should be 4.");
    }

    for (i = 0; i < 4; ++i) {

        line = line_vec[i];
        boost::split(line_split, line, boost::is_any_of("\t "), boost::token_compress_on);

        if (i == 0) {
            // Lattice factor a
            if (line_split.size() == 1) {
                a = boost::lexical_cast<double>(line_split[0]);
            } else {
                error->exit("parse_cell_parameter", "Unacceptable format for &cell field.");
            }

        } else {
            // Lattice vectors a1, a2, a3
            if (line_split.size() == 3) {
                for (j = 0; j < 3; ++j) {
                    lavec_tmp[j][i-1] = boost::lexical_cast<double>(line_split[j]);
                }
            } else {
                error->exit("parse_cell_parameter", "Unacceptable format for &cell field.");
            }
        }
    }

    for (i = 0; i < 3; ++i) {
        for (j = 0; j < 3; ++j) {
            system->lavec[i][j] = a * lavec_tmp[i][j];
        }
    }
}

void Input::parse_interaction_vars()
{
    int i;
    int maxorder;
    int *nbody_include;

    std::vector<std::string> nbody_v;
    std::string str_allowed_list = "NORDER NBODY";
    std::string str_no_defaults = "NORDER";
    std::vector<std::string> no_defaults;
    std::map<std::string, std::string> interaction_var_dict;

    if (from_stdin) {
        std::cin.ignore();
    } else {
        ifs_input.ignore();
    }

    get_var_dict(str_allowed_list, interaction_var_dict);

    boost::split(no_defaults, str_no_defaults, boost::is_space());

    for (std::vector<std::string>::iterator it = no_defaults.begin(); it != no_defaults.end(); ++it) {
        if (interaction_var_dict.find(*it) == interaction_var_dict.end()) {
            error->exit("parse_interaction_vars",
                "The following variable is not found in &interaction input region: ", (*it).c_str());
        }
    }

    assign_val(maxorder, "NORDER", interaction_var_dict);
    if (maxorder < 1) error->exit("parse_interaction_vars", "maxorder has to be a positive integer");

    memory->allocate(nbody_include, maxorder);

    boost::split(nbody_v, interaction_var_dict["NBODY"], boost::is_space());

    if (nbody_v[0].empty()) {
        for (i = 0; i < maxorder; ++i) {
            nbody_include[i] = i + 2;
        }
    } else if (nbody_v.size() == maxorder) {
        for (i = 0; i < maxorder; ++i) {
            try {
                nbody_include[i] = boost::lexical_cast<int>(nbody_v[i]);
            } catch (std::exception &e) {
                std::cout << e.what() << std::endl;
                error->exit("parse_interaction_vars", "NBODY must be an integer.");
            }
        }
    } else {
        error->exit("parse_interaction_vars", "The number of entry of NBODY has to be equal to NORDER");
    }

    if (nbody_include[0] != 2) {
        error->warn("parce_input", "Harmonic interaction is always 2 body (except on-site 1 body)");
    }

    interaction->maxorder = maxorder;
    memory->allocate(interaction->nbody_include, maxorder);

    for (i = 0; i < maxorder; ++i) {
        interaction->nbody_include[i] = nbody_include[i];
    }

    memory->deallocate(nbody_include);
    nbody_v.clear();
    no_defaults.clear();

}

void Input::parse_cutoff_radii()
{
    std::string line, line_wo_comment;
    std::string::size_type pos_first_comment_tag;
    std::vector<std::string> str_cutoff;

    if (from_stdin) {
        std::cin.ignore();
    } else {
        ifs_input.ignore();
    }

    str_cutoff.clear();

    if (from_stdin) {

        while(std::getline(std::cin, line)) {

            pos_first_comment_tag = line.find_first_of('#');

            if (pos_first_comment_tag == std::string::npos) {
                line_wo_comment = line;
            } else {
                line_wo_comment = line.substr(0, pos_first_comment_tag);
            }

            boost::trim_left(line_wo_comment);
            if (line_wo_comment.empty()) continue;
            if (is_endof_entry(line_wo_comment)) break;

            str_cutoff.push_back(line_wo_comment);
        }
    } else {

        while(std::getline(ifs_input, line)) {

            pos_first_comment_tag = line.find_first_of('#');

            if (pos_first_comment_tag == std::string::npos) {
                line_wo_comment = line;
            } else {
                line_wo_comment = line.substr(0, pos_first_comment_tag);
            }

            boost::trim_left(line_wo_comment);
            if (line_wo_comment.empty()) continue;
            if (is_endof_entry(line_wo_comment)) break;

            str_cutoff.push_back(line_wo_comment);
        }

    }

    int i, j, k;
    int nkd = system->nkd;
    int maxorder = interaction->maxorder;
    int ikd, jkd;
    int order;
    std::vector<std::string> cutoff_line;
    std::set<std::string> element_allowed;
    std::vector<std::string> str_pair;
    std::map<std::string, int> kd_map;

    double cutoff_tmp;
    double ***rcs;
    bool ***undefined_cutoff;

    memory->allocate(undefined_cutoff, maxorder, nkd, nkd);

    for (order = 0; order < maxorder; ++order) {
        for (i = 0; i < nkd; ++i) {
            for (j = 0; j < nkd; ++j) {
                undefined_cutoff[order][i][j] = true;
            }
        }
    }

    memory->allocate(rcs, maxorder, nkd, nkd);

    element_allowed.clear();

    for (i = 0; i < nkd; ++i) {
        element_allowed.insert(system->kdname[i]);
        kd_map.insert(std::map<std::string, int>::value_type(system->kdname[i], i));
    }

    element_allowed.insert("*");
    kd_map.insert(std::map<std::string, int>::value_type("*", -1));

    for (std::vector<std::string>::const_iterator it = str_cutoff.begin(); it != str_cutoff.end(); ++it) {

        split_str_by_space(*it, cutoff_line);

        if (cutoff_line.size() < maxorder + 1) {
            error->exit("parse_cutoff_radii", "Invalid format for &cutoff entry");
        }

        boost::split(str_pair, cutoff_line[0], boost::is_any_of("-"));

        if (str_pair.size() != 2) {
            error->exit("parse_cutoff_radii2", "Invalid format for &cutoff entry");
        }

        for (i = 0; i < 2; ++i) {
            if (element_allowed.find(str_pair[i]) == element_allowed.end()) {
                error->exit("parse_cutoff_radii2", "Invalid format for &cutoff entry");
            }
        }

        ikd = kd_map[str_pair[0]];
        jkd = kd_map[str_pair[1]];

        for (order = 0; order < maxorder; ++order) {
            // Accept any strings starting with 'N' or 'n' as 'None'
            if ((cutoff_line[order+1][0] == 'N') || (cutoff_line[order+1][0] == 'n')) {
                // Minus value for cutoff radius.
                // This is a flag for neglecting cutoff radius
                cutoff_tmp = -1.0;
            } else {
                cutoff_tmp = boost::lexical_cast<double>(cutoff_line[order + 1]);
            }

            if (ikd == -1 && jkd == -1) {
                for (i = 0; i < nkd; ++i) {
                    for (j = 0; j < nkd; ++j) {
                        rcs[order][i][j] = cutoff_tmp;
                        undefined_cutoff[order][i][j] = false;
                    }
                }
            } else if (ikd == -1) {
                for (i = 0; i < nkd; ++i) {
                    rcs[order][i][jkd] = cutoff_tmp;
                    rcs[order][jkd][i] = cutoff_tmp;
                    undefined_cutoff[order][i][jkd] = false;
                    undefined_cutoff[order][jkd][i] = false;
                }
            } else if (jkd == -1) {
                for (j = 0; j < nkd; ++j) {
                    rcs[order][j][ikd] = cutoff_tmp;
                    rcs[order][ikd][j] = cutoff_tmp;
                    undefined_cutoff[order][j][ikd] = false;
                    undefined_cutoff[order][ikd][j] = false;
                }
            } else {
                rcs[order][ikd][jkd] = cutoff_tmp;
                rcs[order][jkd][ikd] = cutoff_tmp;
                undefined_cutoff[order][ikd][jkd] = false;
                undefined_cutoff[order][jkd][ikd] = false;
            }
        }
    }
    element_allowed.clear();
    str_cutoff.clear();

    for (order = 0; order < maxorder; ++order) {
        for (j = 0; j < nkd; ++j) {
            for (k = 0; k < nkd; ++k) {
                if (undefined_cutoff[order][j][k]) {
                    std::cout << " Cutoff radius for " << std::setw(3) << order + 2 << "th-order terms" << std::endl;
                    std::cout << " are not defined between elements " << std::setw(3) << j + 1
                        << " and " << std::setw(3) << k + 1 << std::endl;
                    error->exit("parse_cutoff_radii", "Incomplete cutoff radii");
                }
            }
        }
    }
    memory->deallocate(undefined_cutoff);

    memory->allocate(interaction->rcs, maxorder, nkd, nkd);

    for (i = 0; i < maxorder; ++i) {
        for (j = 0; j < nkd; ++j) {
            for (k = 0; k < nkd; ++k) {
                interaction->rcs[i][j][k] = rcs[i][j][k];
            }
        }
    }

    memory->deallocate(rcs);
}

void Input::parse_fitting_vars()
{
    int ndata, nstart, nend, nskip, nboot;
    std::string dfile, ffile;
    int multiply_data, constraint_flag;
    std::string rotation_axis;
    std::string fc2_file, fc3_file;

    std::string str_allowed_list = "NDATA NSTART NEND NSKIP NBOOT DFILE FFILE MULTDAT ICONST ROTAXIS FC2XML FC3XML";
    std::string str_no_defaults = "NDATA DFILE FFILE";
    std::vector<std::string> no_defaults;

    std::map<std::string, std::string> fitting_var_dict;

    bool fix_harmonic, fix_cubic;

    if (from_stdin) {
        std::cin.ignore();
    } else {
        ifs_input.ignore();
    }

    get_var_dict(str_allowed_list, fitting_var_dict);

    boost::split(no_defaults, str_no_defaults, boost::is_space());

    for (std::vector<std::string>::iterator it = no_defaults.begin(); it != no_defaults.end(); ++it) {
        if (fitting_var_dict.find(*it) == fitting_var_dict.end()) {
            error->exit("parse_fitting_vars", "The following variable is not found in &fitting input region: ", (*it).c_str());
        }
    }

    assign_val(ndata, "NDATA", fitting_var_dict);

    if (fitting_var_dict["NSTART"].empty()) {
        nstart = 1;
    } else {
        assign_val(nstart, "NSTART", fitting_var_dict);
    }
    if (fitting_var_dict["NEND"].empty()) {
        nend = ndata;
    } else {
        assign_val(nend, "NEND", fitting_var_dict);
    }
    if (fitting_var_dict["NSKIP"].empty()) {
        nskip = 0;
    } else {
        assign_val(nskip, "NSKIP", fitting_var_dict);
    }

    if (ndata <= 0 || nstart <= 0 || nend <= 0
        || nstart > ndata || nend > ndata || nstart > nend) {
            error->exit("parce_fitting_vars", "ndata, nstart, nend are not consistent with each other");
    }

    if (nskip < -1) error->exit("parce_fitting_vars", "nskip has to be larger than -2.");
    if (nskip == -1) {

        if (fitting_var_dict["NBOOT"].empty()) {
            error->exit("parse_fitting_vars", "NBOOT has to be given when NSKIP=-1");
        } else {
            assign_val(nboot, "NBOOT", fitting_var_dict);
        }

        if (nboot <= 0) error->exit("parce_input", "nboot has to be a positive integer");
    } else {
        nboot = 0;
    }

    dfile = fitting_var_dict["DFILE"];
    ffile = fitting_var_dict["FFILE"];

    if (fitting_var_dict["MULTDAT"].empty()) {
        multiply_data = 1;
    } else {
        assign_val(multiply_data, "MULTDAT", fitting_var_dict);
    }

    if (fitting_var_dict["ICONST"].empty()) {
        constraint_flag = 1;
    } else {
        assign_val(constraint_flag, "ICONST", fitting_var_dict);
    }

    fc2_file = fitting_var_dict["FC2XML"];
    if (fc2_file.empty()) {
        fix_harmonic = false;
    } else {
        fix_harmonic = true;
    }

    fc3_file = fitting_var_dict["FC3XML"];
    if (fc3_file.empty()) {
        fix_cubic = false;
    } else {
        fix_cubic = true;
    }

    if (constraint_flag % 10 >= 2) {
        rotation_axis = fitting_var_dict["ROTAXIS"];
        if (rotation_axis.empty()) {
            error->exit("parse_fitting_vars", "ROTAXIS has to be given when ICONST=2 or 3");
        }
    }

    system->ndata = ndata;
    system->nstart = nstart;
    system->nend = nend;
    system->nskip = nskip;

    fitting->nboot = nboot;
    files->file_disp = dfile;
    files->file_force = ffile;
    symmetry->multiply_data = multiply_data;
    constraint->constraint_mode = constraint_flag;
    constraint->rotation_axis = rotation_axis;
    constraint->fc2_file = fc2_file;
    constraint->fix_harmonic = fix_harmonic;
    constraint->fc3_file = fc3_file;
    constraint->fix_cubic = fix_cubic;

    fitting_var_dict.clear();
}

void Input::parse_atomic_positions()
{
    int i, j;
    std::string line, line_wo_comment;
    std::string str_tmp;
    std::string::size_type pos_first_comment_tag;
    std::vector<std::string> str_v, pos_line;
    double **xeq;
    int *kd;

    int nat = system->nat;

    if (from_stdin) {
        std::cin.ignore();
    } else {
        ifs_input.ignore();
    }

    str_v.clear();

    if (from_stdin) {

        while (std::getline(std::cin, line)) {

            pos_first_comment_tag = line.find_first_of('#');

            if (pos_first_comment_tag == std::string::npos) {
                line_wo_comment = line;
            } else {
                line_wo_comment = line.substr(0, pos_first_comment_tag);
            }

            boost::trim_left(line_wo_comment);
            if (line_wo_comment.empty()) continue;
            if (is_endof_entry(line_wo_comment)) break;

            str_v.push_back(line_wo_comment);
        }

    } else {

        while (std::getline(ifs_input, line)) {

            pos_first_comment_tag = line.find_first_of('#');

            if (pos_first_comment_tag == std::string::npos) {
                line_wo_comment = line;
            } else {
                line_wo_comment = line.substr(0, pos_first_comment_tag);
            }

            boost::trim_left(line_wo_comment);
            if (line_wo_comment.empty()) continue;
            if (is_endof_entry(line_wo_comment)) break;

            str_v.push_back(line_wo_comment);
        }
    }

    if (str_v.size() != nat) {
        error->exit("parse_atomic_positions", "The number of entries for atomic positions should be NAT");
    }

    memory->allocate(xeq, nat, 3);
    memory->allocate(kd, nat);

    for (i = 0; i < nat; ++i) {

        split_str_by_space(str_v[i], pos_line);

        if (pos_line.size() == 4) {
            try {
                kd[i] = boost::lexical_cast<int>(pos_line[0]);
            } catch (std::exception &e) {
                std::cout << e.what() << std::endl;
                error->exit("parse_atomic_positions", "Invalid entry for the &position field at line ", i + 1);
            }

            for (j = 0; j < 3; ++j) {
                xeq[i][j] = boost::lexical_cast<double>(pos_line[j + 1]);
            }

        } else {
            error->exit("parse_atomic_positions", "Bad format for &position region");
        }
    }

    memory->allocate(system->xcoord, nat, 3);
    memory->allocate(system->kd, nat);

    for (i = 0; i < nat; ++i) {

        system->kd[i] = kd[i];

        for (j = 0; j < 3; ++j) {
            system->xcoord[i][j] = xeq[i][j];
        }
    }

    memory->deallocate(xeq);
    memory->deallocate(kd);
    pos_line.clear();
    str_v.clear();

}

void Input::get_var_dict(const std::string keywords, std::map<std::string, std::string> &var_dict)
{
    std::string line, key, val;
    std::string line_wo_comment;
    std::string::size_type pos_first_comment_tag;
    std::vector<std::string> str_entry, str_varval;

    std::set<std::string> keyword_set;

    boost::split(keyword_set, keywords, boost::is_space());

    var_dict.clear();

    if (from_stdin) {
        while (std::getline(std::cin, line)) {

            // Ignore comment region
            pos_first_comment_tag = line.find_first_of('#');

            if (pos_first_comment_tag == std::string::npos) {
                line_wo_comment = line;
            } else {
                line_wo_comment = line.substr(0, pos_first_comment_tag);
            }

            boost::trim_left(line_wo_comment);
            if (line_wo_comment.empty()) continue;
            if (is_endof_entry(line_wo_comment)) break;

            //	std::cout << line_wo_comment << std::endl;

            // Split the input line by ';'

            boost::split(str_entry, line_wo_comment, boost::is_any_of(";"));

            for (std::vector<std::string>::iterator it = str_entry.begin(); it != str_entry.end(); ++it) {

                // Split the input entry by '='

                std::string str_tmp = boost::trim_copy(*it);

                if (!str_tmp.empty()) {

                    boost::split(str_varval, str_tmp, boost::is_any_of("="));

                    if (str_varval.size() != 2) {
                        error->exit("get_var_dict", "Unacceptable format");
                    }

                    key = boost::to_upper_copy(boost::trim_copy(str_varval[0]));
                    val = boost::trim_copy(str_varval[1]);

                    if (keyword_set.find(key) == keyword_set.end()) {
                        std::cout << "Could not recognize the variable " << key << std::endl;
                        error->exit("get_var_dict", "Invalid variable found");
                    }

                    if (var_dict.find(key) != var_dict.end()) {
                        std::cout << "Variable " << key << " appears twice in the input file." << std::endl;
                        error->exit("get_var_dict", "Redundant input parameter");
                    }

                    // If everything is OK, add the variable and the corresponding value
                    // to the dictionary.

                    var_dict.insert(std::map<std::string, std::string>::value_type(key, val));
                }
            }
        }

    } else {

        while (std::getline(ifs_input, line)) {

            // Ignore comment region
            pos_first_comment_tag = line.find_first_of('#');

            if (pos_first_comment_tag == std::string::npos) {
                line_wo_comment = line;
            } else {
                line_wo_comment = line.substr(0, pos_first_comment_tag);
            }

            boost::trim_left(line_wo_comment);
            if (line_wo_comment.empty()) continue;
            if (is_endof_entry(line_wo_comment)) break;

            //	std::cout << line_wo_comment << std::endl;

            // Split the input line by ';'

            boost::split(str_entry, line_wo_comment, boost::is_any_of(";"));

            for (std::vector<std::string>::iterator it = str_entry.begin(); it != str_entry.end(); ++it) {

                // Split the input entry by '='

                std::string str_tmp = boost::trim_copy(*it);

                if (!str_tmp.empty()) {

                    boost::split(str_varval, str_tmp, boost::is_any_of("="));

                    if (str_varval.size() != 2) {
                        error->exit("get_var_dict", "Unacceptable format");
                    }

                    key = boost::to_upper_copy(boost::trim_copy(str_varval[0]));
                    val = boost::trim_copy(str_varval[1]);

                    if (keyword_set.find(key) == keyword_set.end()) {
                        std::cout << "Could not recognize the variable " << key << std::endl;
                        error->exit("get_var_dict", "Invalid variable found");
                    }

                    if (var_dict.find(key) != var_dict.end()) {
                        std::cout << "Variable " << key << " appears twice in the input file." << std::endl;
                        error->exit("get_var_dict", "Redundant input parameter");
                    }

                    // If everything is OK, add the variable and the corresponding value
                    // to the dictionary.

                    var_dict.insert(std::map<std::string, std::string>::value_type(key, val));
                }
            }
        }
    }

    keyword_set.clear();
}

int Input::locate_tag(std::string key)
{
    int ret = 0;
    std::string line;

    if (from_stdin) {

        std::cin.clear();
        std::cin.seekg(0, std::ios_base::beg);

        while (std::cin >> line) {
            boost::to_lower(line);
            if (line == key){
                ret = 1;
                break;
            }
        }
        return ret;

    } else {

        ifs_input.clear();
        ifs_input.seekg(0, std::ios_base::beg);

        while (ifs_input >> line) {
            boost::to_lower(line);
            if (line == key) {
                ret = 1;
                break;
            }
        }
        return ret;
    }

}

bool Input::is_endof_entry(std::string str)
{
    if (str[0] == '/') {
        return true;
    } else {
        return false;
    }
}

void Input::split_str_by_space(const std::string str, std::vector<std::string> &str_vec)
{
    std::string str_tmp;
    std::istringstream is(str);

    str_vec.clear();

    while(1) {
        str_tmp.clear();
        is >> str_tmp;
        if (str_tmp.empty()) {
            break;
        }
        str_vec.push_back(str_tmp);
    }
    str_tmp.clear();
}

template<typename T> void Input::assign_val(T &val, const std::string key, std::map<std::string, std::string> dict)
{
    // Assign a value to the variable "key" using the boost::lexica_cast.

    if (!dict[key].empty()) {
        try {
            val = boost::lexical_cast<T>(dict[key]);
        } catch (std::exception &e) {
            std::string str_tmp;
            std::cout << e.what() << std::endl;
            str_tmp = "Invalid entry for the " + key + " tag.\n";
            str_tmp += " Please check the input value.";
            error->exit("assign_val", str_tmp.c_str());
        }
    }
}

max_stars_repo_name: dlnguyen/alamode

max_issues_repo_name: dlnguyen/alamode

max_forks_repo_name: dlnguyen/alamode


text:
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
// Topper Trading Workbench
//
// Copyright (C) 2018 Hat Boy Software, Inc.
//
//  @author Matthew Alan Gray - <mgray@hatboysoftware.com>
//  @author Tony Richards - <trichards@indiezen.com>
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
#pragma once

#include <Helmet/Blockchain/I_BlockchainNode.hpp>

#include <boost/enable_shared_from_this.hpp>

//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
namespace Topper {
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~

class BlockchainNode
:   public Helmet::Blockchain::I_BlockchainNode
,	public boost::enable_shared_from_this<BlockchainNode>
{
    /// @name Types
    /// @{
public:
    /// @}

    /// @name I_StartupShutdownParticipant implementation
    /// @{
public:
    Helmet::Core::Thread::I_Condition* prepareToStart(Helmet::Core::Thread::ThreadPool& _threadPool) override;
    void start() override;
    Helmet::Core::Thread::I_Condition* prepareToStop() override;
    void stop() override;
    /// @}

    /// @name I_RequestHandler implementation
    /// @{
public:
    void handleRequest(pRequest_type _pRequest, pResponseHandler_type _pResponseHandler) override;
    /// @}

    /// @name I_ApplicationService interface
    /// @{
public:
    Helmet::Enterprise::I_ApplicationServer& getApplicationServer() override;
    const std::string& getServiceName() const override;
    pEndpoint_type getServiceEndpoint() override;
    pResourceLocation_type getServiceLocation() override;
    void handleMessage(pMessage_type _pMessage) override;
    /// @}

    /// @name I_BlockchainNode implementation
    /// @{
public:
    void addPeer(pBlockchainPeer_type _pPeer) override;
    void removePeer(pBlockchainPeer_type _pPeer) override;
    void getPeers(Helmet::Core::Utility::I_Visitor<I_Peer>& _visitor) override;
    /// @}

    /// @name BlockchainNode implementation
    /// @{
public:
    /// @}

    /// @name Static Methods
    /// @{
public:
    /// @}

    /// @name 'Structors
    /// @{
public:
    explicit BlockchainNode(Helmet::Enterprise::I_ApplicationServer& _applicationServer,
                            const std::string& _name);
    virtual ~BlockchainNode();
    /// @}

    /// @name Member Variables
    /// @{
private:
    Helmet::Enterprise::I_ApplicationServer&    m_applicationServer;
    std::string                                 m_name;
    /// @}

};  // class BlockchainNode

//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
}   // namespace Topper
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~

ext: hpp

max_stars_repo_name: hatboysoftware/helmet

max_issues_repo_name: hatboysoftware/helmet

max_forks_repo_name: hatboysoftware/helmet


text:
/***
 *  $Id$
 **
 *  File: performance_indicators_diss.hpp
 *  Created: May 9, 2012
 *
 *  Author: Olga Wodo, Baskar Ganapathysubramanian
 *  Copyright (c) 2012 Olga Wodo, Baskar Ganapathysubramanian
 *  See accompanying LICENSE.
 *
 *  This file is part of GraSPI.
 */

#ifndef PERFORMANCE_INDICATORS_DISS_HPP
#define PERFORMANCE_INDICATORS_DISS_HPP

#include <climits>
#include <sstream>

#include "graspi_types.hpp"
#include "graph_dijkstra.hpp"
#include "graspi_predicates.hpp"
#include <boost/graph/filtered_graph.hpp>

namespace graspi {

  struct foo_w_diss{
      double A1,B1,C1;
      foo_w_diss(){ A1=6.265; B1=-23.0; C1=17.17; }
      double operator()(double d)const{
	  return A1*exp(-((d-B1)/C1)*((d-B1)/C1));
      }
  };

  inline int
  identify_n_vertices_within_distance( const std::vector<float>& d,
				       double Ld){
      int n_Ld = 0;
      for(unsigned int i = 0; i < d.size(); i++){
	  if( (d[i] < Ld) && (d[i] > 0) ) n_Ld++;
      }
      return n_Ld;
  }

  inline double
  identify_weighted_vertices_within_distance( const std::vector<float>& d,
					      double Ld){
      double wn_Ld = 0;
      foo_w_diss wfoo;

      for(unsigned int i = 0; i < d.size(); i++){
	  double d_i = d[i];
	  double wd_i = wfoo(d_i);
	  if( (d_i < Ld) && (d_i > 0) ) wn_Ld+= wd_i;
      }
      return wn_Ld;
  }

  inline std::pair<int,double>
  identify_n_weighted_vertices_within_distance( const std::vector<float>& d,
						double Ld){
      double wn_Ld = 0;
      int n_Ld = 0;
      foo_w_diss wfoo;

      for(unsigned int i = 0; i < d.size(); i++){
	  double d_i = d[i];
	  double wd_i = wfoo(d_i);
	  if( (d_i < Ld) && (d_i > 0) ){
	      wn_Ld+= wd_i;
	      n_Ld++;
	  }
      }
      return std::pair<int,double>(n_Ld,wn_Ld);
  }

  inline std::pair<double,double>
  wf_diss(
	  graph_t* G, const dim_g_t& d_g, const vertex_colors_t& C,
	  const edge_weights_t& W, const vertex_ccs_t& vCC,
	  const ccs_t& CC,
	  double Ld,
	  const std::string& filename_ColorToGreen,
	  const std::string& filename_WColorToGreen,
	  COLOR color = BLACK,
	  COLOR green = GREEN
	  ){
      int n_color = 0;
      int n_color_Ld = 0;
      double wn_color_Ld = 0;

      connect_color_green pred(*G,C,color,green);
      unsigned int n = boost::num_vertices(*G);
      vertex_t int_id = d_g.id(green);
      std::vector<float> d(n);

      determine_shortest_distances( G, W, int_id, pred, d);

      foo_w_diss wfoo;
      std::ostringstream oss_out_d;
      std::ostringstream oss_out_wd;
      for (unsigned int i = 0; i < d.size(); i++) {
	  unsigned int c = C[i];
	  if (c == color) n_color++;
	  if ( ( c == color )
	       && ( fabs(d[i]) < std::numeric_limits<float>::max() )
	       ) {
	      double d_i = d[i];
	      oss_out_d  << d_i       << std::endl;
	      oss_out_wd << d_i << " " << wfoo(d_i) << std::endl;
	  }
      }
      std::ofstream f_out(filename_ColorToGreen.c_str());
      std::string buffer = oss_out_d.str();
      int size = oss_out_d.str().size();
      f_out.write (buffer.c_str(),size);
      f_out.close();
      f_out.open(filename_WColorToGreen.c_str());
      buffer = oss_out_wd.str();
      size = oss_out_wd.str().size();
      f_out.write (buffer.c_str(),size);
      f_out.close();

      std::pair<int,double> pLd
	  = identify_n_weighted_vertices_within_distance(d,Ld);
      n_color_Ld = pLd.first;
      wn_color_Ld = pLd.second;

#ifdef DEBUG
      std::cout << "[DEBUG] Number of " << color << "vertices: "
		<< n_color << std::endl
		<< "[DEBUG] Number of " << color << "vertices in "
		<< Ld << " distance to green: "
		<< n_color_Ld << std::endl;
#endif

      return std::pair<double, double>(
				       (double)wn_color_Ld/n_color,
				       (double)n_color_Ld/n_color
				       );
  }

  inline std::pair<double,double>
  wf_diss(
	  graph_t* G, const dim_g_t& d_g, const vertex_colors_t& C,
	  const edge_weights_t& W, const vertex_ccs_t& vCC,
	  const ccs_t& CC,
	  double Ld,
	  COLOR color = BLACK,
	  COLOR green = GREEN
	  ){
      int n_color = 0;
      int n_color_Ld = 0;
      double wn_color_Ld = 0;

      connect_color_green pred(*G,C,color,green);
      unsigned int n = boost::num_vertices(*G);
      vertex_t int_id = d_g.id(green);
      std::vector<float> d(n);

      determine_shortest_distances( G, W, int_id, pred, d);

      foo_w_diss wfoo;
      for (unsigned int i = 0; i < d.size(); i++) {
	  unsigned int c = C[i];
	  if (c == color) n_color++;
      }

      std::pair<int,double> pLd
	  = identify_n_weighted_vertices_within_distance(d,Ld);
      n_color_Ld = pLd.first;
      wn_color_Ld = pLd.second;

      return std::pair<double, double>(
				       (double)wn_color_Ld/n_color,
				       (double)n_color_Ld/n_color
				       );
  }

}
#endif


text:
// graph-tool -- a general graph modification and manipulation thingy
//
// Copyright (C) 2006-2015 Tiago de Paula Peixoto <tiago@skewed.de>
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

#include "graph_filtering.hh"

#include <boost/python.hpp>

#include "graph.hh"
#include "graph_selectors.hh"

#include "graph_trust_transitivity.hh"

using namespace std;
using namespace boost;
using namespace graph_tool;

void trust_transitivity(GraphInterface& g, int64_t source, int64_t target,
                    boost::any c, boost::any t)
{
    if (!belongs<edge_floating_properties>()(c))
        throw ValueException("edge property must be of floating point value type");
    if (!belongs<vertex_floating_vector_properties>()(t))
        throw ValueException("vertex property must be of floating point valued vector type");

    run_action<>()(g,
                   bind<void>(get_trust_transitivity(), _1, g.GetVertexIndex(),
                              source, target, _2, _3),
                   edge_floating_properties(),
                   vertex_floating_vector_properties())(c,t);
}

void export_trust_transitivity()
{
    using namespace boost::python;
    def("get_trust_transitivity", &trust_transitivity);
}

ext: cc

max_stars_repo_name: johankaito/fufuka

max_issues_repo_name: johankaito/fufuka

max_forks_repo_name: johankaito/fufuka


text:
/*******************************************************************************
 * CLI - A simple command line interface.
 * Copyright (C) 2020 Daniele Pallastrelli
 *
 * Boost Software License - Version 1.0 - August 17th, 2003
 *
 * Permission is hereby granted, free of charge, to any person or organization
 * obtaining a copy of the software and accompanying documentation covered by
 * this license (the "Software") to use, reproduce, display, distribute,
 * execute, and transmit the Software, and to prepare derivative works of the
 * Software, and to permit third-parties to whom the Software is furnished to
 * do so, all subject to the following:
 *
 * The copyright notices in the Software and this entire statement, including
 * the above license grant, this restriction and the following disclaimer,
 * must be included in all copies of the Software, in whole or in part, and
 * all derivative works of the Software, unless such copies or derivative
 * works are solely in the form of machine-executable object code generated by
 * a source language processor.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
 * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
 * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 ******************************************************************************/

#include <boost/test/unit_test.hpp>
#include "cli/cli.h"
#include "cli/clifilesession.h"

using namespace std;
using namespace cli;
using namespace cli::detail;

namespace {

string ExtractFirstPrompt(const stringstream& o)
{
    auto content = o.str();
    std::size_t pos = content.find_first_of(">");
    return content.substr(0, pos);
}

string ExtractLastPrompt(const stringstream& o)
{
    auto content = o.str();
    std::size_t pos = content.find_last_of('\n');
    content = content.substr(pos+1);
    pos = content.find_last_of(">");
    return content.substr(0, pos);
}

/* takes

cli> sub> foo
bar
sub>

and gives

foo
bar

*/
string ExtractContent(const stringstream& o)
{
    auto content = o.str();
    // last line
    auto lastNL = content.find_last_of("\n");
    auto lastLine = content.substr(lastNL+1);
    content = content.substr(0, lastNL);
    auto pos = content.find(lastLine);
    return content.substr(pos+lastLine.size());
}

void UserInput(Cli& cli, stringstream& oss, const string& input)
{
    oss.str("");
    oss.clear();

    stringstream iss;
    iss.str(input + '\n');
    CliFileSession session(cli, iss, oss);
    session.Start();
}

}

BOOST_AUTO_TEST_SUITE(CliSuite)

BOOST_AUTO_TEST_CASE(Basics)
{
    auto rootMenu = make_unique<Menu>("cli");
    rootMenu->Insert("int_cmd", [](ostream& out, int par){ out << par << "\n"; }, "int_cmd help", {"int_par"} );
    rootMenu->Insert("string_cmd", [](ostream& out, const string& par){ out << par << "\n"; }, "string_cmd help", {"string_par"} );

    Cli cli(move(rootMenu));

    stringstream oss;

    UserInput(cli, oss, "help");
    BOOST_CHECK_EQUAL(ExtractFirstPrompt(oss), "cli");
    BOOST_CHECK_EQUAL(ExtractLastPrompt(oss), "cli");
    BOOST_CHECK(ExtractContent(oss).find("int_cmd") != string::npos);
    BOOST_CHECK(ExtractContent(oss).find("<int_par>") != string::npos);
    BOOST_CHECK(ExtractContent(oss).find("string_cmd") != string::npos);
    BOOST_CHECK(ExtractContent(oss).find("<string_par>") != string::npos);

    UserInput(cli, oss, "int_cmd 42");
    BOOST_CHECK_EQUAL(ExtractFirstPrompt(oss), "cli");
    BOOST_CHECK_EQUAL(ExtractLastPrompt(oss), "cli");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "42");

    UserInput(cli, oss, "int_cmd wrong_int_parameter");
    BOOST_CHECK_EQUAL(ExtractFirstPrompt(oss), "cli");
    BOOST_CHECK_EQUAL(ExtractLastPrompt(oss), "cli");
    BOOST_CHECK(ExtractContent(oss).find("wrong command:") != string::npos);

    UserInput(cli, oss, "int_cmd 42 0");
    BOOST_CHECK_EQUAL(ExtractFirstPrompt(oss), "cli");
    BOOST_CHECK_EQUAL(ExtractLastPrompt(oss), "cli");
    BOOST_CHECK(ExtractContent(oss).find("wrong command:") != string::npos);

    UserInput(cli, oss, "string_cmd foo");
    BOOST_CHECK_EQUAL(ExtractFirstPrompt(oss), "cli");
    BOOST_CHECK_EQUAL(ExtractLastPrompt(oss), "cli");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "foo");

    UserInput(cli, oss, R"(string_cmd "foo 'bar' \"foo\\2")");
    BOOST_CHECK_EQUAL(ExtractFirstPrompt(oss), "cli");
    BOOST_CHECK_EQUAL(ExtractLastPrompt(oss), "cli");
    BOOST_CHECK_EQUAL(ExtractContent(oss), R"(foo 'bar' "foo\2)");
}

BOOST_AUTO_TEST_CASE(parameters)
{
    auto rootMenu = make_unique<Menu>("cli");
    rootMenu->Insert("char_cmd", [](ostream& out, char par){ out << par << "\n"; }, "char_cmd help", {"char_par"} );
    rootMenu->Insert("unsigned_char_cmd", [](ostream& out, unsigned char par){ out << static_cast<unsigned int>(par) << "\n"; }, "unsigned_char_cmd help", {"unsigned_char_par"} );
    rootMenu->Insert("signed_char_cmd", [](ostream& out, signed char par){ out << static_cast<int>(par) << "\n"; }, "signed_char_cmd help", {"signed_char_par"} );
    rootMenu->Insert("short_cmd", [](ostream& out, short par){ out << par << "\n"; }, "short_cmd help", {"short_par"} );
    rootMenu->Insert("unsigned_short_cmd", [](ostream& out, unsigned short par){ out << par << "\n"; }, "unsigned_short_cmd help", {"unsigned_short_par"} );
    rootMenu->Insert("int_cmd", [](ostream& out, int par){ out << par << "\n"; }, "int_cmd help", {"int_par"} );
    rootMenu->Insert("unsigned_int_cmd", [](ostream& out, unsigned int par){ out << par << "\n"; }, "unsigned_int_cmd help", {"unsigned_int_par"} );
    rootMenu->Insert("long_cmd", [](ostream& out, long par){ out << par << "\n"; }, "long_cmd help", {"long_par"} );
    rootMenu->Insert("unsigned_long_cmd", [](ostream& out, unsigned long par){ out << par << "\n"; }, "unsigned_long_cmd help", {"unsigned_long_par"} );
    rootMenu->Insert("long_long_cmd", [](ostream& out, long long par){ out << par << "\n"; }, "long_long_cmd help", {"long_long_par"} );
    rootMenu->Insert("unsigned_long_long_cmd", [](ostream& out, unsigned long long par){ out << par << "\n"; }, "unsigned_long_long_cmd help", {"unsigned_long_long_par"} );
    rootMenu->Insert("float_cmd", [](ostream& out, float par){ out << par << "\n"; }, "float_cmd help", {"float_par"} );
    rootMenu->Insert("double_cmd", [](ostream& out, double par){ out << par << "\n"; }, "double_cmd help", {"double_par"} );
    rootMenu->Insert("long_double_cmd", [](ostream& out, long double par){ out << par << "\n"; }, "long_double_cmd help", {"long_double_par"} );
    rootMenu->Insert("string_cmd", [](ostream& out, const string& par){ out << par << "\n"; }, "string_cmd help", {"string_par"} );

    Cli cli(move(rootMenu));

    stringstream oss;

    UserInput(cli, oss, "char_cmd a");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "a");
    UserInput(cli, oss, "char_cmd ' '");
    BOOST_CHECK_EQUAL(ExtractContent(oss), " ");
    UserInput(cli, oss, "char_cmd aa");
    BOOST_CHECK(ExtractContent(oss).find("wrong command:") != string::npos);

    UserInput(cli, oss, "unsigned_char_cmd 42");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "42");
    UserInput(cli, oss, "unsigned_char_cmd -42");
    BOOST_CHECK(ExtractContent(oss).find("wrong command:") != string::npos);
    UserInput(cli, oss, "unsigned_char_cmd a");
    BOOST_CHECK(ExtractContent(oss).find("wrong command:") != string::npos);
    UserInput(cli, oss, "unsigned_char_cmd 99999999999999999999999999999999999999999");
    BOOST_CHECK(ExtractContent(oss).find("wrong command:") != string::npos);

    UserInput(cli, oss, "signed_char_cmd 42");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "42");
    UserInput(cli, oss, "signed_char_cmd -42");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "-42");
    UserInput(cli, oss, "signed_char_cmd a");
    BOOST_CHECK(ExtractContent(oss).find("wrong command:") != string::npos);
    UserInput(cli, oss, "signed_char_cmd 99999999999999999999999999999999999999999");
    BOOST_CHECK(ExtractContent(oss).find("wrong command:") != string::npos);

    UserInput(cli, oss, "short_cmd 42");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "42");
    UserInput(cli, oss, "short_cmd -42");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "-42");
    UserInput(cli, oss, "short_cmd a");
    BOOST_CHECK(ExtractContent(oss).find("wrong command:") != string::npos);
    UserInput(cli, oss, "short_cmd 99999999999999999999999999999999999999999");
    BOOST_CHECK(ExtractContent(oss).find("wrong command:") != string::npos);

    UserInput(cli, oss, "unsigned_short_cmd 42");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "42");
    UserInput(cli, oss, "unsigned_short_cmd -42");
    BOOST_CHECK(ExtractContent(oss).find("wrong command:") != string::npos);
    UserInput(cli, oss, "unsigned_short_cmd a");
    BOOST_CHECK(ExtractContent(oss).find("wrong command:") != string::npos);
    UserInput(cli, oss, "unsigned_short_cmd 99999999999999999999999999999999999999999");
    BOOST_CHECK(ExtractContent(oss).find("wrong command:") != string::npos);

    UserInput(cli, oss, "int_cmd 42");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "42");
    UserInput(cli, oss, "int_cmd -42");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "-42");
    UserInput(cli, oss, "int_cmd a");
    BOOST_CHECK(ExtractContent(oss).find("wrong command:") != string::npos);
    UserInput(cli, oss, "int_cmd 99999999999999999999999999999999999999999");
    BOOST_CHECK(ExtractContent(oss).find("wrong command:") != string::npos);

    UserInput(cli, oss, "unsigned_int_cmd 42");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "42");
    UserInput(cli, oss, "unsigned_int_cmd -42");
    BOOST_CHECK(ExtractContent(oss).find("wrong command:") != string::npos);
    UserInput(cli, oss, "unsigned_int_cmd a");
    BOOST_CHECK(ExtractContent(oss).find("wrong command:") != string::npos);
    UserInput(cli, oss, "unsigned_int_cmd 99999999999999999999999999999999999999999");
    BOOST_CHECK(ExtractContent(oss).find("wrong command:") != string::npos);

    UserInput(cli, oss, "long_cmd 42");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "42");
    UserInput(cli, oss, "long_cmd -42");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "-42");
    UserInput(cli, oss, "long_cmd a");
    BOOST_CHECK(ExtractContent(oss).find("wrong command:") != string::npos);

    UserInput(cli, oss, "unsigned_long_cmd 42");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "42");
    UserInput(cli, oss, "unsigned_long_cmd -42");
    BOOST_CHECK(ExtractContent(oss).find("wrong command:") != string::npos);
    UserInput(cli, oss, "unsigned_long_cmd a");
    BOOST_CHECK(ExtractContent(oss).find("wrong command:") != string::npos);

    UserInput(cli, oss, "long_long_cmd 42");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "42");
    UserInput(cli, oss, "long_long_cmd -42");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "-42");
    UserInput(cli, oss, "long_long_cmd a");
    BOOST_CHECK(ExtractContent(oss).find("wrong command:") != string::npos);

    UserInput(cli, oss, "unsigned_long_long_cmd 42");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "42");
    UserInput(cli, oss, "unsigned_long_long_cmd -42");
    BOOST_CHECK(ExtractContent(oss).find("wrong command:") != string::npos);
    UserInput(cli, oss, "unsigned_long_long_cmd a");
    BOOST_CHECK(ExtractContent(oss).find("wrong command:") != string::npos);

    UserInput(cli, oss, "float_cmd 0.1");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "0.1");
    UserInput(cli, oss, "float_cmd a");
    BOOST_CHECK(ExtractContent(oss).find("wrong command:") != string::npos);

    UserInput(cli, oss, "double_cmd 0.1");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "0.1");
    UserInput(cli, oss, "double_cmd a");
    BOOST_CHECK(ExtractContent(oss).find("wrong command:") != string::npos);

    UserInput(cli, oss, "long_double_cmd 0.1");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "0.1");
    UserInput(cli, oss, "long_double_cmd a");
    BOOST_CHECK(ExtractContent(oss).find("wrong command:") != string::npos);
}

BOOST_AUTO_TEST_CASE(freeform)
{
    auto rootMenu = make_unique<Menu>("cli");
    rootMenu->Insert("cmd_printer_by_ref", [](ostream& out, const std::vector<std::string>& args){
        for (const auto& entry : args) {
            out << entry << "*";
        }
        out << "\n";
    }, "cmd_printer help", {"<string values>"} );

    rootMenu->Insert("cmd_printer_by_value", [](ostream& out, std::vector<std::string> args){
        for (const auto& entry : args) {
            out << entry << "*";
        }
        out << "\n";
    }, "cmd_printer help", {"<string values>"} );

    Cli cli(move(rootMenu));
    stringstream oss;

    UserInput(cli, oss, R"(cmd_printer_by_value a b 'c d e' f)");
    BOOST_CHECK_EQUAL(ExtractFirstPrompt(oss), "cli");
    BOOST_CHECK_EQUAL(ExtractLastPrompt(oss), "cli");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "a*b*c d e*f*");

    UserInput(cli, oss, R"(cmd_printer_by_ref a b 'c d e' f)");
    BOOST_CHECK_EQUAL(ExtractFirstPrompt(oss), "cli");
    BOOST_CHECK_EQUAL(ExtractLastPrompt(oss), "cli");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "a*b*c d e*f*");

    // empty parameters
    UserInput(cli, oss, R"(cmd_printer_by_value)");
    BOOST_CHECK_EQUAL(ExtractFirstPrompt(oss), "cli");
    BOOST_CHECK_EQUAL(ExtractLastPrompt(oss), "cli");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "");
}

BOOST_AUTO_TEST_CASE(borderLine)
{
    auto rootMenu = make_unique<Menu>("cli");
    Cli cli(move(rootMenu));

    stringstream oss;

    UserInput(cli, oss, "");
    BOOST_CHECK_EQUAL(oss.str(), "cli> cli> ");

    UserInput(cli, oss, "\t");
    BOOST_CHECK_EQUAL(oss.str(), "cli> cli> ");
}

BOOST_AUTO_TEST_CASE(Submenus)
{
    auto rootMenu = make_unique<Menu>("cli");
    auto subMenu = make_unique<Menu>("sub");
    subMenu->Insert("int_cmd", [](ostream& out, int par){ out << par << "\n"; }, "int_cmd help", {"int_par"} );
    subMenu->Insert("string_cmd", [](ostream& out, const string& par){ out << par << "\n"; }, "string_cmd help", {"string_par"} );
    auto subSubMenu = make_unique<Menu>("subsub");
    subSubMenu->Insert("double_int_cmd", [](ostream& out, int par1, int par2){ out << par1 << par2 << "\n"; } );
    subSubMenu->Insert("double_string_cmd", [](ostream& out, const string& par1, const string& par2){ out << par1 << par2 << "\n"; } );
    subMenu->Insert(move(subSubMenu));
    rootMenu->Insert(move(subMenu));

    Cli cli(move(rootMenu));

    stringstream oss;

    UserInput(cli, oss, "help");
    BOOST_CHECK_EQUAL(ExtractFirstPrompt(oss), "cli");
    BOOST_CHECK_EQUAL(ExtractLastPrompt(oss), "cli");
    BOOST_CHECK(ExtractContent(oss).find("sub") != string::npos);
    BOOST_CHECK(ExtractContent(oss).find("help") != string::npos);
    BOOST_CHECK(ExtractContent(oss).find("exit") != string::npos);

    // from the root menu

    UserInput(cli, oss, "sub int_cmd 42");
    BOOST_CHECK_EQUAL(ExtractFirstPrompt(oss), "cli");
    BOOST_CHECK_EQUAL(ExtractLastPrompt(oss), "cli");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "42");

    UserInput(cli, oss, "sub string_cmd foo");
    BOOST_CHECK_EQUAL(ExtractFirstPrompt(oss), "cli");
    BOOST_CHECK_EQUAL(ExtractLastPrompt(oss), "cli");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "foo");

    UserInput(cli, oss, "sub subsub double_int_cmd 42 0");
    BOOST_CHECK_EQUAL(ExtractFirstPrompt(oss), "cli");
    BOOST_CHECK_EQUAL(ExtractLastPrompt(oss), "cli");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "420");

    UserInput(cli, oss, "sub subsub double_string_cmd foo bar");
    BOOST_CHECK_EQUAL(ExtractFirstPrompt(oss), "cli");
    BOOST_CHECK_EQUAL(ExtractLastPrompt(oss), "cli");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "foobar");

    // enter the sub menu

    UserInput(cli, oss, "sub\nint_cmd 42");
    BOOST_CHECK_EQUAL(ExtractLastPrompt(oss), "sub");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "42");

    UserInput(cli, oss, "sub\nstring_cmd foo");
    BOOST_CHECK_EQUAL(ExtractLastPrompt(oss), "sub");
    BOOST_CHECK_EQUAL(ExtractContent(oss), "foo");
}

BOOST_AUTO_TEST_CASE(ExitActions)
{
    auto rootMenu = make_unique<Menu>("cli");
    rootMenu->Insert("int_cmd", [](ostream& out, int par){ out << par << "\n"; }, "int_cmd help", {"int_par"} );
    rootMenu->Insert("string_cmd", [](ostream& out, const string& par){ out << par << "\n"; }, "string_cmd help", {"string_par"} );

    Cli cli(move(rootMenu));
    bool exitActionDone = false;
    cli.ExitAction([&](std::ostream&){ exitActionDone=true; });

    stringstream oss;

    UserInput(cli, oss, "exit");
    BOOST_CHECK(exitActionDone);
}

BOOST_AUTO_TEST_CASE(Exceptions)
{
    auto rootMenu = make_unique<Menu>("cli");
    rootMenu->Insert("stdexception", [](ostream&){ throw std::logic_error("myerror"); } );
    rootMenu->Insert("customexception", [](ostream&){ throw 42; } );

    Cli cli(move(rootMenu));

    stringstream oss;

    // std exception type, no custom handler
    BOOST_CHECK_NO_THROW( UserInput(cli, oss, "stdexception") );
    BOOST_CHECK_EQUAL(ExtractContent(oss), "myerror");

    // std exception type, custom handler
    bool excActionDone = false;
    cli.StdExceptionHandler( [&](std::ostream&, const std::string&, const std::exception&){ excActionDone = true; } );
    BOOST_CHECK_NO_THROW( UserInput(cli, oss, "stdexception") );
    BOOST_CHECK(excActionDone);

    // custom exception
    BOOST_CHECK_NO_THROW( UserInput(cli, oss, "customexception") );
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: rajdippatel-emc/cli

max_issues_repo_name: rajdippatel-emc/cli

max_forks_repo_name: rajdippatel-emc/cli


text:
#include "Graph.h"
#include <iostream>
#include <fstream>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <algorithm>
#include <cmath>

using cluster_approx::Graph;
using std::make_pair;
using std::vector;
using std::iostream;
using std:: ofstream;
using std::ifstream;
using std::string;
using std::cout;
using std::vector;
using std::endl;
using std::pair;

Graph::Graph(const std::string graphFilePath, const std::string attributesFilePath, const std::string idMapFilePath, const std::string penaltyFilePath) {

    loadIdmap(idMapFilePath,userIdMap);

    loadPrizes(penaltyFilePath,prizes,terminals);

    loadAttributes(attributesFilePath, attribute_stat, nodeAttrMap, userIdMap);

    loadGraph(graphFilePath, edges, prizes, terminals, nodeAttrMap,edgeAttributeMap,userIdMap);

}

void Graph::loadIdmap(std::string idMapFilePath, std::map<long,long> &userIdMap){
    std::ifstream test(idMapFilePath);
    if (!test)
    {
        std::cout << "The idMapfile doesn't exist" << std::endl;
        throw std::invalid_argument("The idMapfile doesn't exist");
    }
    printf("start loading userId Map file and build the userIdMap");

    printf("\n");
    int temp_line_number = 0;
    string STRING;
    ifstream infile_map;
    long key = 0;
    infile_map.open (idMapFilePath);

    while(!infile_map.eof()){
        getline(infile_map, STRING); // Saves the line in STRING.
        vector<string> currentLine = Graph::split(STRING, "\r");
        try{
            key = stol(currentLine[0]);
        }
        catch (const std::exception &e){
            printf("current line is %d",temp_line_number);
            printf("\n");
        }

        //userIdMap is guaranteed with no id duplication, we don't do the fact checking here
        userIdMap.insert(
                std::pair<long, int>(key, temp_line_number));
        temp_line_number++;
    }

    printf("Done building the userIdMap");
    printf("\n");

}

void Graph::loadPrizes(std::string prizesFilePath, std::vector<double> &prizes,std::set<int> &terminals){
    printf("Start loading prizes......");
    printf("\n");

    string STRING;
    ifstream infile;
    infile.open(prizesFilePath);

    long temp_line_number = 0;

    while (!infile.eof()) {

        getline(infile, STRING); // Saves the line in STRING.

        vector<string> currentLine = Graph::split(STRING, " ");

        int node_id = temp_line_number;
        double prize = stod(currentLine[1]);
        prizes.push_back(prize);
        if(prize > 0){
            terminals.insert(node_id);
        }
	temp_line_number++;

    }

    infile.close();
    printf("Done loading prizes......");
    printf("\n");

}

void Graph::loadGraph(std::string graphFilePath, std::vector<std::pair<std::pair<long, long>, long> > &edges,
                      std::vector<double> &prizes, std::set<int> &terminals, std::map<long, std::vector<double>>&nodeAttrMap,
                      std::map<long,std::vector<int>> &edgeAttributeMap,
                      std::map<long,long> &userIdMap ){
    printf("Start loading graph......");
    printf("\n");

    string STRING;
    ifstream infile;
    infile.open(graphFilePath);
    clock_t edge_trans_startTime,edge_trans_endTime;
    edge_trans_startTime = clock();

    for (int i=0; i<attribute_index_number; ++i){
        attribute_index.push_back(i+1);
    }

    long origin_edge_id = 0;

    while (!infile.eof()) {
        getline(infile, STRING); // Saves the line in STRING.
        vector<string> currentLine = split(STRING, " ");
        long origin_sourceId = stol(currentLine[0]);
        long origin_sinkId = stol(currentLine[1]);
        long sourceId = userIdMap[origin_sourceId];
        long sinkId = userIdMap[origin_sinkId];

        std::map<long, std::vector<double>>::iterator it;
        std::map<long, std::vector<double>>::iterator it2;
        it = nodeAttrMap.find(sourceId);
        it2 = nodeAttrMap.find(sinkId);
        if ((it == nodeAttrMap.end()) || (it2 == nodeAttrMap.end())) {
            origin_edge_id++;
            continue;
        }

        //printf("sourceId is %d, sinkId is %d \n", sourceId, sinkId);
        edges.push_back(std::make_pair(std::make_pair(sourceId, sinkId),origin_edge_id));
        //printf("edge id is %d \n",edges.size()-1);
        //printf("origin edge id is %d \n",edges[edges.size()-1].second);
        origin_edge_id++;
    }
    edge_trans_endTime = clock();

    ofstream outfile;
    outfile.open("result_edge_comp.txt");

    outfile <<"------------------------Final result-------------------------------------" << endl;
    outfile << "Total Running Time : " <<(double)(edge_trans_endTime - edge_trans_startTime) / CLOCKS_PER_SEC << "s" << endl;

    infile.close();
    printf("Done loading graph......");
    printf("\n");

}

void Graph::loadAttributes(std::string attributeFilePath, std::vector<AttributeInfo>&attribute_stat,
                           std::map<long, std::vector<double>>&nodeAttrMap,
                           std::map<long,long> &userIdMap){

    std::ifstream test2(attributeFilePath);
    if (!test2)
    {
        std::cout << "The attributeFile doesn't exist" << std::endl;
    }

    printf("Start loading attributes......");
    printf("\n");

    string STRING;
    ifstream infile;
    infile.open (attributeFilePath);

    for (int i = 0; i< attribute_index_number; i++){
        AttributeInfo singleAttribute;
        singleAttribute.min_value = INT_MAX*1.0;
        singleAttribute.max_value = 0.0;
        singleAttribute.mean_value = 0.0;
        attribute_stat.push_back(singleAttribute);
    }

    long lineNumber =0;

    while(!infile.eof()) {

        getline(infile, STRING); // Saves the line in STRING.
        vector<string> currentLine = Graph::split(STRING, " ");
        std::vector<double> attribute_values;
        long node_id = stol(currentLine[0]);
        //printf("node_id is %ld \n", node_id);´
        long mapped_id = userIdMap[node_id];
        //printf("mapped_node_id is %ld \n",mapped_id);
        for (int i = 1; i <= attribute_index_number; i++) {
            double attribute_value = stod(currentLine[i]);
            //printf("attribute_value is %f \n", attribute_value);
            if (attribute_value < attribute_stat[i - 1].min_value) {
                attribute_stat[i - 1].min_value = attribute_value;
            }
            if (attribute_value > attribute_stat[i - 1].max_value) {
                attribute_stat[i - 1].max_value = attribute_value;
            }
            attribute_values.push_back(attribute_value);
        }

        if (nodeAttrMap.count(mapped_id) == 0) {
            lineNumber++;
            nodeAttrMap.insert(std::pair<long, std::vector<double>>(mapped_id, attribute_values));
        } else {
            lineNumber++;
            continue;
        }
    }

    infile.close();
    printf("Done loading attributes......");
    printf("\n");

    /*
    int i =0;
    std::vector<AttributeInfo>::iterator it2;
    for (it2=attribute_stat.begin(); it2!=attribute_stat.end();++it2){
        printf("attribute_stat i is %d, min_val is %f, max_val is %f \n",i, (*it2).min_value, (*it2).max_value);
        i++;
    }
    */
}

std::vector<std::string> Graph::split(std::string str, std::string s) {

        vector<string> vStr;
        boost::split(vStr, str, boost::is_any_of(s), boost::token_compress_on);
        return vStr;

}

void Graph::pretty_print(const vector<int>& v, const int sourceId, const int sinkId,std::vector<std::pair<std::pair<long, long>, long> > &edges,
                         std::map<long,std::vector<int>> &edgeAttributeMap, long origin_edge_id
) {

    /*
    static int count = 0;
    cout << "combination no " << (++count) << ": [ ";
    for (int i = 0; i < v.size(); ++i) { cout << v[i] << " "; }
    cout << "] " << endl;
    */

    printf("sourceId is %d, sinkId is %d \n", sourceId, sinkId);
    edges.push_back(std::make_pair(std::make_pair(sourceId, sinkId),origin_edge_id));
    printf("edge id is %d \n",edges.size()-1);
    printf("origin edge id is %d \n",edges[edges.size()-1].second);
    edgeAttributeMap.insert(
            std::pair<long, std::vector<int>>(edges.size()-1, v));

}

void Graph::combCalculation(int offset, int k, const int sourceId, const int sinkId,std::vector<std::pair<std::pair<long, long>, long> > &edges,
                            std::map<long,std::vector<int>> &edgeAttributeMap, long origin_edge_id
) {
    if (k == 0) {
        pretty_print(attribute_index_combination, sourceId, sinkId,edges,edgeAttributeMap,origin_edge_id);
        return;
    }
    for (int i = offset; i <= attribute_index.size() - k; ++i) {
        attribute_index_combination.push_back(attribute_index[i]);
        Graph::combCalculation(i+1, k-1, sourceId, sinkId,edges,edgeAttributeMap, origin_edge_id);
        attribute_index_combination.pop_back();
    }
}

max_stars_repo_name: wsu-db/Attribute-Driven-Backbone-

max_issues_repo_name: wsu-db/Attribute-Driven-Backbone-

max_forks_repo_name: wsu-db/Attribute-Driven-Backbone-


text:
//
// Copyright (C) 2009-2013 King Luo (home_king@163.com)
//
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef TEST_REFLECTION_HPP
#define TEST_REFLECTION_HPP

#include <boost/test/minimal.hpp>

#include <boost/reflection/reflection.hpp>
using namespace boost::reflection;

#include "test_interface.hpp"

void test_reflection()
{
    {
        Class t = Class::forName("test.AccountImpl");
        boost::any o = t.newInstance(std::string("Account-id-100"), (unsigned int)26);
        BOOST_REQUIRE(!o.empty());

        t.invokeStatic("echo", o, std::string("TEST"));

        TypeInfoArray tArray;
        tArray.push_back(BOOST_REFL_TYPEID(std::string));
        Method m1 = t.getMethod("setId", tArray);
        m1.invoke(o, std::string("Account-id-200"));

        Method m2 = t.getMethod("getId");
        boost::any ret = m2.invoke(o);
        BOOST_REQUIRE(boost::any_cast<std::string>(ret) == "Account-id-200");

        Field field = t.getField("age");
        field.set(o, (unsigned int)30);
        BOOST_REQUIRE(boost::any_cast<unsigned int>(field.get(o)) == 30);

        test::AccountItf* itf = interface_cast<test::AccountItf*>(o);
        BOOST_REQUIRE(itf);
        BOOST_REQUIRE(itf->getId() == "Account-id-200");

        t.deleteInstance(o);
    }

    {
        Class t1 = Class::forName("test.AccountEchoService");
        TypeInfoArray tArray;
        tArray.push_back(BOOST_REFL_TYPEID(test::AccountItf*));
        tArray.push_back(BOOST_REFL_TYPEID(Deleter<test::AccountItf>));
        Method m1 = t1.getMethod("setImpl", tArray);
        Method m2 = t1.getMethod("getImpl");
        Class t2 = Class::forName("test.AccountImpl");
        Class t3 = Class::forName("test.AnotherAccountImpl");
        test::AccountEchoService* o = t1.newInstance<test::AccountEchoService*>();

        test::AccountItf* someImpl = t2.newInstance<test::AccountItf*>(std::string("Account-id-888"), (unsigned int)26);
        m1.invoke(o, someImpl, t2.getDeleter<test::AccountItf>(someImpl));
        BOOST_REQUIRE(boost::any_cast<test::AccountItf*>(m2.invoke(o)) == someImpl);
        o->echo(std::string("some Account"));

        test::AccountItf* anotherImpl = t3.newInstance<test::AccountItf*>(std::string("Account-id-999"));
        m1.invoke(o, anotherImpl, t3.getDeleter<test::AccountItf>(anotherImpl));
        BOOST_REQUIRE(boost::any_cast<test::AccountItf*>(m2.invoke(o)) == anotherImpl);
        o->echo(std::string("another Account"));

        t1.deleteInstance(o);
    }
}

#endif

max_stars_repo_name: jackfive/boost-reflection

max_issues_repo_name: jackfive/boost-reflection

max_forks_repo_name: jackfive/boost-reflection