text:
#pragma once

#include <Eigen/Dense>
#include <Eigen/Sparse>
#include <array>
#include <boost/assert.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/math/constants/constants.hpp>
#include <boost/multi_array.hpp>
#include <cmath>
#include <fstream>
#include <iostream>
#include <vector>

#include "base/array_buffer.hpp"
#include "base/exceptions.hpp"
#include "base/timer.hpp"
#include "filtered_range.hpp"
#ifndef NOHDF5
#include "base/eigen2hdf.hpp"
#endif
#include "quadrature/qhermitew.hpp"
#include "spectral/basis/toolbox/spectral_basis.hpp"
#include "spectral/laguerren_ks.hpp"
#include "spectral/eval_handlers.hpp"
#include "spectral/pl_radial_eval.hpp"

namespace boltzmann {
namespace detail {

/**
 * @brief sort *polar* elements by `k`
 */
struct CMP
{
  template <typename E>
  bool operator()(const E &e1, const E &e2) const
  {
    // typedef typename boost::mpl::at_c<typename E::types_t,0>::type fa_type;
    typedef typename boost::mpl::at_c<typename E::types_t, 1>::type fr_type;

    typename E::Acc::template get<fr_type> fr_accessor;
    // typename E::Acc::template get<fa_type> fa_accessor;

    const auto &idR1 = fr_accessor(e1).get_id();
    const auto &idR2 = fr_accessor(e2).get_id();

    return std::tie(idR1.k, idR1.j) < std::tie(idR2.k, idR2.j);
  }
};

}  // end namespace detail

template <typename PolarBasis, typename HermiteBasis>
class Polar2Hermite
{
 public:
  Polar2Hermite(const PolarBasis &polar_basis, const HermiteBasis &hermite_basis);
#ifndef NOHDF5
  void exportmat(const std::string &fname) const;
#endif

  void to_hermite(std::vector<double> &dst, const std::vector<double> &src) const;

  template <typename DERIVED1, typename DERIVED2>
  void to_hermite(Eigen::DenseBase<DERIVED1> &dst, const Eigen::DenseBase<DERIVED2> &src) const;

  template <typename DERIVED1, typename DERIVED2>
  void to_hermite_T(Eigen::DenseBase<DERIVED1> &dst, const Eigen::DenseBase<DERIVED2> &src) const;

  void to_polar(std::vector<double> &dst, const std::vector<double> &src) const;

  template <typename DERIVED1, typename DERIVED2>
  void to_polar(Eigen::DenseBase<DERIVED1> &dst, const Eigen::DenseBase<DERIVED2> &src) const;

  void to_polar(double *dst, const double *src) const;

  const Eigen::MatrixXd &get_mat(int k) const;

 private:
  /// Transformation matrices for each polynomial degree k
  std::vector<Eigen::MatrixXd> tmatrices_;
  std::vector<unsigned int> offsets_;
  /// Permutation matrix for polar degrees of freedom
  Eigen::SparseMatrix<double> P_;

  Eigen::VectorXd polar_mass_m_;
  thread_local static ::ArrayBuffer<> buf_;
};

template <typename PolarBasis, typename HermiteBasis>
thread_local ::ArrayBuffer<> Polar2Hermite<PolarBasis, HermiteBasis>::buf_;

template <typename PolarBasis, typename HermiteBasis>
Polar2Hermite<PolarBasis, HermiteBasis>::Polar2Hermite(const PolarBasis &polar_basis,
                                                       const HermiteBasis &hermite_basis)
{
  BOOST_VERIFY(polar_basis.n_dofs() == hermite_basis.n_dofs());
  int K = spectral::get_max_k(polar_basis);
  const unsigned int qpts1d = std::max(40, 2 * (K + 1));
  // initialize quadrature
  QHermiteW quad(1.0, qpts1d);

  // typedef std::array<double, 2> point_t;
  typedef boost::multi_array<double, 2> array2d;
  // typedef boost::multi_array<point_t, 2> array2dpts;
  array2d W(boost::extents[qpts1d][qpts1d]);
  // quad. nodes in cartesian coordinates
  array2d X(boost::extents[qpts1d][qpts1d]);
  array2d Y(boost::extents[qpts1d][qpts1d]);
  array2d R(boost::extents[qpts1d][qpts1d]);
  array2d PHI(boost::extents[qpts1d][qpts1d]);

  for (unsigned int i = 0; i < qpts1d; ++i) {
    const double x = quad.pts(i);
    for (unsigned int j = 0; j < qpts1d; ++j) {
      const double y = quad.pts(j);
      X[i][j] = x;
      Y[i][j] = y;
      W[i][j] = quad.wts(i) * quad.wts(j);
      PHI[i][j] = std::atan2(y, x);
      R[i][j] = std::sqrt(y * y + x * x);
    }
  }
  const unsigned int nq = qpts1d * qpts1d;

  //  ...
  PolarBasis basis_k(polar_basis);
  basis_k.sort(detail::CMP());

  tmatrices_.resize(K + 1);
  P_.resize(polar_basis.n_dofs(), polar_basis.n_dofs());

  // evaluate basis functions at quadrature points
  RDTSCTimer timer;
  timer.start();
  LaguerreNKS<double> L(K);
  unsigned int Rlen = R.shape()[0] * R.shape()[1];
  L.compute(R.data(), Rlen, 0.5);

  typedef typename PolarBasis::elem_t polar_elem_t;
  typedef typename boost::mpl::at_c<typename polar_elem_t::types_t, 1>::type radial_elem_t;
  typedef typename boost::mpl::at_c<typename polar_elem_t::types_t, 0>::type ang_elem_t;
  typename polar_elem_t::Acc::template get<radial_elem_t> get_rad;
  typename polar_elem_t::Acc::template get<ang_elem_t> get_ang;

  typedef typename HermiteBasis::elem_t herm_elem_t;
  typedef typename boost::mpl::at_c<typename herm_elem_t::types_t, 0>::type hx_t;
  typedef typename boost::mpl::at_c<typename herm_elem_t::types_t, 1>::type hy_t;

  typename herm_elem_t::Acc::template get<hx_t> get_hx;
  typename herm_elem_t::Acc::template get<hy_t> get_hy;

  // HermiteEvalHandler2d<HermiteNW<double>, herm_elem_t> heval(H);
  auto heval = hermite_evaluator2d<>::make(hermite_basis, quad.pts());
  PLRadialEval<LaguerreNKS<double>, polar_elem_t> leval(L);
  // permutation matrix entries
  std::vector<unsigned int> p_loc(polar_basis.n_dofs());
  // update offset vector
  unsigned int offset = 0;
  offsets_.resize(K + 2);
  // ----------------------------------------------------
  // loop over block-diagonal matrix and compute offsets
  // ----------------------------------------------------
  offsets_[0] = 0;
  for (int k = 0; k <= K; ++k) {
    std::function<bool(const polar_elem_t &)> pred = [&](const polar_elem_t &e) {
      return (get_rad(e).get_id().k == k);
    };
    auto range = filtered_range(basis_k.begin(), basis_k.end(), pred);

    // collect polar elements of polynomial degree k
    std::vector<polar_elem_t> polar_elems;
    for (auto it = std::get<0>(range); it != std::get<1>(range); ++it) {
      polar_elems.push_back(*it);
    }
    offset += polar_elems.size();
    offsets_[k + 1] = offset;
  }

  // --------------------------------------
  // Compute transformation matrix entries
  // --------------------------------------
  timer.start();
#pragma omp parallel for
  // (* load-balancing will be rather poor *)
  for (int k = 0; k <= K; ++k) {
    std::function<bool(const polar_elem_t &)> pred = [&](const polar_elem_t &e) {
      return (get_rad(e).get_id().k == k);
    };
    auto range = filtered_range(basis_k.begin(), basis_k.end(), pred);

    // collect polar elements of polynomial degree k
    std::vector<polar_elem_t> polar_elems;
    for (auto it = std::get<0>(range); it != std::get<1>(range); ++it) {
      polar_elems.push_back(*it);
    }

    // collect hermite elements of polynomial degree k
    std::vector<herm_elem_t> herm_elems;
    std::function<bool(const herm_elem_t &)> pred2 = [&](const herm_elem_t &e) {
      return (get_hx(e).get_id().k + get_hy(e).get_id().k == k);
    };
    auto range_herm = filtered_range(hermite_basis.begin(), hermite_basis.end(), pred2);
    for (auto it = std::get<0>(range_herm); it != std::get<1>(range_herm); ++it) {
      herm_elems.push_back(*it);
    }

    assert(herm_elems.size() == polar_elems.size());

    // init matrix
    auto &Mk = tmatrices_[k];
    unsigned int nk = herm_elems.size();
    Mk.resize(nk, nk);

    // quadrature nodes and weights
    const double *w = W.origin();
    // const double* x = X.origin();
    // const double* y = Y.origin();
    // const double* r = R.origin();
    const double *phi = PHI.origin();

    for (auto itp = polar_elems.begin(); itp != polar_elems.end(); ++itp) {
      // create permutation matrix
      unsigned int dofx = polar_basis.get_dof_index(itp->get_id());
      unsigned int dofy = basis_k.get_dof_index(itp->get_id());
      p_loc[dofy] = dofx;  // permutation
      //      const unsigned int j = get_rad(*itp).get_id().j;
      const unsigned int k = get_rad(*itp).get_id().k;

      for (auto ith = herm_elems.begin(); ith != herm_elems.end(); ++ith) {
        unsigned int dofy2 = hermite_basis.get_dof_index(ith->get_id());  // index
        // quadrature
        double val = 0;
        for (unsigned int q = 0; q < nq; ++q) {
          // const double rloc = r[q];
          val += (w[q] * leval(*itp, q) * get_ang(*itp).evaluate(phi[q]) *
                  heval(*ith, q / qpts1d, q % qpts1d));
        }
        Mk(dofy2 - offsets_[k], dofy - offsets_[k]) = val;
      }
    }
  }

  for (unsigned int dofy = 0; dofy < p_loc.size(); ++dofy) {
    P_.insert(dofy, p_loc[dofy]) = 1;
  }
  P_.makeCompressed();

  // prepare diagonal entries of mass matrix
  const double PI = boost::math::constants::pi<double>();
  // initialize polar mass m
  const unsigned int N = basis_k.n_dofs();
  polar_mass_m_ = Eigen::VectorXd(N);
  for (unsigned int i = 0; i < N; ++i) {
    const auto &elem = basis_k.get_elem(i);
    if (get_ang(elem).get_id().l == 0)
      polar_mass_m_[i] = PI;
    else
      polar_mass_m_[i] = PI / 2;
  }
}

// ---------------------------------------------------------------------
template <typename PolarBasis, typename HermiteBasis>
void
Polar2Hermite<PolarBasis, HermiteBasis>::to_hermite(std::vector<double> &dst,
                                                    const std::vector<double> &src) const
{
  assert(dst.size() == src.size());
  assert(src.size() == (unsigned int)P_.cols());

  typedef Eigen::Map<Eigen::VectorXd> vec_t;
  typedef Eigen::Map<const Eigen::VectorXd> cvec_t;

  cvec_t vsrc(src.data(), src.size());
  vec_t vdst(dst.data(), dst.size());

  this->to_hermite(vdst, vsrc);
}

// ----------------------------------------------------------------------
template <typename PolarBasis, typename HermiteBasis>
template <typename DERIVED1, typename DERIVED2>
void
Polar2Hermite<PolarBasis, HermiteBasis>::to_hermite(Eigen::DenseBase<DERIVED1> &dst,
                                                    const Eigen::DenseBase<DERIVED2> &src) const
{
  const int K = tmatrices_.size();
  const int N = offsets_[K];

  BOOST_ASSERT(dst.size() == N);
  BOOST_ASSERT(src.size() == N);
  auto vpsrc = buf_.get<Eigen::VectorXd>(N);

  // TODO, this is slow
  vpsrc = P_ * src.derived();

  for (int k = 0; k < tmatrices_.size(); ++k) {
    const unsigned int blocksize = offsets_[k + 1] - offsets_[k];
    dst.segment(offsets_[k], blocksize) = tmatrices_[k] * vpsrc.segment(offsets_[k], blocksize);
  }
}

template <typename PolarBasis, typename HermiteBasis>
template <typename DERIVED1, typename DERIVED2>
void
Polar2Hermite<PolarBasis, HermiteBasis>::to_hermite_T(Eigen::DenseBase<DERIVED1> &dst,
                                                      const Eigen::DenseBase<DERIVED2> &src) const
{
  assert(dst.size() == src.size());
  assert(src.size() == (unsigned int)P_.cols());
  typedef Eigen::Map<Eigen::VectorXd> vec_t;
  typedef Eigen::Map<const Eigen::VectorXd> cvec_t;

  const int K = tmatrices_.size();
  const int N = offsets_[K];

  auto vpsrc = buf_.get<Eigen::VectorXd>(N);

  for (int k = 0; k < tmatrices_.size(); ++k) {
    const unsigned int blocksize = offsets_[k + 1] - offsets_[k];
    vpsrc.segment(offsets_[k], blocksize) =
        tmatrices_[k].transpose() * src.segment(offsets_[k], blocksize);
  }

  dst = P_.transpose() * vpsrc;
}

template <typename PolarBasis, typename HermiteBasis>
void
Polar2Hermite<PolarBasis, HermiteBasis>::to_polar(std::vector<double> &dst,
                                                  const std::vector<double> &src) const
{
  assert(dst.size() == src.size());
  assert(src.size() == (unsigned int)P_.cols());
  typedef Eigen::Map<Eigen::VectorXd> vec_t;
  typedef Eigen::Map<const Eigen::VectorXd> cvec_t;
  vec_t vdst(dst.data(), dst.size());
  cvec_t vsrc(src.data(), src.size());

  this->to_polar(vdst, vsrc);
}

template <typename PolarBasis, typename HermiteBasis>
template <typename DERIVED1, typename DERIVED2>
void
Polar2Hermite<PolarBasis, HermiteBasis>::to_polar(Eigen::DenseBase<DERIVED1> &dst,
                                                  const Eigen::DenseBase<DERIVED2> &src) const
{
  const int K = tmatrices_.size();
  const int N = offsets_[K];

  BOOST_ASSERT(dst.size() == N);
  BOOST_ASSERT(src.size() == N);

  // TODO: use buffer memory instead
  auto vpsrc = buf_.get<Eigen::VectorXd>(N);
  for (int k = 0; k < tmatrices_.size(); ++k) {
    const unsigned int blocksize = offsets_[k + 1] - offsets_[k];
    vpsrc.segment(offsets_[k], blocksize) =
        tmatrices_[k].transpose() * src.segment(offsets_[k], blocksize);
  }
  vpsrc = vpsrc.array() / polar_mass_m_.array();

  dst = P_.transpose() * vpsrc;
}

template <typename PolarBasis, typename HermiteBasis>
const Eigen::MatrixXd &
Polar2Hermite<PolarBasis, HermiteBasis>::get_mat(int k) const
{
  BOOST_ASSERT(k < tmatrices_.size());
  return tmatrices_[k];
}

#ifndef NOHDF5
template <typename PolarBasis, typename HermiteBasis>
void
Polar2Hermite<PolarBasis, HermiteBasis>::exportmat(const std::string &fname) const
{
  hid_t h5f = H5Fcreate(fname.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);

  eigen2hdf::save_sparse(h5f, "P", P_);
  for (unsigned int k = 0; k < tmatrices_.size(); ++k) {
    eigen2hdf::save(h5f, std::to_string(k), tmatrices_[k]);
  }
  H5Fclose(h5f);
}
#endif

}  // end namespace boltzmann


text:
// Project: libv.ctrl, File: src/libv/ctrl/stated_sequence.hpp, Author: Császár Mátyás [Vader]

#pragma once

// ext
#include <boost/container/small_vector.hpp>
// pro
#include <libv/ctrl/duration.hpp>
#include <libv/ctrl/sequence.hpp>
#include <libv/ctrl/time_point.hpp>

// TODO P1: cleanup state_sequence file
namespace libv {
namespace ctrl {

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

struct StatedInput {
	InputID id;
	DigitalInputAction dia;
	bool active = false;
};

struct StatedCombination {
	boost::container::small_vector<StatedInput, 3> inputs;
	bool active = false;

public:
	Combination build_combination() const {
		Combination result;
		for (const StatedInput& input : inputs)
			result.add_input(Input{input.id, input.dia});
		return result;
	}
};

struct StatedSequence {
	boost::container::small_vector<StatedCombination, 2> combinations;
	size_t checkpoint = 0; // The index of the currently active combination
	bool active = false;

	StatedSequence(const Sequence& src_sequence) {
		for (const Combination& src_combination : src_sequence.combinations) {
			StatedCombination& combination = combinations.emplace_back();

			for (const Input& src_input : src_combination.inputs) {
				StatedInput& input = combination.inputs.emplace_back();
				input.id = src_input.id;
				input.dia = src_input.dia;
			}
		}
	}

	Sequence rebuild_sequence() const {
		Sequence result;
		for (const StatedCombination& combination : combinations)
			result.add_combination(combination.build_combination());
		return result;
	}

	StatedCombination& previous_combination() noexcept {
		assert(checkpoint != 0 && "No previous combination");
		return combinations[checkpoint == 0 ? 0 : checkpoint - 1];
	}

	StatedCombination& current_combination() noexcept {
		assert(checkpoint < combinations.size() && "No more current combination");
		return combinations[checkpoint];
	}

	const StatedCombination& current_combination() const noexcept {
		assert(checkpoint < combinations.size() && "No more current combination");
		return combinations[checkpoint];
	}

	[[nodiscard]] inline bool is_active() const noexcept {
		return active;
	}

	bool is_last_combination() const noexcept {
		return checkpoint + 1 == combinations.size();
	}

	bool is_sequence() const noexcept {
		return combinations.size() > 1;
	}

	bool in_progress() const noexcept {
		return checkpoint != 0;
	}
};

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

} //namespace ctrl
} //namespace libv

ext: hpp

max_stars_repo_name: cpplibv/libv

max_issues_repo_name: cpplibv/libv

max_forks_repo_name: cpplibv/libv


text:
/**********************************************************************
*  Copyright (c) 2008-2015, Alliance for Sustainable Energy.
*  All rights reserved.
*
*  This library is free software; you can redistribute it and/or
*  modify it under the terms of the GNU Lesser General Public
*  License as published by the Free Software Foundation; either
*  version 2.1 of the License, or (at your option) any later version.
*
*  This library is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*  Lesser General Public License for more details.
*
*  You should have received a copy of the GNU Lesser General Public
*  Likey = cense along with this library; if not, write to the Free Software
*  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**********************************************************************/

#include <gtest/gtest.h>
#include "RunManagerTestFixture.hpp"
#include <runmanager/Test/ToolBin.hxx>
#include <resources.hxx>

#include "../JobFactory.hpp"
#include "../ModelToRadJob.hpp"
#include "../RunManager.hpp"
#include "../Workflow.hpp"

#include "../../../model/Model.hpp"

#include "../../../utilities/core/Application.hpp"
#include "../../../utilities/idf/IdfFile.hpp"
#include "../../../utilities/idf/IdfObject.hpp"
#include "../../../utilities/data/EndUses.hpp"
#include "../../../utilities/data/Attribute.hpp"
#include "../../../utilities/sql/SqlFile.hpp"

#include <boost/filesystem/path.hpp>

#include <QDir>

using openstudio::Attribute;
using openstudio::IdfFile;
using openstudio::IdfObject;
using openstudio::IddObjectType;
using openstudio::SqlFile;

TEST_F(RunManagerTestFixture, ModelToRadJob)
{
  openstudio::Application::instance().application(false);
  openstudio::path outdir = openstudio::toPath(QDir::tempPath()) / openstudio::toPath("ModelToRadJobRunTest");
  boost::filesystem::create_directories(outdir);
  openstudio::path db = outdir / openstudio::toPath("ModelToRadJobRunDB");
  openstudio::runmanager::RunManager kit(db, true);

  openstudio::path indir = resourcesPath() / openstudio::toPath("radiance/test/");
  boost::filesystem::create_directories(indir);
  openstudio::path infile = indir / openstudio::toPath("ExampleModel.osm");
  openstudio::path weatherdir = resourcesPath() / openstudio::toPath("runmanager") / openstudio::toPath("USA_CO_Golden-NREL.724666_TMY3.epw");

  openstudio::model::Model exampleModel = openstudio::model::exampleModel();
  exampleModel.save(infile, true);

  openstudio::runmanager::Workflow workflow("modeltoradpreprocess->modeltoidf->expandobjects->energyplus->modeltorad");

  workflow.setInputFiles(infile, weatherdir);

  // Build list of tools
  openstudio::runmanager::Tools tools
    = openstudio::runmanager::ConfigOptions::makeTools(
          energyPlusExePath().parent_path(),
          openstudio::path(),
          openstudio::path(),
          openstudio::path(),
          openstudio::path());
  workflow.add(tools);

  openstudio::runmanager::Job job = workflow.create(outdir);

  kit.enqueue(job, true);

  kit.waitForFinished();

  openstudio::runmanager::FileInfo file;

  ASSERT_NO_THROW(file = job.treeOutputFiles().getLastByFilename("model.rad"));

}

ext: cpp


text:
// Copyright (c) 2018 The Unit-e developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <rpc/parameter_conversion.h>
#include <rpc/server.h>
#include <test/rpc_test_utils.h>

#include <boost/algorithm/string.hpp>
#include <boost/test/unit_test.hpp>

UniValue CallRPC(std::string args) {

  std::vector<std::string> vArgs;
  boost::split(vArgs, args, boost::is_any_of(" \t"));

  std::string strMethod = vArgs[0];
  vArgs.erase(vArgs.begin());

  JSONRPCRequest request;
  request.strMethod = strMethod;
  request.params = RPCConvertValues(strMethod, vArgs);
  request.fHelp = false;

  BOOST_CHECK(tableRPC[strMethod]);
  rpcfn_type method = tableRPC[strMethod]->actor;

  try {
    UniValue result = (*method)(request);
    return result;
  } catch (const UniValue &objError) {
    throw RPCErrorResult{
        static_cast<RPCErrorCode>(find_value(objError, "code").get_int()),
        find_value(objError, "message").get_str()};
  }
}

void AssertRPCError(std::string call, RPCErrorCode error, const std::string &message) {
  try {
    CallRPC(std::move(call));
    assert(false); // an exception should be thrown before this point.
  } catch (const RPCErrorResult &err) {
    if (!message.empty()) {
      BOOST_CHECK_EQUAL(err.message, message);
    }
    BOOST_CHECK_EQUAL(err.errorCode, error);
  }
}

max_stars_repo_name: frolosofsky/unit-e

max_issues_repo_name: frolosofsky/unit-e

max_forks_repo_name: frolosofsky/unit-e


text:
#include <iostream>
#include <Eigen/Core>
#include <Eigen/Dense>

#include "utils.hpp"

using namespace std;
using namespace Eigen;

int main(void)
{
    // Make skew symmetric matrix
    Vector3d v;
    v << 8, 5, 6;

    cout << "== The vector ==" << endl;
    cout << v << endl;

    Matrix3d v_hat;
    Vector::wedge<double>(v_hat,v);
    cout << "== The skew symmetric matrix ==" << endl;
    cout << v_hat << endl;

    // Example Vector
    Vector3d a;
    a << 2, 5, 7;

    cout << "== Example vector ==" << endl;
    cout << a << endl;

    // Make Cross
    cout << "== v_hat * a ==" << endl;
    cout << v_hat * a << endl;
    cout << "== v x a ==" << endl;
    cout << v.cross(a) << endl;
    cout << "== -v_hat * a ==" << endl;
    cout << -v_hat * a << endl;
    cout << "== a x v ==" << endl;
    cout << a.cross(v) << endl;

    return 0;
}


text:
/*
 * Copyright 2016 Klemens D. Morgenstern
 * Copyright 2016, 2017 Andrey Semashev
 *
 * Distributed under the Boost Software License, Version 1.0.
 * See http://www.boost.org/LICENSE_1_0.txt
 */

#ifndef BOOST_WINAPI_PIPES_HPP_INCLUDED_
#define BOOST_WINAPI_PIPES_HPP_INCLUDED_

#include <boost/winapi/basic_types.hpp>
#include <boost/winapi/config.hpp>
#include <boost/winapi/overlapped.hpp>

#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif

#if BOOST_WINAPI_PARTITION_DESKTOP_SYSTEM

#if !defined( BOOST_USE_WINDOWS_H ) && BOOST_WINAPI_PARTITION_DESKTOP && !defined( BOOST_NO_ANSI_APIS )
extern "C" {
BOOST_SYMBOL_IMPORT boost::winapi::HANDLE_ BOOST_WINAPI_WINAPI_CC CreateNamedPipeA(
    boost::winapi::LPCSTR_ lpName,
    boost::winapi::DWORD_ dwOpenMode,
    boost::winapi::DWORD_ dwPipeMode,
    boost::winapi::DWORD_ nMaxInstances,
    boost::winapi::DWORD_ nOutBufferSize,
    boost::winapi::DWORD_ nInBufferSize,
    boost::winapi::DWORD_ nDefaultTimeOut,
    _SECURITY_ATTRIBUTES *lpSecurityAttributes);
} // extern "C"
#endif // !defined( BOOST_USE_WINDOWS_H ) && BOOST_WINAPI_PARTITION_DESKTOP && !defined( BOOST_NO_ANSI_APIS )

#if !defined( BOOST_USE_WINDOWS_H )
extern "C" {

BOOST_SYMBOL_IMPORT boost::winapi::BOOL_ BOOST_WINAPI_WINAPI_CC ImpersonateNamedPipeClient(
    boost::winapi::HANDLE_ hNamedPipe);

BOOST_SYMBOL_IMPORT boost::winapi::BOOL_ BOOST_WINAPI_WINAPI_CC CreatePipe(
    boost::winapi::PHANDLE_ hReadPipe,
    boost::winapi::PHANDLE_ hWritePipe,
    _SECURITY_ATTRIBUTES* lpPipeAttributes,
    boost::winapi::DWORD_ nSize);

BOOST_SYMBOL_IMPORT boost::winapi::BOOL_ BOOST_WINAPI_WINAPI_CC ConnectNamedPipe(
    boost::winapi::HANDLE_ hNamedPipe,
    _OVERLAPPED* lpOverlapped);

BOOST_SYMBOL_IMPORT boost::winapi::BOOL_ BOOST_WINAPI_WINAPI_CC DisconnectNamedPipe(
    boost::winapi::HANDLE_ hNamedPipe);

BOOST_SYMBOL_IMPORT boost::winapi::BOOL_ BOOST_WINAPI_WINAPI_CC SetNamedPipeHandleState(
    boost::winapi::HANDLE_ hNamedPipe,
    boost::winapi::LPDWORD_ lpMode,
    boost::winapi::LPDWORD_ lpMaxCollectionCount,
    boost::winapi::LPDWORD_ lpCollectDataTimeout);

BOOST_SYMBOL_IMPORT boost::winapi::BOOL_ BOOST_WINAPI_WINAPI_CC PeekNamedPipe(
    boost::winapi::HANDLE_ hNamedPipe,
    boost::winapi::LPVOID_ lpBuffer,
    boost::winapi::DWORD_ nBufferSize,
    boost::winapi::LPDWORD_ lpBytesRead,
    boost::winapi::LPDWORD_ lpTotalBytesAvail,
    boost::winapi::LPDWORD_ lpBytesLeftThisMessage);

BOOST_SYMBOL_IMPORT boost::winapi::BOOL_ BOOST_WINAPI_WINAPI_CC TransactNamedPipe(
    boost::winapi::HANDLE_ hNamedPipe,
    boost::winapi::LPVOID_ lpInBuffer,
    boost::winapi::DWORD_ nInBufferSize,
    boost::winapi::LPVOID_ lpOutBuffer,
    boost::winapi::DWORD_ nOutBufferSize,
    boost::winapi::LPDWORD_ lpBytesRead,
    _OVERLAPPED* lpOverlapped);

#if !defined( BOOST_NO_ANSI_APIS )
BOOST_SYMBOL_IMPORT boost::winapi::BOOL_ BOOST_WINAPI_WINAPI_CC WaitNamedPipeA(
    boost::winapi::LPCSTR_ lpNamedPipeName,
    boost::winapi::DWORD_ nTimeOut);
#endif // !defined( BOOST_NO_ANSI_APIS )

BOOST_SYMBOL_IMPORT boost::winapi::HANDLE_ BOOST_WINAPI_WINAPI_CC CreateNamedPipeW(
    boost::winapi::LPCWSTR_ lpName,
    boost::winapi::DWORD_ dwOpenMode,
    boost::winapi::DWORD_ dwPipeMode,
    boost::winapi::DWORD_ nMaxInstances,
    boost::winapi::DWORD_ nOutBufferSize,
    boost::winapi::DWORD_ nInBufferSize,
    boost::winapi::DWORD_ nDefaultTimeOut,
    _SECURITY_ATTRIBUTES* lpSecurityAttributes);

BOOST_SYMBOL_IMPORT boost::winapi::BOOL_ BOOST_WINAPI_WINAPI_CC WaitNamedPipeW(
    boost::winapi::LPCWSTR_ lpNamedPipeName,
    boost::winapi::DWORD_ nTimeOut);

#if BOOST_USE_WINAPI_VERSION >= BOOST_WINAPI_VERSION_WIN6
#if !defined( BOOST_NO_ANSI_APIS )
BOOST_SYMBOL_IMPORT boost::winapi::BOOL_ BOOST_WINAPI_WINAPI_CC GetNamedPipeClientComputerNameA(
    boost::winapi::HANDLE_ Pipe,
    boost::winapi::LPSTR_ ClientComputerName,
    boost::winapi::ULONG_ ClientComputerNameLength);
#endif // !defined( BOOST_NO_ANSI_APIS )

BOOST_SYMBOL_IMPORT boost::winapi::BOOL_ BOOST_WINAPI_WINAPI_CC GetNamedPipeClientComputerNameW(
    boost::winapi::HANDLE_ Pipe,
    boost::winapi::LPWSTR_ ClientComputerName,
    boost::winapi::ULONG_ ClientComputerNameLength);
#endif

} // extern "C"
#endif // !defined( BOOST_USE_WINDOWS_H )

namespace boost {
namespace winapi {

#if defined( BOOST_USE_WINDOWS_H )

BOOST_CONSTEXPR_OR_CONST DWORD_ PIPE_ACCESS_DUPLEX_ = PIPE_ACCESS_DUPLEX;
BOOST_CONSTEXPR_OR_CONST DWORD_ PIPE_ACCESS_INBOUND_ = PIPE_ACCESS_INBOUND;
BOOST_CONSTEXPR_OR_CONST DWORD_ PIPE_ACCESS_OUTBOUND_ = PIPE_ACCESS_OUTBOUND;

BOOST_CONSTEXPR_OR_CONST DWORD_ PIPE_TYPE_BYTE_ = PIPE_TYPE_BYTE;
BOOST_CONSTEXPR_OR_CONST DWORD_ PIPE_TYPE_MESSAGE_ = PIPE_TYPE_MESSAGE;

BOOST_CONSTEXPR_OR_CONST DWORD_ PIPE_READMODE_BYTE_ = PIPE_READMODE_BYTE;
BOOST_CONSTEXPR_OR_CONST DWORD_ PIPE_READMODE_MESSAGE_ = PIPE_READMODE_MESSAGE;

BOOST_CONSTEXPR_OR_CONST DWORD_ PIPE_WAIT_ = PIPE_WAIT;
BOOST_CONSTEXPR_OR_CONST DWORD_ PIPE_NOWAIT_ = PIPE_NOWAIT;

BOOST_CONSTEXPR_OR_CONST DWORD_ PIPE_UNLIMITED_INSTANCES_ = PIPE_UNLIMITED_INSTANCES;

BOOST_CONSTEXPR_OR_CONST DWORD_ NMPWAIT_USE_DEFAULT_WAIT_ = NMPWAIT_USE_DEFAULT_WAIT;
BOOST_CONSTEXPR_OR_CONST DWORD_ NMPWAIT_NOWAIT_ = NMPWAIT_NOWAIT;
BOOST_CONSTEXPR_OR_CONST DWORD_ NMPWAIT_WAIT_FOREVER_ = NMPWAIT_WAIT_FOREVER;

#else // defined( BOOST_USE_WINDOWS_H )

BOOST_CONSTEXPR_OR_CONST DWORD_ PIPE_ACCESS_DUPLEX_ = 0x00000003;
BOOST_CONSTEXPR_OR_CONST DWORD_ PIPE_ACCESS_INBOUND_ = 0x00000001;
BOOST_CONSTEXPR_OR_CONST DWORD_ PIPE_ACCESS_OUTBOUND_ = 0x00000002;

BOOST_CONSTEXPR_OR_CONST DWORD_ PIPE_TYPE_BYTE_ = 0x00000000;
BOOST_CONSTEXPR_OR_CONST DWORD_ PIPE_TYPE_MESSAGE_ = 0x00000004;

BOOST_CONSTEXPR_OR_CONST DWORD_ PIPE_READMODE_BYTE_ = 0x00000000;
BOOST_CONSTEXPR_OR_CONST DWORD_ PIPE_READMODE_MESSAGE_ = 0x00000002;

BOOST_CONSTEXPR_OR_CONST DWORD_ PIPE_WAIT_ = 0x00000000;
BOOST_CONSTEXPR_OR_CONST DWORD_ PIPE_NOWAIT_ = 0x00000001;

BOOST_CONSTEXPR_OR_CONST DWORD_ PIPE_UNLIMITED_INSTANCES_ = 255u;

BOOST_CONSTEXPR_OR_CONST DWORD_ NMPWAIT_USE_DEFAULT_WAIT_ = 0x00000000;
BOOST_CONSTEXPR_OR_CONST DWORD_ NMPWAIT_NOWAIT_ = 0x00000001;
BOOST_CONSTEXPR_OR_CONST DWORD_ NMPWAIT_WAIT_FOREVER_ = 0xFFFFFFFF;

#endif // defined( BOOST_USE_WINDOWS_H )

// These constants are not defined in Windows SDK prior to 7.0A
BOOST_CONSTEXPR_OR_CONST DWORD_ PIPE_ACCEPT_REMOTE_CLIENTS_ = 0x00000000;
BOOST_CONSTEXPR_OR_CONST DWORD_ PIPE_REJECT_REMOTE_CLIENTS_ = 0x00000008;

using ::ImpersonateNamedPipeClient;
using ::DisconnectNamedPipe;
using ::SetNamedPipeHandleState;
using ::PeekNamedPipe;

#if !defined( BOOST_NO_ANSI_APIS )
using ::WaitNamedPipeA;
#endif
using ::WaitNamedPipeW;

#if BOOST_USE_WINAPI_VERSION >= BOOST_WINAPI_VERSION_WIN6
#if !defined( BOOST_NO_ANSI_APIS )
using ::GetNamedPipeClientComputerNameA;
#endif // !defined( BOOST_NO_ANSI_APIS )
using ::GetNamedPipeClientComputerNameW;
#endif // BOOST_USE_WINAPI_VERSION >= BOOST_WINAPI_VERSION_WIN6

BOOST_FORCEINLINE BOOL_ CreatePipe(PHANDLE_ hReadPipe, PHANDLE_ hWritePipe, LPSECURITY_ATTRIBUTES_ lpPipeAttributes, DWORD_ nSize)
{
    return ::CreatePipe(hReadPipe, hWritePipe, reinterpret_cast< ::_SECURITY_ATTRIBUTES* >(lpPipeAttributes), nSize);
}

BOOST_FORCEINLINE BOOL_ ConnectNamedPipe(HANDLE_ hNamedPipe, LPOVERLAPPED_ lpOverlapped)
{
    return ::ConnectNamedPipe(hNamedPipe, reinterpret_cast< ::_OVERLAPPED* >(lpOverlapped));
}

BOOST_FORCEINLINE BOOL_ TransactNamedPipe(HANDLE_ hNamedPipe, LPVOID_ lpInBuffer, DWORD_ nInBufferSize, LPVOID_ lpOutBuffer, DWORD_ nOutBufferSize, LPDWORD_ lpBytesRead, LPOVERLAPPED_ lpOverlapped)
{
    return ::TransactNamedPipe(hNamedPipe, lpInBuffer, nInBufferSize, lpOutBuffer, nOutBufferSize, lpBytesRead, reinterpret_cast< ::_OVERLAPPED* >(lpOverlapped));
}

#if BOOST_WINAPI_PARTITION_DESKTOP && !defined( BOOST_NO_ANSI_APIS )
BOOST_FORCEINLINE HANDLE_ CreateNamedPipeA(
    LPCSTR_ lpName,
    DWORD_ dwOpenMode,
    DWORD_ dwPipeMode,
    DWORD_ nMaxInstances,
    DWORD_ nOutBufferSize,
    DWORD_ nInBufferSize,
    DWORD_ nDefaultTimeOut,
    LPSECURITY_ATTRIBUTES_ lpSecurityAttributes)
{
    return ::CreateNamedPipeA(
        lpName,
        dwOpenMode,
        dwPipeMode,
        nMaxInstances,
        nOutBufferSize,
        nInBufferSize,
        nDefaultTimeOut,
        reinterpret_cast< ::_SECURITY_ATTRIBUTES* >(lpSecurityAttributes));
}

BOOST_FORCEINLINE HANDLE_ create_named_pipe(
    LPCSTR_ lpName,
    DWORD_ dwOpenMode,
    DWORD_ dwPipeMode,
    DWORD_ nMaxInstances,
    DWORD_ nOutBufferSize,
    DWORD_ nInBufferSize,
    DWORD_ nDefaultTimeOut,
    LPSECURITY_ATTRIBUTES_ lpSecurityAttributes)
{
    return ::CreateNamedPipeA(
        lpName,
        dwOpenMode,
        dwPipeMode,
        nMaxInstances,
        nOutBufferSize,
        nInBufferSize,
        nDefaultTimeOut,
        reinterpret_cast< ::_SECURITY_ATTRIBUTES* >(lpSecurityAttributes));
}
#endif // BOOST_WINAPI_PARTITION_DESKTOP && !defined( BOOST_NO_ANSI_APIS )

BOOST_FORCEINLINE HANDLE_ CreateNamedPipeW(
    LPCWSTR_ lpName,
    DWORD_ dwOpenMode,
    DWORD_ dwPipeMode,
    DWORD_ nMaxInstances,
    DWORD_ nOutBufferSize,
    DWORD_ nInBufferSize,
    DWORD_ nDefaultTimeOut,
    LPSECURITY_ATTRIBUTES_ lpSecurityAttributes)
{
    return ::CreateNamedPipeW(
        lpName,
        dwOpenMode,
        dwPipeMode,
        nMaxInstances,
        nOutBufferSize,
        nInBufferSize,
        nDefaultTimeOut,
        reinterpret_cast< ::_SECURITY_ATTRIBUTES* >(lpSecurityAttributes));
}

BOOST_FORCEINLINE HANDLE_ create_named_pipe(
    LPCWSTR_ lpName,
    DWORD_ dwOpenMode,
    DWORD_ dwPipeMode,
    DWORD_ nMaxInstances,
    DWORD_ nOutBufferSize,
    DWORD_ nInBufferSize,
    DWORD_ nDefaultTimeOut,
    LPSECURITY_ATTRIBUTES_ lpSecurityAttributes)
{
    return ::CreateNamedPipeW(
        lpName,
        dwOpenMode,
        dwPipeMode,
        nMaxInstances,
        nOutBufferSize,
        nInBufferSize,
        nDefaultTimeOut,
        reinterpret_cast< ::_SECURITY_ATTRIBUTES* >(lpSecurityAttributes));
}

#if !defined( BOOST_NO_ANSI_APIS )
BOOST_FORCEINLINE BOOL_ wait_named_pipe(LPCSTR_ lpNamedPipeName, DWORD_ nTimeOut)
{
    return ::WaitNamedPipeA(lpNamedPipeName, nTimeOut);
}
#endif //BOOST_NO_ANSI_APIS

BOOST_FORCEINLINE BOOL_ wait_named_pipe(LPCWSTR_ lpNamedPipeName, DWORD_ nTimeOut)
{
    return ::WaitNamedPipeW(lpNamedPipeName, nTimeOut);
}

#if BOOST_USE_WINAPI_VERSION >= BOOST_WINAPI_VERSION_WIN6

#if !defined( BOOST_NO_ANSI_APIS )
BOOST_FORCEINLINE BOOL_ get_named_pipe_client_computer_name(HANDLE_ Pipe, LPSTR_ ClientComputerName, ULONG_ ClientComputerNameLength)
{
    return ::GetNamedPipeClientComputerNameA(Pipe, ClientComputerName, ClientComputerNameLength);
}
#endif // !defined( BOOST_NO_ANSI_APIS )

BOOST_FORCEINLINE BOOL_ get_named_pipe_client_computer_name(HANDLE_ Pipe, LPWSTR_ ClientComputerName, ULONG_ ClientComputerNameLength)
{
    return ::GetNamedPipeClientComputerNameW(Pipe, ClientComputerName, ClientComputerNameLength);
}

#endif // BOOST_USE_WINAPI_VERSION >= BOOST_WINAPI_VERSION_WIN6

}
}

#endif // BOOST_WINAPI_PARTITION_DESKTOP_SYSTEM

#endif // BOOST_WINAPI_PIPES_HPP_INCLUDED_

max_stars_repo_name: cpp-pm/boost

max_issues_repo_name: cpp-pm/boost

max_forks_repo_name: cpp-pm/boost


text:
/*
 * Copyright (c) 2014, Stanislav Vorobiov
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "WeaponChainsawComponent.h"
#include "SceneObject.h"
#include "SceneObjectFactory.h"
#include "Scene.h"
#include "Const.h"
#include "Renderer.h"
#include "Utils.h"
#include <boost/make_shared.hpp>

namespace af
{
    static const float chainsawRadius = 0.6f;

    WeaponChainsawComponent::WeaponChainsawComponent(SceneObjectType objectType)
    : WeaponComponent(objectType, WeaponTypeChainsaw),
      damage_(0.0f),
      snd_(audio.createSound("chainsaw.ogg")),
      t_(0.0f)
    {
        snd_->setLoop(true);
    }

    WeaponChainsawComponent::~WeaponChainsawComponent()
    {
    }

    void WeaponChainsawComponent::accept(ComponentVisitor& visitor)
    {
        visitor.visitPhasedComponent(shared_from_this());
    }

    void WeaponChainsawComponent::update(float dt)
    {
        t_ -= dt;

        if (!triggerHeld()) {
            snd_->stop();
            return;
        }

        b2Vec2 p = b2Mul(parent()->getTransform(), pos());

        scene()->stats()->incTimeFired(this, 0.1f);

        bool hit = false;

        b2AABB aabb;

        aabb.lowerBound = p - b2Vec2(chainsawRadius, chainsawRadius);
        aabb.upperBound = p + b2Vec2(chainsawRadius, chainsawRadius);

        scene()->queryAABB(aabb, boost::bind(&WeaponChainsawComponent::queryAABBCb,
            this, _1, boost::cref(p), dt, boost::ref(hit)));

        if (t_ <= 0.0f) {
            t_ = 0.1f;
        }

        if (haveSound() && (snd_->status() != AudioSource::Playing)) {
            snd_->play();
        }
    }

    void WeaponChainsawComponent::debugDraw()
    {
        static const int32 circleSegments = 10;
        static const float32 circleIncrement = 2.0f * b2_pi / circleSegments;

        if (!triggerHeld()) {
            return;
        }

        b2Vec2 center = b2Mul(parent()->getTransform(), pos());

        float32 theta = 0.0f;
        b2Vec2 p0;

        renderer.setProgramColorLines(1.0f);

        RenderLineStrip rop = renderer.renderLineStrip();

        for (int32 i = 0; i < circleSegments; ++i) {
            b2Vec2 v = center + chainsawRadius * b2Vec2(cosf(theta), sinf(theta));

            rop.addVertex(v.x, v.y);

            if (i == 0) {
                p0 = v;
            }

            theta += circleIncrement;
        }

        rop.addVertex(p0.x, p0.y);

        rop.addColors(Color(1.0f, 0.0f, 0.0f));
    }

    void WeaponChainsawComponent::reload()
    {
    }

    void WeaponChainsawComponent::onRegister()
    {
    }

    void WeaponChainsawComponent::onUnregister()
    {
        snd_->stop();
    }

    bool WeaponChainsawComponent::queryAABBCb(b2Fixture* fixture, const b2Vec2& p, float dt, bool& hit)
    {
        SceneObject* obj = SceneObject::fromFixture(fixture);

        if (fixture->IsSensor() || (obj == parent())) {
            return true;
        }

        if (objectType() == SceneObjectTypeEnemyMissile) {
            static SceneObjectTypes hitTypes = SceneObjectTypes(SceneObjectTypePlayer) | SceneObjectTypeAlly | SceneObjectTypeGizmo;
            if (!hitTypes[obj->type()]) {
                return true;
            }
        } else if (objectType() == SceneObjectTypeNeutralMissile) {
            static SceneObjectTypes hitTypes = SceneObjectTypes(SceneObjectTypePlayer) | SceneObjectTypeAlly |
                SceneObjectTypeEnemy | SceneObjectTypeEnemyBuilding | SceneObjectTypeGizmo;
            if (!hitTypes[obj->type()]) {
                return true;
            }
        } else {
            static SceneObjectTypes hitTypes = SceneObjectTypes(SceneObjectTypeEnemy) | SceneObjectTypeEnemyBuilding | SceneObjectTypeGizmo;
            if (!hitTypes[obj->type()]) {
                return true;
            }
        }

        b2Rot rot(2.0f * b2_pi / 5);
        b2Vec2 dir(chainsawRadius, 0.0f);

        bool found = false;

        for (int i = 0; i < 5; ++i) {
            if (fixture->TestPoint(p + dir)) {
                found = true;
                break;
            }

            dir = b2Mul(rot, dir);
        }

        if (!found) {
            return true;
        }

        obj->changeLife(-damage_ * dt);

        if (!hit) {
            hit = scene()->stats()->incTimeHit(this, obj, 0.1f);
        }

        if (t_ <= 0.0f) {
            b2Vec2 offset = angle2vec(getRandom(0.0f, 2.0f * b2_pi), getRandom(0.0f, chainsawRadius));

            scene()->addObject(sceneObjectFactory.createMissileHit1(obj->shared_from_this(), p + offset));
        }

        return true;
    }
}

max_stars_repo_name: Sheph/TriggerTime

max_issues_repo_name: Sheph/TriggerTime

max_forks_repo_name: Sheph/TriggerTime


text:
// Copyright 2002 Rensselaer Polytechnic Institute

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

//  Authors: Lauren Foutz
//           Scott Hill
#include <boost/graph/floyd_warshall_shortest.hpp>
#include <map>
#include <algorithm>
#include <iostream>
#include <boost/random/linear_congruential.hpp>
#include <boost/graph/graph_utility.hpp>
#include <boost/graph/properties.hpp>
#include <boost/graph/bellman_ford_shortest_paths.hpp>
#include <boost/graph/random.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/adjacency_matrix.hpp>
#include <boost/core/lightweight_test.hpp>
#include <algorithm>
using namespace boost;

template < typename T > inline const T& my_min(const T& x, const T& y)
{
    return x < y ? x : y;
}

template < typename Graph > bool acceptance_test(Graph& g, int vec, int e)
{
    boost::minstd_rand ran(vec);

    {
        typename boost::property_map< Graph, boost::vertex_name_t >::type index
            = boost::get(boost::vertex_name, g);
        typename boost::graph_traits< Graph >::vertex_iterator firstv, lastv,
            firstv2, lastv2;
        int x = 0;
        for (boost::tie(firstv, lastv) = boost::vertices(g); firstv != lastv;
             firstv++)
        {
            boost::put(index, *firstv, x);
            x++;
        }

        for (int i = 0; i < e; i++)
        {
            boost::add_edge(index[ran() % vec], index[ran() % vec], g);
        }

        typename boost::graph_traits< Graph >::edge_iterator first, last;
        typename boost::property_map< Graph, boost::edge_weight_t >::type
            local_edge_map
            = boost::get(boost::edge_weight, g);
        for (boost::tie(first, last) = boost::edges(g); first != last; first++)
        {
            if (ran() % vec != 0)
            {
                boost::put(local_edge_map, *first, ran() % 100);
            }
            else
            {
                boost::put(local_edge_map, *first, 0 - (ran() % 100));
            }
        }

        int int_inf = std::numeric_limits< int >::max
        BOOST_PREVENT_MACRO_SUBSTITUTION();
        typedef
            typename boost::graph_traits< Graph >::vertex_descriptor vertex_des;
        std::map< vertex_des, int > matrixRow;
        std::map< vertex_des, std::map< vertex_des, int > > matrix;
        typedef typename boost::property_map< Graph,
            boost::vertex_distance_t >::type distance_type;
        distance_type distance_row = boost::get(boost::vertex_distance, g);
        for (boost::tie(firstv, lastv) = boost::vertices(g); firstv != lastv;
             firstv++)
        {
            boost::put(distance_row, *firstv, int_inf);
            matrixRow[*firstv] = int_inf;
        }
        for (boost::tie(firstv, lastv) = boost::vertices(g); firstv != lastv;
             firstv++)
        {
            matrix[*firstv] = matrixRow;
        }
        for (boost::tie(firstv, lastv) = boost::vertices(g); firstv != lastv;
             firstv++)
        {
            matrix[*firstv][*firstv] = 0;
        }
        std::map< vertex_des, std::map< vertex_des, int > > matrix3(matrix);
        std::map< vertex_des, std::map< vertex_des, int > > matrix4(matrix);
        for (boost::tie(first, last) = boost::edges(g); first != last; first++)
        {
            if (matrix[boost::source(*first, g)][boost::target(*first, g)]
                != int_inf)
            {
                matrix[boost::source(*first, g)][boost::target(*first, g)]
                    = my_min(boost::get(local_edge_map, *first),
                        matrix[boost::source(*first, g)]
                              [boost::target(*first, g)]);
            }
            else
            {
                matrix[boost::source(*first, g)][boost::target(*first, g)]
                    = boost::get(local_edge_map, *first);
            }
        }
        bool is_undirected = boost::is_same<
            typename boost::graph_traits< Graph >::directed_category,
            boost::undirected_tag >::value;
        if (is_undirected)
        {
            for (boost::tie(first, last) = boost::edges(g); first != last;
                 first++)
            {
                if (matrix[boost::target(*first, g)][boost::source(*first, g)]
                    != int_inf)
                {
                    matrix[boost::target(*first, g)][boost::source(*first, g)]
                        = my_min(boost::get(local_edge_map, *first),
                            matrix[boost::target(*first, g)]
                                  [boost::source(*first, g)]);
                }
                else
                {
                    matrix[boost::target(*first, g)][boost::source(*first, g)]
                        = boost::get(local_edge_map, *first);
                }
            }
        }

        bool bellman, floyd1, floyd2, floyd3;
        floyd1 = boost::floyd_warshall_initialized_all_pairs_shortest_paths(g,
            matrix,
            weight_map(boost::get(boost::edge_weight, g))
                .distance_inf(int_inf)
                .distance_zero(0));

        floyd2 = boost::floyd_warshall_all_pairs_shortest_paths(g, matrix3,
            weight_map(local_edge_map).distance_inf(int_inf).distance_zero(0));

        floyd3 = boost::floyd_warshall_all_pairs_shortest_paths(g, matrix4);

        boost::dummy_property_map dummy_map;
        std::map< vertex_des, std::map< vertex_des, int > > matrix2;
        for (boost::tie(firstv, lastv) = vertices(g); firstv != lastv; firstv++)
        {
            boost::put(distance_row, *firstv, 0);
            bellman = boost::bellman_ford_shortest_paths(g, vec,
                weight_map(boost::get(boost::edge_weight, g))
                    .distance_map(boost::get(boost::vertex_distance, g))
                    .predecessor_map(dummy_map));
            distance_row = boost::get(boost::vertex_distance, g);
            for (boost::tie(firstv2, lastv2) = vertices(g); firstv2 != lastv2;
                 firstv2++)
            {
                matrix2[*firstv][*firstv2] = boost::get(distance_row, *firstv2);
                boost::put(distance_row, *firstv2, int_inf);
            }
            if (bellman == false)
            {
                break;
            }
        }

        if (bellman != floyd1 || bellman != floyd2 || bellman != floyd3)
        {
            std::cout << "A negative cycle was detected in one algorithm but "
                         "not the others. "
                      << std::endl;
            return false;
        }
        else if (bellman == false && floyd1 == false && floyd2 == false
            && floyd3 == false)
        {
            return true;
        }
        else
        {
            typename boost::graph_traits< Graph >::vertex_iterator first1,
                first2, last1, last2;
            for (boost::tie(first1, last1) = boost::vertices(g);
                 first1 != last1; first1++)
            {
                for (boost::tie(first2, last2) = boost::vertices(g);
                     first2 != last2; first2++)
                {
                    if (matrix2[*first1][*first2] != matrix[*first1][*first2])
                    {
                        std::cout
                            << "Algorithms do not match at matrix point "
                            << index[*first1] << " " << index[*first2]
                            << " Bellman results: " << matrix2[*first1][*first2]
                            << " floyd 1 results " << matrix[*first1][*first2]
                            << std::endl;
                        return false;
                    }
                    if (matrix2[*first1][*first2] != matrix3[*first1][*first2])
                    {
                        std::cout
                            << "Algorithms do not match at matrix point "
                            << index[*first1] << " " << index[*first2]
                            << " Bellman results: " << matrix2[*first1][*first2]
                            << " floyd 2 results " << matrix3[*first1][*first2]
                            << std::endl;
                        return false;
                    }
                    if (matrix2[*first1][*first2] != matrix4[*first1][*first2])
                    {
                        std::cout
                            << "Algorithms do not match at matrix point "
                            << index[*first1] << " " << index[*first2]
                            << " Bellman results: " << matrix2[*first1][*first2]
                            << " floyd 3 results " << matrix4[*first1][*first2]
                            << std::endl;
                        return false;
                    }
                }
            }
        }
    }
    return true;
}

template < typename Graph > bool acceptance_test2(Graph& g, int vec, int e)
{
    boost::minstd_rand ran(vec);

    {

        typename boost::property_map< Graph, boost::vertex_name_t >::type index
            = boost::get(boost::vertex_name, g);
        typename boost::graph_traits< Graph >::vertex_iterator firstv, lastv,
            firstv2, lastv2;
        int x = 0;
        for (boost::tie(firstv, lastv) = boost::vertices(g); firstv != lastv;
             firstv++)
        {
            boost::put(index, *firstv, x);
            x++;
        }

        boost::generate_random_graph(g, vec, e, ran, true);

        typename boost::graph_traits< Graph >::edge_iterator first, last;
        typename boost::property_map< Graph, boost::edge_weight_t >::type
            local_edge_map
            = boost::get(boost::edge_weight, g);
        for (boost::tie(first, last) = boost::edges(g); first != last; first++)
        {
            if (ran() % vec != 0)
            {
                boost::put(local_edge_map, *first, ran() % 100);
            }
            else
            {
                boost::put(local_edge_map, *first, 0 - (ran() % 100));
            }
        }

        int int_inf = std::numeric_limits< int >::max
        BOOST_PREVENT_MACRO_SUBSTITUTION();
        typedef
            typename boost::graph_traits< Graph >::vertex_descriptor vertex_des;
        std::map< vertex_des, int > matrixRow;
        std::map< vertex_des, std::map< vertex_des, int > > matrix;
        typedef typename boost::property_map< Graph,
            boost::vertex_distance_t >::type distance_type;
        distance_type distance_row = boost::get(boost::vertex_distance, g);
        for (boost::tie(firstv, lastv) = boost::vertices(g); firstv != lastv;
             firstv++)
        {
            boost::put(distance_row, *firstv, int_inf);
            matrixRow[*firstv] = int_inf;
        }
        for (boost::tie(firstv, lastv) = boost::vertices(g); firstv != lastv;
             firstv++)
        {
            matrix[*firstv] = matrixRow;
        }
        for (boost::tie(firstv, lastv) = boost::vertices(g); firstv != lastv;
             firstv++)
        {
            matrix[*firstv][*firstv] = 0;
        }
        std::map< vertex_des, std::map< vertex_des, int > > matrix3(matrix);
        std::map< vertex_des, std::map< vertex_des, int > > matrix4(matrix);
        for (boost::tie(first, last) = boost::edges(g); first != last; first++)
        {
            if (matrix[boost::source(*first, g)][boost::target(*first, g)]
                != int_inf)
            {
                matrix[boost::source(*first, g)][boost::target(*first, g)]
                    = my_min(boost::get(local_edge_map, *first),
                        matrix[boost::source(*first, g)]
                              [boost::target(*first, g)]);
            }
            else
            {
                matrix[boost::source(*first, g)][boost::target(*first, g)]
                    = boost::get(local_edge_map, *first);
            }
        }
        bool is_undirected = boost::is_same<
            typename boost::graph_traits< Graph >::directed_category,
            boost::undirected_tag >::value;
        if (is_undirected)
        {
            for (boost::tie(first, last) = boost::edges(g); first != last;
                 first++)
            {
                if (matrix[boost::target(*first, g)][boost::source(*first, g)]
                    != int_inf)
                {
                    matrix[boost::target(*first, g)][boost::source(*first, g)]
                        = my_min(boost::get(local_edge_map, *first),
                            matrix[boost::target(*first, g)]
                                  [boost::source(*first, g)]);
                }
                else
                {
                    matrix[boost::target(*first, g)][boost::source(*first, g)]
                        = boost::get(local_edge_map, *first);
                }
            }
        }

        bool bellman, floyd1, floyd2, floyd3;
        floyd1 = boost::floyd_warshall_initialized_all_pairs_shortest_paths(g,
            matrix,
            weight_map(boost::get(boost::edge_weight, g))
                .distance_inf(int_inf)
                .distance_zero(0));

        floyd2 = boost::floyd_warshall_all_pairs_shortest_paths(g, matrix3,
            weight_map(local_edge_map).distance_inf(int_inf).distance_zero(0));

        floyd3 = boost::floyd_warshall_all_pairs_shortest_paths(g, matrix4);

        boost::dummy_property_map dummy_map;
        std::map< vertex_des, std::map< vertex_des, int > > matrix2;
        for (boost::tie(firstv, lastv) = vertices(g); firstv != lastv; firstv++)
        {
            boost::put(distance_row, *firstv, 0);
            bellman = boost::bellman_ford_shortest_paths(g, vec,
                weight_map(boost::get(boost::edge_weight, g))
                    .distance_map(boost::get(boost::vertex_distance, g))
                    .predecessor_map(dummy_map));
            distance_row = boost::get(boost::vertex_distance, g);
            for (boost::tie(firstv2, lastv2) = vertices(g); firstv2 != lastv2;
                 firstv2++)
            {
                matrix2[*firstv][*firstv2] = boost::get(distance_row, *firstv2);
                boost::put(distance_row, *firstv2, int_inf);
            }
            if (bellman == false)
            {
                break;
            }
        }

        if (bellman != floyd1 || bellman != floyd2 || bellman != floyd3)
        {
            std::cout << "A negative cycle was detected in one algorithm but "
                         "not the others. "
                      << std::endl;
            return false;
        }
        else if (bellman == false && floyd1 == false && floyd2 == false
            && floyd3 == false)
        {
            return true;
        }
        else
        {
            typename boost::graph_traits< Graph >::vertex_iterator first1,
                first2, last1, last2;
            for (boost::tie(first1, last1) = boost::vertices(g);
                 first1 != last1; first1++)
            {
                for (boost::tie(first2, last2) = boost::vertices(g);
                     first2 != last2; first2++)
                {
                    if (matrix2[*first1][*first2] != matrix[*first1][*first2])
                    {
                        std::cout
                            << "Algorithms do not match at matrix point "
                            << index[*first1] << " " << index[*first2]
                            << " Bellman results: " << matrix2[*first1][*first2]
                            << " floyd 1 results " << matrix[*first1][*first2]
                            << std::endl;
                        return false;
                    }
                    if (matrix2[*first1][*first2] != matrix3[*first1][*first2])
                    {
                        std::cout
                            << "Algorithms do not match at matrix point "
                            << index[*first1] << " " << index[*first2]
                            << " Bellman results: " << matrix2[*first1][*first2]
                            << " floyd 2 results " << matrix3[*first1][*first2]
                            << std::endl;
                        return false;
                    }
                    if (matrix2[*first1][*first2] != matrix4[*first1][*first2])
                    {
                        std::cout
                            << "Algorithms do not match at matrix point "
                            << index[*first1] << " " << index[*first2]
                            << " Bellman results: " << matrix2[*first1][*first2]
                            << " floyd 3 results " << matrix4[*first1][*first2]
                            << std::endl;
                        return false;
                    }
                }
            }
        }
    }
    return true;
}

int main(int, char*[])
{
    typedef boost::adjacency_list< boost::listS, boost::listS, boost::directedS,
        boost::property< boost::vertex_distance_t, int,
            boost::property< boost::vertex_name_t, int > >,
        boost::property< boost::edge_weight_t, int > >
        Digraph;
    Digraph adjlist_digraph;
    BOOST_TEST(acceptance_test2(adjlist_digraph, 100, 2000));

    typedef boost::adjacency_matrix< boost::undirectedS,
        boost::property< boost::vertex_distance_t, int,
            boost::property< boost::vertex_name_t, int > >,
        boost::property< boost::edge_weight_t, int > >
        Graph;
    Graph matrix_graph(100);
    BOOST_TEST(acceptance_test(matrix_graph, 100, 2000));

    return boost::report_errors();
}

max_issues_repo_name: qingkouwei/mediaones

max_forks_repo_name: qingkouwei/mediaones


text:
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//

#include "stdafx.h"
#include "CNTKLibraryInternals.h"

#include <cassert>
#include <cstdint>
#include <cstring>
#include <ctime>
#include <iomanip>
#include <sstream>

#pragma warning(push)
#pragma warning(disable : 4244 4245)
#include <boost/crc.hpp>
#pragma warning(pop)

#pragma warning(push)
#pragma warning(disable : 4800 4267 4610 4512 4100 4510)
#include "tensorboard/tensorboard.pb.h"
#pragma warning(pop)

#include "BackCompat.h"
#include "fileutil.h"
#include "hostname.h"
#include "tensorboard/TensorBoardUtils.h"
#include "Utils.h"

namespace CNTK
{
    namespace Internal
    {
        template<typename T>
        static void Encode(char* buf, T value)
        {
            // Assume little-endian target encoding.
            memcpy(buf, &value, sizeof(value));
        }

        static uint32_t GetMaskedCrc(const char* data, size_t n)
        {
            // Compute CRC32C.
            boost::crc_optimal<32, 0x1EDC6F41, 0xFFFFFFFF, 0xFFFFFFFF, true, true> crc;
            crc.process_bytes(reinterpret_cast<const void*>(data), n);
            uint32_t value = crc();

            // Rotate right by 15 bits and add a constant.
            return ((value >> 15) | (value << 17)) + 0xa282ead8ul;
        }

        static std::wstring GetNewFilePath(const std::wstring& dir, time_t time)
        {
            std::wostringstream filename;
            if (!dir.empty())
            {
                // Windows can tolerate forward slashes in paths.
                filename << dir << L"/";
            }

            filename << L"events.out.tfevents."
                << std::setfill(L'0') << std::setw(10) << time
                << L"." << ToWString(GetHostName());
            return filename.str();
        }

        static std::string Serialize(const tensorflow::Event& event)
        {
            std::string record;
            event.AppendToString(&record);
            // Rely on RVO to make returning a string cheap.
            return record;
        }

        TensorBoardFileWriter::TensorBoardFileWriter(const std::wstring& dir, const FunctionPtr& modelToVisualize)
            : m_model(modelToVisualize),
            m_dir(dir),
            m_file(NULL),
            m_fileName()
        {
        }

        TensorBoardFileWriter::TensorBoardFileWriter(const std::wstring& dir,
                                                     const ::Microsoft::MSR::CNTK::ComputationNetworkPtr& modelToVisualize)
            : TensorBoardFileWriter(dir, ConvertFromLegacyModel(modelToVisualize))
        {
        }

        void TensorBoardFileWriter::Init()
        {
            time_t time = std::time(0);
            std::wstring filePath = GetNewFilePath(m_dir, time);

            msra::files::make_intermediate_dirs(filePath);

            m_file = fopenOrDie(ToString(filePath), "wb");
            m_fileName = filePath;

            // Write the first record with the current version, and flush
            // right away so the file contents will be easily determined.
            WriteVersion(time);

            if (m_model)
            {
                WriteModel();
            }

            Flush();
        }

        void TensorBoardFileWriter::WriteValue(const std::wstring& name, float value, uint64_t step)
        {
            tensorflow::Event event;
            event.set_step(step);
            event.set_wall_time(static_cast<double>(std::time(0)));

            tensorflow::Summary* summary = event.mutable_summary();
            tensorflow::Summary::Value* summaryValue = summary->add_value();
            summaryValue->set_tag(ToString(name));
            summaryValue->set_simple_value(value);

            WriteRecord(Serialize(event));
        }

        void TensorBoardFileWriter::WriteModel()
        {
            assert(m_model != nullptr);

            // Convert the model to tensorflow GraphDef first.
            tensorflow::GraphDef graph;
            CreateTensorBoardGraph(m_model->RootFunction(), graph);

            std::string graphStr;
            graph.AppendToString(&graphStr);

            // Wrap it as an event.
            tensorflow::Event event;
            event.set_wall_time(static_cast<double>(std::time(0)));
            event.set_graph_def(graphStr);

            WriteRecord(Serialize(event));
        }

        void TensorBoardFileWriter::WriteRecord(const std::string& data)
        {
            if (m_file == NULL)
            {
                Init();
            }

            // Header: record length (uint64_t) + masked CRC of that (uint32_t).
            char header[sizeof(uint64_t) + sizeof(uint32_t)];
            Encode(header, static_cast<uint64_t>(data.size()));
            Encode(header + sizeof(uint64_t), GetMaskedCrc(header, sizeof(uint64_t)));

            // Footer: marked CRC of the actual record.
            char footer[sizeof(uint32_t)];
            Encode(footer, GetMaskedCrc(data.data(), data.size()));

            try
            {
                // Record = Header + Data + Footer.
                fwriteOrDie(header, sizeof(header[0]), sizeof(header), m_file);
                fwriteOrDie(data.data(), sizeof(data[0]), data.size(), m_file);
                fwriteOrDie(footer, sizeof(footer[0]), sizeof(footer), m_file);
            }
            catch (const std::runtime_error&)
            {
                // Close the existing file.
                // If the exception was caught upstream, a new file will be created on subsequent writes.
                fprintf(stderr,
                    "TensorBoardFileWriter: Unable to write to the currently open file. "
                    "Subsequent writes will attempt to re-open a new one. (%ls)", m_fileName.c_str());
                Close();
                throw;
            }
        }

#ifndef CNTK_UWP

        void TensorBoardFileWriter::WriteImage(const std::wstring& name, NDArrayViewPtr imageData, uint64_t step)
        {
            assert(imageData != nullptr);
            tensorflow::Event event;
            event.set_wall_time(static_cast<double>(std::time(0)));
            tensorflow::Summary* summary = event.mutable_summary();

            std::vector<size_t> dimensions = imageData->Shape().Dimensions();
            const size_t batch_size = dimensions.at(3);
            const size_t depth = dimensions.at(2);
            const size_t width = dimensions.at(1);
            const size_t height = dimensions.at(0);
            const DataType dtype = imageData->GetDataType();

            std::vector<size_t> start(4, 0);
            std::vector<size_t> extent;
            extent.push_back(height);
            extent.push_back(width);
            extent.push_back(depth);
            extent.push_back(1);

            const std::vector<size_t> imageDim({height, width, depth});

            for (size_t i = 0; i < batch_size; i++) {
                tensorflow::Summary::Value* summaryValue = summary->add_value();
                summaryValue->set_tag(ToString(name) + "/image/" + std::to_string(i));

                tensorflow::Summary::Image* summaryImage = summaryValue->mutable_image();
                summaryImage->set_height(height);
                summaryImage->set_width(width);
                summaryImage->set_colorspace(depth);
                start.back() = static_cast<size_t>(i);
                auto image = imageData->SliceView(start, extent)->AsShape(imageDim);
                vector<unsigned char> buffer;

                switch (dtype)
                {
                case DataType::Float:
                    WriteImageToBuffer(image->WritableDataBuffer<float>(), dtype, height, width, depth, buffer);
                    break;

                case DataType::Double:
                    WriteImageToBuffer(image->WritableDataBuffer<double>(), dtype, height, width, depth, buffer);
                    break;

                default:
                    fprintf(stderr, "TensorBoardFileWriter: Unsupported data type: %d ", static_cast<int>(dtype));
                    break;
                }

                string str(buffer.begin(), buffer.end());
                summaryImage->set_encoded_image_string(str);
            }

            WriteRecord(Serialize(event));
        }

#endif // !CNTK_UWP

        void TensorBoardFileWriter::WriteVersion(time_t time)
        {
            // Version string present in the first entry of every event file.
            tensorflow::Event event;
            event.set_wall_time(static_cast<double>(time));
            event.set_file_version("brain.Event:2");

            WriteRecord(Serialize(event));
        }

        bool TensorBoardFileWriter::Flush()
        {
            if (m_file == NULL)
            {
                return false;
            }

            if (fflush(m_file))
            {
                fprintf(stderr, "TensorBoardFileWriter: Error flushing the event file (%ls).", m_fileName.c_str());
                return false;
            }

            return true;
        }

        bool TensorBoardFileWriter::Close()
        {
            if (m_file == NULL)
            {
                return false;
            }

            bool success = Flush();
            if (fclose(m_file))
            {
                fprintf(stderr,
                        "TensorBoardFileWriter: Error closing the previous event file (%ls).", m_fileName.c_str());
                success = false;
            }

            m_file = NULL;
            m_fileName.clear();
            return success;
        }
    }
}

max_stars_repo_name: chunxiaosz/CNTK

max_issues_repo_name: chunxiaosz/CNTK

max_forks_repo_name: chunxiaosz/CNTK


text:
#ifndef INCLUDED_STDDEFX
#include "stddefx.h"
#define INCLUDED_STDDEFX
#endif

#ifndef INCLUDED_GEO_MOORENEIGHBOURHOOD
#include "geo_mooreneighbourhood.h"
#define INCLUDED_GEO_MOORENEIGHBOURHOOD
#endif

// Library headers.
#ifndef INCLUDED_BOOST_MATH_SPECIAL_FUNCTIONS_ROUND
#include <boost/math/special_functions/round.hpp>
#define INCLUDED_BOOST_MATH_SPECIAL_FUNCTIONS_ROUND
#endif

// PCRaster library headers.

// Module headers.

/*!
  \file
  This file contains the implementation of the MooreNeighbourhood class.
*/

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

/*
namespace geo {

class MooreNeighbourhoodPrivate
{
public:

  MooreNeighbourhoodPrivate()
  {
  }

  ~MooreNeighbourhoodPrivate()
  {
  }

};

} // namespace geo
*/

//------------------------------------------------------------------------------
// DEFINITION OF STATIC MOORENEIGHBOURHOOD MEMBERS
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// DEFINITION OF MOORENEIGHBOURHOOD MEMBERS
//------------------------------------------------------------------------------

//! Constructor.
/*!
  \param     radius Radius of the neighbourhood.

  Concentric square rings of cells are added to the neighbourhood if the
  following holds for the cell to the west/north/east or south of the center
  cell:

  The center is at a distance <= toRadius of the center of the center cell.

  If you want to exclude the center cell use MooreNeighbourhood(size_t, size_t)
  with fromRadius 1.
*/
geo::MooreNeighbourhood::MooreNeighbourhood(double toRadius)

  : Neighbourhood(toRadius)

{
  init();
}

//! Constructor.
/*!
  \param     fromRadius Radius of inner border of donut.
  \param     toRadius Radius of outer border of donut.

  This constructor constructs a donut shaped neighbourhood in which the inner
  cells are not part of the neighbourhood. With this constructor it is possible
  to create square zones around a center cell.

  Concentric square rings of cells are added to the neighbourhood if the
  following holds for the cell to the west/north/east or south of the center
  cell:

  The center is at a distance >= \a fromRadius and <= toRadius of the center
  of the center cell.
*/
geo::MooreNeighbourhood::MooreNeighbourhood(double fromRadius, double toRadius)

  : Neighbourhood(fromRadius, toRadius)

{
  init();
}

//! Destructor.
/*!
*/
geo::MooreNeighbourhood::~MooreNeighbourhood()
{
}

//! Initialises the object.
/*!
*/
void geo::MooreNeighbourhood::init()
{
  for(size_t radius = static_cast<size_t>(boost::math::round(fromRadius()));
         radius <= static_cast<size_t>(boost::math::round(toRadius())); ++radius) {
    addRing(radius);
  }
}

//! Adds a ring with radius \a radius to the neighbourhood.
/*!
  \param     radius Radius of ring around center cell to add to neighbourhood.
*/
void geo::MooreNeighbourhood::addRing(size_t radius)
{
  PRECOND(radius <= this->radius());

  size_t upperLeft = this->radius() - radius;

  for(size_t row = upperLeft; row < upperLeft + 2 * radius + 1; ++row) {
    cell(row, upperLeft) = 1.0;
    cell(row, upperLeft + 2 * radius) = 1.0;
  }

  for(size_t col = upperLeft + 1; col < upperLeft + 2 * radius; ++col) {
    cell(upperLeft, col) = 1.0;
    cell(upperLeft + 2 * radius, col) = 1.0;
  }
}

//------------------------------------------------------------------------------
// DEFINITION OF FREE OPERATORS
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// DEFINITION OF FREE FUNCTIONS
//------------------------------------------------------------------------------

ext: cc

max_stars_repo_name: quanpands/wflow

max_issues_repo_name: quanpands/wflow

max_forks_repo_name: quanpands/wflow


text:
#include "multiply.h"

#define BOOST_TEST_MODULE multiply_test

#include <boost/test/included/unit_test.hpp>

BOOST_AUTO_TEST_CASE(zero) {
   BOOST_TEST(0 == multiply(0, 0));
}

BOOST_AUTO_TEST_CASE(little_float) {
   BOOST_TEST(0 == multiply(0.5, 0.5));
}

BOOST_AUTO_TEST_CASE(one) {
   BOOST_TEST(1 == multiply(1, 1));
}


text:
/*
Brian Staber (brian.staber@gmail.com)
*/

#include "Epetra_ConfigDefs.h"
#ifdef HAVE_MPI
#include "mpi.h"
#include "Epetra_MpiComm.h"
#else
#include "Epetra_SerialComm.h"
#endif

#include "Teuchos_CommandLineProcessor.hpp"
#include "Teuchos_StandardCatchMacros.hpp"
#include "Teuchos_ParameterList.hpp"
#include "Teuchos_XMLParameterListCoreHelpers.hpp"

#include "neumannInnerSurface_StochasticPolyconvexHGO.hpp"
#include <boost/math/special_functions/gamma.hpp>

#include "shinozukapp.hpp"

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

    std::string    xmlInFileName = "";
    std::string    extraXmlFile = "";
    std::string    xmlOutFileName = "paramList.out";

    Teuchos::CommandLineProcessor  clp(false);
    clp.setOption("xml-in-file",&xmlInFileName,"The XML file to read into a parameter list");
    clp.setDocString("TO DO.");

    Teuchos::CommandLineProcessor::EParseCommandLineReturn
    parse_return = clp.parse(argc,argv);
    if( parse_return != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL ) {
        std::cout << "\nEnd Result: TEST FAILED" << std::endl;
        return parse_return;
    }

#ifdef HAVE_MPI
    MPI_Init(&argc, &argv);
    Epetra_MpiComm Comm(MPI_COMM_WORLD);
#else
    Epetra_SerialComm Comm;
#endif

    Teuchos::RCP<Teuchos::ParameterList> paramList = Teuchos::rcp(new Teuchos::ParameterList);
    if(xmlInFileName.length()) {
        Teuchos::updateParametersFromXmlFile(xmlInFileName, inoutArg(*paramList));
    }

    if (Comm.MyPID()==0){
        paramList->print(std::cout,2,true,true);
    }

    Teuchos::RCP<neumannInnerSurface_StochasticPolyconvexHGO> interface
    = Teuchos::rcp(new neumannInnerSurface_StochasticPolyconvexHGO(Comm,*paramList));

    std::ifstream parameters_file_1, parameters_file_2, parameters_file_3, parameters_file_4;

    std::string path1 = "/Users/Brian/Documents/Thesis/Trilinos_results/arteries/gmrf_neumann/a100_gamma3_delta010/";
    parameters_file_1.open(path1+"w1.txt");
    parameters_file_2.open(path1+"w2.txt");
    parameters_file_3.open(path1+"w3.txt");
    parameters_file_4.open(path1+"w4.txt");

    unsigned int n_cells_p1_med = 297828;
    unsigned int n_nodes_p1_med = 58464;

    std::string path = "/Users/Brian/Documents/Thesis/Trilinos/arteries/mesh/connectivity_p1_media.txt";
    interface->get_media(n_cells_p1_med,n_nodes_p1_med,path);

    if (parameters_file_1.is_open() && parameters_file_2.is_open() && parameters_file_3.is_open() && parameters_file_4.is_open()){

        for (unsigned nmc=0; nmc<1; ++nmc){
            for (int i=0; i<n_nodes_p1_med; ++i){
                parameters_file_1 >> interface->w1_gmrf(i);
                parameters_file_2 >> interface->w2_gmrf(i);
                parameters_file_3 >> interface->w3_gmrf(i);
                parameters_file_4 >> interface->w4_gmrf(i);
            }
        }
        Comm.Barrier();
        parameters_file_1.close();
        parameters_file_2.close();
        parameters_file_3.close();
        parameters_file_4.close();
    }
    else{
        std::cout << "Couldn't open one of the parameters_file.\n";
    }

    int e_gid;
    int n_local_cells = interface->Mesh->n_local_cells;
    int n_gauss_cells = interface->Mesh->n_gauss_cells;
    std::vector<int> local_gauss_points(n_local_cells*n_gauss_cells);
    for (unsigned int e_lid=0; e_lid<n_local_cells; ++e_lid){
        e_gid = interface->Mesh->local_cells[e_lid];
        for (unsigned int gp=0; gp<n_gauss_cells; ++gp){
            local_gauss_points[e_lid*n_gauss_cells+gp] = e_gid*n_gauss_cells+gp;
        }

    }
    Epetra_Map GaussMap(-1,n_local_cells*n_gauss_cells,&local_gauss_points[0],0,Comm);

    Epetra_Vector mu1_gmrf(GaussMap);
    Epetra_Vector mu2_gmrf(GaussMap);
    Epetra_Vector mu3_gmrf(GaussMap);
    Epetra_Vector mu4_gmrf(GaussMap);
    Epetra_Vector x_coord(GaussMap);
    Epetra_Vector y_coord(GaussMap);
    Epetra_Vector z_coord(GaussMap);

    int node;
    double xi, eta, zeta;
    Epetra_SerialDenseMatrix matrix_X(3,interface->Mesh->el_type);
    Epetra_SerialDenseVector vector_X(3);
    Epetra_SerialDenseVector N(interface->Mesh->el_type);
    for (unsigned int e_lid=0; e_lid<n_local_cells; ++e_lid){
        e_gid = interface->Mesh->local_cells[e_lid];
        for (int inode=0; inode<interface->Mesh->el_type; ++inode){
            node = interface->Mesh->cells_nodes[interface->Mesh->el_type*e_gid+inode];
            matrix_X(0,inode) = interface->Mesh->nodes_coord[3*node+0];
            matrix_X(1,inode) = interface->Mesh->nodes_coord[3*node+1];
            matrix_X(2,inode) = interface->Mesh->nodes_coord[3*node+2];
        }
        for (unsigned int gp=0; gp<n_gauss_cells; ++gp){
            xi   = interface->Mesh->xi_cells[gp];
            eta  = interface->Mesh->eta_cells[gp];
            zeta = interface->Mesh->zeta_cells[gp];
            tetra10::shape_functions(N,xi,eta,zeta);
            vector_X.Multiply('N','N',1.0,matrix_X,N,0.0);
            interface->get_material_parameters(e_lid,gp);
            mu1_gmrf[GaussMap.LID(int(e_gid*n_gauss_cells+gp))] = interface->mu1;
            mu2_gmrf[GaussMap.LID(int(e_gid*n_gauss_cells+gp))] = interface->mu2;
            mu3_gmrf[GaussMap.LID(int(e_gid*n_gauss_cells+gp))] = interface->mu3;
            mu4_gmrf[GaussMap.LID(int(e_gid*n_gauss_cells+gp))] = interface->mu4;
            x_coord[GaussMap.LID(int(e_gid*n_gauss_cells+gp))] = vector_X(0);
            y_coord[GaussMap.LID(int(e_gid*n_gauss_cells+gp))] = vector_X(1);
            z_coord[GaussMap.LID(int(e_gid*n_gauss_cells+gp))] = vector_X(2);
         }
    }

    int error;
    int NumTargetElements = 0;
    if (Comm.MyPID()==0){
        NumTargetElements = interface->Mesh->n_cells*n_gauss_cells;
    }
    Epetra_Map MapOnRoot(-1,NumTargetElements,0,Comm);
    Epetra_Export ExportOnRoot(GaussMap,MapOnRoot);
    Epetra_MultiVector lhs_root(MapOnRoot,true);
    lhs_root.Export(mu1_gmrf,ExportOnRoot,Insert);
    std::string filename = "/Users/Brian/Documents/Thesis/Trilinos_results/arteries/boost_gmrf/gmrf_gauss/mu1_gmrf.mtx";
    error = EpetraExt::MultiVectorToMatrixMarketFile(filename.c_str(),lhs_root,0,0,false);

    lhs_root.PutScalar(0.0);
    lhs_root.Export(mu2_gmrf,ExportOnRoot,Insert);
    filename = "/Users/Brian/Documents/Thesis/Trilinos_results/arteries/boost_gmrf/gmrf_gauss/mu2_gmrf.mtx";
    error = EpetraExt::MultiVectorToMatrixMarketFile(filename.c_str(),lhs_root,0,0,false);

    lhs_root.PutScalar(0.0);
    lhs_root.Export(mu3_gmrf,ExportOnRoot,Insert);
    filename = "/Users/Brian/Documents/Thesis/Trilinos_results/arteries/boost_gmrf/gmrf_gauss/mu3_gmrf.mtx";
    error = EpetraExt::MultiVectorToMatrixMarketFile(filename.c_str(),lhs_root,0,0,false);

    lhs_root.PutScalar(0.0);
    lhs_root.Export(mu4_gmrf,ExportOnRoot,Insert);
    filename = "/Users/Brian/Documents/Thesis/Trilinos_results/arteries/boost_gmrf/gmrf_gauss/mu4_gmrf.mtx";
    error = EpetraExt::MultiVectorToMatrixMarketFile(filename.c_str(),lhs_root,0,0,false);

    lhs_root.PutScalar(0.0);
    lhs_root.Export(x_coord,ExportOnRoot,Insert);
    filename = "/Users/Brian/Documents/Thesis/Trilinos_results/arteries/boost_gmrf/gmrf_gauss/x_coord.mtx";
    error = EpetraExt::MultiVectorToMatrixMarketFile(filename.c_str(),lhs_root,0,0,false);

    lhs_root.PutScalar(0.0);
    lhs_root.Export(y_coord,ExportOnRoot,Insert);
    filename = "/Users/Brian/Documents/Thesis/Trilinos_results/arteries/boost_gmrf/gmrf_gauss/y_coord.mtx";
    error = EpetraExt::MultiVectorToMatrixMarketFile(filename.c_str(),lhs_root,0,0,false);

    lhs_root.PutScalar(0.0);
    lhs_root.Export(z_coord,ExportOnRoot,Insert);
    filename = "/Users/Brian/Documents/Thesis/Trilinos_results/arteries/boost_gmrf/gmrf_gauss/z_coord.mtx";
    error = EpetraExt::MultiVectorToMatrixMarketFile(filename.c_str(),lhs_root,0,0,false);

#ifdef HAVE_MPI
    MPI_Finalize();
#endif
    return 0;

}

max_stars_repo_name: bstaber/Trilinos

max_issues_repo_name: bstaber/Trilinos

max_forks_repo_name: bstaber/Trilinos


text:
#ifndef __IRODS_ERROR_HPP__
#define __IRODS_ERROR_HPP__

// =-=-=-=-=-=-=-
// STL Includes
#include <string>
#include <vector>
#include <cstdarg>

#include <boost/optional.hpp>

// =-=-=-=-=-=-=-
// irods includes
#include "rodsType.h"
#include "irods_exception.hpp"

#include <boost/assert.hpp>
#include <boost/format.hpp>

namespace irods {
/// =-=-=-=-=-=-=-
/// @brief error stack object which holds error history
    class error {
        public:
            // =-=-=-=-=-=-=-
            // Constructors
            error();
            error(
                bool,          // status
                long long,     // error code
                std::string,   // message
                std::string,   // file name
                int,           // line number
                std::string ); // function
            error(
                bool,          // status
                long long,     // error code
                boost::format, // message
                std::string,   // file name
                int,           // line number
                std::string ); // function
            error(                  // deprecated since 4.0.3
                bool,           // status
                long long,      // error code
                std::string,    // message
                std::string,    // file name
                int,            // line number
                std::string,    // function
                const error& ); // previous error
            error(
                std::string,    // message
                std::string,    // file name
                int,            // line number
                std::string,    // function
                const error& ); // previous error
            error( const error& );
            error( const exception& );

            // =-=-=-=-=-=-=-
            // Destructor
            ~error();

            // =-=-=-=-=-=-=-
            // Operators
            error& operator=( const error& );

            // =-=-=-=-=-=-=-
            // Members
            bool        status() const;
            long long   code() const;
            std::string result() const;
            std::string user_result() const;
            bool        ok();          // deprecated since 4.0.3
            bool        ok() const;

            // =-=-=-=-=-=-=-
            // Mutators
            void code( long long _code ) {
                code_   = _code;
            }
            void status( bool      _status ) {
                status_ = _status;
            }
            void message( const std::string& _message ) {
                message_ = _message;
            }

        private:
            // =-=-=-=-=-=-=-
            // Attributes
            bool        status_;
            long long   code_;
            std::string message_;
            std::vector< std::string > result_stack_;
            boost::optional< exception > exception_;

            // These are hard-coded strings that are used in creating
            // the strings that go in result_stack_, and that are searched
            // for as such.  See static declarations in irods_error.cpp for initialization.
            static const char *iRODS_token_;
            static const char *colon_token_;
            static const char *status_token_;

            // =-=-=-=-=-=-=-
            // Members
            std::string build_result_string( std::string, int, std::string );

    }; // class error

    error assert_error( bool expr_, long long code_, const std::string& file_, const std::string& function_, const std::string& format_, int line_, ... );
    error assert_pass( const error& _error, const std::string& _file, const std::string& _function, const std::string& _format, int line_, ... );

}; // namespace irods

#define ERROR( code_, message_ ) ( irods::error( false, code_, message_, __FILE__, __LINE__, __PRETTY_FUNCTION__ ) )
#define PASS( prev_error_ ) (irods::error( "", __FILE__, __LINE__, __PRETTY_FUNCTION__, prev_error_ ) )
#define PASSMSG( message_, prev_error_ ) (irods::error( message_, __FILE__, __LINE__, __PRETTY_FUNCTION__, prev_error_ ) )
#define CODE( code_ ) ( irods::error( true, code_, "", __FILE__, __LINE__, __PRETTY_FUNCTION__ ) )
#define SUCCESS( ) ( irods::error( true, 0, "", __FILE__, __LINE__, __PRETTY_FUNCTION__ ) )

#define ASSERT_ERROR(expr_, code_, format_, ...)  (irods::assert_error(expr_, code_, __FILE__, __PRETTY_FUNCTION__, format_, __LINE__, ##__VA_ARGS__))
#define ASSERT_PASS(prev_error_, format_, ...) (irods::assert_pass(prev_error_, __FILE__, __PRETTY_FUNCTION__, format_, __LINE__, ##__VA_ARGS__))

#endif // __IRODS_ERROR_HPP__

max_stars_repo_name: JustinKyleJames/irods

max_issues_repo_name: JustinKyleJames/irods

max_forks_repo_name: JustinKyleJames/irods


text:
#include <Eigen/Core>

#include <numpy_eigen/boost_python_headers.hpp>
Eigen::Matrix<double, 6, 4> test_double_6_4(const Eigen::Matrix<double, 6, 4> & M)
{
	return M;
}
void export_double_6_4()
{
	boost::python::def("test_double_6_4",test_double_6_4);
}

max_stars_repo_name: PushyamiKaveti/kalibr

max_issues_repo_name: PushyamiKaveti/kalibr

max_forks_repo_name: PushyamiKaveti/kalibr


text:
#include <chrono>
#include <fstream>
#include <iostream>
#include <random>
#include <utility>
#include <vector>

#include <Eigen/Geometry>
#include <common_robotics_utilities/math.hpp>
#include <common_robotics_utilities/simple_hierarchical_clustering.hpp>
#include <common_robotics_utilities/simple_kmeans_clustering.hpp>

int main(int argc, char** argv)
{
  const size_t num_points
      = (argc >= 2) ? static_cast<size_t>(atoi(argv[1])) : 1000;
  std::cout << "Generating " << num_points << " points..." << std::endl;
  const int64_t seed = 42;
  std::mt19937_64 prng(seed);
  std::uniform_real_distribution<double> dist(0.0, 10.0);
  std::vector<Eigen::VectorXd> random_points(num_points);
  std::vector<size_t> indices(num_points);
  for (size_t idx = 0; idx < num_points; idx++)
  {
    const double x = dist(prng);
    const double y = dist(prng);
    Eigen::VectorXd random_point(3);
    random_point << x, y, 0.0;
    random_points[idx] = random_point;
    indices[idx] = idx;
  }
  const std::vector<bool> use_parallel_options = {false, true};
  for (const bool use_parallel : use_parallel_options)
  {
    std::cout << "Complete-link hierarchical clustering " << num_points
              << " points..." << std::endl;
    std::function<double(const Eigen::VectorXd&, const Eigen::VectorXd&)>
        distance_fn = [] (const Eigen::VectorXd& v1, const Eigen::VectorXd& v2)
    {
      return common_robotics_utilities::math::Distance(v1, v2);
    };
    const Eigen::MatrixXd distance_matrix
        = common_robotics_utilities::math
            ::BuildPairwiseDistanceMatrixParallel(random_points, distance_fn);
    const std::vector<std::vector<size_t>> hierarchical_index_clusters
        = common_robotics_utilities::simple_hierarchical_clustering
            ::ClusterWithDistanceMatrix<int64_t>(
                indices, distance_matrix, 1.0,
                common_robotics_utilities::simple_hierarchical_clustering
                    ::ClusterStrategy::COMPLETE_LINK, use_parallel).first;
    std::vector<Eigen::VectorXd> hierarchical_clustered_points = random_points;
    for (size_t cluster_idx = 0;
         cluster_idx < hierarchical_index_clusters.size(); cluster_idx++)
    {
      const std::vector<size_t>& current_cluster
          = hierarchical_index_clusters[cluster_idx];
      const double cluster_num = 1.0 + (double)cluster_idx;
      for (size_t element_idx = 0; element_idx < current_cluster.size();
           element_idx++)
      {
        const size_t index = current_cluster[element_idx];
        hierarchical_clustered_points.at(index)(2) = cluster_num;
      }
    }
    std::cout << "K-means clustering " << num_points << " points..."
              << std::endl;
    std::function<Eigen::VectorXd(const std::vector<Eigen::VectorXd>&)>
        average_fn = [] (const std::vector<Eigen::VectorXd>& cluster)
    {
      return common_robotics_utilities::math::AverageEigenVectorXd(cluster);
    };
    const std::vector<int32_t> kmeans_labels
        = common_robotics_utilities::simple_kmeans_clustering::Cluster(
            random_points, distance_fn, average_fn, 50, 42, true, use_parallel);
    std::vector<Eigen::VectorXd> kmeans_clustered_points = random_points;
    for (size_t idx = 0; idx < kmeans_clustered_points.size(); idx++)
    {
      kmeans_clustered_points.at(idx)(2) = kmeans_labels.at(idx);
    }
    std::cout << "Saving to CSV..." << std::endl;
    const std::string hierarchical_log_file_name
        = (use_parallel) ? "/tmp/test_parallel_hierarchical_clustering.csv"
                         : "/tmp/test_hierarchical_clustering.csv";
    std::ofstream hierarchical_log_file(
        hierarchical_log_file_name, std::ios_base::out);
    if (!hierarchical_log_file.is_open())
    {
      std::cerr << "\x1b[31;1m Unable to create folder/file to log to: "
                << hierarchical_log_file_name << "\x1b[0m \n";
      throw std::invalid_argument("Log filename must be write-openable");
    }
    for (size_t idx = 0; idx < num_points; idx++)
    {
      const Eigen::VectorXd& point = hierarchical_clustered_points.at(idx);
      hierarchical_log_file << point(0) << "," << point(1) << "," << point(2)
                            << std::endl;
    }
    hierarchical_log_file.close();
    const std::string kmeans_log_file_name
        = (use_parallel) ? "/tmp/test_parallel_kmeans_clustering.csv"
                         : "/tmp/test_kmeans_clustering.csv";
    std::ofstream kmeans_log_file(kmeans_log_file_name, std::ios_base::out);
    if (!kmeans_log_file.is_open())
    {
      std::cerr << "\x1b[31;1m Unable to create folder/file to log to: "
                << kmeans_log_file_name << "\x1b[0m \n";
      throw std::invalid_argument("Log filename must be write-openable");
    }
    for (size_t idx = 0; idx < num_points; idx++)
    {
      const Eigen::VectorXd& point = kmeans_clustered_points.at(idx);
      kmeans_log_file << point(0) << "," << point(1) << "," << point(2)
                      << std::endl;
    }
    kmeans_log_file.close();
  }
  std::cout << "Done saving, you can plot as a 3d scatterplot to see clustering"
            << std::endl;
  return 0;
}


text:
// Copyright 2015 Nikita Chudinov

#include "storage.h"
#include <sys/stat.h>
#include <string>
#include <vector>
#include <boost/unordered_set.hpp>
#include <boost/filesystem.hpp>
#include <plog/Log.h>

void Storage::StoreMetadata(const std::string &filename) {
    struct stat attributes;
    stat(filename.c_str(), &attributes);

    DbRecord record(filename, attributes);

    digest.DigestFile(filename, record.data.digest);

    db.Store(record);
}

Storage::CheckResult Storage::CheckMetadata(const std::string &filename) const {
    struct stat attributes;
    stat(filename.c_str(), &attributes);
    DbRecord current_metadata(filename, attributes);

    digest.DigestFile(filename, current_metadata.data.digest);

    DbRecord database_metadata;
    database_metadata.filename = filename;
    if (db.Get(&database_metadata)) {
        return NOT_FOUND;
    }

    if (current_metadata == database_metadata) {
        return PASS;
    } else {
        return FAIL;
    }
}

void Storage::StorePathListMetadata(const PathListParser &parser) {
    namespace fs = boost::filesystem;
    boost::unordered_set<fs::path> files = parser.Files();

    mtx.lock();
    for (auto pathname : files) {
        LOG_INFO << "Scanned " << pathname.string();
        this->StoreMetadata(pathname.string());
    }
    mtx.unlock();
}

bool Storage::CheckPathListMetadata(const PathListParser &parser) const {
    bool fail = false;
    namespace fs = boost::filesystem;

    boost::unordered_set<fs::path> files = parser.Files();

    mtx.lock();
    for (auto pathname : files) {
        auto result = this->CheckMetadata(pathname.string());

        switch (result) {
            case Storage::NOT_FOUND:
                fail = true;
                LOG_WARNING << "No hash for this file: " << pathname.string();
                break;
            case Storage::FAIL:
                fail = true;
                LOG_WARNING << "File is corrupted: " << pathname.string();
                break;
            case Storage::PASS:
                break;
        }
    }
    mtx.unlock();

    return fail;
}

max_stars_repo_name: Monory/file-integrity

max_issues_repo_name: Monory/file-integrity

max_forks_repo_name: Monory/file-integrity


text:
/*!
@file
Defines `boost::hana::Applicative::mcd`.

@copyright Louis Dionne 2014
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
 */

#ifndef BOOST_HANA_APPLICATIVE_MCD_HPP
#define BOOST_HANA_APPLICATIVE_MCD_HPP

#include <boost/hana/applicative/applicative.hpp>

namespace boost { namespace hana {
    //! Minimal complete definition : `lift` and `ap`
    struct Applicative::mcd { };
}} // end namespace boost::hana

#endif // !BOOST_HANA_APPLICATIVE_MCD_HPP

max_stars_repo_name: rbock/hana

max_issues_repo_name: rbock/hana

max_forks_repo_name: rbock/hana