text:
/**
 * Copyright Soramitsu Co., Ltd. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

#include "ametsuchi/impl/postgres_block_query.hpp"

#include <boost/format.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <boost/range/algorithm/for_each.hpp>

#include "ametsuchi/impl/soci_utils.hpp"
#include "common/byteutils.hpp"

namespace iroha {
  namespace ametsuchi {
    PostgresBlockQuery::PostgresBlockQuery(
        soci::session &sql,
        KeyValueStorage &file_store,
        std::shared_ptr<shared_model::interface::BlockJsonDeserializer>
            converter)
        : sql_(sql),
          block_store_(file_store),
          converter_(std::move(converter)),
          log_(logger::log("PostgresBlockQuery")) {}

    PostgresBlockQuery::PostgresBlockQuery(
        std::unique_ptr<soci::session> sql,
        KeyValueStorage &file_store,
        std::shared_ptr<shared_model::interface::BlockJsonDeserializer>
            converter)
        : psql_(std::move(sql)),
          sql_(*psql_),
          block_store_(file_store),
          converter_(std::move(converter)),
          log_(logger::log("PostgresBlockQuery")) {}

    std::vector<BlockQuery::wBlock> PostgresBlockQuery::getBlocks(
        shared_model::interface::types::HeightType height, uint32_t count) {
      shared_model::interface::types::HeightType last_id =
          block_store_.last_id();
      auto to = std::min(last_id, height + count - 1);
      std::vector<BlockQuery::wBlock> result;
      if (height > to or count == 0) {
        return result;
      }
      for (auto i = height; i <= to; i++) {
        auto block = getBlock(i);
        block.match(
            [&result](
                expected::Value<std::unique_ptr<shared_model::interface::Block>>
                    &v) { result.emplace_back(std::move(v.value)); },
            [this](const expected::Error<std::string> &e) {
              log_->error(e.error);
            });
      }
      return result;
    }

    std::vector<BlockQuery::wBlock> PostgresBlockQuery::getBlocksFrom(
        shared_model::interface::types::HeightType height) {
      return getBlocks(height, block_store_.last_id());
    }

    std::vector<BlockQuery::wBlock> PostgresBlockQuery::getTopBlocks(
        uint32_t count) {
      auto last_id = block_store_.last_id();
      count = std::min(count, last_id);
      return getBlocks(last_id - count + 1, count);
    }

    std::vector<shared_model::interface::types::HeightType>
    PostgresBlockQuery::getBlockIds(
        const shared_model::interface::types::AccountIdType &account_id) {
      std::vector<shared_model::interface::types::HeightType> result;
      soci::indicator ind;
      std::string row;
      soci::statement st =
          (sql_.prepare << "SELECT DISTINCT height FROM height_by_account_set "
                           "WHERE account_id = :id",
           soci::into(row, ind),
           soci::use(account_id));
      st.execute();

      processSoci(st, ind, row, [&result](std::string &r) {
        result.push_back(std::stoull(r));
      });
      return result;
    }

    boost::optional<shared_model::interface::types::HeightType>
    PostgresBlockQuery::getBlockId(const shared_model::crypto::Hash &hash) {
      boost::optional<uint64_t> blockId = boost::none;
      boost::optional<std::string> block_str;
      auto hash_str = hash.hex();

      sql_ << "SELECT height FROM position_by_hash WHERE hash = :hash",
          soci::into(block_str), soci::use(hash_str);
      if (block_str) {
        blockId = std::stoull(block_str.get());
      } else {
        log_->info("No block with transaction {}", hash);
      }
      return blockId;
    }

    std::function<void(std::vector<std::string> &result)>
    PostgresBlockQuery::callback(std::vector<wTransaction> &blocks,
                                 uint64_t block_id) {
      return [this, &blocks, block_id](std::vector<std::string> &result) {
        auto block = getBlock(block_id);
        block.match(
            [&result, &blocks](
                expected::Value<std::unique_ptr<shared_model::interface::Block>>
                    &v) {
              boost::for_each(
                  result | boost::adaptors::transformed([](const auto &x) {
                    std::istringstream iss(x);
                    size_t size;
                    iss >> size;
                    return size;
                  }),
                  [&](const auto &x) {
                    blocks.emplace_back(clone(v.value->transactions()[x]));
                  });
            },
            [this](const expected::Error<std::string> &e) {
              log_->error(e.error);
            });
      };
    }

    std::vector<BlockQuery::wTransaction>
    PostgresBlockQuery::getAccountTransactions(
        const shared_model::interface::types::AccountIdType &account_id) {
      std::vector<BlockQuery::wTransaction> result;
      auto block_ids = this->getBlockIds(account_id);
      if (block_ids.empty()) {
        return result;
      }
      for (const auto &block_id : block_ids) {
        std::vector<std::string> index;
        soci::indicator ind;
        std::string row;
        soci::statement st =
            (sql_.prepare
                 << "SELECT DISTINCT index FROM index_by_creator_height "
                    "WHERE creator_id = :id AND height = :height",
             soci::into(row, ind),
             soci::use(account_id),
             soci::use(block_id));
        st.execute();

        processSoci(
            st, ind, row, [&index](std::string &r) { index.push_back(r); });
        this->callback(result, block_id)(index);
      }
      return result;
    }

    std::vector<BlockQuery::wTransaction>
    PostgresBlockQuery::getAccountAssetTransactions(
        const shared_model::interface::types::AccountIdType &account_id,
        const shared_model::interface::types::AssetIdType &asset_id) {
      std::vector<BlockQuery::wTransaction> result;
      auto block_ids = this->getBlockIds(account_id);
      if (block_ids.empty()) {
        return result;
      }

      for (const auto &block_id : block_ids) {
        std::vector<std::string> index;
        soci::indicator ind;
        std::string row;
        soci::statement st =
            (sql_.prepare
                 << "SELECT DISTINCT index FROM position_by_account_asset "
                    "WHERE account_id = :id AND height = :height "
                    "AND asset_id = :asset_id",
             soci::into(row, ind),
             soci::use(account_id),
             soci::use(block_id),
             soci::use(asset_id));
        st.execute();

        processSoci(
            st, ind, row, [&index](std::string &r) { index.push_back(r); });
        this->callback(result, block_id)(index);
      }
      return result;
    }

    std::vector<boost::optional<BlockQuery::wTransaction>>
    PostgresBlockQuery::getTransactions(
        const std::vector<shared_model::crypto::Hash> &tx_hashes) {
      std::vector<boost::optional<BlockQuery::wTransaction>> result;
      std::for_each(tx_hashes.begin(),
                    tx_hashes.end(),
                    [this, &result](const auto &tx_hash) {
                      result.push_back(this->getTxByHashSync(tx_hash));
                    });
      return result;
    }

    boost::optional<BlockQuery::wTransaction>
    PostgresBlockQuery::getTxByHashSync(
        const shared_model::crypto::Hash &hash) {
      return getBlockId(hash) |
          [this](const auto &block_id) {
            auto result = this->getBlock(block_id);
            return result.match(
                [](expected::Value<
                    std::unique_ptr<shared_model::interface::Block>> &v)
                    -> boost::optional<
                        std::unique_ptr<shared_model::interface::Block>> {
                  return std::move(v.value);
                },
                [this](const expected::Error<std::string> &e)
                    -> boost::optional<
                        std::unique_ptr<shared_model::interface::Block>> {
                  log_->error(e.error);
                  return boost::none;
                });
          }
      | [&hash, this](const auto &block) {
          auto it = std::find_if(
              block->transactions().begin(),
              block->transactions().end(),
              [&hash](const auto &tx) { return tx.hash() == hash; });
          if (it != block->transactions().end()) {
            return boost::make_optional<PostgresBlockQuery::wTransaction>(
                clone(*it));
          } else {
            log_->error("Failed to find transaction {} in block {}",
                        hash.hex(),
                        block->height());
            // return type specification for lambda breaks formatting.
            // That is why optional is constructed explicitly
            return boost::optional<PostgresBlockQuery::wTransaction>(
                boost::none);
          }
        };
    }

    boost::optional<TxCacheStatusType> PostgresBlockQuery::checkTxPresence(
        const shared_model::crypto::Hash &hash) {
      int res = -1;
      const auto &hash_str = hash.hex();

      try {
        sql_ << "SELECT status FROM tx_status_by_hash WHERE hash = :hash",
            soci::into(res), soci::use(hash_str);
      } catch (const std::exception &e) {
        log_->error("Failed to execute query: {}", e.what());
        return boost::none;
      }

      // res > 0 => Committed
      // res == 0 => Rejected
      // res < 0 => Missing
      if (res > 0) {
        return boost::make_optional<TxCacheStatusType>(
            tx_cache_status_responses::Committed{hash});
      } else if (res == 0) {
        return boost::make_optional<TxCacheStatusType>(
            tx_cache_status_responses::Rejected{hash});
      }
      return boost::make_optional<TxCacheStatusType>(
          tx_cache_status_responses::Missing{hash});
    }

    uint32_t PostgresBlockQuery::getTopBlockHeight() {
      return block_store_.last_id();
    }

    expected::Result<BlockQuery::wBlock, std::string>
    PostgresBlockQuery::getTopBlock() {
      return getBlock(block_store_.last_id())
          .match(
              [](expected::Value<
                  std::unique_ptr<shared_model::interface::Block>> &v)
                  -> expected::Result<BlockQuery::wBlock, std::string> {
                return expected::makeValue<BlockQuery::wBlock>(
                    std::move(v.value));
              },
              [](expected::Error<std::string> &e)
                  -> expected::Result<BlockQuery::wBlock, std::string> {
                return expected::makeError(std::move(e.error));
              });
    }

    expected::Result<std::unique_ptr<shared_model::interface::Block>,
                     std::string>
    PostgresBlockQuery::getBlock(
        shared_model::interface::types::HeightType id) const {
      auto serialized_block = block_store_.get(id);
      if (not serialized_block) {
        auto error = boost::format("Failed to retrieve block with id %d") % id;
        return expected::makeError(error.str());
      }
      return converter_->deserialize(bytesToString(*serialized_block));
    }
  }  // namespace ametsuchi
}  // namespace iroha

max_stars_repo_name: coderintherye/iroha

max_issues_repo_name: coderintherye/iroha

max_forks_repo_name: coderintherye/iroha


text: #include <boost/preprocessor/inc.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// Software License Agreement (BSD-3-Clause)
//
// Copyright 2018 The University of North Carolina at Chapel Hill
//
// 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.
//
// 3. Neither the name of the copyright holder nor the names of its
//    contributors may be used to endorse or promote products derived
//    from this software without specific prior written permission.
//
// 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 HOLDER 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.

//! @author Jeff Ichnowski

#ifndef LINEAR_H
#define LINEAR_H

#include <Eigen/Dense>
#include <Eigen/Geometry>

namespace nao_cup {
    template <typename S>
    using Transform = Eigen::Transform<S, 3, Eigen::Isometry>;

    template <typename S>
    using Vec2 = Eigen::Matrix<S, 2, 1>;
    template <typename S>
    using Vec3 = Eigen::Matrix<S, 3, 1>;
    template <typename S>
    using Vec4 = Eigen::Matrix<S, 4, 1>;

    template <typename S>
    S v3_len(const Vec3<S> *v) { return v->norm(); }

    template <typename S>
    S v3_dot(const Vec3<S> *a, const Vec3<S> *b) {
        return a->dot(*b);
    }

    template <typename S>
    S v3_dist(const Vec3<S> *a, const Vec3<S> *b) {
        return (*a - *b).norm();
    }

    template <typename S>
    void v3_sub(Vec3<S>* r, const Vec3<S>* a, const Vec3<S>* b) { *r = *a - *b; }

    template <typename S>
    void v3_add(Vec3<S>* r, const Vec3<S>* a, const Vec3<S>* b) { *r = *a + *b; }

    template <typename S>
    void v3_scale(Vec3<S>* r, const Vec3<S> *v, S s) { *r = *v * s; }

    template <typename S>
    void m4_mul(
        Transform<S>* r,
        const Transform<S> *a,
        const Transform<S> *b)
    {
        *r = *a * *b;
    }

    template <typename S>
    void m4_rotate(
        Transform<S> *m,
        const Transform<S> *t,
        S a, S x, S y, S z)
    {
        *m = *t * Eigen::AngleAxis<S>(a, Vec3<S>(x, y, z));
    }

    template <typename S>
    void m4_translate(Transform<S> *m, const Transform<S> *t, S x, S y, S z) {
        *m = *t * Eigen::Translation<S, 3>(x, y, z);
    }

    template <typename S>
    void m4_transform_i3(Vec3<S> *r, const Transform<S> *m, S x, S y, S z) {
        *r = *m * Vec3<S>(x, y, z);
    }

    template <typename S>
    void m4_extract_translation(
        Vec3<S>* r,
        const Transform<S> *m)
    {
        *r = m->translation().template head<3>();
    }

    template <typename S>
    void m4_transform_i(Vec4<S> *r, const Transform<S> *m, S x, S y, S z, S w) {
        *r = *m * Vec4<S>(x, y, z, w);
    }

    template <typename S>
    void m4_transform_i(Vec3<S>* r, const Transform<S> *m, S x, S y, S z) {
        *r = *m * Vec3<S>(x, y, z);
    }

    template <typename S>
    void v3_norm(Vec3<S> *r, const Vec3<S> *a) {
        *r = a->normalized();
    }

    template <typename S>
    S v3_dist_segment_point(const Vec3<S> *s0, const Vec3<S> *s1, const Vec3<S> *pt) {
        Vec3<S> v, w;
        S c1, c2, b;

        v3_sub(&v, s1, s0);
        v3_sub(&w, pt, s0);

        c1 = v3_dot(&w, &v);
        if (c1 <= 0.0) {
            return v3_len(&w);
        }

        c2 = v3_dot(&v, &v);
        if (c2 <= c1) {
            return v3_dist(pt, s1);
        }

        b = c1 / c2;

        v3_scale(&v, &v, b);
        v3_add(&v, s0, &v);

        return v3_dist(&v, pt);
    }
}

#endif /* LINEAR_H */

max_stars_repo_name: elishafer/mpt

max_issues_repo_name: elishafer/mpt

max_forks_repo_name: elishafer/mpt


text:
#include <iostream>
#include <vector>
#include <queue>
#include <boost/unordered_map.hpp>
#include <tclap/CmdLine.h>
#include <boost/algorithm/string/join.hpp>

#include "neuralLM.h"
#include "util.h"

using namespace std;
using namespace TCLAP;
using namespace boost;
using namespace nplm;

void writeNgrams(const vector<vector<string> > &data,
		 int ngram_size, const vocabulary &vocab,
		 bool numberize, bool add_start_stop, bool ngramize,
		 const string &filename)
{
    ofstream file(filename.c_str());
    if (!file)
    {
	cerr << "error: could not open " << filename << endl;
	exit(1);
    }

    vector<vector<int> > ngrams;
    for (int i=0; i<data.size(); i++) {
        preprocessWords(data[i], ngrams, ngram_size, vocab, numberize, add_start_stop, ngramize);
	// write out n-grams
	for (int j=0; j<ngrams.size(); j++)
	  {
	    for (int k=0; k<ngram_size; k++)
	      {
	        file << ngrams[j][k] << " ";
	      }
	    file << endl;
	  }
    }
    file.close();
}

int main(int argc, char *argv[])
{
    int ngram_size, vocab_size, validation_size;
    bool numberize, ngramize, add_start_stop;
    string train_text, train_file, validation_text, validation_file, words_file, write_words_file;

    try
    {
	CmdLine cmd("Prepares training data for training a language model.", ' ', "0.1");

	// The options are printed in reverse order

    ValueArg<bool> arg_ngramize("", "ngramize", "If true, convert lines to ngrams. Default: true.", false, true, "bool", cmd);
    ValueArg<bool> arg_numberize("", "numberize", "If true, convert words to numbers. Default: true.", false, true, "bool", cmd);
    ValueArg<bool> arg_add_start_stop("", "add_start_stop", "If true, prepend <s> and append </s>. Default: true.", false, true, "bool", cmd);

    ValueArg<int> arg_vocab_size("", "vocab_size", "Vocabulary size.", false, -1, "int", cmd);
    ValueArg<string> arg_words_file("", "words_file", "File specifying words that should be included in vocabulary; all other words will be replaced by <unk>.", false, "", "string", cmd);
    ValueArg<int> arg_ngram_size("", "ngram_size", "Size of n-grams.", true, -1, "int", cmd);
	ValueArg<string> arg_write_words_file("", "write_words_file", "Output vocabulary.", false, "", "string", cmd);
    ValueArg<int> arg_validation_size("", "validation_size", "How many lines from training data to hold out for validation. Default: 0.", false, 0, "int", cmd);
	ValueArg<string> arg_validation_file("", "validation_file", "Output validation data (numberized n-grams).", false, "", "string", cmd);
	ValueArg<string> arg_validation_text("", "validation_text", "Input validation data (tokenized). Overrides --validation_size. Default: none.", false, "", "string", cmd);
	ValueArg<string> arg_train_file("", "train_file", "Output training data (numberized n-grams).", false, "", "string", cmd);
	ValueArg<string> arg_train_text("", "train_text", "Input training data (tokenized).", true, "", "string", cmd);

	cmd.parse(argc, argv);

	train_text = arg_train_text.getValue();
	train_file = arg_train_file.getValue();
	validation_text = arg_validation_text.getValue();
	validation_file = arg_validation_file.getValue();
	validation_size = arg_validation_size.getValue();
	write_words_file = arg_write_words_file.getValue();
	ngram_size = arg_ngram_size.getValue();
	vocab_size = arg_vocab_size.getValue();
	words_file = arg_words_file.getValue();
	numberize = arg_numberize.getValue();
	ngramize = arg_ngramize.getValue();
	add_start_stop = arg_add_start_stop.getValue();

    // check command line arguments

    // Notes:
    // - either --words_file or --vocab_size is required.
    // - if --words_file is set,
    // - if --vocab_size is not set, it is inferred from the length of the file
    // - if --vocab_size is set, it is an error if the vocab file has a different number of lines
    // - if --numberize 0 is set and --words_file f is not set, then the output model file will not have a vocabulary, and a warning should be printed.

    // Notes:
    // - if --ngramize 0 is set, then
    // - if --ngram_size is not set, it is inferred from the training file (different from current)
    // - if --ngram_size is set, it is an error if the training file has a different n-gram size
    // - if neither --validation_file or --validation_size is set, validation will not be performed.
    // - if --numberize 0 is set, then --validation_size cannot be used.

    cerr << "Command line: " << endl;
    cerr << boost::algorithm::join(vector<string>(argv, argv+argc), " ") << endl;

	const string sep(" Value: ");
	cerr << arg_train_text.getDescription() << sep << arg_train_text.getValue() << endl;
	cerr << arg_train_file.getDescription() << sep << arg_train_file.getValue() << endl;
	cerr << arg_validation_text.getDescription() << sep << arg_validation_text.getValue() << endl;
	cerr << arg_validation_file.getDescription() << sep << arg_validation_file.getValue() << endl;
	cerr << arg_validation_size.getDescription() << sep << arg_validation_size.getValue() << endl;
	cerr << arg_write_words_file.getDescription() << sep << arg_write_words_file.getValue() << endl;
	cerr << arg_ngram_size.getDescription() << sep << arg_ngram_size.getValue() << endl;
	cerr << arg_vocab_size.getDescription() << sep << arg_vocab_size.getValue() << endl;
	cerr << arg_words_file.getDescription() << sep << arg_words_file.getValue() << endl;
	cerr << arg_numberize.getDescription() << sep << arg_numberize.getValue() << endl;
	cerr << arg_ngramize.getDescription() << sep << arg_ngramize.getValue() << endl;
	cerr << arg_add_start_stop.getDescription() << sep << arg_add_start_stop.getValue() << endl;
    }
    catch (TCLAP::ArgException &e)
    {
      cerr << "error: " << e.error() <<  " for arg " << e.argId() << endl;
      exit(1);
    }

    // VLF: why is this true?
    // DC: it's because the vocabulary has to be constructed from the training data only.
    // If the vocabulary is preset, we can't create the validation data.
    // - if --numberize 0 is set, then --validation_size cannot be used.
    // if (!numberize && (validation_size > 0)) {
    //     cerr <<  "Warning: without setting --numberize to 1, --validation_size cannot be used." << endl;
    // }

    // Read in training data and validation data
    vector<vector<string> > train_data;
    readSentFile(train_text, train_data);
    for (int i=0; i<train_data.size(); i++) {
        // if data is already ngramized, set/check ngram_size
        if (!ngramize) {
            if (ngram_size > 0) {
                if (ngram_size != train_data[i].size()) {
                    cerr << "Error: size of training ngrams does not match specified value of --ngram_size!" << endl;
                }
            }
            // else if --ngram_size has not been specified, set it now
            else {
                ngram_size=train_data[i].size();
            }
        }
    }

    vector<vector<string> > validation_data;
    if (validation_text != "") {
        readSentFile(validation_text, validation_data);
        for (int i=0; i<validation_data.size(); i++) {
	    // if data is already ngramized, set/check ngram_size
            if (!ngramize) {
                // if --ngram_size has been specified, check that it does not conflict with --ngram_size
                if (ngram_size > 0) {
                    if (ngram_size != validation_data[i].size()) {
                        cerr << "Error: size of validation ngrams does not match specified value of --ngram_size!" << endl;
                    }
                }
                // else if --ngram_size has not been specified, set it now
                else {
                    ngram_size=validation_data[i].size();
                }
            }
        }
    }
    else if (validation_size > 0)
    {
        // Create validation data
        if (validation_size > train_data.size())
	{
	    cerr << "error: requested validation size is greater than training data size" << endl;
	    exit(1);
	}
	validation_data.insert(validation_data.end(), train_data.end()-validation_size, train_data.end());
	train_data.resize(train_data.size() - validation_size);
    }

    // Construct vocabulary
    vocabulary vocab;
    int start, stop;

    // read vocabulary from file
    if (words_file != "") {
        vector<string> words;
        readWordsFile(words_file,words);
        for(vector<string>::iterator it = words.begin(); it != words.end(); ++it) {
            vocab.insert_word(*it);
        }

        // was vocab_size set? if so, verify that it does not conflict with size of vocabulary read from file
        if (vocab_size > 0) {
            if (vocab.size() != vocab_size) {
                cerr << "Error: size of vocabulary file " << vocab.size() << " != --vocab_size " << vocab_size << endl;
            }
        }
        // else, set it to the size of vocabulary read from file
        else {
            vocab_size = vocab.size();
        }

    }

    // construct vocabulary to contain top <vocab_size> most frequent words; all other words replaced by <unk>
    else {
        vocab.insert_word("<s>");
	vocab.insert_word("</s>");
	vocab.insert_word("<null>");

        // warn user that if --numberize is not set, there will be no vocabulary!
        if (!numberize) {
            cerr << "Warning: with --numberize 0 and --words_file == "", there will be no vocabulary!" << endl;
        }
        unordered_map<string,int> count;
        for (int i=0; i<train_data.size(); i++) {
            for (int j=0; j<train_data[i].size(); j++) {
                count[train_data[i][j]] += 1;
            }
        }

        vocab.insert_most_frequent(count, vocab_size);
        if (vocab.size() < vocab_size) {
            cerr << "warning: fewer than " << vocab_size << " types in training data; the unknown word will not be learned" << endl;
        }
    }

    // write vocabulary to file
    if (write_words_file != "") {
        cerr << "Writing vocabulary to " << write_words_file << endl;
        writeWordsFile(vocab.words(), write_words_file);
    }

    // Write out numberized n-grams
    if (train_file != "")
    {
        cerr << "Writing training data to " << train_file << endl;
        writeNgrams(train_data, ngram_size, vocab, numberize, add_start_stop, ngramize, train_file);
    }
    if (validation_file != "")
    {
        cerr << "Writing validation data to " << validation_file << endl;
        writeNgrams(validation_data, ngram_size, vocab, numberize, add_start_stop, ngramize, validation_file);
    }
}

ext: cpp


text:
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License,Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.

// $Source: /CVSROOT/boost/libs/mpl/test/if.cpp,v $
// $Date: 2007/10/29 07:32:56 $
// $Revision: 1.1.1.1 $

#include <boost/mpl/if.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/aux_/test.hpp>

MPL_TEST_CASE()
{
    typedef if_<true_,char,long>::type t1;
    typedef if_c<true,char,long>::type t2;
    typedef if_<false_,char,long>::type t3;
    typedef if_c<false,char,long>::type t4;

    MPL_ASSERT(( is_same<t1, char> ));
    MPL_ASSERT(( is_same<t2, char> ));
    MPL_ASSERT(( is_same<t3, long> ));
    MPL_ASSERT(( is_same<t4, long> ));
}

max_stars_repo_name: hackerlank/SourceCode

max_issues_repo_name: shacojx/SourceCodeGameTLBB

max_forks_repo_name: shacojx/SourceCodeGameTLBB


text:
#define BOOST_MATH_DOMAIN_ERROR_POLICY ignore_error
#include <boost/math/distributions/fisher_f.hpp>

#include "statsutil.h"

using std::size_t;

double fpval(double x, double df1, double df2)
{
    boost::math::fisher_f f(df1, df2);
    return boost::math::cdf(boost::math::complement(f, x));
}

int idummy1(const std::vector<int> &g, std::vector< std::vector<double> > &x)
{
    if ( g.empty() ) {
        x.clear();
        return 0;
    }

    auto p = std::minmax_element(g.begin(), g.end());

    if (*p.first != 0) {
        x.clear();
        return 1;
    }

    if (*p.second == 0) {
        x.clear();
        return 0;
    }

    auto n = g.size();
    auto m = static_cast<size_t>( * p.second );

    x.assign(m, std::vector<double>(n, 0.0));

    for (size_t i = 0; i < n; ++i) {
        auto k = static_cast<size_t>(g[i]);
        if (k != m)
            x[k][i] = 1.0;
        else
            for (size_t j = 0; j < m; ++j)
                x[j][i] = -1.0;
    }

    return 0;
}

int idummy2(const std::vector<int> &g, std::vector< std::vector<double> > &x)
{
    if ( g.empty() ) {
        x.clear();
        return 1;
    }

    auto p = std::minmax_element(g.begin(), g.end());

    if (*p.first != 0) {
        x.clear();
        return 1;
    }

    if (*p.second == 0) {
        x.clear();
        return 0;
    }

    auto n = g.size();
    auto m = static_cast<size_t>( * p.second );

    x.assign(m, std::vector<double>(n, 0.0));

    for (size_t i = 0; i < n; ++i) {
        auto k = static_cast<size_t>(g[i]);
        if (k != m)
            x[k][i] = 1.0;
    }

    return 0;
}

int idummy3(const std::vector<int> &g, std::vector< std::vector<double> > &x)
{
    if ( g.empty() ) {
        x.clear();
        return 0;
    }

    auto p = std::minmax_element(g.begin(), g.end());

    if (*p.first != 0) {
        x.clear();
        return 1;
    }

    if (*p.second == 0) {
        x.assign(1, std::vector<double>(g.size(), 1.0));
        return 0;
    }

    auto n = g.size();
    auto m = static_cast<size_t>( * p.second );

    x.assign(m + 1, std::vector<double>(n, 0.0));

    for (size_t i = 0; i < n; ++i) {
        auto k = static_cast<size_t>(g[i]);
        x[k][i] = 1.0;
    }

    return 0;
}

max_stars_repo_name: njau-sri/glm-gwas

max_issues_repo_name: njau-sri/glm-gwas

max_forks_repo_name: njau-sri/glm-gwas


text:
#include "get_config.h"
#include <boost/algorithm/string/join.hpp>
#include <google/protobuf/util/json_util.h>
#include "spdlog/spdlog.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include "config/config.pb.validate.h"

using namespace std;
using namespace google::protobuf::util;
using namespace authservice::config;

namespace authservice {
namespace config {

unique_ptr<authservice::config::Config> GetConfig(
    const string &configFileName) {
  ifstream configFile(configFileName);
  if (!configFile) {
    throw runtime_error("failed to open filter config");
  }
  stringstream buf;
  buf << configFile.rdbuf();
  configFile.close();

  unique_ptr<Config> config(new Config);
  auto status = JsonStringToMessage(buf.str(), config.get());
  if (!status.ok()) {
    throw runtime_error(status.error_message());
  }

  std::string error;
  if (!Validate(*(config.get()), &error)) {
    throw runtime_error(error);
  }

  return config;
}

spdlog::level::level_enum GetConfiguredLogLevel(const authservice::config::Config& config) {
  auto log_level_string = config.log_level();
  spdlog::level::level_enum level;

  if (log_level_string == "trace" || log_level_string.empty()) {
    level = spdlog::level::level_enum::trace;
  } else if (log_level_string == "debug") {
    level = spdlog::level::level_enum::debug;
  } else if (log_level_string == "info") {
    level = spdlog::level::level_enum::info;
  } else if (log_level_string == "error") {
    level = spdlog::level::level_enum::err;
  } else if (log_level_string == "critical") {
    level = spdlog::level::level_enum::critical;
  } else {
    spdlog::error("{}: Unexpected log_level config '{}': must be one of [trace, debug, info, error, critical]",
                  __func__, log_level_string);
    abort();
  }

  return level;
}

std::string GetConfiguredAddress(const authservice::config::Config& config) {
  std::stringstream address_string_builder;

  address_string_builder << config.listen_address() << ":" << std::dec
                         << config.listen_port();
  auto address = address_string_builder.str();
  return address;
}

}  // namespace config
}  // namespace authservice

ext: cc

max_stars_repo_name: blockspacer/authservice

max_issues_repo_name: blockspacer/authservice

max_forks_repo_name: blockspacer/authservice


text:
// Copyright 2019 Hans Dembinski
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_HISTOGRAM_DETAIL_SAFE_COMPARISON_HPP
#define BOOST_HISTOGRAM_DETAIL_SAFE_COMPARISON_HPP

#include <boost/mp11/utility.hpp>
#include <boost/type.hpp>
#include <type_traits>

namespace boost {
namespace histogram {
namespace detail {

template <class T>
auto make_unsigned(const T& t) noexcept {
  static_assert(std::is_integral<T>::value, "");
  return static_cast<std::make_unsigned_t<T>>(t);
}

template <class T>
using number_category =
    mp11::mp_if<std::is_integral<T>,
                mp11::mp_if<std::is_signed<T>, type<int>, type<unsigned>>, type<void>>;

// version of std::equal_to<> which handles signed and unsigned integers correctly
struct safe_equal {
  template <class T, class U>
  bool operator()(const T& t, const U& u) const noexcept {
    return impl(number_category<T>{}, number_category<U>{}, t, u);
  }

  template <class C1, class C2, class T, class U>
  bool impl(C1, C2, const T& t, const U& u) const noexcept {
    return t == u;
  }

  template <class T, class U>
  bool impl(type<int>, type<unsigned>, const T& t, const U& u) const noexcept {
    return t >= 0 && make_unsigned(t) == u;
  }

  template <class T, class U>
  bool impl(type<unsigned>, type<int>, const T& t, const U& u) const noexcept {
    return impl(type<int>{}, type<unsigned>{}, u, t);
  }
};

// version of std::less<> which handles signed and unsigned integers correctly
struct safe_less {
  template <class T, class U>
  bool operator()(const T& t, const U& u) const noexcept {
    return impl(number_category<T>{}, number_category<U>{}, t, u);
  }

  template <class C1, class C2, class T, class U>
  bool impl(C1, C2, const T& t, const U& u) const noexcept {
    return t < u;
  }

  template <class T, class U>
  bool impl(type<int>, type<unsigned>, const T& t, const U& u) const noexcept {
    return t < 0 || make_unsigned(t) < u;
  }

  template <class T, class U>
  bool impl(type<unsigned>, type<int>, const T& t, const U& u) const noexcept {
    return 0 < u && t < make_unsigned(u);
  }
};

// version of std::greater<> which handles signed and unsigned integers correctly
struct safe_greater {
  template <class T, class U>
  bool operator()(const T& t, const U& u) const noexcept {
    return safe_less()(u, t);
  }
};

} // namespace detail
} // namespace histogram
} // namespace boost

#endif


text:
// ---------------------------------------------------------------------
//
// Copyright (c) 2014 - 2020 by the IBAMR developers
// All rights reserved.
//
// This file is part of IBAMR.
//
// IBAMR is free software and is distributed under the 3-clause BSD
// license. The full text of the license can be found in the file
// COPYRIGHT at the top level directory of IBAMR.
//
// ---------------------------------------------------------------------

/////////////////////////////// INCLUDES /////////////////////////////////////

#include "ibamr/IBInstrumentPanel.h"
#include "ibamr/IBInstrumentationSpec.h"
#include "ibamr/ibamr_utilities.h"

#include "ibtk/IBTK_CHKERRQ.h"
#include "ibtk/IBTK_MPI.h"
#include "ibtk/IndexUtilities.h"
#include "ibtk/LData.h"
#include "ibtk/LDataManager.h"
#include "ibtk/LMesh.h"
#include "ibtk/LNode.h"
#include "ibtk/ibtk_utilities.h"

#include "BasePatchLevel.h"
#include "Box.h"
#include "BoxArray.h"
#include "CartesianGridGeometry.h"
#include "CartesianPatchGeometry.h"
#include "CellData.h"
#include "CellIndex.h"
#include "Index.h"
#include "IntVector.h"
#include "Patch.h"
#include "PatchHierarchy.h"
#include "PatchLevel.h"
#include "SideData.h"
#include "SideIndex.h"
#include "tbox/Database.h"
#include "tbox/MathUtilities.h"
#include "tbox/PIO.h"
#include "tbox/Pointer.h"
#include "tbox/RestartManager.h"
#include "tbox/Timer.h"
#include "tbox/TimerManager.h"
#include "tbox/Utilities.h"

#include "petscvec.h"

#include "ibamr/namespaces.h" // IWYU pragma: keep

IBTK_DISABLE_EXTRA_WARNINGS
#include <boost/multi_array.hpp>
IBTK_ENABLE_EXTRA_WARNINGS

IBTK_DISABLE_EXTRA_WARNINGS
#include "Eigen/Geometry" // IWYU pragma: keep
IBTK_ENABLE_EXTRA_WARNINGS

#include <algorithm>
#include <array>
#include <cmath>
#include <fstream>
#include <limits>
#include <string>
#include <utility>
#include <vector>

#if defined(IBAMR_HAVE_SILO)
#include <silo.h>
#endif

/////////////////////////////// NAMESPACE ////////////////////////////////////

namespace IBAMR
{
/////////////////////////////// STATIC ///////////////////////////////////////

namespace
{
// Timers.
static Timer* t_initialize_hierarchy_independent_data;
static Timer* t_initialize_hierarchy_dependent_data;
static Timer* t_read_instrument_data;
static Timer* t_write_plot_data;

// The rank of the root MPI process and the MPI tag number.
static const unsigned int SILO_MPI_ROOT = 0;

// The name of the Silo dumps and database filenames.
static const int SILO_NAME_BUFSIZE = 128;
static const std::string VISIT_DUMPS_FILENAME = "meter_data.visit";
static const std::string SILO_DUMP_DIR_PREFIX = "meter_data.cycle_";
static const std::string SILO_SUMMARY_FILE_PREFIX = "meter_data.cycle_";
static const std::string SILO_SUMMARY_FILE_POSTFIX = ".summary.silo";
static const std::string SILO_PROCESSOR_FILE_PREFIX = "meter_data.proc_";
static const std::string SILO_PROCESSOR_FILE_POSTFIX = ".silo";

void
init_meter_elements(boost::multi_array<Point, 2>& X_web,
                    boost::multi_array<Vector, 2>& dA_web,
                    const boost::multi_array<Point, 1>& X_perimeter,
                    const Point& X_centroid)
{
#if (NDIM == 2)
    TBOX_ERROR("no support for 2D flow meters at this time!\n");
    NULL_USE(X_web);
    NULL_USE(dA_web);
    NULL_USE(X_perimeter);
    NULL_USE(X_centroid);
#endif
#if (NDIM == 3)
#if !defined(NDEBUG)
    TBOX_ASSERT(X_web.shape()[0] == X_perimeter.shape()[0]);
    TBOX_ASSERT(dA_web.shape()[0] == X_perimeter.shape()[0]);
#endif
    const int num_perimeter_nodes = static_cast<int>(X_web.shape()[0]);
    const int num_web_nodes = static_cast<int>(X_web.shape()[1]);
    for (int m = 0; m < num_perimeter_nodes; ++m)
    {
        const Point& X_perimeter0(X_perimeter[m]);
        const Vector dX0((X_centroid - X_perimeter0) / static_cast<double>(num_web_nodes));

        const Point& X_perimeter1(X_perimeter[(m + 1) % num_perimeter_nodes]);
        const Vector dX1((X_centroid - X_perimeter1) / static_cast<double>(num_web_nodes));

        // Away from the center of the web, each web patch is a planar
        // quadrilateral.  At the web centroid, the quadrilateral is degenerate,
        // i.e., it is a triangle.
        for (int n = 0; n < num_web_nodes; ++n)
        {
            // Compute the four vertices of the quadrilateral web patch.
            //
            // Note that here the vertices are placed in "standard" (i.e.,
            // "counter-clockwise") orientation.
            const Point X0(X_perimeter0 + static_cast<double>(n) * dX0);
            const Point X1(X_perimeter1 + static_cast<double>(n) * dX1);
            const Point X2(X_perimeter1 + static_cast<double>(n + 1) * dX1);
            const Point X3(X_perimeter0 + static_cast<double>(n + 1) * dX0);

            // Compute the midpoints of the edges of the quadrilateral.
            const Point X01(0.5 * (X0 + X1));
            const Point X12(0.5 * (X1 + X2));
            const Point X23(0.5 * (X2 + X3));
            const Point X30(0.5 * (X3 + X0));

            // Construct a parametric representation of the lines connecting the
            // midpoints of the edges.
            const Point& l0 = X01;
            const Vector d0 = X23 - X01;

            const Point& l1 = X12;
            const Vector d1 = X30 - X12;

            // Compute the centroid as the intersection of the lines connecting
            // the midpoints of the edges.
            const double d0d0 = d0.dot(d0);
            const double d0d1 = d0.dot(d1);
            const double d1d1 = d1.dot(d1);
            const double d0l0 = d0.dot(l0);
            const double d0l1 = d0.dot(l1);
            const double d1l0 = d1.dot(l0);
            const double d1l1 = d1.dot(l1);
            const double t = (-d0l0 * d1d1 + d0l1 * d1d1 + d0d1 * d1l0 - d0d1 * d1l1) / (-d0d1 * d0d1 + d1d1 * d0d0);
            const double s = (d1l0 * d0d0 - d0d1 * d0l0 + d0d1 * d0l1 - d1l1 * d0d0) / (-d0d1 * d0d1 + d1d1 * d0d0);
            X_web[m][n] = 0.5 * (l0 + t * d0 + l1 + s * d1);

            // Compute the area-weighted normal to the quadrilateral web patch,
            // i.e.,
            //
            //    dA = 0.5*((X2-X0) X (X3-X1))
            //
            // Note that by construction, the quadrilateral is guaranteed to lie
            // within a plane.  Also, note that if X2 == X3, the following is
            // simply the formula for the area-weighted normal to a triangle.
            dA_web[m][n] = 0.5 * (X2 - X0).cross(X3 - X1);
        }
    }
#endif
    return;
} // init_meter_elements

double
compute_flow_correction(const boost::multi_array<Vector, 1>& U_perimeter,
                        const Vector& U_centroid,
                        const boost::multi_array<Point, 1>& X_perimeter,
                        const Point& X_centroid)
{
    double U_dot_dA = 0.0;
#if (NDIM == 2)
    TBOX_ERROR("no support for 2D flow meters at this time!\n");
    NULL_USE(U_perimeter);
    NULL_USE(U_centroid);
    NULL_USE(X_perimeter);
    NULL_USE(X_centroid);
#endif
#if (NDIM == 3)
    const int num_perimeter_nodes = static_cast<int>(X_perimeter.shape()[0]);
    for (int m = 0; m < num_perimeter_nodes; ++m)
    {
        const Vector& U_perimeter0(U_perimeter[m]);
        const Point& X_perimeter0(X_perimeter[m]);

        const Vector& U_perimeter1(U_perimeter[(m + 1) % num_perimeter_nodes]);
        const Point& X_perimeter1(X_perimeter[(m + 1) % num_perimeter_nodes]);

        // Compute the linear interpolation of the velocity at the center of the
        // triangle.
        const Vector U = (U_perimeter0 + U_perimeter1 + U_centroid) / 3.0;

        // Compute the area weighted normal to the triangle.
        const Vector dA = 0.5 * (X_centroid - X_perimeter0).cross(X_centroid - X_perimeter1);

        // Compute the contribution to U_dot_dA.
        U_dot_dA += U.dot(dA);
    }
#endif
    return U_dot_dA;
} // compute_flow_correction

#if defined(IBAMR_HAVE_SILO)
/*!
 * \brief Build a local mesh database entry corresponding to a meter web.
 */
void
build_meter_web(DBfile* dbfile,
                std::string& dirname,
                const boost::multi_array<Point, 2>& X_web,
                const boost::multi_array<Vector, 2>& dA_web,
                const int timestep,
                const double simulation_time)
{
    const int npoints = static_cast<int>(X_web.num_elements());

    std::vector<float> block_X(NDIM * npoints);
    std::vector<float> block_dA(NDIM * npoints);

    for (unsigned int m = 0, i = 0; m < X_web.shape()[0]; ++m)
    {
        for (unsigned int n = 0; n < X_web.shape()[1]; ++n, ++i)
        {
            // Get the coordinate and normal vector data.
            for (unsigned int d = 0; d < NDIM; ++d)
            {
                block_X[d * npoints + i] = static_cast<float>(X_web[m][n][d]);
                block_dA[d * npoints + i] = static_cast<float>(dA_web[m][n][d]);
            }
        }
    }

    // Set the working directory in the Silo database.
    if (DBSetDir(dbfile, dirname.c_str()) == -1)
    {
        TBOX_ERROR("IBInstrumentPanel::build_meter_web():\n"
                   << "  Could not set directory " << dirname << std::endl);
    }

    // Write out the variables.
    int cycle = timestep;
    auto time = static_cast<float>(simulation_time);
    double dtime = simulation_time;

    static const int MAX_OPTS = 3;
    DBoptlist* optlist = DBMakeOptlist(MAX_OPTS);
    DBAddOption(optlist, DBOPT_CYCLE, &cycle);
    DBAddOption(optlist, DBOPT_TIME, &time);
    DBAddOption(optlist, DBOPT_DTIME, &dtime);

    const char* meshname = "mesh";
    std::vector<float*> coords(NDIM);
    for (unsigned int d = 0; d < NDIM; ++d)
    {
        coords[d] = &block_X[d * npoints];
    }

    int ndims = NDIM;

    DBPutPointmesh(dbfile, meshname, ndims, &coords[0], npoints, DB_FLOAT, optlist);

    const char* varname = "scaled_normal";
    std::vector<float*> vars(NDIM);
    for (unsigned int d = 0; d < NDIM; ++d)
    {
        vars[d] = &block_dA[d * npoints];
    }

    DBPutPointvar(dbfile, varname, meshname, ndims, &vars[0], npoints, DB_FLOAT, optlist);

    DBFreeOptlist(optlist);

    // Reset the working directory in the Silo database.
    if (DBSetDir(dbfile, "..") == -1)
    {
        TBOX_ERROR("IBInstrumentPanel::build_meter_web():\n"
                   << "  Could not return to the base directory from subdirectory " << dirname << std::endl);
    }
    return;
} // build_meter_web
#endif

double
linear_interp(const Point& X,
              const hier::Index<NDIM>& i_cell,
              const Point& X_cell,
              const CellData<NDIM, double>& v,
              const hier::Index<NDIM>& /*patch_lower*/,
              const hier::Index<NDIM>& /*patch_upper*/,
              const double* const /*x_lower*/,
              const double* const /*x_upper*/,
              const double* const dx)
{
    std::array<bool, NDIM> is_lower;
    for (unsigned int d = 0; d < NDIM; ++d)
    {
        is_lower[d] = X[d] < X_cell[d];
    }
    double U = 0.0;
#if (NDIM == 3)
    for (int i_shift2 = (is_lower[2] ? -1 : 0); i_shift2 <= (is_lower[2] ? 0 : 1); ++i_shift2)
    {
#endif
        for (int i_shift1 = (is_lower[1] ? -1 : 0); i_shift1 <= (is_lower[1] ? 0 : 1); ++i_shift1)
        {
            for (int i_shift0 = (is_lower[0] ? -1 : 0); i_shift0 <= (is_lower[0] ? 0 : 1); ++i_shift0)
            {
                const Point X_center(X_cell[0] + static_cast<double>(i_shift0) * dx[0],
                                     X_cell[1] + static_cast<double>(i_shift1) * dx[1]
#if (NDIM == 3)
                                     ,
                                     X_cell[2] + static_cast<double>(i_shift2) * dx[2]
#endif
                );
                const double wgt =
                    (((X[0] < X_center[0] ? X[0] - (X_center[0] - dx[0]) : (X_center[0] + dx[0]) - X[0]) / dx[0]) *
                     ((X[1] < X_center[1] ? X[1] - (X_center[1] - dx[1]) : (X_center[1] + dx[1]) - X[1]) / dx[1])
#if (NDIM == 3)
                     * ((X[2] < X_center[2] ? X[2] - (X_center[2] - dx[2]) : (X_center[2] + dx[2]) - X[2]) / dx[2])
#endif
                    );
                const hier::Index<NDIM> i(i_shift0 + i_cell(0),
                                          i_shift1 + i_cell(1)
#if (NDIM == 3)
                                              ,
                                          i_shift2 + i_cell(2)
#endif
                );
                const CellIndex<NDIM> i_c(i);
                U += v(i_c) * wgt;
            }
        }
#if (NDIM == 3)
    }
#endif
    return U;
} // linear_interp

template <int N>
Eigen::Matrix<double, N, 1>
linear_interp(const Point& X,
              const hier::Index<NDIM>& i_cell,
              const Point& X_cell,
              const CellData<NDIM, double>& v,
              const hier::Index<NDIM>& /*patch_lower*/,
              const hier::Index<NDIM>& /*patch_upper*/,
              const double* const /*x_lower*/,
              const double* const /*x_upper*/,
              const double* const dx)
{
#if !defined(NDEBUG)
    TBOX_ASSERT(v.getDepth() == N);
#endif
    std::array<bool, NDIM> is_lower;
    for (unsigned int d = 0; d < NDIM; ++d)
    {
        is_lower[d] = X[d] < X_cell[d];
    }
    Eigen::Matrix<double, N, 1> U(Eigen::Matrix<double, N, 1>::Zero());
#if (NDIM == 3)
    for (int i_shift2 = (is_lower[2] ? -1 : 0); i_shift2 <= (is_lower[2] ? 0 : 1); ++i_shift2)
    {
#endif
        for (int i_shift1 = (is_lower[1] ? -1 : 0); i_shift1 <= (is_lower[1] ? 0 : 1); ++i_shift1)
        {
            for (int i_shift0 = (is_lower[0] ? -1 : 0); i_shift0 <= (is_lower[0] ? 0 : 1); ++i_shift0)
            {
                const Point X_center(X_cell[0] + static_cast<double>(i_shift0) * dx[0],
                                     X_cell[1] + static_cast<double>(i_shift1) * dx[1]
#if (NDIM == 3)
                                     ,
                                     X_cell[2] + static_cast<double>(i_shift2) * dx[2]
#endif
                );
                const double wgt =
                    (((X[0] < X_center[0] ? X[0] - (X_center[0] - dx[0]) : (X_center[0] + dx[0]) - X[0]) / dx[0]) *
                     ((X[1] < X_center[1] ? X[1] - (X_center[1] - dx[1]) : (X_center[1] + dx[1]) - X[1]) / dx[1])
#if (NDIM == 3)
                     * ((X[2] < X_center[2] ? X[2] - (X_center[2] - dx[2]) : (X_center[2] + dx[2]) - X[2]) / dx[2])
#endif
                    );
                const hier::Index<NDIM> i(i_shift0 + i_cell(0),
                                          i_shift1 + i_cell(1)
#if (NDIM == 3)
                                              ,
                                          i_shift2 + i_cell(2)
#endif
                );
                const CellIndex<NDIM> i_c(i);
                for (int k = 0; k < N; ++k)
                {
                    U[k] += v(i_c, k) * wgt;
                }
            }
        }
#if (NDIM == 3)
    }
#endif
    return U;
} // linear_interp

Vector
linear_interp(const Point& X,
              const hier::Index<NDIM>& i_cell,
              const Point& X_cell,
              const SideData<NDIM, double>& v,
              const hier::Index<NDIM>& /*patch_lower*/,
              const hier::Index<NDIM>& /*patch_upper*/,
              const double* const /*x_lower*/,
              const double* const /*x_upper*/,
              const double* const dx)
{
#if !defined(NDEBUG)
    TBOX_ASSERT(v.getDepth() == 1);
#endif
    Vector U(Vector::Zero());
    for (unsigned int axis = 0; axis < NDIM; ++axis)
    {
        std::array<bool, NDIM> is_lower;
        for (unsigned int d = 0; d < NDIM; ++d)
        {
            if (d == axis)
            {
                is_lower[d] = false;
            }
            else
            {
                is_lower[d] = X[d] < X_cell[d];
            }
        }
#if (NDIM == 3)
        for (int i_shift2 = (is_lower[2] ? -1 : 0); i_shift2 <= (is_lower[2] ? 0 : 1); ++i_shift2)
        {
#endif
            for (int i_shift1 = (is_lower[1] ? -1 : 0); i_shift1 <= (is_lower[1] ? 0 : 1); ++i_shift1)
            {
                for (int i_shift0 = (is_lower[0] ? -1 : 0); i_shift0 <= (is_lower[0] ? 0 : 1); ++i_shift0)
                {
                    const Point X_side(X_cell[0] + (static_cast<double>(i_shift0) + (axis == 0 ? -0.5 : 0.0)) * dx[0],
                                       X_cell[1] + (static_cast<double>(i_shift1) + (axis == 1 ? -0.5 : 0.0)) * dx[1]
#if (NDIM == 3)
                                       ,
                                       X_cell[2] + (static_cast<double>(i_shift2) + (axis == 2 ? -0.5 : 0.0)) * dx[2]
#endif
                    );
                    const double wgt =
                        (((X[0] < X_side[0] ? X[0] - (X_side[0] - dx[0]) : (X_side[0] + dx[0]) - X[0]) / dx[0]) *
                         ((X[1] < X_side[1] ? X[1] - (X_side[1] - dx[1]) : (X_side[1] + dx[1]) - X[1]) / dx[1])
#if (NDIM == 3)
                         * ((X[2] < X_side[2] ? X[2] - (X_side[2] - dx[2]) : (X_side[2] + dx[2]) - X[2]) / dx[2])
#endif
                        );
                    const hier::Index<NDIM> i(i_shift0 + i_cell(0),
                                              i_shift1 + i_cell(1)
#if (NDIM == 3)
                                                  ,
                                              i_shift2 + i_cell(2)
#endif
                    );
                    const SideIndex<NDIM> i_s(i, axis, SideIndex<NDIM>::Lower);
                    U[axis] += v(i_s) * wgt;
                }
            }
#if (NDIM == 3)
        }
#endif
    }
    return U;
} // linear_interp
} // namespace

/////////////////////////////// PUBLIC ///////////////////////////////////////

IBInstrumentPanel::IBInstrumentPanel(std::string object_name, Pointer<Database> input_db)
    : d_object_name(std::move(object_name)),
      d_plot_directory_name(NDIM == 2 ? "viz_inst2d" : "viz_inst3d"),
      d_log_file_name(NDIM == 2 ? "inst2d.log" : "inst3d.log")
{
#if defined(IBAMR_HAVE_SILO)
// intentionally blank
#else
    TBOX_WARNING("IBInstrumentPanel::IBInstrumentPanel(): SILO is not installed; cannot write data." << std::endl);
#endif

    // Initialize object with data read from the input database.
    if (input_db) getFromInput(input_db);

    // Setup Timers.
    IBAMR_DO_ONCE(
        t_initialize_hierarchy_independent_data =
            TimerManager::getManager()->getTimer("IBAMR::IBInstrumentPanel::initializeHierarchyIndependentData()");
        t_initialize_hierarchy_dependent_data =
            TimerManager::getManager()->getTimer("IBAMR::IBInstrumentPanel::initializeHierarchyDependentData()");
        t_read_instrument_data = TimerManager::getManager()->getTimer("IBAMR::IBInstrumentPanel::readInstrumentData()");
        t_write_plot_data = TimerManager::getManager()->getTimer("IBAMR::IBInstrumentPanel::writePlotData()"););
    return;
} // IBInstrumentPanel

IBInstrumentPanel::~IBInstrumentPanel()
{
    // Close the log file stream.
    if (IBTK_MPI::getRank() == 0)
    {
        d_log_file_stream.close();
    }
    return;
} // ~IBInstrumentPanel

const std::vector<std::string>&
IBInstrumentPanel::getInstrumentNames() const
{
    return d_instrument_names;
} // getInstrumentNames

const double&
IBInstrumentPanel::getInstrumentDataReadTime() const
{
    return d_instrument_read_time;
} // getInstrumentDataReadTime

const std::vector<double>&
IBInstrumentPanel::getFlowValues() const
{
    return d_flow_values;
} // getFlowValues

const std::vector<double>&
IBInstrumentPanel::getMeanPressureValues() const
{
    return d_mean_pres_values;
} // getMeanPressureValues

const std::vector<double>&
IBInstrumentPanel::getPointwisePressureValues() const
{
    return d_point_pres_values;
} // getPointwisePressureValues

bool
IBInstrumentPanel::isInstrumented() const
{
    if (!d_initialized)
    {
        TBOX_WARNING(d_object_name << "::isInstrumented():\n"
                                   << "  instrument data has not been initialized." << std::endl);
        return false;
    }
    return (d_num_meters > 0);
} // isInstrumented

void
IBInstrumentPanel::initializeHierarchyIndependentData(const Pointer<PatchHierarchy<NDIM> > hierarchy,
                                                      LDataManager* const l_data_manager)
{
    IBAMR_TIMER_START(t_initialize_hierarchy_independent_data);

    const int coarsest_ln = 0;
    const int finest_ln = hierarchy->getFinestLevelNumber();

    // Determine how many flow meters/pressure gauges are present in the local
    // data.
    int max_meter_index = -1;
    std::vector<int> max_node_index;
    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)
    {
        if (l_data_manager->levelContainsLagrangianData(ln))
        {
            const Pointer<LMesh> mesh = l_data_manager->getLMesh(ln);
            const std::vector<LNode*>& local_nodes = mesh->getLocalNodes();
            for (const auto& node_idx : local_nodes)
            {
                const IBInstrumentationSpec* const spec = node_idx->getNodeDataItem<IBInstrumentationSpec>();
                if (spec)
                {
                    const int m = spec->getMeterIndex();
                    max_meter_index = std::max(m, max_meter_index);

                    const int n = spec->getNodeIndex();
                    max_node_index.resize(max_meter_index + 1, -1);
                    max_node_index[m] = std::max(n, max_node_index[m]);
                }
            }
        }
    }

    // Communicate local data to all processes.
    d_num_meters = IBTK_MPI::maxReduction(max_meter_index) + 1;
    max_node_index.resize(d_num_meters, -1);
    d_num_perimeter_nodes.clear();
    d_num_perimeter_nodes.resize(d_num_meters, -1);
    for (unsigned int m = 0; m < d_num_meters; ++m)
    {
        d_num_perimeter_nodes[m] = max_node_index[m] + 1;
    }
    IBTK_MPI::maxReduction(d_num_meters > 0 ? &d_num_perimeter_nodes[0] : nullptr, d_num_meters);
#if !defined(NDEBUG)
    for (unsigned int m = 0; m < d_num_meters; ++m)
    {
        TBOX_ASSERT(d_num_perimeter_nodes[m] > 0);
    }
#endif

    // Resize arrays.
    d_X_centroid.resize(d_num_meters);
    d_X_perimeter.resize(d_num_meters);
    for (unsigned int m = 0; m < d_num_meters; ++m)
    {
        d_X_perimeter[m].resize(boost::extents[d_num_perimeter_nodes[m]]);
    }
    d_X_web.resize(d_num_meters);
    d_dA_web.resize(d_num_meters);
    d_instrument_names = IBInstrumentationSpec::getInstrumentNames();
    if (d_instrument_names.size() != d_num_meters)
    {
        TBOX_WARNING(d_object_name << "::initializeHierarchyIndependentData():\n"
                                   << "  instrument names are not initialized\n"
                                   << "  using default names" << std::endl);
        d_instrument_names.resize(d_num_meters);
        for (unsigned int m = 0; m < d_num_meters; ++m)
        {
            d_instrument_names[m] = "meter_" + std::to_string(m);
        }
        IBInstrumentationSpec::setInstrumentNames(d_instrument_names);
    }
    d_flow_values.resize(d_num_meters, std::numeric_limits<double>::quiet_NaN());
    d_mean_pres_values.resize(d_num_meters, std::numeric_limits<double>::quiet_NaN());
    d_point_pres_values.resize(d_num_meters, std::numeric_limits<double>::quiet_NaN());

    // Open the log file stream.
    d_max_instrument_name_len = 0;
    for (unsigned int m = 0; m < d_num_meters; ++m)
    {
        d_max_instrument_name_len =
            std::max(d_max_instrument_name_len, static_cast<int>(d_instrument_names[m].length()));
    }

    if (d_output_log_file && IBTK_MPI::getRank() == 0 && !d_log_file_stream.is_open())
    {
        const bool from_restart = RestartManager::getManager()->isFromRestart();
        if (from_restart)
        {
            d_log_file_stream.open(d_log_file_name.c_str(), std::ios::app);
        }
        else
        {
            d_log_file_stream.open(d_log_file_name.c_str(), std::ios::out);
            if (d_flow_units != "") d_log_file_stream << "flow units: " << d_flow_units << "    ";
            if (d_pres_units != "") d_log_file_stream << "pressure units: " << d_pres_units << "    ";
            if (d_flow_units != "" || d_pres_units != "") d_log_file_stream << "\n";
            d_log_file_stream << std::string(d_max_instrument_name_len, ' ') << "  time       "
                              << "  x_centroid "
                              << "  y_centroid " << (NDIM == 3 ? "  z_centroid " : "") << "  flow rate   "
                              << "  mean pres.  "
                              << "  point pres. "
                              << "\n";
        }
    }

    // Indicate that the hierarchy-independent data has been initialized.
    d_initialized = true;

    IBAMR_TIMER_STOP(t_initialize_hierarchy_independent_data);
    return;
} // initializeHierarchyIndependentData

void
IBInstrumentPanel::initializeHierarchyDependentData(const Pointer<PatchHierarchy<NDIM> > hierarchy,
                                                    LDataManager* const l_data_manager,
                                                    const int timestep_num,
                                                    const double data_time)
{
    if (!d_initialized)
    {
        initializeHierarchyIndependentData(hierarchy, l_data_manager);
    }
    if (d_num_meters == 0) return;

    IBAMR_TIMER_START(t_initialize_hierarchy_dependent_data);

    const int coarsest_ln = 0;
    const int finest_ln = hierarchy->getFinestLevelNumber();

    // Keep track of the timestep number and time at which the instrument data
    // was collected.
    d_instrument_read_timestep_num = timestep_num;
    d_instrument_read_time = data_time;

    // Loop over all local nodes to determine the positions of the local
    // perimeter nodes.
    for (unsigned int m = 0; m < d_num_meters; ++m)
    {
        for (int n = 0; n < d_num_perimeter_nodes[m]; ++n)
        {
            d_X_perimeter[m][n] = Point::Zero();
        }
    }
    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)
    {
        if (l_data_manager->levelContainsLagrangianData(ln))
        {
            // Extract the local position array.
            Pointer<LData> X_data = l_data_manager->getLData(LDataManager::POSN_DATA_NAME, ln);
            Vec X_vec = X_data->getVec();
            double* X_arr;
            int ierr = VecGetArray(X_vec, &X_arr);
            IBTK_CHKERRQ(ierr);

            // Store the local positions of the perimeter nodes.
            const Pointer<LMesh> mesh = l_data_manager->getLMesh(ln);
            const std::vector<LNode*>& local_nodes = mesh->getLocalNodes();
            for (const auto& node_idx : local_nodes)
            {
                const IBInstrumentationSpec* const spec = node_idx->getNodeDataItem<IBInstrumentationSpec>();
                if (spec)
                {
                    const int& petsc_idx = node_idx->getLocalPETScIndex();
                    const double* const X = &X_arr[NDIM * petsc_idx];
                    const int m = spec->getMeterIndex();
                    const int n = spec->getNodeIndex();
                    std::copy(X, X + NDIM, d_X_perimeter[m][n].data());
                }
            }

            // Restore the local position array.
            ierr = VecGetArray(X_vec, &X_arr);
            IBTK_CHKERRQ(ierr);
        }
    }

    // Set the positions of all perimeter nodes on all processes.
    std::vector<double> X_perimeter_flattened;
    for (unsigned int m = 0; m < d_num_meters; ++m)
    {
        for (int n = 0; n < d_num_perimeter_nodes[m]; ++n)
        {
            X_perimeter_flattened.insert(
                X_perimeter_flattened.end(), d_X_perimeter[m][n].data(), d_X_perimeter[m][n].data() + NDIM);
        }
    }
    IBTK_MPI::sumReduction(&X_perimeter_flattened[0], static_cast<int>(X_perimeter_flattened.size()));
    for (unsigned int m = 0, k = 0; m < d_num_meters; ++m)
    {
        for (int n = 0; n < d_num_perimeter_nodes[m]; ++n, ++k)
        {
            std::copy(&X_perimeter_flattened[NDIM * k],
                      (&X_perimeter_flattened[NDIM * k]) + NDIM,
                      d_X_perimeter[m][n].data());
        }
    }

    // Determine the centroid of each perimeter.
    std::fill(d_X_centroid.begin(), d_X_centroid.end(), Point::Zero());
    for (unsigned int m = 0; m < d_num_meters; ++m)
    {
        for (int n = 0; n < d_num_perimeter_nodes[m]; ++n)
        {
            d_X_centroid[m] += d_X_perimeter[m][n];
        }
        d_X_centroid[m] /= static_cast<double>(d_num_perimeter_nodes[m]);
    }

    // Determine the maximum distance from perimeter nodes to centroids.
    std::vector<double> r_max(d_num_meters, 0.0);
    for (unsigned int m = 0; m < d_num_meters; ++m)
    {
        for (int n = 0; n < d_num_perimeter_nodes[m]; ++n)
        {
            const Vector r(d_X_perimeter[m][n] - d_X_centroid[m]);
            r_max[m] = std::max(r_max[m], r.norm());
        }
    }

    // Determine the finest grid spacing in the Cartesian grid hierarchy.
    Pointer<CartesianGridGeometry<NDIM> > grid_geom = hierarchy->getGridGeometry();
    const double* const domainXLower = grid_geom->getXLower();
    const double* const domainXUpper = grid_geom->getXUpper();
    const double* const dx_coarsest = grid_geom->getDx();
    TBOX_ASSERT(grid_geom->getDomainIsSingleBox());
    const Box<NDIM> domain_box = grid_geom->getPhysicalDomain()[0];

    const IntVector<NDIM>& ratio_to_level_zero = hierarchy->getPatchLevel(finest_ln)->getRatio();
    std::array<double, NDIM> dx_finest;
    for (unsigned int d = 0; d < NDIM; ++d)
    {
        dx_finest[d] = dx_coarsest[d] / static_cast<double>(ratio_to_level_zero(d));
    }
    const double h_finest = *std::min_element(dx_finest.begin(), dx_finest.end());

    // Build the meter web patch centroids and area elements.
    //
    // Note that we set the number of web nodes in each meter to that the
    // spacing is approximately half a meshwidth on the finest level of the
    // Cartesian grid hierarchy.
    for (unsigned int m = 0; m < d_num_meters; ++m)
    {
        const int num_web_nodes = 2 * static_cast<int>(ceil(r_max[m] / h_finest));
        d_X_web[m].resize(boost::extents[d_num_perimeter_nodes[m]][num_web_nodes]);
        d_dA_web[m].resize(boost::extents[d_num_perimeter_nodes[m]][num_web_nodes]);
        init_meter_elements(d_X_web[m], d_dA_web[m], d_X_perimeter[m], d_X_centroid[m]);
    }

    // Setup the mappings from cell indices to the web patch and web centroid
    // data.
    //
    // NOTE: Each meter web patch/centroid is assigned to precisely one
    // Cartesian grid cell in precisely one level.  In particular, each web
    // patch is assigned to whichever grid cell is the finest cell that contains
    // the region of physical space in which the centroid of the web patch is
    // located.  Similarly, each web centroid is assigned to which ever grid
    // cell is the finest cell that contains the region of physical space in
    // which the web centroid is located.
    d_web_patch_map.clear();
    d_web_patch_map.resize(finest_ln + 1);
    d_web_centroid_map.clear();
    d_web_centroid_map.resize(finest_ln + 1);
    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)
    {
        Pointer<PatchLevel<NDIM> > level = hierarchy->getPatchLevel(ln);
        const IntVector<NDIM>& ratio = level->getRatio();
        const Box<NDIM> domain_box_level = Box<NDIM>::refine(domain_box, ratio);
        const hier::Index<NDIM>& domain_box_level_lower = domain_box_level.lower();
        const hier::Index<NDIM>& domain_box_level_upper = domain_box_level.upper();
        std::array<double, NDIM> dx;
        for (unsigned int d = 0; d < NDIM; ++d)
        {
            dx[d] = dx_coarsest[d] / static_cast<double>(ratio(d));
        }

        Pointer<PatchLevel<NDIM> > finer_level =
            (ln < finest_ln ? hierarchy->getPatchLevel(ln + 1) : Pointer<BasePatchLevel<NDIM> >(nullptr));
        const IntVector<NDIM>& finer_ratio = (ln < finest_ln ? finer_level->getRatio() : IntVector<NDIM>(1));
        const Box<NDIM> finer_domain_box_level = Box<NDIM>::refine(domain_box, finer_ratio);
        const hier::Index<NDIM>& finer_domain_box_level_lower = finer_domain_box_level.lower();
        const hier::Index<NDIM>& finer_domain_box_level_upper = finer_domain_box_level.upper();
        std::array<double, NDIM> finer_dx;
        for (unsigned int d = 0; d < NDIM; ++d)
        {
            finer_dx[d] = dx_coarsest[d] / static_cast<double>(finer_ratio(d));
        }

        for (unsigned int l = 0; l < d_num_meters; ++l)
        {
            // Setup the web patch mapping.
            for (unsigned int m = 0; m < d_X_web[l].shape()[0]; ++m)
            {
                for (unsigned int n = 0; n < d_X_web[l].shape()[1]; ++n)
                {
                    const Point& X = d_X_web[l][m][n];
                    const hier::Index<NDIM> i = IndexUtilities::getCellIndex(
                        X, domainXLower, domainXUpper, dx.data(), domain_box_level_lower, domain_box_level_upper);
                    const hier::Index<NDIM> finer_i = IndexUtilities::getCellIndex(X,
                                                                                domainXLower,
                                                                                domainXUpper,
                                                                                finer_dx.data(),
                                                                                finer_domain_box_level_lower,
                                                                                finer_domain_box_level_upper);
                    if (level->getBoxes().contains(i) &&
                        (ln == finest_ln || !finer_level->getBoxes().contains(finer_i)))
                    {
                        WebPatch p;
                        p.meter_num = l;
                        p.X = &d_X_web[l][m][n];
                        p.dA = &d_dA_web[l][m][n];
                        d_web_patch_map[ln].insert(std::make_pair(i, p));
                    }
                }
            }

            // Setup the web centroid mapping.
            const Point& X = d_X_centroid[l];
            const hier::Index<NDIM> i = IndexUtilities::getCellIndex(
                X, domainXLower, domainXUpper, dx.data(), domain_box_level_lower, domain_box_level_upper);
            const hier::Index<NDIM> finer_i = IndexUtilities::getCellIndex(X,
                                                                           domainXLower,
                                                                           domainXUpper,
                                                                           finer_dx.data(),
                                                                           finer_domain_box_level_lower,
                                                                           finer_domain_box_level_upper);
            if (level->getBoxes().contains(i) && (ln == finest_ln || !finer_level->getBoxes().contains(finer_i)))
            {
                WebCentroid c;
                c.meter_num = l;
                c.X = &d_X_centroid[l];
                d_web_centroid_map[ln].insert(std::make_pair(i, c));
            }
        }
    }

    IBAMR_TIMER_STOP(t_initialize_hierarchy_dependent_data);
    return;
} // initializeHierarchyDependentData

void
IBInstrumentPanel::readInstrumentData(const int U_data_idx,
                                      const int P_data_idx,
                                      const Pointer<PatchHierarchy<NDIM> > hierarchy,
                                      LDataManager* const l_data_manager,
                                      const int timestep_num,
                                      const double data_time)
{
    if (d_num_meters == 0) return;

    IBAMR_TIMER_START(t_read_instrument_data);

    const int coarsest_ln = 0;
    const int finest_ln = hierarchy->getFinestLevelNumber();

    // Ensure we are collecting data at the
    if (timestep_num != d_instrument_read_timestep_num)
    {
        TBOX_ERROR(d_object_name << "::readInstrumentData():\n"
                                 << "  time step number: " << timestep_num
                                 << " is != instrumentation time step number: " << d_instrument_read_timestep_num
                                 << std::endl);
    }

    if (!MathUtilities<double>::equalEps(data_time, d_instrument_read_time))
    {
        TBOX_ERROR(d_object_name << "::readInstrumentData():\n"
                                 << "  data read time: " << data_time
                                 << " is != instrumentation data read time: " << d_instrument_read_time << std::endl);
    }

    // Reset the instrument values.
    std::fill(d_flow_values.begin(), d_flow_values.end(), 0.0);
    std::fill(d_mean_pres_values.begin(), d_mean_pres_values.end(), 0.0);
    std::fill(d_point_pres_values.begin(), d_point_pres_values.end(), 0.0);
    std::vector<double> A(d_num_meters, 0.0);

    // Compute the local contributions to the flux of U through the flow meter,
    // the average value of P in the flow meter, and the pointwise value of P at
    // the centroid of the meter.
    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)
    {
        Pointer<PatchLevel<NDIM> > level = hierarchy->getPatchLevel(ln);
        for (PatchLevel<NDIM>::Iterator p(level); p; p++)
        {
            Pointer<Patch<NDIM> > patch = level->getPatch(p());
            const Box<NDIM>& patch_box = patch->getBox();
            const hier::Index<NDIM>& patch_lower = patch_box.lower();
            const hier::Index<NDIM>& patch_upper = patch_box.upper();

            const Pointer<CartesianPatchGeometry<NDIM> > pgeom = patch->getPatchGeometry();
            const double* const x_lower = pgeom->getXLower();
            const double* const x_upper = pgeom->getXUpper();
            const double* const dx = pgeom->getDx();

            Pointer<CellData<NDIM, double> > U_cc_data = patch->getPatchData(U_data_idx);
            Pointer<SideData<NDIM, double> > U_sc_data = patch->getPatchData(U_data_idx);
            Pointer<CellData<NDIM, double> > P_cc_data = patch->getPatchData(P_data_idx);

            for (Box<NDIM>::Iterator b(patch_box); b; b++)
            {
                const hier::Index<NDIM>& i = b();
                std::pair<WebPatchMap::const_iterator, WebPatchMap::const_iterator> patch_range =
                    d_web_patch_map[ln].equal_range(i);
                if (patch_range.first != patch_range.second)
                {
                    const Point X_cell(x_lower[0] + dx[0] * (static_cast<double>(i(0) - patch_lower(0)) + 0.5),
                                       x_lower[1] + dx[1] * (static_cast<double>(i(1) - patch_lower(1)) + 0.5)
#if (NDIM == 3)
                                           ,
                                       x_lower[2] + dx[2] * (static_cast<double>(i(2) - patch_lower(2)) + 0.5)
#endif
                    );
                    if (U_cc_data)
                    {
                        for (auto it = patch_range.first; it != patch_range.second; ++it)
                        {
                            const int& meter_num = it->second.meter_num;
                            const Point& X = *(it->second.X);
                            const Vector& dA = *(it->second.dA);
                            const Vector U = linear_interp<NDIM>(
                                X, i, X_cell, *U_cc_data, patch_lower, patch_upper, x_lower, x_upper, dx);
                            d_flow_values[meter_num] += U.dot(dA);
                        }
                    }
                    if (U_sc_data)
                    {
                        for (auto it = patch_range.first; it != patch_range.second; ++it)
                        {
                            const int& meter_num = it->second.meter_num;
                            const Point& X = *(it->second.X);
                            const Vector& dA = *(it->second.dA);
                            const Vector U =
                                linear_interp(X, i, X_cell, *U_sc_data, patch_lower, patch_upper, x_lower, x_upper, dx);
                            d_flow_values[meter_num] += U.dot(dA);
                        }
                    }
                    if (P_cc_data)
                    {
                        for (auto it = patch_range.first; it != patch_range.second; ++it)
                        {
                            const int& meter_num = it->second.meter_num;
                            const Point& X = *(it->second.X);
                            const Vector& dA = *(it->second.dA);
                            double P =
                                linear_interp(X, i, X_cell, *P_cc_data, patch_lower, patch_upper, x_lower, x_upper, dx);
                            d_mean_pres_values[meter_num] += P * dA.norm();
                            A[meter_num] += dA.norm();
                        }
                    }
                }

                std::pair<WebCentroidMap::const_iterator, WebCentroidMap::const_iterator> centroid_range =
                    d_web_centroid_map[ln].equal_range(i);
                if (centroid_range.first != centroid_range.second)
                {
                    const Point X_cell(x_lower[0] + dx[0] * (static_cast<double>(i(0) - patch_lower(0)) + 0.5),
                                       x_lower[1] + dx[1] * (static_cast<double>(i(1) - patch_lower(1)) + 0.5)
#if (NDIM == 3)
                                           ,
                                       x_lower[2] + dx[2] * (static_cast<double>(i(2) - patch_lower(2)) + 0.5)
#endif
                    );
                    if (P_cc_data)
                    {
                        for (auto it = centroid_range.first; it != centroid_range.second; ++it)
                        {
                            const int& meter_num = it->second.meter_num;
                            const Point& X = *(it->second.X);
                            const double P =
                                linear_interp(X, i, X_cell, *P_cc_data, patch_lower, patch_upper, x_lower, x_upper, dx);
                            d_point_pres_values[meter_num] = P;
                        }
                    }
                }
            }
        }
    }

    // Synchronize the values across all processes.
    IBTK_MPI::sumReduction(&d_flow_values[0], d_num_meters);
    IBTK_MPI::sumReduction(&d_mean_pres_values[0], d_num_meters);
    IBTK_MPI::sumReduction(&d_point_pres_values[0], d_num_meters);
    IBTK_MPI::sumReduction(&A[0], d_num_meters);

    // Normalize the mean pressure.
    for (unsigned int m = 0; m < d_num_meters; ++m)
    {
        d_mean_pres_values[m] /= A[m];
    }

    // Loop over all local nodes to determine the velocities of the local
    // perimeter nodes.
    std::vector<boost::multi_array<Vector, 1> > U_perimeter(d_num_meters);
    for (unsigned int m = 0; m < d_num_meters; ++m)
    {
        U_perimeter[m].resize(boost::extents[d_num_perimeter_nodes[m]]);
        for (int n = 0; n < d_num_perimeter_nodes[m]; ++n)
        {
            U_perimeter[m][n] = Vector::Zero();
        }
    }
    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)
    {
        if (l_data_manager->levelContainsLagrangianData(ln))
        {
            // Extract the local velocity array.
            Pointer<LData> U_data = l_data_manager->getLData(LDataManager::VEL_DATA_NAME, ln);
            Vec U_vec = U_data->getVec();
            double* U_arr;
            int ierr = VecGetArray(U_vec, &U_arr);
            IBTK_CHKERRQ(ierr);

            // Store the local velocities of the perimeter nodes.
            const Pointer<LMesh> mesh = l_data_manager->getLMesh(ln);
            const std::vector<LNode*>& local_nodes = mesh->getLocalNodes();
            for (const auto& node_idx : local_nodes)
            {
                const IBInstrumentationSpec* const spec = node_idx->getNodeDataItem<IBInstrumentationSpec>();
                if (spec)
                {
                    const int& petsc_idx = node_idx->getLocalPETScIndex();
                    const double* const U = &U_arr[NDIM * petsc_idx];
                    const int m = spec->getMeterIndex();
                    const int n = spec->getNodeIndex();
                    std::copy(U, U + NDIM, U_perimeter[m][n].data());
                }
            }

            // Restore the local position array.
            ierr = VecGetArray(U_vec, &U_arr);
            IBTK_CHKERRQ(ierr);
        }
    }

    // Set the velocities of all perimeter nodes on all processes.
    std::vector<double> U_perimeter_flattened;
    for (unsigned int m = 0; m < d_num_meters; ++m)
    {
        for (int n = 0; n < d_num_perimeter_nodes[m]; ++n)
        {
            U_perimeter_flattened.insert(
                U_perimeter_flattened.end(), U_perimeter[m][n].data(), U_perimeter[m][n].data() + NDIM);
        }
    }
    IBTK_MPI::sumReduction(&U_perimeter_flattened[0], static_cast<int>(U_perimeter_flattened.size()));
    for (unsigned int m = 0, k = 0; m < d_num_meters; ++m)
    {
        for (int n = 0; n < d_num_perimeter_nodes[m]; ++n, ++k)
        {
            std::copy(
                &U_perimeter_flattened[NDIM * k], (&U_perimeter_flattened[NDIM * k]) + NDIM, U_perimeter[m][n].data());
        }
    }

    // Determine the velocity of the centroid of each perimeter.
    std::vector<Vector> U_centroid(d_num_meters, Vector::Zero());
    for (unsigned int m = 0; m < d_num_meters; ++m)
    {
        for (int n = 0; n < d_num_perimeter_nodes[m]; ++n)
        {
            U_centroid[m] += U_perimeter[m][n];
        }
        U_centroid[m] /= static_cast<double>(d_num_perimeter_nodes[m]);
    }

    // Correct for the relative motion of the flow meters.
    for (unsigned int m = 0; m < d_num_meters; ++m)
    {
        d_flow_values[m] -= compute_flow_correction(U_perimeter[m], U_centroid[m], d_X_perimeter[m], d_X_centroid[m]);
    }

    // Output meter data.
    plog << std::string(d_max_instrument_name_len + 94, '*') << "\n";
    plog << d_object_name << "::readInstrumentData():\n";
    plog << std::string(d_max_instrument_name_len, ' ') << "  time       "
         << "  x_centroid "
         << "  y_centroid " << (NDIM == 3 ? "  z_centroid " : "") << "  flow rate   "
         << "  mean pres.  "
         << "  point pres. "
         << "\n";

    outputLogData(plog);
    if (d_flow_units != "") plog << "flow units: " << d_flow_units << "    ";
    if (d_pres_units != "") plog << "pressure units: " << d_pres_units;
    if (d_flow_units != "" || d_pres_units != "") plog << "\n";
    plog << std::string(d_max_instrument_name_len + 94, '*') << "\n";

    if (d_output_log_file && IBTK_MPI::getRank() == 0)
    {
        outputLogData(d_log_file_stream);
        d_log_file_stream.flush();
    }

    IBAMR_TIMER_STOP(t_read_instrument_data);
    return;
} // readInstrumentData

void
IBInstrumentPanel::setPlotDirectory(const std::string& plot_directory_name)
{
    d_plot_directory_name = plot_directory_name;
    return;
} // setPlotDirectory

void
IBInstrumentPanel::writePlotData(const int timestep_num, const double simulation_time)
{
    if (d_num_meters == 0) return;

    IBAMR_TIMER_START(t_write_plot_data);
#if defined(IBAMR_HAVE_SILO)
#if !defined(NDEBUG)
    TBOX_ASSERT(timestep_num >= 0);
    TBOX_ASSERT(!d_plot_directory_name.empty());
#endif

    if (timestep_num != d_instrument_read_timestep_num)
    {
        TBOX_ERROR(d_object_name << "::writePlotData():\n"
                                 << "  time step number: " << timestep_num
                                 << " is != last time step number: " << d_instrument_read_timestep_num << std::endl);
    }

    if (d_plot_directory_name.empty())
    {
        TBOX_ERROR(d_object_name << "::writePlotData():\n"
                                 << "  dump directory name is empty" << std::endl);
    }

    char temp_buf[SILO_NAME_BUFSIZE];
    std::string current_file_name;
    DBfile* dbfile;
    const int mpi_rank = IBTK_MPI::getRank();
    const int mpi_nodes = IBTK_MPI::getNodes();

    // Create the working directory.
    sprintf(temp_buf, "%06d", d_instrument_read_timestep_num);
    std::string current_dump_directory_name = SILO_DUMP_DIR_PREFIX + temp_buf;
    std::string dump_dirname = d_plot_directory_name + "/" + current_dump_directory_name;

    Utilities::recursiveMkdir(dump_dirname);

    // Create one local DBfile per MPI process.
    sprintf(temp_buf, "%04d", mpi_rank);
    current_file_name = dump_dirname + "/" + SILO_PROCESSOR_FILE_PREFIX;
    current_file_name += temp_buf;
    current_file_name += SILO_PROCESSOR_FILE_POSTFIX;

    if (!(dbfile = DBCreate(current_file_name.c_str(), DB_CLOBBER, DB_LOCAL, nullptr, DB_PDB)))
    {
        TBOX_ERROR(d_object_name + "::writePlotData():\n"
                   << "  Could not create DBfile named " << current_file_name << std::endl);
    }

    // Output the web data on the available MPI processes.
    for (unsigned int meter = 0; meter < d_num_meters; ++meter)
    {
        if (static_cast<int>(meter) % mpi_nodes == mpi_rank)
        {
            std::string dirname = d_instrument_names[meter];
            if (DBMkDir(dbfile, dirname.c_str()) == -1)
            {
                TBOX_ERROR(d_object_name + "::writePlotData():\n"
                           << "  Could not create directory named " << dirname << std::endl);
            }
            build_meter_web(dbfile, dirname, d_X_web[meter], d_dA_web[meter], timestep_num, simulation_time);
        }
    }

    DBClose(dbfile);

    if (mpi_rank == SILO_MPI_ROOT)
    {
        // Create and initialize the multimesh Silo database on the root MPI
        // process.
        sprintf(temp_buf, "%06d", d_instrument_read_timestep_num);
        std::string summary_file_name =
            dump_dirname + "/" + SILO_SUMMARY_FILE_PREFIX + temp_buf + SILO_SUMMARY_FILE_POSTFIX;
        if (!(dbfile = DBCreate(summary_file_name.c_str(), DB_CLOBBER, DB_LOCAL, nullptr, DB_PDB)))
        {
            TBOX_ERROR(d_object_name + "::writePlotData():\n"
                       << "  Could not create DBfile named " << summary_file_name << std::endl);
        }

        int cycle = timestep_num;
        auto time = static_cast<float>(simulation_time);
        double dtime = simulation_time;

        static const int MAX_OPTS = 3;
        DBoptlist* optlist = DBMakeOptlist(MAX_OPTS);
        DBAddOption(optlist, DBOPT_CYCLE, &cycle);
        DBAddOption(optlist, DBOPT_TIME, &time);
        DBAddOption(optlist, DBOPT_DTIME, &dtime);

        for (unsigned int meter = 0; meter < d_num_meters; ++meter)
        {
            const int proc = meter % mpi_nodes;
            sprintf(temp_buf, "%04d", proc);
            current_file_name = SILO_PROCESSOR_FILE_PREFIX;
            current_file_name += temp_buf;
            current_file_name += SILO_PROCESSOR_FILE_POSTFIX;

            std::string meshname = current_file_name + ":" + d_instrument_names[meter] + "/mesh";
            auto meshname_ptr = const_cast<char*>(meshname.c_str());
            int meshtype = DB_POINTMESH;

            std::string meter_name = d_instrument_names[meter];

            DBPutMultimesh(dbfile, meter_name.c_str(), 1, &meshname_ptr, &meshtype, optlist);

            if (DBMkDir(dbfile, meter_name.c_str()) == -1)
            {
                TBOX_ERROR(d_object_name + "::writePlotData():\n"
                           << "  Could not create directory named " << meter_name << std::endl);
            }

            std::string varname = current_file_name + ":" + d_instrument_names[meter] + "/scaled_normal";
            auto varname_ptr = const_cast<char*>(varname.c_str());
            int vartype = DB_POINTVAR;

            std::string var_name = d_instrument_names[meter] + "_normal";

            DBPutMultivar(dbfile, var_name.c_str(), 1, &varname_ptr, &vartype, optlist);
        }

        DBClose(dbfile);

        // Create or update the dumps file on the root MPI process.
        static bool summary_file_opened = false;
        std::string path = d_plot_directory_name + "/" + VISIT_DUMPS_FILENAME;
        sprintf(temp_buf, "%06d", d_instrument_read_timestep_num);
        std::string file =
            current_dump_directory_name + "/" + SILO_SUMMARY_FILE_PREFIX + temp_buf + SILO_SUMMARY_FILE_POSTFIX;
        if (!summary_file_opened)
        {
            summary_file_opened = true;
            std::ofstream sfile(path.c_str(), std::ios::out);
            sfile << file << std::endl;
            sfile.close();
        }
        else
        {
            std::ofstream sfile(path.c_str(), std::ios::app);
            sfile << file << std::endl;
            sfile.close();
        }
    }
#else
    NULL_USE(timestep_num);
    NULL_USE(simulation_time);
    TBOX_WARNING("IBInstrumentPanel::writePlotData(): SILO is not installed; cannot write data." << std::endl);
#endif // if defined(IBAMR_HAVE_SILO)
    IBAMR_TIMER_STOP(t_write_plot_data);
    return;
} // writePlotData

/////////////////////////////// PROTECTED ////////////////////////////////////

/////////////////////////////// PRIVATE //////////////////////////////////////

void
IBInstrumentPanel::getFromInput(Pointer<Database> db)
{
#if !defined(NDEBUG)
    TBOX_ASSERT(db);
#endif
    if (db->keyExists("plot_directory_name")) d_plot_directory_name = db->getString("plot_directory_name");
    if (db->keyExists("output_log_file")) d_output_log_file = db->getBool("output_log_file");
    if (d_output_log_file)
    {
        if (db->keyExists("log_file_name")) d_log_file_name = db->getString("log_file_name");
    }
    if (db->keyExists("flow_conv")) d_flow_conv = db->getDouble("flow_conv");
    if (db->keyExists("pres_conv")) d_pres_conv = db->getDouble("pres_conv");
    if (db->keyExists("flow_units")) d_flow_units = db->getString("flow_units");
    if (db->keyExists("pres_units")) d_pres_units = db->getString("pres_units");
    return;
} // getFromInput

void
IBInstrumentPanel::outputLogData(std::ostream& os)
{
    for (unsigned int m = 0; m < d_num_meters; ++m)
    {
        std::string meter_name(d_instrument_names[m]);
        meter_name.resize(d_max_instrument_name_len, ' ');
        os << meter_name;

        os.setf(std::ios_base::scientific);
        os.precision(5);
        os << "  " << d_instrument_read_time;

        os.setf(std::ios_base::scientific);
        os.precision(5);
        os << "  " << d_X_centroid[m][0];
        os.setf(std::ios_base::scientific);
        os.precision(5);
        os << "  " << d_X_centroid[m][1];
#if (NDIM == 3)
        os.setf(std::ios_base::scientific);
        os.precision(5);
        os << "  " << d_X_centroid[m][2];
#endif

        os.setf(std::ios_base::scientific);
        os.setf(std::ios_base::showpos);
        os.precision(5);
        os << "  " << d_flow_conv * d_flow_values[m];

        os.setf(std::ios_base::scientific);
        os.setf(std::ios_base::showpos);
        os.precision(5);
        os << "  " << d_pres_conv * d_mean_pres_values[m];

        os.setf(std::ios_base::scientific);
        os.setf(std::ios_base::showpos);
        os.precision(5);
        os << "  " << d_pres_conv * d_point_pres_values[m];

        os << "\n";

        os.unsetf(std::ios_base::scientific);
        os.unsetf(std::ios_base::showpos);
    }
    return;
} // outputLogData

/////////////////////////////// NAMESPACE ////////////////////////////////////

} // namespace IBAMR

//////////////////////////////////////////////////////////////////////////////

max_stars_repo_name: alexkaiser/IBAMR

max_issues_repo_name: alexkaiser/IBAMR

max_forks_repo_name: alexkaiser/IBAMR


text:
//
// Copyright (c) 2013-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef BEAST_HTTP_IMPL_MESSAGE_IPP
#define BEAST_HTTP_IMPL_MESSAGE_IPP

#include <beast/core/error.hpp>
#include <beast/http/concepts.hpp>
#include <beast/http/rfc7230.hpp>
#include <beast/core/detail/ci_char_traits.hpp>
#include <beast/core/detail/type_traits.hpp>
#include <boost/assert.hpp>
#include <boost/optional.hpp>
#include <stdexcept>

namespace beast {
namespace http {

template<class Fields>
void
swap(
    header<true, Fields>& m1,
    header<true, Fields>& m2)
{
    using std::swap;
    swap(m1.version, m2.version);
    swap(m1.method, m2.method);
    swap(m1.url, m2.url);
    swap(m1.fields, m2.fields);
}

template<class Fields>
void
swap(
    header<false, Fields>& a,
    header<false, Fields>& b)
{
    using std::swap;
    swap(a.version, b.version);
    swap(a.status, b.status);
    swap(a.reason, b.reason);
    swap(a.fields, b.fields);
}

template<bool isRequest, class Body, class Fields>
void
swap(
    message<isRequest, Body, Fields>& m1,
    message<isRequest, Body, Fields>& m2)
{
    using std::swap;
    swap(m1.base(), m2.base());
    swap(m1.body, m2.body);
}

template<bool isRequest, class Fields>
bool
is_keep_alive(header<isRequest, Fields> const& msg)
{
    BOOST_ASSERT(msg.version == 10 || msg.version == 11);
    if(msg.version == 11)
    {
        if(token_list{msg.fields["Connection"]}.exists("close"))
            return false;
        return true;
    }
    if(token_list{msg.fields["Connection"]}.exists("keep-alive"))
        return true;
    return false;
}

template<bool isRequest, class Fields>
bool
is_upgrade(header<isRequest, Fields> const& msg)
{
    BOOST_ASSERT(msg.version == 10 || msg.version == 11);
    if(msg.version == 10)
        return false;
    if(token_list{msg.fields["Connection"]}.exists("upgrade"))
        return true;
    return false;
}

namespace detail {

struct prepare_info
{
    boost::optional<connection> connection_value;
    boost::optional<std::uint64_t> content_length;
};

template<bool isRequest, class Body, class Fields>
inline
void
prepare_options(prepare_info& pi,
    message<isRequest, Body, Fields>& msg)
{
    beast::detail::ignore_unused(pi, msg);
}

template<bool isRequest, class Body, class Fields>
void
prepare_option(prepare_info& pi,
    message<isRequest, Body, Fields>& msg,
        connection value)
{
    beast::detail::ignore_unused(msg);
    pi.connection_value = value;
}

template<
    bool isRequest, class Body, class Fields,
    class Opt, class... Opts>
void
prepare_options(prepare_info& pi,
    message<isRequest, Body, Fields>& msg,
        Opt&& opt, Opts&&... opts)
{
    prepare_option(pi, msg, opt);
    prepare_options(pi, msg,
        std::forward<Opts>(opts)...);
}

template<bool isRequest, class Body, class Fields>
void
prepare_content_length(prepare_info& pi,
    message<isRequest, Body, Fields> const& msg,
        std::true_type)
{
    typename Body::writer w(msg);
    // VFALCO This is a design problem!
    error_code ec;
    w.init(ec);
    if(ec)
        throw system_error{ec};
    pi.content_length = w.content_length();
}

template<bool isRequest, class Body, class Fields>
void
prepare_content_length(prepare_info& pi,
    message<isRequest, Body, Fields> const& msg,
        std::false_type)
{
    beast::detail::ignore_unused(msg);
    pi.content_length = boost::none;
}

} // detail

template<
    bool isRequest, class Body, class Fields,
    class... Options>
void
prepare(message<isRequest, Body, Fields>& msg,
    Options&&... options)
{
    using beast::detail::make_exception;

    // VFALCO TODO
    static_assert(is_Body<Body>::value,
        "Body requirements not met");
    static_assert(has_writer<Body>::value,
        "Body has no writer");
    static_assert(is_Writer<typename Body::writer,
        message<isRequest, Body, Fields>>::value,
            "Writer requirements not met");
    detail::prepare_info pi;
    detail::prepare_content_length(pi, msg,
        detail::has_content_length<typename Body::writer>{});
    detail::prepare_options(pi, msg,
        std::forward<Options>(options)...);

    if(msg.fields.exists("Connection"))
        throw make_exception<std::invalid_argument>(
            "prepare called with Connection field set", __FILE__, __LINE__);

    if(msg.fields.exists("Content-Length"))
        throw make_exception<std::invalid_argument>(
            "prepare called with Content-Length field set", __FILE__, __LINE__);

    if(token_list{msg.fields["Transfer-Encoding"]}.exists("chunked"))
        throw make_exception<std::invalid_argument>(
            "prepare called with Transfer-Encoding: chunked set", __FILE__, __LINE__);

    if(pi.connection_value != connection::upgrade)
    {
        if(pi.content_length)
        {
            struct set_field
            {
                void
                operator()(message<true, Body, Fields>& msg,
                    detail::prepare_info const& pi) const
                {
                    using beast::detail::ci_equal;
                    if(*pi.content_length > 0 ||
                        ci_equal(msg.method, "POST"))
                    {
                        msg.fields.insert(
                            "Content-Length", *pi.content_length);
                    }
                }

                void
                operator()(message<false, Body, Fields>& msg,
                    detail::prepare_info const& pi) const
                {
                    if((msg.status / 100 ) != 1 &&
                        msg.status != 204 &&
                        msg.status != 304)
                    {
                        msg.fields.insert(
                            "Content-Length", *pi.content_length);
                    }
                }
            };
            set_field{}(msg, pi);
        }
        else if(msg.version >= 11)
        {
            msg.fields.insert("Transfer-Encoding", "chunked");
        }
    }

    auto const content_length =
        msg.fields.exists("Content-Length");

    if(pi.connection_value)
    {
        switch(*pi.connection_value)
        {
        case connection::upgrade:
            msg.fields.insert("Connection", "upgrade");
            break;

        case connection::keep_alive:
            if(msg.version < 11)
            {
                if(content_length)
                    msg.fields.insert("Connection", "keep-alive");
            }
            break;

        case connection::close:
            if(msg.version >= 11)
                msg.fields.insert("Connection", "close");
            break;
        }
    }

    // rfc7230 6.7.
    if(msg.version < 11 && token_list{
            msg.fields["Connection"]}.exists("upgrade"))
        throw make_exception<std::invalid_argument>(
            "invalid version for Connection: upgrade", __FILE__, __LINE__);
}

} // http
} // beast

#endif

ext: ipp

max_stars_repo_name: MassICTBV/casinocoind

max_issues_repo_name: MassICTBV/casinocoind

max_forks_repo_name: MassICTBV/casinocoind


text:
#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>

#include "asiohandler.h"

int main(void)
{
    boost::asio::io_service ioService;
    AsioHandler handler(ioService);
    handler.connect("localhost", 5672);

    AMQP::Connection connection(&handler, AMQP::Login("guest", "guest"), "/");

    AMQP::Channel channel(&connection);
    auto receiveMessageCallback = [](const AMQP::Message &message,
            uint64_t deliveryTag,
            bool redelivered)
    {

        std::cout <<" [x] "<<message.message() << std::endl;
    };

    AMQP::QueueCallback callback =
            [&](const std::string &name, int msgcount, int consumercount)
            {
                channel.bindQueue("logs", name,"");
                channel.consume(name, AMQP::noack).onReceived(receiveMessageCallback);
            };

    AMQP::SuccessCallback success = [&]()
            {
                channel.declareQueue(AMQP::exclusive).onSuccess(callback);
            };

    channel.declareExchange("logs", AMQP::fanout).onSuccess(success);

    std::cout << " [*] Waiting for messages. To exit press CTRL-C\n";

    ioService.run();
    return 0;
}