text:
/*ckwg +29
 * Copyright 2011-2013 by Kitware, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 *  * 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.
 *
 *  * Neither name of Kitware, Inc. nor the names of any 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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "print_number_process.h"

#include <sprokit/pipeline_util/path.h>

#include <sprokit/pipeline/config.h>
#include <sprokit/pipeline/process_exception.h>

#include <boost/filesystem/fstream.hpp>
#include <boost/cstdint.hpp>

#include <string>

/**
 * \file print_number_process.cxx
 *
 * \brief Implementation of the number printer process.
 */

namespace sprokit
{

class print_number_process::priv
{
  public:
    typedef int32_t number_t;

    priv(path_t const& output_path);
    ~priv();

    path_t const path;

    boost::filesystem::ofstream fout;

    static config::key_t const config_path;
    static port_t const port_input;
};

config::key_t const print_number_process::priv::config_path = config::key_t("output");
process::port_t const print_number_process::priv::port_input = port_t("number");

print_number_process
::print_number_process(config_t const& config)
  : process(config)
  , d()
{
  declare_configuration_key(
    priv::config_path,
    config::value_t(),
    config::description_t("The path of the file to output to."));

  port_flags_t required;

  required.insert(flag_required);

  declare_input_port(
    priv::port_input,
    "integer",
    required,
    port_description_t("Where numbers are read from."));
}

print_number_process
::~print_number_process()
{
}

void
print_number_process
::_configure()
{
  // Configure the process.
  {
    path_t const path = config_value<path_t>(priv::config_path);

    d.reset(new priv(path));
  }

  if (d->path.empty())
  {
    static std::string const reason = "The path given was empty";
    config::value_t const value = d->path.string<config::value_t>();

    throw invalid_configuration_value_exception(name(), priv::config_path, value, reason);
  }

  d->fout.open(d->path);

  if (!d->fout.good())
  {
    std::string const file_path = d->path.string<std::string>();
    std::string const reason = "Failed to open the path: " + file_path;

    throw invalid_configuration_exception(name(), reason);
  }

  process::_configure();
}

void
print_number_process
::_reset()
{
  d->fout.close();

  process::_reset();
}

void
print_number_process
::_step()
{
  priv::number_t const input = grab_from_port_as<priv::number_t>(priv::port_input);

  d->fout << input << std::endl;

  process::_step();
}

print_number_process::priv
::priv(path_t const& output_path)
  : path(output_path)
  , fout()
{
}

print_number_process::priv
::~priv()
{
}

}

ext: cxx

max_stars_repo_name: linus-sherrill/sprokit

max_issues_repo_name: linus-sherrill/sprokit

max_forks_repo_name: linus-sherrill/sprokit


text: #include <boost/geometry/strategies/geographic/disjoint_segment_box.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


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

#include <cstdlib>
#include <iostream>

#include <boost/context/all.hpp>

namespace ctx=boost::context;

ctx::execution_context * other = nullptr;

int main() {
    ctx::execution_context ctx1( ctx::fixedsize_stack(),
               [] () mutable {
                    std::cout << "ctx1 started" << std::endl;
                    ( * other)();
                    std::cout << "ctx1 will terminate" << std::endl;
               });
    ctx::execution_context ctx2( ctx::fixedsize_stack(),
               [&ctx1] () mutable {
                    std::cout << "ctx2 started" << std::endl;
                    ctx1();
                    std::cout << "ctx2 will terminate" << std::endl;
               });
    ctx::execution_context ctx3( ctx::fixedsize_stack(),
               [&ctx1, &ctx2] () mutable {
                    std::cout << "ctx3 started" << std::endl;
                    ctx2();
                    ctx1();
                    std::cout << "ctx3 will terminate" << std::endl;
               });
    other = & ctx3;
    ctx3();

    std::cout << "main: done" << std::endl;

    return EXIT_SUCCESS;
}

ext: cpp


text:
// Copyright 2014-2015 SDL plc
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//     http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**

   \file

   applyYaml(yamlRootNode, &rootConfiguration) will initialize
   rootConfiguration, update its values as specified by yamlRootNode, and
   validate them. You don't even need to create a ConfigureYaml object yourself.

   (see docs/configuration-xmt-library.md to see how to specify
   rootConfiguration's initialization and transfer from yamlRootNode)

   TODO: allow configure() library to exclude certain options as being cmdline only?

   TODO: effectiveYAML: return a YAML config object that would give current values (with and without defaults)
*/

#ifndef CONFIGURE_JG2012615_HPP
#define CONFIGURE_JG2012615_HPP
#pragma once

#ifndef SDL_NFC_NORMALIZE_CONFIGURE
#define SDL_NFC_NORMALIZE_CONFIGURE 1
#endif

#ifndef SDL_ALLOW_NON_STRING_MAP_KEY_CONFIGURE
#define SDL_ALLOW_NON_STRING_MAP_KEY_CONFIGURE 1
#endif

#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4146)
#endif
#include <yaml-cpp/yaml.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include <sdl/Config/Config.hpp>
#include <sdl/Util/FormattedOstream.hpp>
#include <sdl/Util/Nfc.hpp>
#include <sdl/Util/Unordered.hpp>
#include <sdl/Util/Warn.hpp>
#include <sdl/LexicalCast.hpp>
#include <sdl/Printer.hpp>
#include <boost/noncopyable.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <graehl/shared/configure.hpp>

namespace sdl {
namespace Config {

#if SDL_NFC_NORMALIZE_CONFIGURE
typedef Util::NfcStringRef YamlScalarRef;
#else
typedef std::string const& YamlScalarRef;
#endif

struct ConfigureYaml;

/** \return string quoted in help format - human readable, not parseable. */
inline std::string helpQuoteStringScalar(std::string const& s) {
  std::string r(1, '"');
  r.append(s).push_back('"');
  return r;
}

/** \return string quoted in YAML scalar string format. */
inline std::string yamlQuoteStringScalar(std::string const& s) {
  return sdl::lexical_cast<std::string>(ConfigNode(s));
}

// actions:
using configure::init_config;
using configure::store_config;
using configure::validate_config;
// construct w/ ostream:
using configure::show_effective_config;
using configure::help_config;
using configure::show_example_config;  // TODO: output YAML

// free fns:
using configure::configure_action;
using configure::validate_stored;

/** a configure library backend that maintains a stack of ConfigNode (aka YAML
   subtree) for store_action. Also provides YAML-like formatting for help and
   show_effective actions.
 */
struct ConfigureYaml : configure::configure_backend_base<ConfigureYaml> {
 private:
  typedef configure::configure_backend_base<ConfigureYaml> Base;
  unsigned endColumn, minUsageIndent;
  void defaults() {
    endColumn = 80;
    minUsageIndent = 16;
  }

 public:
  friend inline unsigned max_column(ConfigureYaml const& x) { return x.endColumn; }
  /** for store action, need Yaml ConfigNode. */
  ConfigureYaml(ConfigNode const& root, StringConsumer const& warn)  // = Util::logWarning("configure")
      : Base(warn),
        ctx(new Context()),
        root(root) {
    defaults();
  }
  /** for non-store actions only. */
  explicit ConfigureYaml(StringConsumer const& warn, int verbosity = 0) : Base(warn), ctx(), root() {
    verbose_max = verbosity;
    defaults();
  }

  void setRoot(ConfigNode const& rootNode) {
    ctx.reset(new Context());
    root = rootNode;
  }

  /// the rest of this class is configure-library implementation (not for the library user)
  static inline std::string quote(std::string const& s) { return yamlQuoteStringScalar(s); }

  /// the rest of this class is configure-library implementation (not for the library user)
  static inline std::string help_quote(std::string const& s) { return helpQuoteStringScalar(s); }

 private:
  enum { kWarnOnMissingRequired = false, kThrowOnMissingRequired = true };
  typedef configure::conf_expr_base Conf;
  typedef configure::conf_opt Opt;
  friend struct configure::configure_backend_base<ConfigureYaml>;

  static inline void print_name_val(std::ostream& o, std::string const& name, std::string const& val) {
    o << name << ": " << val;
  }

  unsigned print_usage(std::ostream& out, std::string const& usage, unsigned startColumn,
                       unsigned indentColumn) const {
    indentColumn += 4;
    if (indentColumn < minUsageIndent) indentColumn = minUsageIndent;
    std::string indent(indentColumn, ' ');
    if (startColumn) out << '\n';
    return Util::printFormatted(out, usage, indent, indent, endColumn);
  }

  static inline std::string option_name(configure::conf_expr_base const& conf) { return conf.name(); }

  typedef std::map<std::string, YAML::Node> ChildMap;
  typedef ChildMap::value_type ChildPair;
  typedef configure::conf_opt::allow_unrecognized_args UnrecognizedOpt;

  /** For tree_action nodes need keeping track of unrecognized options. We put
      these on a stack alongside the ConfigureYaml objects. For leaf vector/map
      nodes we also have an item on stack and may recurse to other tree or leaf
      actions, even though technically vector and map are leaves */
  struct Subtree {
    ConfigNode root;
    bool exists() const { return !is_null(root); }

    /** for missing/dup key errors. */
    StringConsumer warn;
    std::string pathname;  // TODO: build including sequence/open-map key in path (not using conf.path_name())
    std::string fullname(std::string const& key) const {
      return (pathname.empty() ? "" : (pathname + ".")) + key;
    }
    std::string rootstr() const { return (pathname.empty() ? "<ROOT>" : pathname) + ": " + to_string(root); }

    /** contained is a one-shot register set by "leaf" map and string for each
       of the values, which we cannot look up by a pathname in configure() space
       (the keys are arbitrary).
     */
    boost::optional<ConfigNode> contained;

    /// \return get root[key], !IsDefined() if not found. error if root is defined, non-null, non-map
    ConfigNode node(std::string const& key, bool required = false, bool requiredThrow = true) {
      if (!is_null(root)) {
        if (!root.IsMap())
          trouble("Key '" + key + "' missing - can't find in non-map YAML node: " + rootstr(), true);
        ChildMap::iterator i = unprocessedMapChildren.find(key);
        if (i != unprocessedMapChildren.end()) {
          ConfigNode r = i->second;
          unprocessedMapChildren.erase(i);
          return r;
        } else if (required)
          trouble("Key '" + key + "' missing from YAML node: " + rootstr(), requiredThrow);
      }
      return ConfigNode(YAML::NodeType::Undefined);
    }

    /** a yaml map's entries are stored here, but after we use each one we remove it.

        what remain at finish() might be typos, and get stored in unrecognizedOpt (or give an error if those
       aren't allowed)
    */
    ChildMap unprocessedMapChildren;

    UnrecognizedOpt unrecognizedOpt;

    /// any child of a non-required struct that has no yaml path for it gets
    /// ignored in the store phase (if you want an error for a missing node it
    /// needs to be .require()
    bool nothingToStore;

    Subtree(ConfigNode const& n, std::string const& pathname, StringConsumer const& warn, bool nothingToStore)
        : root(n)
        , pathname(pathname)
        , warn(warn)
        , unrecognizedOpt(false)
        , nothingToStore(nothingToStore)
        , finished(false) {
      if (n.IsMap()) {
        for (YAML::const_iterator i = n.begin(), e = n.end(); i != e; ++i) {
          YamlScalarRef key = i->first.Scalar();
          if (!Util::supplyMissing(unprocessedMapChildren, key, i->second))
            trouble(fullname(key) + " duplicated in YAML map; " + "was: " + (std::string const&)key + ": "
                        + to_string(i->second) + ", and now: " + to_string(i->second),
                    true);
        }
      }
    }

    void trouble(std::string const& msg, bool throwException = true) const {
      warn(msg);
      if (throwException) throw ConfigException(msg);
    }

    bool finished;

    /**
       may throw. call just before destructor (this used to be done in
       destructor, but this caused any exception e.g. in string->leaf to
       complain about things that would have been recognized had we continued
       walking the configure() tree without exception
    */
    void finish() {
      if (finished) return;
      finished = true;
      const bool allow = unrecognizedOpt.enable, warn = unrecognizedOpt.warn,
                 store = unrecognizedOpt.unrecognized_storage;
      if (allow && !warn && !store) return;
      for (ChildMap::const_iterator i = unprocessedMapChildren.begin(), e = unprocessedMapChildren.end();
           i != e; ++i) {
        ChildPair const& keyNode = *i;
        std::string const& key = keyNode.first;
        if (warn || !allow)
          trouble(key + ": " + to_string(keyNode.second) + " - '" + fullname(key)
                      + "' is an unrecognized option (check spelling ? )",
                  !allow);
        if (store) (*unrecognizedOpt.unrecognized_storage)[key] = to_string(keyNode.second);
      }
    }
    friend inline std::ostream& operator<<(std::ostream& out, Subtree const& self) {
      self.print(out);
      return out;
    }
    void print(std::ostream& out) const {
      YAML::Emitter em;
      em << root;
      out << em.c_str();
    }
    std::string str() const {
      YAML::Emitter em;
      em << root;
      return em.c_str();
    }
  };

  /** Context keeps track of where we are in the input Yaml tree while storing
      values into our configured objects. Actions other than store don'\t
      reference the input Yaml at all. */
  struct Context : boost::noncopyable {
    bool nothingToStore() const { return stack.empty() ? false : top().nothingToStore; }
    void setNothingToStore() { top().nothingToStore = true; }

    /// null unless we're about to store a map or sequence element
    boost::optional<ConfigNode> collectionElementConfig;
    /** set a one-shot register (collectionElementConfig) that modifies the next
       node() call since we already retrived the subconfig (lookup depends on
     * seq or map). */
    void pushCollectionYaml(ConfigNode const& subconfig) {
      assert(!collectionElementConfig);
      collectionElementConfig = subconfig;
    }

    typedef boost::ptr_vector<Subtree> Stack;
    Stack stack;

    bool ignore() {
      if (nothingToStore()) {
        collectionElementConfig.reset();
        return true;
      } else
        return false;
    }

    /**
       \return last collection value if parent was a map/sequence/set, else look
       up 'key' from previous top-of-stack node. return is !IsDefined() if not
       present
    */
    ConfigNode node(std::string const& key, bool required = false, bool requiredThrow = true) {
      if (collectionElementConfig) {
        ConfigNode r = *collectionElementConfig;
        collectionElementConfig.reset();
        return r;
      } else
        return top().node(key, required, requiredThrow);
    }
    Subtree& top() {
      assert(!stack.empty());
      return stack.back();
    }
    Subtree const& top() const {
      assert(!stack.empty());
      return stack.back();
    }
    void push(Subtree* sub) {
      if (!stack.empty() && top().root.is(sub->root))
        throw ConfigException("infinite loop in yaml subtree " + top().rootstr());
      stack.push_back(sub);
    }
    void pop() {
      top().finish();
      stack.pop_back();
    }
    std::string str() const {
      if (stack.empty()) return std::string();
      return stack.back().str();
    }
    friend std::string to_string(Context const& x) { return x.str(); }
    template <class O>
    void print(O& o) const {
      o << to_string(*this);
    }
    template <class Ch, class Tr>
    friend std::basic_ostream<Ch, Tr>& operator<<(std::basic_ostream<Ch, Tr>& o, Context const& self) {
      self.print(o);
      return o;
    }
  };

  typedef shared_ptr<Context> ContextPtr;
  ContextPtr ctx;

  ConfigNode root;

  void trouble(std::string const& name, std::string const& is, std::string const& reason = "configure error",
               std::string const& detail = "", bool throwException = false) const {
    std::string detailSuffix;
    if (!detail.empty()) detailSuffix = " (" + detail + ")";
    trouble(reason + " for option '" + name + "' of type " + is + detailSuffix, throwException);
  }
  void fatal(std::string const& name, std::string const& is, std::string const& reason = "configure error",
             std::string const& detail = "") const {
    trouble(name, is, reason, detail, true);
  }
  void trouble(std::string const& msg, bool throwException) const {
    warn(msg);
    if (throwException) throw ConfigException(msg);
  }

  template <class Val>
  void requireTrouble(Val* pval, Conf const& conf, bool throwException) const {
    trouble("Missing configuration for option '" + conf.path_name() + "' of type " + conf.opt->get_is(pval),
            throwException);
  }

 public:
  /** called by configure::conf_expr. */
  template <class Val>
  bool init_tree(configure::help_config help, Val* pval, Conf const& conf) const {
    if (this->too_verbose(conf)) return false;
    return Base::init_tree(help, pval, conf);
  }

  /** called by configure::conf_expr. */
  template <class Val>
  bool init_tree(configure::store_config, Val*, Conf const& conf) const {
    assert(conf.depth || root);
    ConfigNode const& yaml = conf.depth ? ctx->node(conf.name()) : root;
    bool const shouldStore = conf.depth ? yaml.IsDefined() : true;
    SDL_TRACE(ConfigureYaml, "store=" << shouldStore << " init_tree " << conf.path_name() << ": "
                                      << printer(yaml, Config::kShallow));
    ctx->push(new Subtree(yaml, conf.path_name(), warn, !shouldStore));
    return shouldStore;
  }

  /** called by configure::conf_expr. */
  template <class Val>
  void tree_action(configure::store_config, Val* v, Conf const& conf) const {
    Subtree& top = ctx->top();
    Opt const& opt = *conf.opt;
    top.unrecognizedOpt = opt.get_unrecognized();
    const bool require = opt.is_required(), requireThrow = opt.is_required_err();
    if (top.exists())
      conf.warn_if_deprecated();
    else if (require && !top.nothingToStore)
      requireTrouble(v, conf, requireThrow);
    ctx->pop();
  }

  /** called by configure::conf_expr. */
  template <class Val>
  void sequence_action(configure::store_config, Val* pval, Conf const& conf) const {
    // if (ctx->nothingToStore()) return;
    Opt const& opt = *conf.opt;
    std::string const& name = conf.name();
    std::string const& pathname = conf.path_name();
    ConfigNode const& n = ctx->node(name, opt.is_required(), opt.is_required_err());
    SDL_TRACE(ConfigureYaml, "store sequence " << pathname << ": " << printer(n, Config::kShallow));
    if (!n.IsDefined()) return;
    if (n.IsNull()) return;  // null value should not be acceptable, but:
    // user may prefer to have shorthand feature-weights: (end of line/indent) meaning empty seq
    if (n.IsScalar()) {  // special case: allow single scalar value as singleton list
      conf.warn_if_deprecated();
      pval->clear();
      typename Val::value_type& subval = configure::append_default(*pval);
      ctx->pushCollectionYaml(n);
      configure::configure_store_init_from_base(*this, &subval, conf);
    } else if (!n.IsNull() && !n.IsSequence())
      throw ConfigException(pathname + " expected a YAML sequence");
    else {
      // TODO: handle map with int keys ?
      conf.warn_if_deprecated();
      pval->clear();
      unsigned key = 0;
      for (YAML::const_iterator i = n.begin(), e = n.end(); i != e; ++i) {
        typename Val::value_type& subval = configure::append_default(*pval);
        configure::conf_expr_base subconf(conf, graehl::to_string(key++));
        ctx->pushCollectionYaml(*i);
        configure::configure_store_init_from_base(*this, &subval, subconf);
      }
    }
  }

  /** called by configure::conf_expr. */
  template <class Val>
  void set_action(configure::store_config, Val* pval, Conf const& conf) const {
    // if (ctx->nothingToStore()) return;
    Opt const& opt = *conf.opt;
    std::string const& name = conf.name();
    std::string const& pathname = conf.path_name();
    ConfigNode const& n = ctx->node(name, opt.is_required(), opt.is_required_err());
    SDL_TRACE(ConfigureYaml, "store set " << pathname << ": " << printer(n, Config::kShallow));
    if (!n.IsDefined()) return;
    if (n.IsNull()) return;  // null value should not be acceptable, but:
    // user may prefer to have shorthand feature-weights: (end of line/indent) meaning empty set
    if (!n.IsSequence()) throw ConfigException(pathname + " expected a YAML sequence");
    conf.warn_if_deprecated();
    // TODO: handle map with int keys ?
    pval->clear();
    unsigned key = 0;
    for (YAML::const_iterator i = n.begin(), e = n.end(); i != e; ++i) {
      configure::defaulted<typename Val::value_type> subval;
      configure::conf_expr_base subconf(conf, graehl::to_string(key++));
      ctx->pushCollectionYaml(*i);
      configure::configure_store_init_from_base(*this, &subval.val, subconf);
      pval->insert(subval.val);
    }
  }

  /** called by configure::conf_expr. */
  template <class Val>
  void map_action(configure::store_config, std::map<std::string, Val>* pval, Conf const& conf) const {
    // if (ctx->nothingToStore()) return;
    Opt const& opt = *conf.opt;
    std::string const& name = conf.name();
    std::string const& pathname = conf.path_name();
    ConfigNode const& n = ctx->node(name, opt.is_required(), opt.is_required_err());
    SDL_TRACE(ConfigureYaml, "store map " << pathname << ": " << printer(n, Config::kShallow));
    if (!n.IsDefined()) return;
    if (n.IsNull()) return;  // null value should not be acceptable, but:
    // 1. yaml-cpp parser mis-parses {} as null
    // 2. user may prefer to have shorthand feature-weights: (end of line/indent) meaning empty map
    if (!n.IsMap()) throw ConfigException(pathname + " expected a YAML map: " + to_string(*ctx));
    conf.warn_if_deprecated();
    pval->clear();
    for (YAML::const_iterator i = n.begin(), e = n.end(); i != e; ++i) {
      YamlScalarRef key = i->first.Scalar();
      Val& subval = configure::append_default(*pval, (std::string const&)key);
      configure::conf_expr_base subconf(conf, key);
      ctx->pushCollectionYaml(i->second);
      configure::configure_store_init_from_base(*this, &subval, subconf);
    }
  }

  /** called by configure::conf_expr.

     // e.g. ReweightOptions uses map<FeatureId, FeatureValue>

   */
  template <class Val>
  void map_action(configure::store_config, Val* pval, Conf const& conf) const {
    // if (ctx->nothingToStore()) return;
    Opt const& opt = *conf.opt;
    std::string const& name = conf.name();
    std::string const& pathname = conf.path_name();
    ConfigNode const& n = ctx->node(name, opt.is_required(), opt.is_required_err());
    SDL_TRACE(ConfigureYaml, "store map " << pathname << ": " << printer(n, Config::kShallow));
    if (!n.IsDefined()) return;
    if (n.IsNull()) return;  // null value should not be acceptable, but:
    // 1. yaml-cpp parser mis-parses {} as null
    // 2. user may prefer to have shorthand feature-weights: (end of line/indent) meaning empty map
    if (!n.IsMap()) throw ConfigException(pathname + " expected a YAML map: " + to_string(*ctx));
    conf.warn_if_deprecated();
    typedef configure::map_leaf_configurable<Val> ValTraits;
    ValTraits::clear(pval);
    unsigned npairs = 0;
    for (YAML::const_iterator i = n.begin(), e = n.end(); i != e; ++i) {
      if (ValTraits::is_pair && npairs++)
        throw ConfigException(pathname + " expected a single-element map (for a value of pair type)");
      YamlScalarRef keystr = i->first.Scalar();
      typename ValTraits::key_type key;
      graehl::string_to((std::string const&)keystr, key);
      typename ValTraits::mapped_type& subval = configure::append_default(*pval, key);
      configure::conf_expr_base subconf(conf, keystr);
      ctx->pushCollectionYaml(i->second);
      configure::configure_store_init_from_base(*this, &subval, subconf);
    }
  }

  /** called by configure::conf_expr. */
  template <class Val>
  void leaf_action(configure::store_config, Val* pval, Conf const& conf) const {
    if (ctx->ignore()) return;
    Opt const& opt = *conf.opt;
    std::string const& name = conf.name();
    std::string const& pathname = conf.path_name();

    ConfigNode const& n = ctx->node(name, opt.is_required(), opt.is_required_err());
    SDL_TRACE(ConfigureYaml, "store leaf " << pathname << ": " << printer(n, Config::kShallow));
    if (n.IsDefined()) {
      conf.warn_if_deprecated();
      if (n.IsNull()) {
        if (opt.is_implicit()) try {
            opt.apply_implicit_value(pval, pathname, warn);
          } catch (std::exception& e) {
            trouble(pathname, opt.get_is(pval),
                    "implicit (null) value error (find a programmer; this is a bug)", e.what(), "");
          }
        else
          fatal(pathname, opt.get_is(pval), "null value (for non-implicit/flag)", "");
      } else {
        try {
          if (!n.IsScalar()) throw ConfigException(pathname + " expected a YAML scalar");
          YamlScalarRef scalar = n.Scalar();
          conf.opt->apply_string_value(scalar, pval, pathname, warn);
        } catch (std::exception& e) {
          fatal(pathname, opt.get_is(pval), "Error storing value from yaml config: '" + to_string(n) + "'",
                e.what());
        }
      }
    } else {
      if (opt.is_required())
        trouble(pathname, opt.get_is(pval), "missing required value", "", opt.is_required_err());
    }
    // TODO: check and store allow_undefined (iterate over existing keys rather than looking up only specified
    // ones)
  }

  /**  Since we only overrode for store_action, this macro forwards for all other actions (since we hid the
   * base-class functions of the same name). */
  FORWARD_BASE_CONFIGURE_ACTIONS(Base)
  // TODO: separate backend for building actual YAML tree ?
};

/** perform config action by binding yamlRoot into a ConfigureYaml, and calling
it on pRootVal. (yamlRoot is only relevant for store_action). */
template <class Action, class Val>
void configureYaml(Action action, ConfigNode const& yamlRoot, Val* pRootVal,
                   std::string const& component = "configure") {
  StringConsumer warn = Util::logWarning(component);
  ConfigureYaml cy(yamlRoot, warn);
  configure::configure_action(cy, action, pRootVal, warn);
}

/** print help for pRootVal and all its configurable sub-ojects. vaguely YAML-like output */
template <class Val>
void showHelp(std::ostream& o, Val* pRootVal, std::string const& component = "configure", int verbosity = 0) {
  // configure::help(o, pRootVal, Util::logWarning(component));
  StringConsumer warn = Util::logWarning(component);
  ConfigureYaml cy(warn);
  cy.verbose_max = verbosity;
  configure::configure_action(cy, configure::help_config(o), pRootVal, warn);
}

/** print example configuration (with placeholder values). YAML-like output. */
template <class Val>
void showExample(std::ostream& o, Val* pRootVal, std::string const& component = "configure", bool init = true) {
  StringConsumer warn = Util::logWarning(component);
  if (init) configure::configure_init(pRootVal, warn);
  configure::show_example(pRootVal, warn);
}

template <class Configurable>
inline std::ostream& help(std::ostream& out, std::string const& component = "configure", int verbosity = 0) {
  Configurable c;  // needed to show self_init default
  showHelp(out, &c, component, verbosity);
  return out;
}

template <class Configurable>
inline std::ostream& example(std::ostream& out, std::string const& component = "configure", int verbosity = 0) {
  Configurable c;  // needed to show self_init default
  showExample(out, &c, component, verbosity);
  return out;
}

/** print effective configuration. YAML-like output. ideally this can be parsed
    as a YAML tree and passed to applyYaml to initialize another Val in exactly
    the same way.

    call after you've initialized values via applyYaml or otherwise */
template <class Val>
void showEffective(std::ostream& o, Val const* pRootVal, std::string const& component = "configure") {
  //  configure::show_effective(o, pRootVal, Util::logWarning(component));
  StringConsumer warn = Util::logWarning("effective." + component);
  ConfigureYaml cy(warn);
  configure::configure_action(cy, configure::show_effective_config(o), const_cast<Val*>(pRootVal), warn);
}

/** string return instead of printing with showEffective. */
template <class Val>
std::string getEffective(Val* pRootVal, std::string const& component = "configure") {
  std::ostringstream o;
  showEffective(o, pRootVal, component);
  return o.str();
}

/** TODO: return a YAML tree instead of printing with showEffective. */
template <class Val>
ConfigNode effectiveYaml(Val* pRootVal, std::string const& component = "configure") {
  return ConfigNode();  // TODO
}

/** TODO: return a YAML tree instead of printing with showExample. */
template <class Val>
ConfigNode exampleYaml(Val* pRootVal, std::string const& component = "configure") {
  return ConfigNode();  // TODO
}
}

template <class Val>
struct PrintEffective {
  Val const& val;
  std::string component;
  PrintEffective(Val const& val, char const* component) : val(val), component(component) {}
  PrintEffective(Val const& val, std::string const& component) : val(val), component(component) {}
  friend inline std::ostream& operator<<(std::ostream& out, PrintEffective const& self) {
    self.print(out);
    return out;
  }
  void print(std::ostream& out) const { Config::showEffective(out, &val, component); }
};

template <class Val>
PrintEffective<Val> printEffective(Val const& val, char const* component) {
  return PrintEffective<Val>(val, component);
}

template <class Val>
PrintEffective<Val> printEffective(Val const& val) {
  return PrintEffective<Val>(val, "configure");
}

template <class Val>
PrintEffective<Val> printEffective(Val const& val, std::string const& component) {
  return PrintEffective<Val>(val, component);
}

struct PrintEffectiveYamlConfigurable {
  YamlConfigurable const& val;
  int verbosity;
  explicit PrintEffectiveYamlConfigurable(YamlConfigurable const& val, int verbosity = 0)
      : val(val), verbosity(verbosity) {}
  friend inline std::ostream& operator<<(std::ostream& out, PrintEffectiveYamlConfigurable const& self) {
    self.print(out);
    return out;
  }
  void print(std::ostream& out) const { val.showEffective(out, verbosity); }
};

inline PrintEffectiveYamlConfigurable printEffective(YamlConfigurable const& val, char const* = 0) {
  return PrintEffectiveYamlConfigurable(val);
}

inline PrintEffectiveYamlConfigurable printEffective(YamlConfigurable const& val, std::string const&) {
  return PrintEffectiveYamlConfigurable(val);
}

namespace Config {

#include <graehl/shared/warning_push.h>
GCC_DIAG_IGNORE(uninitialized)

/** applyYaml(yamlRootNode, &rootConfiguration) will initialize
    rootConfiguration, update its values as specified by yamlRootNode, and
    validate them. */
template <class Val>
void applyYaml(ConfigNode const& yamlRoot, Val* pRootVal, char const* component = "configure",
               bool init = true, bool validate = true, bool verbose = true, bool trace = true) {
  StringConsumer warn = Util::logWarning(component);
  LOG_TRACE_NAMESTR(kLogPrefix + component, "applyYaml node:\n" << printer(yamlRoot, Config::oneline));
  if (init) configure::configure_init(pRootVal, warn);

  if (trace) {
    // TODO: fix gcc warning: ‘<anonymous>’ may be used uninitialized in this function:
    LOG_TRACE_NAMESTR(kLogPrefix + component, "before store for " << component << ":\n"
                                                                  << printEffective(*pRootVal, component)
                                                                  << "\n");
  }

  configureYaml(configure::store_config(), yamlRoot, pRootVal, component);
  if (trace) {
    LOG_TRACE_NAMESTR(kLogPrefix + component, "after store for " << component << ":\n"
                                                                 << printEffective(*pRootVal, component) << "\n");
  }

  if (validate) configure::validate_stored(pRootVal, warn);
  if (verbose)
    LOG_INFO_NAMESTR(kLogPrefix + component, "effective (YAML applied) configuration for "
                                                 << component << ":\n"
                                                 << printEffective(*pRootVal, component) << "\n");
}

template <class Val>
void applyYaml(ConfigNode const& yamlRoot, Val* pRootVal, std::string const& component, bool init = true,
               bool validate = true, bool verbose = true) {
  applyYaml(yamlRoot, pRootVal, component.c_str(), init, validate, verbose);
}

#include <graehl/shared/warning_pop.h>

}  // ns

/** usage: struct MyModule : YamlConfigurable<MyModule, ModuleConfig>

    or Base = ResourceConfig

    (note: both ModuleConfig and ResourceConfig are YamlConfigurable)
*/
template <class Impl, class Base = YamlConfigurable>
struct YamlConfigure : Base {
 private:
  Impl* pimpl() { return static_cast<Impl*>(this); }
  Impl* pimpl() const { return const_cast<Impl*>(static_cast<Impl const*>(this)); }
  StringConsumer log() const { return Base::log(); }

 public:
  virtual void help(std::ostream& out, int verbosity) const override {
    Config::ConfigureYaml cy(log(), verbosity);
    Config::configure_action(cy, Config::help_config(out), pimpl(), log());
  }
  virtual void showExample(std::ostream& out, int verbosity) const override {
    Config::ConfigureYaml cy(log(), verbosity);
    Config::configure_action(cy, Config::show_example_config(out), pimpl(), log());
  }
  virtual void showEffective(std::ostream& out, int verbosity) const override {
    Config::ConfigureYaml cy(log(), verbosity);
    Config::configure_action(cy, Config::show_effective_config(out), pimpl(), log());
  }

  virtual void init() override { configure::configure_init(pimpl(), log()); }
  virtual void validateStored() override { Config::validate_stored(pimpl(), log()); }
  virtual void store(ConfigNode const& configNode) override {
    Config::ConfigureYaml cy(configNode, log());
    Config::configure_action(cy, Config::store_config(), pimpl(), log());
  }
};

}

#endif

max_stars_repo_name: sdl-research/hyp

max_issues_repo_name: hypergraphs/hyp

max_forks_repo_name: hypergraphs/hyp


text:
#pragma once

#include <chratos/lib/interface.h>
#include <chratos/secure/common.hpp>

#include <boost/asio.hpp>

#include <bitset>

#include <xxhash/xxhash.h>

namespace chratos
{
using endpoint = boost::asio::ip::udp::endpoint;
bool parse_port (std::string const &, uint16_t &);
bool parse_address_port (std::string const &, boost::asio::ip::address &, uint16_t &);
using tcp_endpoint = boost::asio::ip::tcp::endpoint;
bool parse_endpoint (std::string const &, chratos::endpoint &);
bool parse_tcp_endpoint (std::string const &, chratos::tcp_endpoint &);
bool reserved_address (chratos::endpoint const &, bool);
}
static uint64_t endpoint_hash_raw (chratos::endpoint const & endpoint_a)
{
	assert (endpoint_a.address ().is_v6 ());
	chratos::uint128_union address;
	address.bytes = endpoint_a.address ().to_v6 ().to_bytes ();
	XXH64_state_t hash;
	XXH64_reset (&hash, 0);
	XXH64_update (&hash, address.bytes.data (), address.bytes.size ());
	auto port (endpoint_a.port ());
	XXH64_update (&hash, &port, sizeof (port));
	auto result (XXH64_digest (&hash));
	return result;
}
static uint64_t ip_address_hash_raw (boost::asio::ip::address const & ip_a)
{
	assert (ip_a.is_v6 ());
	chratos::uint128_union bytes;
	bytes.bytes = ip_a.to_v6 ().to_bytes ();
	XXH64_state_t hash;
	XXH64_reset (&hash, 0);
	XXH64_update (&hash, bytes.bytes.data (), bytes.bytes.size ());
	auto result (XXH64_digest (&hash));
	return result;
}

namespace std
{
template <size_t size>
struct endpoint_hash
{
};
template <>
struct endpoint_hash<8>
{
	size_t operator() (chratos::endpoint const & endpoint_a) const
	{
		return endpoint_hash_raw (endpoint_a);
	}
};
template <>
struct endpoint_hash<4>
{
	size_t operator() (chratos::endpoint const & endpoint_a) const
	{
		uint64_t big (endpoint_hash_raw (endpoint_a));
		uint32_t result (static_cast<uint32_t> (big) ^ static_cast<uint32_t> (big >> 32));
		return result;
	}
};
template <>
struct hash<chratos::endpoint>
{
	size_t operator() (chratos::endpoint const & endpoint_a) const
	{
		endpoint_hash<sizeof (size_t)> ehash;
		return ehash (endpoint_a);
	}
};
template <size_t size>
struct ip_address_hash
{
};
template <>
struct ip_address_hash<8>
{
	size_t operator() (boost::asio::ip::address const & ip_address_a) const
	{
		return ip_address_hash_raw (ip_address_a);
	}
};
template <>
struct ip_address_hash<4>
{
	size_t operator() (boost::asio::ip::address const & ip_address_a) const
	{
		uint64_t big (ip_address_hash_raw (ip_address_a));
		uint32_t result (static_cast<uint32_t> (big) ^ static_cast<uint32_t> (big >> 32));
		return result;
	}
};
template <>
struct hash<boost::asio::ip::address>
{
	size_t operator() (boost::asio::ip::address const & ip_a) const
	{
		ip_address_hash<sizeof (size_t)> ihash;
		return ihash (ip_a);
	}
};
}
namespace boost
{
template <>
struct hash<chratos::endpoint>
{
	size_t operator() (chratos::endpoint const & endpoint_a) const
	{
		std::hash<chratos::endpoint> hash;
		return hash (endpoint_a);
	}
};
}

namespace chratos
{
/**
 * Message types are serialized to the network and existing values must thus never change as
 * types are added, removed and reordered in the enum.
 */
enum class message_type : uint8_t
{
	invalid = 0x0,
	not_a_type = 0x1,
	keepalive = 0x2,
	publish = 0x3,
	confirm_req = 0x4,
	confirm_ack = 0x5,
	bulk_pull = 0x6,
	bulk_push = 0x7,
	frontier_req = 0x8,
	bulk_pull_blocks = 0x9,
	node_id_handshake = 0x0a,
	bulk_pull_account = 0x0b
};
enum class bulk_pull_blocks_mode : uint8_t
{
	list_blocks,
	checksum_blocks
};
enum class bulk_pull_account_flags : uint8_t
{
	pending_hash_and_amount = 0x0,
	pending_address_only = 0x1,
	pending_hash_amount_and_address = 0x2
};
class message_visitor;
class message_header
{
public:
	message_header (chratos::message_type);
	message_header (bool &, chratos::stream &);
	void serialize (chratos::stream &);
	bool deserialize (chratos::stream &);
	chratos::block_type block_type () const;
	void block_type_set (chratos::block_type);
	bool ipv4_only ();
	void ipv4_only_set (bool);
	static std::array<uint8_t, 2> constexpr magic_number = chratos::chratos_network == chratos::chratos_networks::chratos_test_network ? std::array<uint8_t, 2> { { 'C', 'A' } } : chratos::chratos_network == chratos::chratos_networks::chratos_beta_network ? std::array<uint8_t, 2> { { 'C', 'B' } } : std::array<uint8_t, 2> { { 'C', 'C' } };
	uint8_t version_max;
	uint8_t version_using;
	uint8_t version_min;
	chratos::message_type type;
	std::bitset<16> extensions;
	static size_t constexpr ipv4_only_position = 1;
	static size_t constexpr bootstrap_server_position = 2;
	static std::bitset<16> constexpr block_type_mask = std::bitset<16> (0x0f00);
	inline bool valid_magic () const
	{
		return magic_number[0] == 'C' && magic_number[1] >= 'A' && magic_number[1] <= 'C';
	}
	inline bool valid_network () const
	{
		return (magic_number[1] - 'A') == static_cast<int> (chratos::chratos_network);
	}
};
class message
{
public:
	message (chratos::message_type);
	message (chratos::message_header const &);
	virtual ~message () = default;
	virtual void serialize (chratos::stream &) = 0;
	virtual bool deserialize (chratos::stream &) = 0;
	virtual void visit (chratos::message_visitor &) const = 0;
	chratos::message_header header;
};
class work_pool;
class message_parser
{
public:
	enum class parse_status
	{
		success,
		insufficient_work,
		invalid_header,
		invalid_message_type,
		invalid_keepalive_message,
		invalid_publish_message,
		invalid_confirm_req_message,
		invalid_confirm_ack_message,
		invalid_node_id_handshake_message,
		outdated_version,
		invalid_magic,
		invalid_network
	};
	message_parser (chratos::message_visitor &, chratos::work_pool &);
	void deserialize_buffer (uint8_t const *, size_t);
	void deserialize_keepalive (chratos::stream &, chratos::message_header const &);
	void deserialize_publish (chratos::stream &, chratos::message_header const &);
	void deserialize_confirm_req (chratos::stream &, chratos::message_header const &);
	void deserialize_confirm_ack (chratos::stream &, chratos::message_header const &);
	void deserialize_node_id_handshake (chratos::stream &, chratos::message_header const &);
	bool at_end (chratos::stream &);
	chratos::message_visitor & visitor;
	chratos::work_pool & pool;
	parse_status status;
	std::string status_string ();
	static const size_t max_safe_udp_message_size;
};
class keepalive : public message
{
public:
	keepalive (bool &, chratos::stream &, chratos::message_header const &);
	keepalive ();
	void visit (chratos::message_visitor &) const override;
	bool deserialize (chratos::stream &) override;
	void serialize (chratos::stream &) override;
	bool operator== (chratos::keepalive const &) const;
	std::array<chratos::endpoint, 8> peers;
};
class publish : public message
{
public:
	publish (bool &, chratos::stream &, chratos::message_header const &);
	publish (std::shared_ptr<chratos::block>);
	void visit (chratos::message_visitor &) const override;
	bool deserialize (chratos::stream &) override;
	void serialize (chratos::stream &) override;
	bool operator== (chratos::publish const &) const;
	std::shared_ptr<chratos::block> block;
};
class confirm_req : public message
{
public:
	confirm_req (bool &, chratos::stream &, chratos::message_header const &);
	confirm_req (std::shared_ptr<chratos::block>);
	bool deserialize (chratos::stream &) override;
	void serialize (chratos::stream &) override;
	void visit (chratos::message_visitor &) const override;
	bool operator== (chratos::confirm_req const &) const;
	std::shared_ptr<chratos::block> block;
};
class confirm_ack : public message
{
public:
	confirm_ack (bool &, chratos::stream &, chratos::message_header const &);
	confirm_ack (std::shared_ptr<chratos::vote>);
	bool deserialize (chratos::stream &) override;
	void serialize (chratos::stream &) override;
	void visit (chratos::message_visitor &) const override;
	bool operator== (chratos::confirm_ack const &) const;
	std::shared_ptr<chratos::vote> vote;
};
class frontier_req : public message
{
public:
	frontier_req ();
	frontier_req (bool &, chratos::stream &, chratos::message_header const &);
	bool deserialize (chratos::stream &) override;
	void serialize (chratos::stream &) override;
	void visit (chratos::message_visitor &) const override;
	bool operator== (chratos::frontier_req const &) const;
	chratos::account start;
	uint32_t age;
	uint32_t count;
};
class bulk_pull : public message
{
public:
	bulk_pull ();
	bulk_pull (bool &, chratos::stream &, chratos::message_header const &);
	bool deserialize (chratos::stream &) override;
	void serialize (chratos::stream &) override;
	void visit (chratos::message_visitor &) const override;
	chratos::uint256_union start;
	chratos::block_hash end;
};
class bulk_pull_account : public message
{
public:
	bulk_pull_account ();
	bulk_pull_account (bool &, chratos::stream &, chratos::message_header const &);
	bool deserialize (chratos::stream &) override;
	void serialize (chratos::stream &) override;
	void visit (chratos::message_visitor &) const override;
	chratos::uint256_union account;
	chratos::uint128_union minimum_amount;
	bulk_pull_account_flags flags;
};
class bulk_pull_blocks : public message
{
public:
	bulk_pull_blocks ();
	bulk_pull_blocks (bool &, chratos::stream &, chratos::message_header const &);
	bool deserialize (chratos::stream &) override;
	void serialize (chratos::stream &) override;
	void visit (chratos::message_visitor &) const override;
	chratos::block_hash min_hash;
	chratos::block_hash max_hash;
	bulk_pull_blocks_mode mode;
	uint32_t max_count;
};
class bulk_push : public message
{
public:
	bulk_push ();
	bulk_push (chratos::message_header const &);
	bool deserialize (chratos::stream &) override;
	void serialize (chratos::stream &) override;
	void visit (chratos::message_visitor &) const override;
};
class node_id_handshake : public message
{
public:
	node_id_handshake (bool &, chratos::stream &, chratos::message_header const &);
	node_id_handshake (boost::optional<chratos::block_hash>, boost::optional<std::pair<chratos::account, chratos::signature>>);
	bool deserialize (chratos::stream &) override;
	void serialize (chratos::stream &) override;
	void visit (chratos::message_visitor &) const override;
	bool operator== (chratos::node_id_handshake const &) const;
	boost::optional<chratos::uint256_union> query;
	boost::optional<std::pair<chratos::account, chratos::signature>> response;
	static size_t constexpr query_flag = 0;
	static size_t constexpr response_flag = 1;
};
class message_visitor
{
public:
	virtual void keepalive (chratos::keepalive const &) = 0;
	virtual void publish (chratos::publish const &) = 0;
	virtual void confirm_req (chratos::confirm_req const &) = 0;
	virtual void confirm_ack (chratos::confirm_ack const &) = 0;
	virtual void bulk_pull (chratos::bulk_pull const &) = 0;
	virtual void bulk_pull_account (chratos::bulk_pull_account const &) = 0;
	virtual void bulk_pull_blocks (chratos::bulk_pull_blocks const &) = 0;
	virtual void bulk_push (chratos::bulk_push const &) = 0;
	virtual void frontier_req (chratos::frontier_req const &) = 0;
	virtual void node_id_handshake (chratos::node_id_handshake const &) = 0;
	virtual ~message_visitor ();
};

/**
 * Returns seconds passed since unix epoch (posix time)
 */
inline uint64_t seconds_since_epoch ()
{
	return std::chrono::duration_cast<std::chrono::seconds> (std::chrono::system_clock::now ().time_since_epoch ()).count ();
}
}

max_stars_repo_name: chratos-system/chratos

max_issues_repo_name: chratos-system/chratos

max_forks_repo_name: chratos-system/chratos


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

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

#ifndef BOOST_HANA_LENGTH_HPP
#define BOOST_HANA_LENGTH_HPP

#include <boost/hana/fwd/length.hpp>

#include <boost/hana/concept/foldable.hpp>
#include <boost/hana/config.hpp>
#include <boost/hana/core/dispatch.hpp>
#include <boost/hana/integral_constant.hpp>
#include <boost/hana/unpack.hpp>

BOOST_HANA_NAMESPACE_BEGIN
    //! @cond
    template <typename Xs>
    constexpr auto length_t::operator()(Xs const& xs) const {
        using S = typename hana::tag_of<Xs>::type;
        using Length = BOOST_HANA_DISPATCH_IF(length_impl<S>,
            hana::Foldable<S>::value
        );

    #ifndef BOOST_HANA_CONFIG_DISABLE_CONCEPT_CHECKS
        static_assert(hana::Foldable<S>::value,
        "hana::length(xs) requires 'xs' to be Foldable");
    #endif

        return Length::apply(xs);
    }
    //! @endcond

    namespace detail {
        struct argn {
            template <typename ...Xs>
            constexpr auto operator()(Xs const& ...) const
            { return hana::size_c<sizeof...(Xs)>; }
        };
    }

    template <typename T, bool condition>
    struct length_impl<T, when<condition>> : default_ {
        template <typename Xs>
        static constexpr auto apply(Xs const& xs) {
            return hana::unpack(xs, detail::argn{});
        }
    };
BOOST_HANA_NAMESPACE_END

#endif // !BOOST_HANA_LENGTH_HPP

max_stars_repo_name: kodxana/lib-ledger-core

max_issues_repo_name: kodxana/lib-ledger-core

max_forks_repo_name: kodxana/lib-ledger-core


text:
/*
 * Copyright (C) 2012 Open Source Robotics Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/
#include <boost/bind.hpp>

#include "gazebo/common/Profiler.hh"
#include "gazebo/common/MeshManager.hh"
#include "gazebo/transport/transport.hh"

#include "gazebo/rendering/Conversions.hh"
#include "gazebo/rendering/Scene.hh"
#include "gazebo/rendering/DynamicLines.hh"
#include "gazebo/rendering/WrenchVisualPrivate.hh"
#include "gazebo/rendering/WrenchVisual.hh"

using namespace gazebo;
using namespace rendering;

/////////////////////////////////////////////////
WrenchVisual::WrenchVisual(const std::string &_name, VisualPtr _vis,
    const std::string &_topicName)
  : Visual(*new WrenchVisualPrivate, _name, _vis)
{
  WrenchVisualPrivate *dPtr =
      reinterpret_cast<WrenchVisualPrivate *>(this->dataPtr);

  dPtr->type = VT_PHYSICS;

  dPtr->enabled = true;
  dPtr->receivedMsg = false;

  // Transport
  dPtr->node = transport::NodePtr(new transport::Node());
  dPtr->node->Init(dPtr->scene->Name());

  dPtr->wrenchSub = dPtr->node->Subscribe(_topicName,
      &WrenchVisual::OnMsg, this, true);

  dPtr->connections.push_back(
      event::Events::ConnectPreRender(
      std::bind(&WrenchVisual::Update, this)));
}

/////////////////////////////////////////////////
WrenchVisual::~WrenchVisual()
{
  this->Fini();
}

/////////////////////////////////////////////////
void WrenchVisual::Fini()
{
  WrenchVisualPrivate *dPtr =
      reinterpret_cast<WrenchVisualPrivate *>(this->dataPtr);

  dPtr->wrenchSub.reset();
  if (dPtr->node)
    dPtr->node->Fini();
  dPtr->node.reset();
  dPtr->connections.clear();

  dPtr->wrenchMsg.reset();

  // Remove force visual and line
  if (dPtr->forceVisual && dPtr->forceLine)
    dPtr->forceVisual->DeleteDynamicLine(dPtr->forceLine);

  if (dPtr->scene && dPtr->forceVisual &&
      dPtr->scene->GetVisual(dPtr->forceVisual->Name()))
  {
    dPtr->scene->RemoveVisual(dPtr->forceVisual);
  }
  dPtr->forceVisual.reset();

  Visual::Fini();
}

/////////////////////////////////////////////////
void WrenchVisual::Load(ConstJointPtr &_msg)
{
  Visual::Load();

  WrenchVisualPrivate *dPtr =
      reinterpret_cast<WrenchVisualPrivate *>(this->dataPtr);

  // Make sure the meshes are in Ogre
  this->InsertMesh("unit_cone");

  // Initialize visuals on Load because we can't use shared_from_this in the
  // constructor

  // Torque visual
  dPtr->coneXVis.reset(
      new Visual(this->Name()+"__WRENCH_X_CONE__", shared_from_this(),
      false));
  dPtr->coneXVis->Load();
  dPtr->coneXVis->AttachMesh("unit_cone");
  dPtr->coneXVis->SetMaterial("__GAZEBO_TRANS_RED_MATERIAL__");

  dPtr->coneYVis.reset(
      new Visual(this->Name()+"__WRENCH_Y_CONE__", shared_from_this(),
      false));
  dPtr->coneYVis->Load();
  dPtr->coneYVis->AttachMesh("unit_cone");
  dPtr->coneYVis->SetMaterial("__GAZEBO_TRANS_GREEN_MATERIAL__");

  dPtr->coneZVis.reset(
      new Visual(this->Name()+"__WRENCH_Z_CONE__", shared_from_this(),
      false));
  dPtr->coneZVis->Load();
  dPtr->coneZVis->AttachMesh("unit_cone");
  dPtr->coneZVis->SetMaterial("__GAZEBO_TRANS_BLUE_MATERIAL__");

  ignition::math::Quaterniond q;
  q.Axis(0, 1, 0, -IGN_PI_2);
  dPtr->coneXVis->SetRotation(q);
  dPtr->coneXVis->SetScale(ignition::math::Vector3d(0.02, 0.02, 0.02));

  q.Axis(1, 0, 0, IGN_PI_2);
  dPtr->coneYVis->SetRotation(q);
  dPtr->coneYVis->SetScale(ignition::math::Vector3d(0.02, 0.02, 0.02));

  q.Axis(1, 0, 0, IGN_PI);
  dPtr->coneZVis->SetRotation(q);
  dPtr->coneZVis->SetScale(ignition::math::Vector3d(0.02, 0.02, 0.02));

  // Force visual
  dPtr->forceVisual.reset(new rendering::Visual(
      this->Name() + "_FORCE_VISUAL_", shared_from_this()));
  dPtr->forceVisual->Load();

  dPtr->forceLine = dPtr->forceVisual->CreateDynamicLine(RENDERING_LINE_LIST);
  dPtr->forceLine->AddPoint(ignition::math::Vector3d::Zero);
  dPtr->forceLine->AddPoint(ignition::math::Vector3d(0, 0, 0.1));
  dPtr->forceLine->setMaterial("__GAZEBO_TRANS_PURPLE_MATERIAL__");

  this->SetVisibilityFlags(GZ_VISIBILITY_GUI);

  dPtr->connections.push_back(
      event::Events::ConnectPreRender(
        boost::bind(&WrenchVisual::Update, this)));

  this->SetPosition(msgs::ConvertIgn(_msg->pose().position()));
  this->SetRotation(msgs::ConvertIgn(_msg->pose().orientation()));
}

/////////////////////////////////////////////////
void WrenchVisual::Update()
{
  GZ_PROFILE("rendering::WrenchVisual::Update");
  WrenchVisualPrivate *dPtr =
      reinterpret_cast<WrenchVisualPrivate *>(this->dataPtr);

  boost::mutex::scoped_lock lock(dPtr->mutex);

  if (!dPtr->wrenchMsg || !dPtr->receivedMsg)
  {
    return;
  }

  double magScale = 100;
  double vMax = 0.5;
  double vMin = 0.1;
  double vRange = vMax - vMin;
  double offset = vRange - vMin;

  // Scaling factor.
  double xScale = (2.0 * vRange) / (1 +
      exp(-dPtr->wrenchMsg->wrench().torque().x() / magScale)) - offset;

  double yScale = (2.0 * vRange) / (1 +
      exp(-dPtr->wrenchMsg->wrench().torque().y() / magScale)) - offset;

  double zScale = (2.0 * vRange) / (1 +
      exp(-dPtr->wrenchMsg->wrench().torque().z() / magScale)) - offset;

  magScale = 50000;
  ignition::math::Vector3d force =
    msgs::ConvertIgn(dPtr->wrenchMsg->wrench().force());
  double forceScale = (2.0 * vRange) / (1 +
      exp(force.SquaredLength() / magScale)) - offset;

  dPtr->forceLine->SetPoint(1, force*forceScale);
  dPtr->forceLine->Update();

  dPtr->coneXVis->SetScale(ignition::math::Vector3d(0.02, 0.02, xScale));
  dPtr->coneXVis->SetPosition(ignition::math::Vector3d(xScale * 0.5, 0, 0));

  dPtr->coneYVis->SetScale(ignition::math::Vector3d(0.02, 0.02, yScale));
  dPtr->coneYVis->SetPosition(ignition::math::Vector3d(0, yScale * 0.5, 0));

  dPtr->coneZVis->SetScale(ignition::math::Vector3d(0.02, 0.02, zScale));
  dPtr->coneZVis->SetPosition(ignition::math::Vector3d(0, 0, zScale * 0.5));
}

/////////////////////////////////////////////////
void WrenchVisual::OnMsg(ConstWrenchStampedPtr &_msg)
{
  WrenchVisualPrivate *dPtr =
      reinterpret_cast<WrenchVisualPrivate *>(this->dataPtr);

  boost::mutex::scoped_lock lock(dPtr->mutex);
  if (dPtr->enabled)
  {
    dPtr->wrenchMsg = _msg;
    dPtr->receivedMsg = true;
  }
}

ext: cc

max_stars_repo_name: nyxrobotics/gazebo

max_issues_repo_name: nyxrobotics/gazebo

max_forks_repo_name: nyxrobotics/gazebo


text:
#include "basic_logger.hpp"

#include <boost/log/core.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <string>

#include "../configurator/configurator.hpp"

void lb::log_init() {
    namespace log = boost::log;
    namespace keywords = boost::log::keywords;

    const std::string file_name{lb::helpers::configurator::default_config_path};
    log::add_file_log(keywords::file_name = file_name,
                      keywords::target_file_name = file_name,
                      keywords::open_mode = std::ios_base::in);

    // log::core::get()->set_filter (log::trivial::severity >=
    // log::trivial::info);
}

void lb::console_write(const std::string &message) {
    BOOST_LOG_TRIVIAL(info) << message << '\n';
}

void lb::log_error(const std::string &message) { (void)message; }

void lb::log_info(const std::string &message) { (void)message; }

void lb::log_trace(const std::string &message) { (void)message; }

max_stars_repo_name: yuriyzakharchuk/lbalancer

max_issues_repo_name: yuriyzakharchuk/lbalancer

max_forks_repo_name: yuriyzakharchuk/lbalancer


text:
#include <radioacek/udp_connection.h>
#include <radioacek/exceptions.h>
#include <radioacek/tcp_connection.h>
#include <radioacek/listener.h>
#include <radioacek/timer.h>
#include <radioacek/remote_player.h>

#include <thread>
#include <regex>
#include <string>
#include <atomic>
#include <boost/regex.hpp>
#include <time.h>
#include <mutex>

using namespace std;
namespace radioacek {

    int how_long_to_end(int end_hour, int end_minutes) {
        time_t current = time(0);
        struct tm *end_tm = localtime(&current);
        end_tm->tm_hour = end_hour;
        end_tm->tm_min = end_minutes;
        end_tm->tm_sec = 0;

        time_t end_t = mktime(end_tm);

        /* add one day */
        if (end_t < current) {
            end_t += 24 * 60 * 60;
        }
        return end_t - current;
    }

    RemotePlayer::RemotePlayer(
            string server,
            int port,
            string command,
            int id,
            std::shared_ptr<TCPConnection> telnet,
            int hour,
            int minutes,
            int timetodie) :
        to_start(how_long_to_end(hour,minutes)),
        telnet(telnet),
        id(id),
        time_to_die(timetodie),
        to_die(timetodie * 60)
    {
        if(!is_suicidal())
            to_start.reinit(0);

        this->server_name = server;
        this->server_port = port;

        this->lives = true;
        this->open_player.lock();
        this->launch_command = "ssh " + server_name + " \"bash -cl 'player " + command + "'\"";
        std::thread start(run_player, this);
        start.detach();
    }

    string RemotePlayer::play() {
        manager.sendMessage("PLAY");
        return std::string("OK ") + std::to_string(id);
    }

    string RemotePlayer::title() {
        manager.sendMessage("TITLE");
        radioacek::Listener l({manager.get_socket()});

        if (l.listen(TITLE_TIMEOUT) < 0) {
            return "ERROR " + std::to_string(id) + string(" title not received");
        }
        else {
            return manager.receiveMessage();
        }
    }

    void RemotePlayer::quit() {
        cancel();
        manager.sendMessage("QUIT");
    }

    string RemotePlayer::pause() {
        manager.sendMessage("PAUSE");
        return std::string("OK ") + std::to_string(id);
    }
}


text:
#define BOOST_TEST_MODULE CreateHost
#include <boost/test/unit_test.hpp>
#include <boost/test/included/unit_test.hpp>

#include <piga/host.h>
BOOST_AUTO_TEST_CASE(CreateHostCase)
{
    piga_host *host = piga_host_create();

    piga_host_config *config = piga_host_config_default();

    piga_status status = PIGA_STATUS_OK;
    status = piga_host_consume_config(host, config);
    BOOST_REQUIRE_EQUAL(status, PIGA_STATUS_OK);

    status = piga_host_startup(host);
    if(status != PIGA_STATUS_OK) {
        BOOST_TEST_MESSAGE(piga_status_what(&status));
        BOOST_TEST_MESSAGE(piga_errno_what());
    }
    BOOST_REQUIRE_EQUAL(status, PIGA_STATUS_OK);

    // Test default name
    piga_player *player = piga_host_get_player_by_id(host, 0);
    char *receivedName_c = piga_player_get_name(player);
    std::string receivedName(receivedName_c);
    free(receivedName_c);

    BOOST_REQUIRE_EQUAL(receivedName, PIGA_PLAYER_DEFAULT_NAME);

    // Test customized name
    std::string name = "Hello World!";
    piga_player_set_name(player, name.c_str(), name.length());

    receivedName_c = piga_player_get_name(piga_host_get_player_by_id(host, 0));
    receivedName = std::string(receivedName_c);
    free(receivedName_c);

    BOOST_REQUIRE_EQUAL(name, receivedName);

    piga_host_free(host);
}

max_stars_repo_name: Pigaco/libpiga

max_issues_repo_name: Pigaco/libpiga

max_forks_repo_name: Pigaco/libpiga


text:
// Do NOT add anything to this file
// This header from boost takes ages to compile, so we make sure it is compiled
// only once (here)
//#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
#include "test_utils.hpp"

std::string rdfTestFiles[] = { "test/data/om-schema-v0.1.owl", "test/data/om-schema-v0.2.owl", "test/data/om-schema-v0.5.owl" };

std::string getRootDir()
{
    char buffer[1024];
    BOOST_REQUIRE_MESSAGE( readlink("/proc/self/exe", buffer, 1024) != -1, "Retrieving current execution path");
    std::string str(buffer);
    std::vector<std::string> foldernames = { "organization_model", "moreorg" };
    std::string mainfolder;
    size_t textPos;
    for(const std::string& foldername : foldernames )
    {
        size_t pos = str.rfind(foldername + "/");
        if(pos != std::string::npos)
        {
            textPos = pos;
            mainfolder = foldername;
            break;
        }
    }

    std::string executionDir = str.substr(0, textPos);
    std::string configurationPath = executionDir + mainfolder + "/";
    return configurationPath;
}

std::string getOMSchema()
{
    return getRootDir() + "test/data/om-schema-latest.owl";
}

max_stars_repo_name: tomcreutz/knowledge-reasoning-moreorg

max_issues_repo_name: tomcreutz/knowledge-reasoning-moreorg

max_forks_repo_name: tomcreutz/knowledge-reasoning-moreorg


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

 /*
  *   LOCATION:    see http://www.boost.org for most recent version.
  *   FILE         regex_merge_example.cpp
  *   VERSION      see <boost/version.hpp>
  *   DESCRIPTION: regex_merge example:
  *                converts a C++ file to syntax highlighted HTML.
  */

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <iterator>
#include <boost/regex.hpp>
#include <fstream>
#include <iostream>

// purpose:
// takes the contents of a file and transform to
// syntax highlighted code in html format

boost::regex e1, e2;
extern const char* expression_text;
extern const char* format_string;
extern const char* pre_expression;
extern const char* pre_format;
extern const char* header_text;
extern const char* footer_text;

void load_file(std::string& s, std::istream& is)
{
   s.erase();
   if(is.bad()) return;
   s.reserve(static_cast<std::string::size_type>(is.rdbuf()->in_avail()));
   char c;
   while(is.get(c))
   {
      if(s.capacity() == s.size())
         s.reserve(s.capacity() * 3);
      s.append(1, c);
   }
}

int main(int argc, const char** argv)
{
   try{
   e1.assign(expression_text);
   e2.assign(pre_expression);
   for(int i = 1; i < argc; ++i)
   {
      std::cout << "Processing file " << argv[i] << std::endl;
      std::ifstream fs(argv[i]);
      std::string in;
      load_file(in, fs);
      fs.close();
      std::string out_name = std::string(argv[i]) + std::string(".htm");
      std::ofstream os(out_name.c_str());
      os << header_text;
      // strip '<' and '>' first by outputting to a
      // temporary string stream
      std::ostringstream t(std::ios::out | std::ios::binary);
      std::ostream_iterator<char> oi(t);
      boost::regex_merge(oi, in.begin(), in.end(), e2, pre_format, boost::match_default | boost::format_all);
      // then output to final output stream
      // adding syntax highlighting:
      std::string s(t.str());
      std::ostream_iterator<char> out(os);
      boost::regex_merge(out, s.begin(), s.end(), e1, format_string, boost::match_default | boost::format_all);
      os << footer_text;
      os.close();
   }
   }
   catch(...)
   { return -1; }
   return 0;
}

const char* pre_expression = "(<)|(>)|\\r";
const char* pre_format = "(?1<)(?2>)";

const char* expression_text = // preprocessor directives: index 1
                              "(^[[:blank:]]*#(?:[^\\\\\\n]|\\\\[^\\n[:punct:][:word:]]*[\\n[:punct:][:word:]])*)|"
                              // comment: index 2
                              "(//[^\\n]*|/\\*.*?\\*/)|"
                              // literals: index 3
                              "\\<([+-]?(?:(?:0x[[:xdigit:]]+)|(?:(?:[[:digit:]]*\\.)?[[:digit:]]+(?:[eE][+-]?[[:digit:]]+)?))u?(?:(?:int(?:8|16|32|64))|L)?)\\>|"
                              // string literals: index 4
                              "('(?:[^\\\\']|\\\\.)*'|\"(?:[^\\\\\"]|\\\\.)*\")|"
                              // keywords: index 5
                              "\\<(__asm|__cdecl|__declspec|__export|__far16|__fastcall|__fortran|__import"
                              "|__pascal|__rtti|__stdcall|_asm|_cdecl|__except|_export|_far16|_fastcall"
                              "|__finally|_fortran|_import|_pascal|_stdcall|__thread|__try|asm|auto|bool"
                              "|break|case|catch|cdecl|char|class|const|const_cast|continue|default|delete"
                              "|do|double|dynamic_cast|else|enum|explicit|extern|false|float|for|friend|goto"
                              "|if|inline|int|long|mutable|namespace|new|operator|pascal|private|protected"
                              "|public|register|reinterpret_cast|return|short|signed|sizeof|static|static_cast"
                              "|struct|switch|template|this|throw|true|try|typedef|typeid|typename|union|unsigned"
                              "|using|virtual|void|volatile|wchar_t|while)\\>"
                              ;

const char* format_string = "(?1$&)"
                            "(?2$&)"
                            "(?3$&)"
                            "(?4$&)"
                            "(?5$&)";

const char* header_text = "\n\n"
                          "<TITLE>Auto-generated html formated source</TITLE>\n"
                          "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=windows-1252\">\n"
                          "\n"
                          "\n"
                          "

\n
";

const char* footer_text = "
\n\n\n";

max_stars_repo_name: zyiacas/boost-doc-zh

max_issues_repo_name: sdfict/boost-doc-zh

max_forks_repo_name: sdfict/boost-doc-zh


text:
/**************************************************************
 * Copyright (c) 2008 Daniel Pfeifer                          *
 *                                                            *
 * Distributed under the Boost Software License, Version 1.0. *
 **************************************************************/

#ifndef BOOST_SQL_POSTGRES_CONNECTION_HPP
#define BOOST_SQL_POSTGRES_CONNECTION_HPP

#include <libpq-fe.h>
#include <boost/sql/postgres/detail/service.hpp>
#include <boost/sql/detail/connection_base.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/bind.hpp>
#include <boost/sql/detail/callable.hpp>
#include <boost/function.hpp>
#include <stdexcept>
#include <pg_config.h>

namespace boost
{
namespace sql
{
namespace postgres
{

template<typename Param, typename Result>
class statement;

class connection: sql::detail::connection_base<detail::service>
{
public:
	connection(asio::io_service& io_service) :
		sql::detail::connection_base<detail::service>(io_service), impl(0),
				socket(io_service)
	{
	}

	~connection()
	{
		PQfinish(impl);
	}

	void open(const char* conninfo)
	{
		impl = PQconnectdb(conninfo);
		if (PQstatus(impl) != CONNECTION_OK)
			throw std::runtime_error(PQerrorMessage(impl));

		socket.assign(asio::ip::tcp::v4(), PQsocket(impl));
	}

	unsigned long client_version()
	{
		return PG_VERSION_NUM;
	}

	unsigned long server_version()
	{
		return PQserverVersion(impl);
	}

	void execute(const std::string& cmd)
	{
		boost::shared_ptr<PGresult> res(PQexec(impl, cmd.c_str()), PQclear);
		if (PQresultStatus(res.get()) != PGRES_COMMAND_OK)
		{
			throw std::runtime_error(PQresultErrorMessage(res.get()));
		}
	}

	template<typename Signature>
	boost::function<Signature> prepare(std::string const& query)
	{
		return sql::detail::callable<connection, statement, Signature>(*this,
				query);
	}

	PGconn* implementation() const
	{
		return impl;
	}

private:

	void read_handler(const system::error_code& ec)
	{
		if (ec)
		{
			//ois.post(Callback, ec);
		}

		if (!PQconsumeInput(impl))
		{
			//ois.post(Callback, error);
		}

		if (!PQisBusy(impl))
		{
			PGresult * res = PQgetResult(impl);
			//ois.post(Callback, result(res));
		}

		socket.async_read_some(boost::asio::null_buffers(), //
				boost::bind(&connection::read_handler, this, _1));
	}

	PGconn* impl;
	asio::ip::tcp::socket socket;
};

} // end namespace postgres
} // end namespace sql
} // end namespace boost

#endif /*BOOST_SQL_POSTGRES_CONNECTION_HPP*/

max_stars_repo_name: purpleKarrot/async-db

max_issues_repo_name: purpleKarrot/async-db

max_forks_repo_name: purpleKarrot/async-db


text:
 /*
 * Location - Enumeration of location types known to MkE Client
 *
 * Copyright (c) 2017-2021, Magik-Eye Inc.
 * author: Jan Heller, jan@magik-eye.com
 */

#include <boost/asio.hpp>

#include "mke/error.h"
#include "mke/device/location.h"

using namespace mke::device;

LocationEnum Location::toEnum(const std::string &location)
{
  boost::system::error_code ec;
  boost::asio::ip::address ipaddr = boost::asio::ip::address::from_string(location, ec);

  if (!ec)
    {
      if (ipaddr.is_v4())
        return mke::device::IP4_LOCATION;
      else if (ipaddr.is_v6())
       return mke::device::IP6_LOCATION;
    }
  else
    {
      if (location.find("COM") == 0)
        return mke::device::SERIALPORT_LOCATION;
      else if (location.find("/") == 0)
        return mke::device::SERIALPORT_LOCATION;
    }

  return mke::device::UNDEF_LOCATION;
}

max_stars_repo_name: MagikEyeInc/SDK

max_issues_repo_name: MagikEyeInc/SDK

max_forks_repo_name: MagikEyeInc/SDK


text:
#ifndef STAN_MATH_PRIM_SCAL_PROB_CHI_SQUARE_RNG_HPP
#define STAN_MATH_PRIM_SCAL_PROB_CHI_SQUARE_RNG_HPP

#include <boost/random/chi_squared_distribution.hpp>
#include <boost/random/variate_generator.hpp>
#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>
#include <stan/math/prim/scal/err/check_nonnegative.hpp>
#include <stan/math/prim/scal/err/check_not_nan.hpp>
#include <stan/math/prim/scal/err/check_positive_finite.hpp>
#include <stan/math/prim/scal/fun/constants.hpp>
#include <stan/math/prim/scal/fun/multiply_log.hpp>
#include <stan/math/prim/scal/fun/value_of.hpp>
#include <stan/math/prim/scal/fun/gamma_p.hpp>
#include <stan/math/prim/scal/fun/digamma.hpp>
#include <stan/math/prim/scal/fun/grad_reg_inc_gamma.hpp>
#include <stan/math/prim/scal/meta/include_summand.hpp>

namespace stan {
  namespace math {

    /**
     * Return a pseudorandom chi squared variate with the nu degrees of freedom
     * using the specified random number generator.
     *
     * @tparam RNG class of random number generator
     * @param nu positive degrees of freedom parameter
     * @param rng random number generator
     * @return chi squared random variate
     * @throw std::domain_error if nu is nonpositive
     */
    template <class RNG>
    inline double
    chi_square_rng(double nu,
                   RNG& rng) {
      using boost::variate_generator;
      using boost::random::chi_squared_distribution;

      static const char* function("chi_square_rng");

      check_positive_finite(function, "Degrees of freedom parameter", nu);

      variate_generator<RNG&, chi_squared_distribution<> >
        chi_square_rng(rng, chi_squared_distribution<>(nu));
      return chi_square_rng();
    }

  }
}
#endif

max_stars_repo_name: yizhang-cae/torsten

max_issues_repo_name: yizhang-cae/torsten

max_forks_repo_name: yizhang-cae/torsten


text:
#pragma once

#include <string>
#include <vector>
#include <map>
#include <fstream>
#include <memory>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>

namespace proj2cmake
{
namespace vcx
{

namespace fs = boost::filesystem;

enum class ConfigurationType
{
   StaticLibrary,
   DynamicLibrary,
   Application,
   Utility,
   Makefile
};

struct ProjectInfo
{
   std::string guid;
   std::string name;
   fs::path projectFile;
   ProjectInfo() = default;

   ProjectInfo(const ProjectInfo&) = default;

   bool operator<(const ProjectInfo& other) const
   {
      return guid < other.guid;
   }

   bool operator==(const ProjectInfo& other) const
   {
      return guid == other.guid;
   }
};

struct Project
{
    Project() {
        bMultiThreaded = false;
		bMultiThreadedDebug = false;
        spCompileFiles = std::make_shared<std::vector<fs::path>>();
		spIncludeFiles = std::make_shared<std::vector<fs::path>>();
        spAdditionalIncludeDirs = std::make_shared<std::vector<fs::path>>();
        spAdditionalLinkDirs = std::make_shared<std::vector<fs::path>>();
		spReferencedProjects = std::make_shared<std::vector<ProjectInfo>>();
   }
   ConfigurationType type;

   bool bMultiThreaded;
   bool bMultiThreadedDebug;
   std::shared_ptr<std::vector<fs::path>> spCompileFiles;
   std::shared_ptr<std::vector<fs::path>> spIncludeFiles;
   std::shared_ptr<std::vector<fs::path>> spAdditionalIncludeDirs;
   std::shared_ptr<std::vector<fs::path>> spAdditionalLinkDirs;
   std::shared_ptr<std::vector<ProjectInfo>> spReferencedProjects;
};

struct Solution
{
  fs::path basePath;
  std::string name;
  std::map<ProjectInfo, Project> projects;
};

using ProjectPair = std::pair<const ProjectInfo, Project>;
using ProjectsPaths = std::map<fs::path, std::vector<std::shared_ptr<ProjectPair>>>;
};
}


text:
//
// Copyright (c) 2013-2016 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)
//

// Test that header file is self-contained.
#include <beast/http/basic_parser.hpp>

#include "message_fuzz.hpp"

#include <beast/streambuf.hpp>
#include <beast/buffers_debug.hpp>
#include <beast/write_streambuf.hpp>
#include <beast/http/error.hpp>
#include <beast/http/rfc2616.hpp>
#include <beast/detail/ci_char_traits.hpp>
#include <beast/detail/unit_test/suite.hpp>
#include <boost/utility/string_ref.hpp>
#include <cassert>
#include <climits>
#include <map>
#include <new>
#include <random>
#include <type_traits>

namespace beast {
namespace http {

class basic_parser_test : public beast::detail::unit_test::suite
{
    std::mt19937 rng_;

public:
    struct cb_req_checker
    {
        bool method = false;
        bool uri = false;
        bool request = false;
    };

    struct cb_res_checker
    {
        bool reason = false;
        bool response = false;
    };

    template<bool isRequest>
    struct cb_checker
        : public basic_parser<isRequest, cb_checker<isRequest>>
        , std::conditional<isRequest,
                cb_req_checker, cb_res_checker>::type

    {
        bool field = false;
        bool value = false;
        bool headers = false;
        bool body = false;
        bool complete = false;

    private:
        friend class basic_parser<isRequest, cb_checker<isRequest>>;

        void on_method(boost::string_ref const&, error_code&)
        {
            this->method = true;
        }
        void on_uri(boost::string_ref const&, error_code&)
        {
            this->uri = true;
        }
        void on_reason(boost::string_ref const&, error_code&)
        {
            this->reason = true;
        }
        void on_request(error_code&)
        {
            this->request = true;
        }
        void on_response(error_code&)
        {
            this->response = true;
        }
        void on_field(boost::string_ref const&, error_code&)
        {
            field = true;
        }
        void on_value(boost::string_ref const&, error_code&)
        {
            value = true;
        }
        int on_headers(error_code&)
        {
            headers = true;
            return 0;
        }
        void on_body(boost::string_ref const&, error_code&)
        {
            body = true;
        }
        void on_complete(error_code&)
        {
            complete = true;
        }
    };

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

    static
    std::string
    escaped_string(boost::string_ref const& s)
    {
        std::string out;
        out.reserve(s.size());
        char const* p = s.data();
        while(p != s.end())
        {
            if(*p == '\r')
                out.append("\\r");
            else if(*p == '\n')
                out.append("\\n");
            else if (*p == '\t')
                out.append("\\t");
            else
                out.append(p, 1);
            ++p;
        }
        return out;
    }

    template<bool isRequest>
    struct null_parser : basic_parser<isRequest, null_parser<isRequest>>
    {
    };

    template<bool isRequest>
    class test_parser :
        public basic_parser<isRequest, test_parser<isRequest>>
    {
        std::string field_;
        std::string value_;

        void check()
        {
            if(! value_.empty())
            {
                rfc2616::trim_right_in_place(value_);
                fields.emplace(field_, value_);
                field_.clear();
                value_.clear();
            }
        }

    public:
        std::map<std::string, std::string,
            beast::detail::ci_less> fields;
        std::string body;

        void on_field(boost::string_ref const& s, error_code&)
        {
            check();
            field_.append(s.data(), s.size());
        }

        void on_value(boost::string_ref const& s, error_code&)
        {
            value_.append(s.data(), s.size());
        }

        int on_headers(error_code&)
        {
            check();
            return 0;
        }

        void on_body(boost::string_ref const& s, error_code&)
        {
            body.append(s.data(), s.size());
        }
    };

    void
    testCallbacks()
    {
        {
            cb_checker<true> p;
            error_code ec;
            std::string const s =
                "GET / HTTP/1.1\r\n"
                "User-Agent: test\r\n"
                "Content-Length: 1\r\n"
                "\r\n"
                "*";
            p.write(s.data(), s.size(), ec);
            if( expect(! ec))
            {
                expect(p.method);
                expect(p.uri);
                expect(p.request);
                expect(p.field);
                expect(p.value);
                expect(p.headers);
                expect(p.body);
                expect(p.complete);
            }
        }
        {
            cb_checker<false> p;
            error_code ec;
            std::string const s =
                "HTTP/1.1 200 OK\r\n"
                "Server: test\r\n"
                "Content-Length: 1\r\n"
                "\r\n"
                "*";
            p.write(s.data(), s.size(), ec);
            if( expect(! ec))
            {
                expect(p.reason);
                expect(p.response);
                expect(p.field);
                expect(p.value);
                expect(p.headers);
                expect(p.body);
                expect(p.complete);
            }
        }
    }

    // Parse the entire input buffer as a valid message,
    // then parse in two pieces of all possible lengths.
    //
    template<class Parser, class F>
    void
    parse(boost::string_ref const& m, F&& f)
    {
        {
            error_code ec;
            Parser p;
            p.write(m.data(), m.size(), ec);
            if(expect(p.complete()))
                if(expect(! ec, ec.message()))
                    f(p);
        }
        for(std::size_t i = 1; i < m.size() - 1; ++i)
        {
            error_code ec;
            Parser p;
            p.write(&m[0], i, ec);
            if(! expect(! ec, ec.message()))
                continue;
            if(p.complete())
            {
                f(p);
            }
            else
            {
                p.write(&m[i], m.size() - i, ec);
                if(! expect(! ec, ec.message()))
                    continue;
                expect(p.complete());
                f(p);
            }
        }
    }

    // Parse with an expected error code
    //
    template<bool isRequest>
    void
    parse_ev(boost::string_ref const& m, parse_error ev)
    {
        {
            error_code ec;
            null_parser<isRequest> p;
            p.write(m.data(), m.size(), ec);
            if(expect(! p.complete()))
                expect(ec == ev, ec.message());
        }
        for(std::size_t i = 1; i < m.size() - 1; ++i)
        {
            error_code ec;
            null_parser<isRequest> p;
            p.write(&m[0], i, ec);
            if(! expect(! p.complete()))
                continue;
            if(ec)
            {
                expect(ec == ev, ec.message());
                continue;
            }
            p.write(&m[i], m.size() - i, ec);
            if(! expect(! p.complete()))
                continue;
            if(! expect(ec == ev, ec.message()))
                continue;
        }
    }

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

    template<class UInt = std::size_t>
    UInt
    rand(std::size_t n)
    {
        return static_cast<UInt>(
            std::uniform_int_distribution<
                std::size_t>{0, n-1}(rng_));
    }

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

    // Parse a valid message with expected version
    //
    template<bool isRequest>
    void
    version(boost::string_ref const& m,
        unsigned major, unsigned minor)
    {
        parse<null_parser<isRequest>>(m,
            [&](null_parser<isRequest> const& p)
            {
                expect(p.http_major() == major);
                expect(p.http_minor() == minor);
            });
    }

    // Parse a valid message with expected flags mask
    //
    void
    checkf(boost::string_ref const& m, std::uint8_t mask)
    {
        parse<null_parser<true>>(m,
            [&](null_parser<true> const& p)
            {
                expect(p.flags() & mask);
            });
    }

    void
    testVersion()
    {
        version<true>("GET / HTTP/0.0\r\n\r\n", 0, 0);
        version<true>("GET / HTTP/0.1\r\n\r\n", 0, 1);
        version<true>("GET / HTTP/0.9\r\n\r\n", 0, 9);
        version<true>("GET / HTTP/1.0\r\n\r\n", 1, 0);
        version<true>("GET / HTTP/1.1\r\n\r\n", 1, 1);
        version<true>("GET / HTTP/9.9\r\n\r\n", 9, 9);
        version<true>("GET / HTTP/999.999\r\n\r\n", 999, 999);
        parse_ev<true>("GET / HTTP/1000.0\r\n\r\n", parse_error::bad_version);
        parse_ev<true>("GET / HTTP/0.1000\r\n\r\n", parse_error::bad_version);
        parse_ev<true>("GET / HTTP/99999999999999999999.0\r\n\r\n", parse_error::bad_version);
        parse_ev<true>("GET / HTTP/0.99999999999999999999\r\n\r\n", parse_error::bad_version);
    }

    void
    testConnection(std::string const& token,
        std::uint8_t flag)
    {
        checkf("GET / HTTP/1.1\r\nConnection:" + token + "\r\n\r\n", flag);
        checkf("GET / HTTP/1.1\r\nConnection: " + token + "\r\n\r\n", flag);
        checkf("GET / HTTP/1.1\r\nConnection:\t" + token + "\r\n\r\n", flag);
        checkf("GET / HTTP/1.1\r\nConnection: \t" + token + "\r\n\r\n", flag);
        checkf("GET / HTTP/1.1\r\nConnection: " + token + " \r\n\r\n", flag);
        checkf("GET / HTTP/1.1\r\nConnection: " + token + "\t\r\n\r\n", flag);
        checkf("GET / HTTP/1.1\r\nConnection: " + token + " \t\r\n\r\n", flag);
        checkf("GET / HTTP/1.1\r\nConnection: " + token + "\t \r\n\r\n", flag);
        checkf("GET / HTTP/1.1\r\nConnection: \r\n" " " + token + "\r\n\r\n", flag);
        checkf("GET / HTTP/1.1\r\nConnection:\t\r\n" " " + token + "\r\n\r\n", flag);
        checkf("GET / HTTP/1.1\r\nConnection: \r\n" "\t" + token + "\r\n\r\n", flag);
        checkf("GET / HTTP/1.1\r\nConnection:\t\r\n" "\t" + token + "\r\n\r\n", flag);
        checkf("GET / HTTP/1.1\r\nConnection: X," + token + "\r\n\r\n", flag);
        checkf("GET / HTTP/1.1\r\nConnection: X, " + token + "\r\n\r\n", flag);
        checkf("GET / HTTP/1.1\r\nConnection: X,\t" + token + "\r\n\r\n", flag);
        checkf("GET / HTTP/1.1\r\nConnection: X,\t " + token + "\r\n\r\n", flag);
        checkf("GET / HTTP/1.1\r\nConnection: X," + token + " \r\n\r\n", flag);
        checkf("GET / HTTP/1.1\r\nConnection: X," + token + "\t\r\n\r\n", flag);
    }

    void
    testContentLength()
    {
        std::size_t const length = 0;
        std::string const length_s =
            std::to_string(length);

        checkf("GET / HTTP/1.1\r\nContent-Length:"+ length_s + "\r\n\r\n", parse_flag::contentlength);
        checkf("GET / HTTP/1.1\r\nContent-Length: "+ length_s + "\r\n\r\n", parse_flag::contentlength);
        checkf("GET / HTTP/1.1\r\nContent-Length:\t"+ length_s + "\r\n\r\n", parse_flag::contentlength);
        checkf("GET / HTTP/1.1\r\nContent-Length: \t"+ length_s + "\r\n\r\n", parse_flag::contentlength);
        checkf("GET / HTTP/1.1\r\nContent-Length: "+ length_s + " \r\n\r\n", parse_flag::contentlength);
        checkf("GET / HTTP/1.1\r\nContent-Length: "+ length_s + "\t\r\n\r\n", parse_flag::contentlength);
        checkf("GET / HTTP/1.1\r\nContent-Length: "+ length_s + " \t\r\n\r\n", parse_flag::contentlength);
        checkf("GET / HTTP/1.1\r\nContent-Length: "+ length_s + "\t \r\n\r\n", parse_flag::contentlength);
        checkf("GET / HTTP/1.1\r\nContent-Length: \r\n" " "+ length_s + "\r\n\r\n", parse_flag::contentlength);
        checkf("GET / HTTP/1.1\r\nContent-Length:\t\r\n" " "+ length_s + "\r\n\r\n", parse_flag::contentlength);
        checkf("GET / HTTP/1.1\r\nContent-Length: \r\n" "\t"+ length_s + "\r\n\r\n", parse_flag::contentlength);
        checkf("GET / HTTP/1.1\r\nContent-Length:\t\r\n" "\t"+ length_s + "\r\n\r\n", parse_flag::contentlength);
    }

    void
    testTransferEncoding()
    {
        checkf("GET / HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n0\r\n\r\n", parse_flag::chunked);
        checkf("GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n\r\n", parse_flag::chunked);
        checkf("GET / HTTP/1.1\r\nTransfer-Encoding:\tchunked\r\n\r\n0\r\n\r\n", parse_flag::chunked);
        checkf("GET / HTTP/1.1\r\nTransfer-Encoding: \tchunked\r\n\r\n0\r\n\r\n", parse_flag::chunked);
        checkf("GET / HTTP/1.1\r\nTransfer-Encoding: chunked \r\n\r\n0\r\n\r\n", parse_flag::chunked);
        checkf("GET / HTTP/1.1\r\nTransfer-Encoding: chunked\t\r\n\r\n0\r\n\r\n", parse_flag::chunked);
        checkf("GET / HTTP/1.1\r\nTransfer-Encoding: chunked \t\r\n\r\n0\r\n\r\n", parse_flag::chunked);
        checkf("GET / HTTP/1.1\r\nTransfer-Encoding: chunked\t \r\n\r\n0\r\n\r\n", parse_flag::chunked);
        checkf("GET / HTTP/1.1\r\nTransfer-Encoding: \r\n" " chunked\r\n\r\n0\r\n\r\n", parse_flag::chunked);
        checkf("GET / HTTP/1.1\r\nTransfer-Encoding:\t\r\n" " chunked\r\n\r\n0\r\n\r\n", parse_flag::chunked);
        checkf("GET / HTTP/1.1\r\nTransfer-Encoding: \r\n" "\tchunked\r\n\r\n0\r\n\r\n", parse_flag::chunked);
        checkf("GET / HTTP/1.1\r\nTransfer-Encoding:\t\r\n" "\tchunked\r\n\r\n0\r\n\r\n", parse_flag::chunked );
    }

    void
    testFlags()
    {
        testConnection("keep-alive",
            parse_flag::connection_keep_alive);

        testConnection("close",
            parse_flag::connection_close);

        testConnection("upgrade",
            parse_flag::connection_upgrade);

        testContentLength();

        testTransferEncoding();

        checkf(
            "GET / HTTP/1.1\r\n"
            "Upgrade: x\r\n"
            "\r\n",
            parse_flag::upgrade
        );

        parse_ev<true>(
            "GET / HTTP/1.1\r\n"
            "Transfer-Encoding:chunked\r\n"
            "Content-Length: 0\r\n"
            "\r\n", parse_error::illegal_content_length);
    }

    void
    testUpgrade()
    {
        null_parser<true> p;
        boost::string_ref s =
            "GET / HTTP/1.1\r\nConnection: upgrade\r\nUpgrade: WebSocket\r\n\r\n";
        error_code ec;
        p.write(s.data(), s.size(), ec);
        if(! expect(! ec, ec.message()))
            return;
        expect(p.complete());
        expect(p.upgrade());
    }

    void testBad()
    {
        parse_ev<true>(" ",                     parse_error::bad_method);
        parse_ev<true>(" G",                    parse_error::bad_method);
        parse_ev<true>("G:",                    parse_error::bad_request);
        parse_ev<true>("GET  /",                parse_error::bad_uri);
        parse_ev<true>("GET / X",               parse_error::bad_version);
        parse_ev<true>("GET / HX",              parse_error::bad_version);
        parse_ev<true>("GET / HTTX",            parse_error::bad_version);
        parse_ev<true>("GET / HTTPX",           parse_error::bad_version);
        parse_ev<true>("GET / HTTP/.",          parse_error::bad_version);
        parse_ev<true>("GET / HTTP/1000",       parse_error::bad_version);
        parse_ev<true>("GET / HTTP/1. ",        parse_error::bad_version);
        parse_ev<true>("GET / HTTP/1.1000",     parse_error::bad_version);
        parse_ev<true>("GET / HTTP/1.1\r ",     parse_error::bad_crlf);
        parse_ev<true>("GET / HTTP/1.1\r\nf :", parse_error::bad_field);
    }

    void
    testRandomReq(std::size_t N)
    {
        using boost::asio::buffer_cast;
        using boost::asio::buffer_size;
        message_fuzz mg;
        for(std::size_t i = 0; i < N; ++i)
        {
            std::string s;
            {
                streambuf sb;
                mg.request(sb);
                s.reserve(buffer_size(sb.data()));
                for(auto const& b : sb.data())
                    s.append(buffer_cast<char const*>(b),
                        buffer_size(b));
            }
            null_parser<true> p;
            for(std::size_t j = 1; j < s.size() - 1; ++j)
            {
                error_code ec;
                p.write(&s[0], j, ec);
                if(! expect(! ec, ec.message()))
                {
                    log << escaped_string(s);
                    break;
                }
                if(! p.complete())
                {
                    p.write(&s[j], s.size() - j, ec);
                    if(! expect(! ec, ec.message()))
                    {
                        log << escaped_string(s);
                        break;
                    }
                }
                if(! expect(p.complete()))
                    break;
                if(! p.keep_alive())
                {
                    p.~null_parser();
                    new(&p) null_parser<true>{};
                }
            }
        }
    }

    void
    testRandomResp(std::size_t N)
    {
        using boost::asio::buffer_cast;
        using boost::asio::buffer_size;
        message_fuzz mg;
        for(std::size_t i = 0; i < N; ++i)
        {
            std::string s;
            {
                streambuf sb;
                mg.response(sb);
                s.reserve(buffer_size(sb.data()));
                for(auto const& b : sb.data())
                    s.append(buffer_cast<char const*>(b),
                        buffer_size(b));
            }
            null_parser<false> p;
            for(std::size_t j = 1; j < s.size() - 1; ++j)
            {
                error_code ec;
                p.write(&s[0], j, ec);
                if(! expect(! ec, ec.message()))
                {
                    log << escaped_string(s);
                    break;
                }
                if(! p.complete())
                {
                    p.write(&s[j], s.size() - j, ec);
                    if(! expect(! ec, ec.message()))
                    {
                        log << escaped_string(s);
                        break;
                    }
                }
                if(! expect(p.complete()))
                    break;
                if(! p.keep_alive())
                {
                    p.~null_parser();
                    new(&p) null_parser<false>{};
                }
            }
        }
    }

    void testBody()
    {
        auto match =
            [&](std::string const& body)
            {
                return
                    [&](test_parser<true> const& p)
                    {
                        expect(p.body == body);
                    };
            };
        parse<test_parser<true>>(
            "GET / HTTP/1.1\r\nContent-Length: 1\r\n\r\n123", match("1"));
        parse<test_parser<true>>(
            "GET / HTTP/1.1\r\nContent-Length: 3\r\n\r\n123", match("123"));
        parse<test_parser<true>>(
            "GET / HTTP/1.1\r\nContent-Length: 0\r\n\r\n", match(""));
        parse<test_parser<true>>(
            "GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n"
            "1\r\n"
            "a\r\n"
            "0\r\n"
            "\r\n", match("a"));
        parse<test_parser<true>>(
            "GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n"
            "2\r\n"
            "ab\r\n"
            "0\r\n"
            "\r\n", match("ab"));
        parse<test_parser<true>>(
            "GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n"
            "2\r\n"
            "ab\r\n"
            "1\r\n"
            "c\r\n"
            "0\r\n"
            "\r\n", match("abc"));
        parse<test_parser<true>>(
            "GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n"
            "10\r\n"
            "1234567890123456\r\n"
            "0\r\n"
            "\r\n", match("1234567890123456"));
    }

    void run() override
    {
        testCallbacks();
        testVersion();
        testFlags();
        testUpgrade();
        testBad();
        testRandomReq(100);
        testRandomResp(100);
        testBody();
    }
};

BEAST_DEFINE_TESTSUITE(basic_parser,http,beast);

} // http
} // beast