text:
/*
 * MIT License
 *
 * Copyright (c) 2015 Alexis LE GOADEC
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * 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 AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF 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/program_options/cmdline.hpp>
#include <boost/program_options/config.hpp>
#include <boost/program_options/environment_iterator.hpp>
#include <boost/program_options/eof_iterator.hpp>
#include <boost/program_options/errors.hpp>
#include <boost/program_options/option.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/positional_options.hpp>
#include <boost/program_options/value_semantic.hpp>
#include <boost/program_options/variables_map.hpp>

#include <boost/shared_ptr.hpp>
#include <boost/version.hpp>
#include <fstream>
#include <iostream>

#include "include/Client.hh"
#include "include/RandomHypergraphe.hh"

#include "../include/Hypergraph/model/LibType.hh"
#include "../include/Hypergraph/model/Hypergraphe.hh"
#include "../include/Hypergraph/model/HyperFactory.hh"
#include "../include/Hypergraph/model/HyperVertex.hh"
#include "../include/Hypergraph/model/HyperEdge.hh"
#include "../include/Hypergraph/model/MotorAlgorithm.hh"

#include "../include/Hypergraph/algorithm/Dual.hh"
#include "../include/Hypergraph/algorithm/Path.hh"
#include "../include/Hypergraph/algorithm/Helly.hh"
#include "../include/Hypergraph/algorithm/kRegular.hh"
#include "../include/Hypergraph/algorithm/kUniform.hh"
#include "../include/Hypergraph/algorithm/Simple.hh"
#include "../include/Hypergraph/algorithm/Linear.hh"
#include "../include/Hypergraph/algorithm/Connected.hh"
#include "../include/Hypergraph/algorithm/HyperGraphStat.hh"
#include "../include/Hypergraph/algorithm/Isomorph.hh"

#include "../include/Hypergraph/io/WriterFile.hh"
#include "../include/Hypergraph/io/ReaderFile.hh"

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

	boost::program_options::options_description desc("Paramètres");
	desc.add_options()
					("version", "Afficher la version")
					("help", "Afficher l'aide")
					("inputfile", boost::program_options::value<std::string>(), "Fichier d'entrée")
					("random", boost::program_options::value<int>(), "Hypergraphe aléatoire de n vertex")
					("adjacence", "Affiche la matrice d'adjacence de l'hypergraphe")
					("dual", "Produit le Dual de l'hypergraphe")
					("kuniform", boost::program_options::value<int>(), "Décide si l'hypergraphe est k-uniforme")
					("linear", "Décide si l'hypergraphe est linéaire")
					("kregular", "Décide si l'hypergraphe est k-regulier")
					("simple", "Décide si l'hypergraphe est simple")
					("helly", "Décide si un hypergraphe possède la propriété de Helly")
					("connexe", "Décide si l'hypergraphe est connexe")
					("isomorph", boost::program_options::value<std::string>(), "Décide si deux hypergraphes sont isomorphe")
					("stat", "Retourne les statistiques de l'hypergraphe")
					("path", "Retourne le chemins")
					("source", boost::program_options::value<int>(), "Source de la reherche de chemins")
					("destination", boost::program_options::value<int>(), "Destination de la recherche de chemins");

	boost::program_options::variables_map vm;
	boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
	boost::program_options::notify(vm);

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

	if( vm.count("version") ) {
		std::cout << "HypergraphLib "
				  << VERSION_MAJOR << "."
				  << VERSION_MINOR << "-"
				  << VERSION_BUILD
				  << std::endl
				  << "Université de Caen Basse-Normandie, 2015 - Alexis LE GOADEC."
				  << std::endl
				  << "Boost version: " << BOOST_VERSION << std::endl
				  << "GCC version: " << __VERSION__ << std::endl
#ifdef __x86_64
				  << "x86_64: " << __x86_64 << std::endl
#endif
				  << "---" << std::endl;
		return 0;
	}

	boost::shared_ptr<HypergrapheAbstrait> ptrHpg;

	if( vm.count("inputfile") && vm.count("random")==0 ) {
		std::ifstream ifs(vm["inputfile"].as<std::string>(), std::ifstream::in);

		ReaderFile fReader;
		fReader.readHypergraphe( ifs );
		ifs.close();

		ptrHpg = fReader.getHypergraphe();

	} else if( vm.count("inputfile")==0 && vm.count("random")==0) {
		ReaderFile fReader;
		fReader.readHypergraphe( std::cin );
		ptrHpg = fReader.getHypergraphe();
	}

	// Isomorphism special parameters configuration
	if( vm.count("isomorph") && vm.count("inputfile") ) {

		boost::shared_ptr<HypergrapheAbstrait> ptrHpg2;

		std::ifstream ifs(vm["isomorph"].as<std::string>(), std::ifstream::in);

		ReaderFile fReader;
		fReader.readHypergraphe( ifs );
		ifs.close();

		ptrHpg2 = fReader.getHypergraphe();

		NewAlgorithm2(isomorphHpg, Isomorph, ptrHpg, ptrHpg2);

		MotorAlgorithm::setAlgorithme( isomorphHpg );
		MotorAlgorithm::runAlgorithme();

		RStructure r( isomorphHpg->getResult() );

		if( r.getBooleanResult() ) {
			std::cout << "L'hypergraphe est isomorphe." << std::endl;
		} else {
			std::cout << "L'hypergraphe n'est pas isomorphe." << std::endl;
		}

		return 0;
	}

	if( vm.count("random") ) {
		RandomHypergraphe rHyp;
		rHyp.generateHypergraphe(vm["random"].as<int>(), vm["random"].as<int>());
		ptrHpg = rHyp.getHypergraphe();
	}

	if( vm.count("stat") ) {
		NewAlgorithm(statHpg, HyperGraphStat, ptrHpg);

		MotorAlgorithm::setAlgorithme( statHpg );
		MotorAlgorithm::runAlgorithme();

		boost::shared_ptr<HyperGraphStat> s = boost::static_pointer_cast<HyperGraphStat>( statHpg );

		std::cout << "Hyper-vertex : " << s->getNbrHyperVertex() << std::endl
				  << "Hyper-edge   : " << s->getNbrHyperEdge()   << std::endl
				  << "Nbr. links   : " << s->getNbrLinks()       << std::endl
				  << "Rang         : " << s->getRang()           << std::endl
				  << "Co-rang      : " << s->getCoRang()         << std::endl;

		return 0;
	}

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

		NewAlgorithm(dualAlgo, Dual, ptrHpg);

		MotorAlgorithm::setAlgorithme( dualAlgo );
		MotorAlgorithm::runAlgorithme();

		RStructure r( dualAlgo->getResult() );

		WriterFile w(r.getHypergrapheResult());
		if( vm.count("adjacence") ) {
			w.writeAdjacentMatrix( std::cout );
		} else {
			w.writeHypergraph( std::cout );
		}

		return 0;
	}

	if( vm.count("kuniform") ) {
		boost::shared_ptr<AlgorithmeAbstrait> kuniformAlgo( new kUniform( ptrHpg, vm["kuniform"].as<int>() ) );
		MotorAlgorithm::setAlgorithme( kuniformAlgo );
		MotorAlgorithm::runAlgorithme();

		RStructure r( kuniformAlgo->getResult() );
		if( r.getBooleanResult() ) {
			std::cout << "L'hypergraphe est " << vm["kuniform"].as<int>() << "-uniforme." << std::endl;
		} else {
			std::cout << "L'hypergraphe n'est pas " << vm["kuniform"].as<int>() << "-uniforme." << std::endl;
		}

		return 0;
	}

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

		NewAlgorithm(linearAlgo, Linear, ptrHpg);

		MotorAlgorithm::setAlgorithme( linearAlgo );
		MotorAlgorithm::runAlgorithme();

		RStructure r( linearAlgo->getResult() );
		if( r.getBooleanResult() ) {
			std::cout << "L'hypergraphe est Linéaire." << std::endl;
		} else {
			std::cout << "L'hypergraphe n'est pas Linéaire." << std::endl;
		}

		return 0;
	}

	if( vm.count("helly") ) {
		NewAlgorithm(hellyAlgo, Helly, ptrHpg);

		MotorAlgorithm::setAlgorithme( hellyAlgo );
		MotorAlgorithm::runAlgorithme();

		RStructure r( hellyAlgo->getResult() );
		if( r.getBooleanResult() ) {
			std::cout << "L'hypergraphe est Helly." << std::endl;
		} else {
			std::cout << "L'hypergraphe n'est pas Helly." << std::endl;
		}
		return 0;
	}

	if( vm.count("kregular") ) {
		NewAlgorithm(kregularAlgo, kRegular, ptrHpg);

		MotorAlgorithm::setAlgorithme( kregularAlgo );
		MotorAlgorithm::runAlgorithme();

		RStructure r( kregularAlgo->getResult() );
		if( r.getBooleanResult() ) {
			std::cout << "L'hypergraphe est k-regulier." << std::endl;
		} else {
			std::cout << "L'hypergraphe n'est pas k-regulier." << std::endl;
		}

		return 0;
	}

	if( vm.count("simple") ) {
		NewAlgorithm(simpleAlgo, Simple, ptrHpg);

		MotorAlgorithm::setAlgorithme( simpleAlgo );
		MotorAlgorithm::runAlgorithme();

		RStructure r( simpleAlgo->getResult() );
		if( r.getBooleanResult() ) {
			std::cout << "L'hypergraphe est simple." << std::endl;
		} else {
			std::cout << "L'hypergraphe n'est pas simple." << std::endl;
		}

		return 0;
	}

	if(vm.count("path") ) {
		boost::shared_ptr<Path> pathAlgo( new Path( ptrHpg ) );

		pathAlgo->setHyperVertex(
				ptrHpg->getHyperVertexById(vm["source"].as<int>()),
				ptrHpg->getHyperVertexById(vm["destination"].as<int>() )
			);

		boost::shared_ptr<AlgorithmeAbstrait> algoPathAbstrait( pathAlgo );

		MotorAlgorithm::setAlgorithme( algoPathAbstrait );
		MotorAlgorithm::runAlgorithme();

		RStructurePath r( pathAlgo->getPathResult() );

		for(unsigned int i=0; i<r.getPathResult()->size(); i++) {
			LibType::ListHyperVertex hvl( r.getPathResult()->at(i) );
			for(unsigned int j=0; j<hvl.size(); j++) {
				std::cout << hvl.at(j)->getIdentifier() << " ";
			}
			std::cout << std::endl;
		}

	}

	if( vm.count("connexe") ) {
		NewAlgorithm(algoConnected, Connected, ptrHpg);

		MotorAlgorithm::setAlgorithme( algoConnected );
		MotorAlgorithm::runAlgorithme();

		RStructure r( algoConnected->getResult() );
		if( r.getBooleanResult() ) {
			std::cout << "L'hypergraphe est connexe." << std::endl;
		} else {
			std::cout << "L'hypergraphe n'est pas connexe." << std::endl;
		}

		return 0;
	}

	if( vm.count("adjacence") ) {
		WriterFile w( ptrHpg );
		w.writeAdjacentMatrix( std::cout );
	} else {
		WriterFile w( ptrHpg );
		w.writeHypergraph( std::cout );
	}

	return 0;
}

max_stars_repo_name: ehzawad/HyperGraphLib

max_issues_repo_name: ehzawad/HyperGraphLib

max_forks_repo_name: ehzawad/HyperGraphLib


text:
// https://projecteuler.net/problem=56
/*
Powerful digit sum

A googol (10^100) is a massive number:
one followed by one-hundred zeros;

100^100 is almost unimaginably large:
one followed by two-hundred zeros.

Despite their size, the sum of the digits in each number is only 1.

Considering natural numbers of the form, a^b, where a, b < 100,
what is the maximum digital sum?

Solution:

*/

#include <iostream>
#include <cstdint>
#include <string>
#include <boost/multiprecision/cpp_int.hpp>
#include <chrono>

auto digitCount(uint32_t a, uint32_t b) {
	using namespace boost;
	multiprecision::cpp_int p = a;
	p = multiprecision::pow(p, b);
	auto ans = p.str();
	uint32_t sum = 0;
	for (const auto &c : ans)
		sum += c - '0';
	return sum;
}

auto compute() {
	constexpr uint32_t limit = 100;

	uint32_t max = 0;
	for (uint32_t a = 1; a < limit; ++a)
		for (uint32_t b = 1, c; b < limit; ++b)
			if (max < (c = digitCount(a, b)))
				max = c;

	return max;
}

#ifdef _MSC_VER
	template <class T>
	inline void DoNotOptimize(const T &value) {
		__asm { lea ebx, value }
	}
#else
	template <class T>
	__attribute__((always_inline)) inline void DoNotOptimize(const T &value) {
		asm volatile("" : "+m"(const_cast<T &>(value)));
	}
#endif

int main() {
	using namespace std;
	using namespace chrono;
	auto start = high_resolution_clock::now();
	auto result = compute();
	DoNotOptimize(result);
	cout << "Done in "
		<< duration_cast<nanoseconds>(high_resolution_clock::now() - start).count() / 1e6
		<< " miliseconds." << endl;
	cout << result << endl;
}

ext: cpp

max_stars_repo_name: ankitdixit/code-gems

max_issues_repo_name: ankitdixit/code-gems

max_forks_repo_name: ankitdixit/code-gems


text:
#define BOOST_TEST_MODULE test modelpp::model
#include <boost/test/unit_test.hpp>

#include "modelpp/fields.hpp"

namespace modelpp
{
  using field_types = fields<int, std::string, std::vector<int>>;
}

#include "modelpp/model.hpp"

class model_container : public modelpp::model
{
  public:
    int id() const                          { return id_; }
    void id(int value)                      { change("id", &id_, value); }

    const std::string& name() const         { return name_; }
    void name(const std::string& value)     { change("name", &name_, value); }

    const std::vector<int>& vec() const     { return vec_; }
    void vec(const std::vector<int>& value) { change("vec", &vec_, value); }

    static modelpp::metadata<model_container> metadata;

    MODELPP_IMPLEMENT_METHODS()

  private:
    int id_;
    std::string name_;
    std::vector<int> vec_;
};

modelpp::metadata<model_container> model_container::metadata{
  modelpp::metadata<model_container>("model_container")
    .field("id", &model_container::id_)
    .field("name", &model_container::name_)
    .field("vec", &model_container::vec_)
};

BOOST_FIXTURE_TEST_SUITE(s, model_container)

BOOST_AUTO_TEST_CASE(test_container_field)
{
  std::vector<int> v;
  v.push_back(1);

  vec(v);
  BOOST_CHECK(changed("vec"));

  auto [old, newv] = changes().at("vec");

  BOOST_CHECK(std::get<std::vector<int>>(old) == std::vector<int>{});
  BOOST_CHECK(std::get<std::vector<int>>(newv) == std::vector<int>{1});

  auto model_data = data();

  vec({});

  load(model_data);

  BOOST_CHECK(vec() == std::vector<int>{1});
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: Aethelflaed/modelpp

max_issues_repo_name: Aethelflaed/modelpp

max_forks_repo_name: Aethelflaed/modelpp


text:
#include <iostream>
#include <thread>
#include <boost/program_options.hpp>
#include <boost/format.hpp>
#include <boost/filesystem.hpp>
#include "net_bandwidth.hpp"

using namespace std;
int main(int argc, char* argv[])
{
    Unit unit {Unit::KB};
    vector<Interfaces> nics {};
    int period {1000};
    int duration {-1};

    namespace po = boost::program_options;

    po::options_description desc;
    desc.add_options()
        ("help", "print this help")
        ("list", "list NICs")
        ("add", po::value<vector<string>>(), "add NIC to monitor [default: only physical]")
        ("unit", po::value<string>(), "set Unit(Kb, KB, MB, GB) [default: KB]")
        ("period", po::value<int>(), "set print period(in milisecond) [default: 1000]")
        ("duration", po::value<int>(), "set monitoring duration(in second) [default: infinit]")
        ;

    ///////  Check Arguments ///////////////////////////
    po::variables_map vmap;
    try{
        po::store(po::parse_command_line(argc, argv, desc), vmap);
        po::notify(vmap);
    }catch(std::exception& e){
        cerr << "Exception: " << e.what() << '\n';
        return -1;
    }
    if(vmap.count("help")){
        std::cout << desc;
        return 0;
    }
    if(vmap.count("list")){
        cout << "List of interfaces:\n";
        for(const auto nic: System::get_interfaces()){
            cout << '\t' << nic << '\n';
        }
        return 0;
    }
    if(vmap.count("unit")){
        const auto str = vmap["unit"].as<string>();
        if(str == "Kb") unit = Unit::Kb;
        else if(str == "KB") unit = Unit::KB;
        else if(str == "MB") unit = Unit::MB;
        else if(str == "GB") unit = Unit::GB;
    }
    if(vmap.count("add")){
        const auto nics_str = vmap["add"].as<vector<string>>();
        for(const string nic_str : nics_str){
            nics.emplace_back(nic_str);
        }
    }else{
        for(const auto nic_str : System::get_interfaces()){
            if(boost::filesystem::exists("/sys/class/net/" + nic_str + "/device"))
                nics.emplace_back(nic_str);
        }
    }
    if(vmap.count("period")){
        period = vmap["period"].as<int>();
    }
    if(vmap.count("duration")){
        duration = vmap["duration"].as<int>();
    }

    ///////  Start Monitoring ///////////////////////////
    float unit_div = (1<<10) / 8;
    if(unit == Unit::KB) unit_div = (1<<10);
    else if(unit == Unit::MB) unit_div = (1<<20);
    else if(unit == Unit::GB) unit_div = (1<<30);
    time_t now = time(NULL);
    cout << "\nDuration: " << duration
         << "\nPeriod: " << period
         << "\nUnit: " << unit_str[size_t(unit)]
         << "\nNICs: ";
    for(auto& nic : nics){
        cout << nic.get_name() << ' ';
    }
    cout << "\n------------------------------" << endl;
    while(true){
        string line;
        for(auto& nic : nics){
            auto out = boost::format("%5s(rx:%-5.3f, tx:%-5.3f) ")
                        % nic.get_name()
                        % (nic.get_rx() / unit_div)
                        % (nic.get_tx() / unit_div);
            line += out.str();
        }
        cout << line << endl;
        std::this_thread::sleep_for(std::chrono::microseconds(1000 * period));
        if(duration != -1 &&  duration + now <= time(NULL)) break;
    }
}


text:
#include <boost/assign.hpp>
#include <glog/logging.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <vector>
#include "caffe/internode/configuration.hpp"
#include "caffe/serialization/BlobCodec.hpp"
#include "caffe/test/test_caffe_main.hpp"
#include "caffe/util/math_functions.hpp"

namespace caffe {
namespace {

using ::testing::_;
using ::testing::Return;

template <typename TypeParam>
class BlobCodecTest : public MultiDeviceTest<TypeParam> {
    typedef typename TypeParam::Dtype Dtype;
};
TYPED_TEST_CASE(BlobCodecTest, TestDtypesAndDevices);

TYPED_TEST(BlobCodecTest, encode_4321_diff) {
  BlobUpdate msg;
  Blob<float> srcblob;
  vector<int> v = boost::assign::list_of(4)(3)(2)(1);
  srcblob.Reshape(v);
  vector<float> diff = boost::assign::list_of(999.99)(12.3)(0.1)(-3.3)
                                             (+2.0)(12.3)(10.2)(FLT_MAX)
                                             (+4.4)(12.3)(0.0)(-1.3)
                                             (+6.5)(12.3)(24.42)(1010.10)
                                             (FLT_MIN)(12.3)(66.6)(133.1)
                                             (12.4)(12.3)(0.0001)(100.3);

  ASSERT_EQ(diff.size(), srcblob.count());

  caffe_copy(srcblob.count(),
          &diff.front(),
          srcblob.mutable_cpu_diff());

  shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
          MultinodeParameter::default_instance(), true);

  codec->encode(&msg, &srcblob, BlobEncoding::GRADS, msg.info().part());

  EXPECT_EQ(0, memcmp(msg.data().c_str(), &diff.front(),
           sizeof(float)*diff.size()));
}

TYPED_TEST(BlobCodecTest, encode_decode_2222_data) {
  BlobUpdate msg;
  Blob<float> srcblob;
  Blob<float> dstblob;
  vector<int> v = boost::assign::list_of(2)(2)(2)(2);
  srcblob.Reshape(v);
  dstblob.Reshape(v);
  vector<float> data = boost::assign::list_of(1.1)(-2.2)(3.3)(5.5)
                                             (6.6)(-7.7)(8.8)(9.9)
                                             (13.13)(-12.12)(12.12)(11.11)
                                             (128.128)(-132.312)(1.1)(-10.10);
  vector<float> data_zero = boost::assign::list_of(0.0)(0.0)(0.0)(0.0)
                                                  (0.0)(0.0)(0.0)(0.0)
                                                  (0.0)(0.0)(0.0)(0.0)
                                                  (0.0)(0.0)(0.0)(0.0);
  ASSERT_EQ(data.size(), srcblob.count());
  ASSERT_EQ(data_zero.size(), dstblob.count());

  caffe_copy<float>(srcblob.count(),
          &data.front(),
          srcblob.mutable_cpu_data());
  caffe_copy<float>(dstblob.count(),
          &data_zero.front(),
          dstblob.mutable_cpu_diff());

  shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
          MultinodeParameter::default_instance(), true);

  codec->encode(&msg, &srcblob, BlobEncoding::PARAMS, msg.info().part());
  codec->decode(msg,  &dstblob, BlobEncoding::PARAMS, 1.0f, 0.0f);

  EXPECT_EQ(0, memcmp(dstblob.cpu_data(), &data.front(),
          sizeof(float)*dstblob.count()));
}

TYPED_TEST(BlobCodecTest, encode_8width_data_) {
  BlobUpdate msg;
  Blob<float> srcblob;
  vector<int> v = boost::assign::list_of(1)(1)(1)(8);
  srcblob.Reshape(v);
  vector<float> data = boost::assign::list_of(-0.0)(-0.3)(-2.2)(-3.3)
                                             (+0.0)(12.3)(10.2)(-1.3);

  ASSERT_EQ(data.size(), srcblob.count());

  caffe_copy<float>(srcblob.count(),
          &data.front(),
          srcblob.mutable_cpu_data());

  shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
          MultinodeParameter::default_instance(), true);

  codec->encode(&msg, &srcblob, BlobEncoding::PARAMS, msg.info().part());

  EXPECT_EQ(0, memcmp(msg.data().c_str(), &data.front(),
          sizeof(float)*data.size()));
}

TYPED_TEST(BlobCodecTest, encode_4width_diff) {
  BlobUpdate msg;
  Blob<float> srcblob;
  vector<int> v = boost::assign::list_of(1)(1)(1)(4);
  srcblob.Reshape(v);
  vector<float> diff = boost::assign::list_of(-0.0)(-99.99)(-0.3)(0.4);

  ASSERT_EQ(diff.size(), srcblob.count());

  caffe_copy<float>(srcblob.count(),
          &diff.front(),
          srcblob.mutable_cpu_diff());

  shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
          MultinodeParameter::default_instance(), true);

  codec->encode(&msg, &srcblob, BlobEncoding::GRADS, msg.info().part());

  EXPECT_EQ(0, memcmp(msg.data().c_str(), &diff.front(),
          sizeof(float)*diff.size()));
}

TYPED_TEST(BlobCodecTest, encode_decode_4width_diff) {
  BlobUpdate msg;
  Blob<float> srcblob;
  Blob<float> dstblob;
  vector<int> v = boost::assign::list_of(1)(1)(1)(4);
  srcblob.Reshape(v);
  dstblob.Reshape(v);
  vector<float> diff_zero = boost::assign::list_of(0.0)(0.0)(0.0)(0.0);
  vector<float> diff = boost::assign::list_of(1.0)(2.2)(3.3)(4.4);

  ASSERT_EQ(diff.size(), srcblob.count());
  ASSERT_EQ(diff_zero.size(), srcblob.count());

  caffe_copy<float>(srcblob.count(),
          &diff.front(),
          srcblob.mutable_cpu_diff());
  caffe_copy<float>(dstblob.count(),
          &diff_zero.front(),
          dstblob.mutable_cpu_diff());

  shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
           MultinodeParameter::default_instance(), true);

  codec->encode(&msg, &srcblob, BlobEncoding::GRADS, msg.info().part());
  codec->decode(msg,  &dstblob, BlobEncoding::GRADS, 1.0f, 0.0f);

  EXPECT_EQ(0, memcmp(dstblob.cpu_diff(), &diff.front(),
          sizeof(float)*dstblob.count()));
}

TYPED_TEST(BlobCodecTest, encode_decode_4width_data) {
  BlobUpdate msg;
  Blob<float> srcblob;
  Blob<float> dstblob;
  vector<int> v = boost::assign::list_of(1)(1)(1)(4);
  srcblob.Reshape(v);
  dstblob.Reshape(v);
  vector<float> data_zero = boost::assign::list_of(0.0)(0.0)(0.0)(0.0);
  vector<float> data = boost::assign::list_of(4.0)(3.2)(2.3)(1.4);

  ASSERT_EQ(data.size(), srcblob.count());
  ASSERT_EQ(data_zero.size(), srcblob.count());

  caffe_copy<float>(srcblob.count(),
          &data.front(),
          srcblob.mutable_cpu_data());
  caffe_copy<float>(dstblob.count(),
          &data_zero.front(),
          dstblob.mutable_cpu_data());

  shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
          MultinodeParameter::default_instance(), true);

  codec->encode(&msg, &srcblob, BlobEncoding::PARAMS, msg.info().part());
  codec->decode(msg,  &dstblob, BlobEncoding::PARAMS, 1.0f, 0.0f);

  EXPECT_EQ(0, memcmp(dstblob.cpu_data(), &data.front(),
          sizeof(float)*dstblob.count()));
}

TYPED_TEST(BlobCodecTest, encode_decode_4width_data_alpha_0_5) {
  BlobUpdate msg;
  Blob<float> srcblob;
  Blob<float> dstblob;
  vector<int> v = boost::assign::list_of(1)(1)(1)(4);
  srcblob.Reshape(v);
  dstblob.Reshape(v);
  vector<float> data_zero = boost::assign::list_of(0.0)(0.0)(0.0)(0.0);
  vector<float> data = boost::assign::list_of(4.0)(3.2)(2.4)(1.4);
  vector<float> data_expected = boost::assign::list_of(2.0)(1.6)(1.2)(0.7);

  ASSERT_EQ(data.size(), srcblob.count());
  ASSERT_EQ(data_zero.size(), srcblob.count());

  caffe_copy<float>(srcblob.count(),
          &data.front(),
          srcblob.mutable_cpu_data());
  caffe_copy<float>(dstblob.count(),
          &data_zero.front(),
          dstblob.mutable_cpu_data());

  shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
          MultinodeParameter::default_instance(), true);

  codec->encode(&msg, &srcblob, BlobEncoding::PARAMS, msg.info().part());
  codec->decode(msg,  &dstblob, BlobEncoding::PARAMS, 0.5f, 0.0f);

  EXPECT_EQ(0, memcmp(dstblob.cpu_data(), &data_expected.front(),
          sizeof(float)*dstblob.count()));
}

TYPED_TEST(BlobCodecTest, encode_decode_4width_data_beta_0_5) {
  BlobUpdate msg;
  Blob<float> srcblob;
  Blob<float> dstblob;
  vector<int> v = boost::assign::list_of(1)(1)(1)(4);
  srcblob.Reshape(v);
  dstblob.Reshape(v);
  vector<float> data_one = boost::assign::list_of(1.0)(1.0)(1.0)(1.0);
  vector<float> data = boost::assign::list_of(4.0)(3.2)(2.4)(1.4);
  vector<float> data_expected = boost::assign::list_of(4.5)(3.7)(2.9)(1.9);

  ASSERT_EQ(data.size(), srcblob.count());
  ASSERT_EQ(data_one.size(), srcblob.count());

  caffe_copy<float>(srcblob.count(), &data.front(),
          srcblob.mutable_cpu_data());
  caffe_copy<float>(dstblob.count(), &data_one.front(),
          dstblob.mutable_cpu_data());

  shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
          MultinodeParameter::default_instance(), true);

  codec->encode(&msg, &srcblob, BlobEncoding::PARAMS, msg.info().part());
  codec->decode(msg,  &dstblob, BlobEncoding::PARAMS, 1.0f, 0.5f);

  EXPECT_EQ(0, memcmp(dstblob.cpu_data(), &data_expected.front(),
          sizeof(float)*dstblob.count()));
}

TYPED_TEST(BlobCodecTest, encode_decode_4width_data_alpha_0_5_beta_0_5) {
  BlobUpdate msg;
  Blob<float> srcblob;
  Blob<float> dstblob;
  vector<int> v = boost::assign::list_of(1)(1)(1)(4);
  srcblob.Reshape(v);
  dstblob.Reshape(v);
  vector<float> data_one = boost::assign::list_of(1.0)(1.0)(1.0)(1.0);
  vector<float> data = boost::assign::list_of(4.0)(3.2)(2.4)(1.4);
  vector<float> data_expected = boost::assign::list_of(2.5)(2.1)(1.7)(1.2);

  ASSERT_EQ(data.size(), srcblob.count());
  ASSERT_EQ(data_one.size(), srcblob.count());

  caffe_copy<float>(srcblob.count(), &data.front(),
          srcblob.mutable_cpu_data());
  caffe_copy<float>(dstblob.count(), &data_one.front(),
          dstblob.mutable_cpu_data());

  shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
          MultinodeParameter::default_instance(), true);

  codec->encode(&msg, &srcblob, BlobEncoding::PARAMS, msg.info().part());
  codec->decode(msg,  &dstblob, BlobEncoding::PARAMS, 0.5f, 0.5f);

  EXPECT_EQ(0, memcmp(dstblob.cpu_data(), &data_expected.front(),
          sizeof(float)*dstblob.count()));
}

TYPED_TEST(BlobCodecTest, encode_decode_4width_data_alpha_0_beta_1) {
  BlobUpdate msg;
  Blob<float> srcblob;
  Blob<float> dstblob;
  vector<int> v = boost::assign::list_of(1)(1)(1)(4);
  srcblob.Reshape(v);
  dstblob.Reshape(v);
  vector<float> data_one = boost::assign::list_of(1.1)(2.3)(1.4)(0.01);
  vector<float> data = boost::assign::list_of(4.0)(3.2)(2.4)(1.4);
  vector<float> data_expected = boost::assign::list_of(1.1)(2.3)(1.4)(0.01);

  ASSERT_EQ(data.size(), srcblob.count());
  ASSERT_EQ(data_one.size(), srcblob.count());

  caffe_copy<float>(srcblob.count(), &data.front(),
          srcblob.mutable_cpu_data());
  caffe_copy<float>(dstblob.count(), &data_one.front(),
          dstblob.mutable_cpu_data());

  shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
          MultinodeParameter::default_instance(), true);

  codec->encode(&msg, &srcblob, BlobEncoding::PARAMS, msg.info().part());
  codec->decode(msg,  &dstblob, BlobEncoding::PARAMS, 0.0f, 1.0f);

  EXPECT_EQ(0, memcmp(dstblob.cpu_data(), &data_expected.front(),
          sizeof(float)*dstblob.count()));
}

}  // namespace
}  // namespace caffe