text:
/*
(c) Matthew Slocum 2015

msgComponent.cpp

msgComponent is resbonaible for sending and revieving messages
    upon creation it spins off a thread to listen for incoming messages.
    the parent process takes input from the user and executes commands or sends messages.

*/

#include <iostream>
#include <stdlib.h>
#include <boost/asio.hpp>
#include <pthread.h>
#include <string>
#include "msgComponent.h"
#include "regComponent.h"
#include "secComponent.h"

using namespace std;
using boost::asio::ip::tcp;

msgComponent::msgComponent() {

}

//Code derived from:
// daytime_server.cpp
// ~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See
// at http://www.boost.org/LICENSE_1_0.txt)

//Function for listener thread
//This fucntion listens for incoming connections, recieves a message, decrypts it and displays it.
void* listen(void *threadid) {
    try
      {
        extern regComponent* reg;
        extern secComponent* sec;
        boost::asio::io_service io_service;
        tcp::endpoint endpoint(tcp::v4(), 6283);
        tcp::acceptor acceptor(io_service, endpoint);
        for (;;)
        {
          tcp::iostream stream;
          boost::system::error_code ec;
          acceptor.accept(*stream.rdbuf(), ec);
          //if the is an incomming connection
          if (!ec)
          {
            string message = "";
            string line;
            char c;
            char msg [1034];
            int msg_count=0;
            //get message
            while(stream.get(c)) {
                msg[msg_count++]=c;
            }
            //make holder for plaintext
            char plaintext[msg_count];
            //decrypt message and store in plaintext
            sec->decrypt(msg, msg_count, reg->key, 20, plaintext);
            //display plaintext message if it exists
            if(msg_count>0) {
                cout << endl << endl;
                for(int i=0; i<msg_count-10; i++) {
                    cout << plaintext[i];
                }
                cout << endl;
            }
            //redraw user input prompt
            cout.clear();cout.flush();
            cout << endl << "TauNet [TO: " << reg->name_list[reg->dest] << "]> "; cout.clear(); cout.flush();
          }
        }

      }
      //catch any std exceptions
      catch (std::exception& e)
      {
        std::cerr << e.what() << std::endl;
      }
    pthread_exit(NULL);
}

void msgComponent::run() {
    //spin off thread for listener
    pthread_t thread;
    int rc;
    rc = pthread_create(&thread, NULL, listen, NULL);
    if (rc){
        cout << "Error:unable to create thread," << rc << endl;
        exit(-1);
    }
    command="";
    //draw some ui
    draw_header();
    draw_dest();
    //c&c loop
    while(command!=":q") {
        //get input
        get_input();
        //parse special commands
        //list destinations
        if(command==":dlist") {
            reg->printDest();
        }
        //set destination
        else if (command.find(":dset")==0) {
            //cout << command.substr(6) << endl;
            int d = atoi((command.substr(6)).c_str());
            d--;
            if(d>=0 && d<reg->dest_count) {
                reg->setDest(d);
                draw_dest();
            } else {
                cout << "Destination out of range." << endl;
            }
        }
        //else, its a message, send it!
        //CODE derived from daytime_client.cpp (Boost::asio)
        //Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com)
        //Distributed under the Boost Software License, Version 1.0 at http://www.boost.org/LICENSE_1_0.txt)
        else {
            try {
                boost::asio::io_service io_service;
                boost::asio::ip::tcp::resolver resolver(io_service);
                boost::asio::ip::tcp::resolver::query query(reg->dest_list[reg->dest], "6283");
                //attempt to open connection
                tcp::iostream stream(reg->dest_list[reg->dest], "6283");
                if (!stream)
                {
                  std::cout << "Unable to connect: " << stream.error().message() << std::endl;
                }
                //build message
                string message;
                message = string("version: 0.2\r\n")
                        + "from: " + reg->username + "\r\n"
                        + "to: " + reg->name_list[reg->dest] + "\r\n"
                        + "\r\n"
                        + command + "\r\n";

                //init holder for ciphertext
                char ciphertext [message.length()+10];
                //encrypt the message
                sec->encrypt(message,reg->key,20, ciphertext);
                //send the message
                for(unsigned int i=0; i<message.length()+10; i++) {
                    stream << ciphertext[i];
                }
                //close the connection
                stream.close();
            }
            catch (std::exception& e) {
                std::cout << "Exception: " << e.what() << std::endl;
            }
        }

    }
}

//let the msgComponent know about the regComponent
void msgComponent::bind_regComponent(regComponent * in) {
    reg = in;
}

//let the msgComponent know about the secComponent
void msgComponent::bind_secComponent(secComponent * in) {
    sec = in;
}

void msgComponent::draw_header() {
    system("clear");
    cout << "|------------TauNet Messenger------------|" << endl;
    cout << "|  Commands" << endl;
    cout << "|   :q        - quit" << endl;
    cout << "|   :dlist    - list destinations" << endl;
    cout << "|   :dset #   - set destination" << endl;
    cout << "|------------TauNet Messenger------------|" << endl;
}

void msgComponent::draw_dest() {
    cout << "***     DESTINATION: [" << reg->name_list[reg->dest] << "]" << reg->dest_list[reg->dest] << "     ***" << endl;
}

void msgComponent::get_input() {
    cout << endl;
    cin.clear();
    cout << "TauNet [TO: " << reg->name_list[reg->dest] << "]> ";
    getline(cin,command);
}

void msgComponent::draw_get_input() {
    cout << "TauNet [TO: " << reg->name_list[reg->dest] << "]> ";
}

ext: cpp


text:
/**
 *  @file
 *  @copyright defined in eos/LICENSE.txt
 *  @brief generates serialization/deserialization functions for contracts types
 **/
#include <string>
#include <sstream>
#include <vector>

#include <boost/algorithm/string.hpp>
#include <eosio/chain/types.hpp>
#include <eosio/chain/contracts/abi_serializer.hpp>

#include <fc/io/json.hpp>

using namespace std;
using namespace eosio::chain::contracts;

const string tab = "   ";

struct codegen {

   abi_def abi;
   abi_serializer abis;
   codegen(const abi_def& abi)
   :abi(abi)
   {
      abis.set_abi(abi);
   }

   void generate_ident(ostringstream& output) {
      output << tab << "void print_ident(int n){while(n-->0){print(\"  \");}};" << endl;
   }

   void generate_dump(ostringstream& output, const struct_def& type) {
      output << tab << "void dump(const " << type.name << "& value, int tab=0) {" << endl;
      for(const auto& field : type.fields ) {
         auto field_type = abis.resolve_type(field.type);
         output << tab << tab << "print_ident(tab);";
         output << "print(\"" << field.name << ":[\");";
         if( abis.is_struct(field_type) ) {
            output << "print(\"\\n\"); eosio::dump(value."<< field.name <<", tab+1);";
            output << "print_ident(tab);";
         } else if( field_type == "string" ) {
            output << "prints_l(value."<< field.name <<".get_data(), value."<< field.name <<".get_size());";
         } else if( field_type == "fixed_string32" || field_type == "fixed_string16" ) {
            output << "prints_l(value."<< field.name <<".str, value."<< field.name <<".len);";
         } else if( field_type == "Bytes" ) {
            output << "printhex(value."<< field.name <<".data, value."<< field.name <<".len);";
         } else if( abis.is_integer(field_type) ) {
            auto size = abis.get_integer_size(field_type);
            if(size <= 64) {
               output << "printi(uint64_t(value."<< field.name <<"));";
            } else if (size == 128) {
               output << "printi128(&value."<< field.name <<");";
            } else if (size == 256) {
               output << "printhex((void*)&value."<< field.name <<", sizeof(value."<< field.name <<"));";
            }

         } else if( field_type == "bytes" ) {
            output << "printhex(value."<< field.name <<".data, value."<< field.name <<".len);";
         } else if( field_type == "name" || field_type == "account_name" || field_type == "permission_name" ||\
          field_type == "token_name" || field_type == "table_name" || field_type == "func_name" ) {
            output << "printn(value."<< field.name <<");";
         } else if( field_type == "public_key" ) {
            output << "printhex((void*)value."<< field.name <<".data, 33);";
         } else if( field_type == "time" ) {
            output << "printi(value."<< field.name <<");";
         } else if( field_type == "price" ) {
            output << "printi(value."<< field.name <<".base.amount);print(\"/\");printi(value."<< field.name <<".quote.amount);";
         } else {

         }
         output << "print(\"]\\n\");" << endl;
      }
      output << tab << "}" << endl;
   }

   void generate_current_message_ex(ostringstream& output) {
      output << tab << "template<typename Type>" << endl;
      output << tab << "Type current_message_ex() {" << endl;
      output << tab << tab << "uint32_t size = message_size();" << endl;
      output << tab << tab << "char* data = (char *)eosio::malloc(size);" << endl;
      output << tab << tab << "assert(data && read_message(data, size) == size, \"error reading message\");" << endl;
      output << tab << tab << "Type value;" << endl;
      output << tab << tab << "eosio::raw::unpack(data, size, value);" << endl;
      output << tab << tab << "eosio::free(data);" << endl;
      output << tab << tab << "return value;" << endl;
      output << tab << "}" << endl;
   }

   void generate_current_message(ostringstream& output, const struct_def& type) {
      output << tab << "template<>" << endl;
      output << tab << type.name << " current_message<" << type.name << ">() {" << endl;
      output << tab << tab << "return current_message_ex<" << type.name << ">();" << endl;
      output << tab << "}" << endl;
   }

   void generate_pack(ostringstream& output, const struct_def& type) {
      output << tab << "template<typename Stream> inline void pack( Stream& s, const " << type.name << "& value ) {" << endl;
      for(const auto& field : type.fields ) {
         output << tab << tab << "raw::pack(s, value." << field.name << ");" << endl;
      }
      if( type.base != type_name() )
         output << tab << tab << "raw::pack(s, static_cast<const " << type.base << "&>(value));" << endl;
      output << tab << "}" << endl;
   }

   void generate_unpack(ostringstream& output, const struct_def& type) {
      output << tab << "template<typename Stream> inline void unpack( Stream& s, " << type.name << "& value ) {" << endl;
      for(const auto& field : type.fields ) {
         output << tab << tab << "raw::unpack(s, value." << field.name << ");" << endl;
      }
      if( type.base != type_name() )
         output << tab << tab << "raw::unpack(s, static_cast<" << type.base << "&>(value));" << endl;
      output << tab << "}" << endl;
   }

   void generate() {
      ostringstream output;
      output << "#pragma once" << endl;
      output << "#include <eosiolib/types.hpp>" << endl;
      output << "#include <eosiolib/message.hpp>" << endl;
      output << "#include <eosiolib/datastream.hpp>" << endl;
      output << "#include <eosiolib/raw_fwd.hpp>" << endl;

      output << endl;

      //Generate serialization/deserialization for every cotract type
      output << "namespace eosio { namespace raw {" << endl;
      for(const auto& type : abi.structs) {
         generate_pack(output, type);
         generate_unpack(output, type);
      }
      output << "} }" << endl << endl;

      output << "#include <eosiolib/raw.hpp>" << endl;

      output << "namespace eosio {" << endl;

      generate_ident(output);
      generate_current_message_ex(output);

      for(const auto& type : abi.structs) {
         generate_dump(output, type);
         generate_current_message(output, type);
      }

      output << "} //eosio" << endl;

      cout << output.str() << endl;
   }

};

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

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

   if( argc < 2 )
      return 1;

   auto abi = fc::json::from_file<abi_def>(argv[1]);
   codegen generator(abi);
   generator.generate();

   return 0;
}

max_stars_repo_name: anauman/eosio

max_issues_repo_name: anauman/eosio

max_forks_repo_name: anauman/eosio


text:
/**
 * @file recurrent_attention.hpp
 * @author Marcus Edel
 *
 * Definition of the RecurrentAttention class.
 *
 * mlpack is free software; you may redistribute it and/or modify it under the
 * terms of the 3-clause BSD license.  You should have received a copy of the
 * 3-clause BSD license along with mlpack.  If not, see
 * http://www.opensource.org/licenses/BSD-3-Clause for more information.
 */
#ifndef MLPACK_METHODS_ANN_LAYER_RECURRENT_ATTENTION_HPP
#define MLPACK_METHODS_ANN_LAYER_RECURRENT_ATTENTION_HPP

#include <mlpack/prereqs.hpp>
#include <boost/ptr_container/ptr_vector.hpp>

#include "../visitor/delta_visitor.hpp"
#include "../visitor/output_parameter_visitor.hpp"
#include "../visitor/reset_visitor.hpp"
#include "../visitor/weight_size_visitor.hpp"

#include "layer_types.hpp"
#include "add_merge.hpp"
#include "sequential.hpp"

namespace mlpack {
namespace ann /** Artificial Neural Network. */ {

/**
 * This class implements the Recurrent Model for Visual Attention, using a
 * variety of possible layer implementations.
 *
 * For more information, see the following paper.
 *
 * @code
 * @article{MnihHGK14,
 *   title={Recurrent Models of Visual Attention},
 *   author={Volodymyr Mnih, Nicolas Heess, Alex Graves, Koray Kavukcuoglu},
 *   journal={CoRR},
 *   volume={abs/1406.6247},
 *   year={2014}
 * }
 * @endcode
 *
 * @tparam InputDataType Type of the input data (arma::colvec, arma::mat,
 *         arma::sp_mat or arma::cube).
 * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat,
 *         arma::sp_mat or arma::cube).
 */
template <
    typename InputDataType = arma::mat,
    typename OutputDataType = arma::mat
>
class RecurrentAttention
{
 public:
  /**
   * Default constructor: this will not give a usable RecurrentAttention object,
   * so be sure to set all the parameters before use.
   */
  RecurrentAttention();

  /**
   * Create the RecurrentAttention object using the specified modules.
   *
   * @param start The module output size.
   * @param start The recurrent neural network module.
   * @param start The action module.
   * @param rho Maximum number of steps to backpropagate through time (BPTT).
   */
  template<typename RNNModuleType, typename ActionModuleType>
  RecurrentAttention(const size_t outSize,
                     const RNNModuleType& rnn,
                     const ActionModuleType& action,
                     const size_t rho);

  /**
   * Ordinary feed forward pass of a neural network, evaluating the function
   * f(x) by propagating the activity forward through f.
   *
   * @param input Input data used for evaluating the specified function.
   * @param output Resulting output activation.
   */
  template<typename eT>
  void Forward(arma::Mat<eT>&& input, arma::Mat<eT>&& output);

  /**
   * Ordinary feed backward pass of a neural network, calculating the function
   * f(x) by propagating x backwards trough f. Using the results from the feed
   * forward pass.
   *
   * @param input The propagated input activation.
   * @param gy The backpropagated error.
   * @param g The calculated gradient.
   */
  template<typename eT>
  void Backward(const arma::Mat<eT>&& /* input */,
                arma::Mat<eT>&& gy,
                arma::Mat<eT>&& g);

  /*
   * Calculate the gradient using the output delta and the input activation.
   *
   * @param input The input parameter used for calculating the gradient.
   * @param error The calculated error.
   * @param gradient The calculated gradient.
   */
  template<typename eT>
  void Gradient(arma::Mat<eT>&& /* input */,
                arma::Mat<eT>&& /* error */,
                arma::Mat<eT>&& /* gradient */);

  //! Get the model modules.
  std::vector<LayerTypes<>>& Model() { return network; }

    //! The value of the deterministic parameter.
  bool Deterministic() const { return deterministic; }
  //! Modify the value of the deterministic parameter.
  bool& Deterministic() { return deterministic; }

  //! Get the parameters.
  OutputDataType const& Parameters() const { return parameters; }
  //! Modify the parameters.
  OutputDataType& Parameters() { return parameters; }

  //! Get the input parameter.
  InputDataType const& InputParameter() const { return inputParameter; }
  //! Modify the input parameter.
  InputDataType& InputParameter() { return inputParameter; }

  //! Get the output parameter.
  OutputDataType const& OutputParameter() const { return outputParameter; }
  //! Modify the output parameter.
  OutputDataType& OutputParameter() { return outputParameter; }

  //! Get the delta.
  OutputDataType const& Delta() const { return delta; }
  //! Modify the delta.
  OutputDataType& Delta() { return delta; }

  //! Get the gradient.
  OutputDataType const& Gradient() const { return gradient; }
  //! Modify the gradient.
  OutputDataType& Gradient() { return gradient; }

  /**
   * Serialize the layer
   */
  template<typename Archive>
  void serialize(Archive& ar, const unsigned int /* version */);

 private:
  //! Calculate the gradient of the attention module.
  void IntermediateGradient()
  {
    intermediateGradient.zeros();

    // Gradient of the action module.
    if (backwardStep == (rho - 1))
    {
      boost::apply_visitor(GradientVisitor(std::move(initialInput),
          std::move(actionError)), actionModule);
    }
    else
    {
      boost::apply_visitor(GradientVisitor(std::move(boost::apply_visitor(
          outputParameterVisitor, actionModule)), std::move(actionError)),
          actionModule);
    }

    // Gradient of the recurrent module.
    boost::apply_visitor(GradientVisitor(std::move(boost::apply_visitor(
        outputParameterVisitor, rnnModule)), std::move(recurrentError)),
        rnnModule);

    attentionGradient += intermediateGradient;
  }

  //! Locally-stored module output size.
  size_t outSize;

  //! Locally-stored start module.
  LayerTypes<> rnnModule;

  //! Locally-stored input module.
  LayerTypes<> actionModule;

  //! Number of steps to backpropagate through time (BPTT).
  size_t rho;

  //! Locally-stored number of forward steps.
  size_t forwardStep;

  //! Locally-stored number of backward steps.
  size_t backwardStep;

  //! If true dropout and scaling is disabled, see notes above.
  bool deterministic;

  //! Locally-stored weight object.
  OutputDataType parameters;

  //! Locally-stored model modules.
  std::vector<LayerTypes<>> network;

  //! Locally-stored weight size visitor.
  WeightSizeVisitor weightSizeVisitor;

  //! Locally-stored delta visitor.
  DeltaVisitor deltaVisitor;

  //! Locally-stored output parameter visitor.
  OutputParameterVisitor outputParameterVisitor;

  //! Locally-stored feedback output parameters.
  std::vector<arma::mat> feedbackOutputParameter;

  //! List of all module parameters for the backward pass (BBTT).
  std::vector<arma::mat> moduleOutputParameter;

  //! Locally-stored delta object.
  OutputDataType delta;

  //! Locally-stored gradient object.
  OutputDataType gradient;

  //! Locally-stored input parameter object.
  InputDataType inputParameter;

  //! Locally-stored output parameter object.
  OutputDataType outputParameter;

  //! Locally-stored recurrent error parameter.
  arma::mat recurrentError;

  //! Locally-stored action error parameter.
  arma::mat actionError;

  //! Locally-stored action delta.
  arma::mat actionDelta;

  //! Locally-stored recurrent delta.
  arma::mat rnnDelta;

  //! Locally-stored initial action input.
  arma::mat initialInput;

  //! Locally-stored reset visitor.
  ResetVisitor resetVisitor;

  //! Locally-stored attention gradient.
  arma::mat attentionGradient;

  //! Locally-stored intermediate gradient for the attention module.
  arma::mat intermediateGradient;
}; // class RecurrentAttention

} // namespace ann
} // namespace mlpack

// Include implementation.
#include "recurrent_attention_impl.hpp"

#endif

ext: hpp


text:
#ifndef _MD5_HIERACHY_HPP
#define _MD5_HIERACHY_HPP

#include <boost/fusion/include/adapt_struct.hpp>

namespace md5 {

 struct hierarchy_section
  {
    std::string joint_name;
    int parent_index;
    int flags;
    int start_index;
  };
} /* namespace md5 */

BOOST_FUSION_ADAPT_STRUCT
  (
   md5::hierarchy_section,
   (std::string, joint_name)
   (int, parent_index)
   (int, flags)
   (int, start_index)
  )

#endif /* end of include guard: _MD5_HIERACHY_HPP */


text:
// Eigen::Ref can be used to refer to a matrix *or* a block without copying.
// The referred matrix must have its memory fully allocated: cannot be resized.

#include <iostream>
#include <stdlib.h>
#include <string>
#include <vector>

#include <Eigen/Dense>

using namespace std;

Eigen::MatrixXd A = Eigen::MatrixXd::Random(1, 2);
Eigen::Ref<Eigen::MatrixXd> ref_from_address(Eigen::MatrixXd *address) {
  return *address;
}

int main() {
  std::cout << "A: " << std::endl << A << std::endl << std::endl;

  Eigen::MatrixXd *A_address = &A;
  std::cout << "A_address: " << A_address << std::endl;

  std::cout << "A = Eigen::MatrixXd::Random(2, 4);" << std::endl;
  A = Eigen::MatrixXd::Random(2, 4);
  std::cout << A << std::endl << std::endl;

  std::cout << "ref_from_address(A_address) =  Eigen::MatrixXd::Random(2, 4);"
            << " // Okay, since shape matches" << std::endl;
  ref_from_address(A_address) =  Eigen::MatrixXd::Random(2, 4);
  std::cout << A << std::endl << std::endl;

  std::cout << "ref_from_address(A_address).col(2) = "
            << "Eigen::MatrixXd::Zero(2, 1); // Also okay" << std::endl;
  ref_from_address(A_address).col(2) =  Eigen::MatrixXd::Zero(2, 1);
  std::cout << A << std::endl << std::endl;

  std::cout << "// ref_from_address(A_address) =  "
            << "Eigen::MatrixXd::Ones(2, 10); // ERROR! "
            << "\"DenseBase::resize() does not actually allow to resize.\""
            << std::endl << std::endl;
  // ref_from_address(A_address) =  Eigen::MatrixXd::Ones(2, 10);

  std::cout << "// First need to directly resize NOT USING REF. This destroys "
            << "coeffs if the number of coeffs is different." << std::endl;
  std::cout << "A_address->resize(2, 10);  " << std::endl;
  A_address->resize(2, 10);
  // ref_from_address(A_address).resize(2, 4);  // This gives error.
  std::cout << A << std::endl << std::endl;

  std::cout << "ref_from_address(A_address) =  "
            << "Eigen::MatrixXd::Ones(2, 10); // Now okay" << std::endl;
  ref_from_address(A_address) =  Eigen::MatrixXd::Ones(2, 10);
  std::cout << A << std::endl << std::endl;

  std::cout << "ref_from_address(A_address) << 1, 3, 5, 7, 9, 11, 13, 15, 17, "
            << "19, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20; // Also okay"
            << std::endl;
  ref_from_address(A_address) <<
      1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20;
  std::cout << A << std::endl << std::endl;

  std::cout << "// Aside: resizing is conservative when the number of coeffs "
            << "remains the same." << std::endl;
  std::cout << "A_address->resize(2, 10);  " << std::endl;
  A_address->resize(4, 5);
  std::cout << A << std::endl << std::endl;

  std::cout << "// Coefficient access" << std::endl;
  std::cout << "ref_from_address(A_address)(1, 2) = "
            << ref_from_address(A_address)(1, 2) << std::endl;
  std::cout << "ref_from_address(A_address).data()[9] = "
            << ref_from_address(A_address).data()[9] << std::endl;

  return 0;
}

ext: cc

max_stars_repo_name: karlstratos/mesosphere


text:
/**
 * @Author: Julien Vial-Detambel <l3ninj>
 * @Date:   2018-06-12T11:57:649+01:00
 * @Email:  julien.vial-detambel@epitech.eu
 * @Project: CUDA-Based Simulator of Quantum Systems
 * @Filename: main.cpp
 * @Last modified by:   l3ninj
 * @Last modified time: 2018-08-21T22:17:22+02:00
 * @License: MIT License
 */

#include <iostream>
#include <cmath>
#include <boost/program_options.hpp>

#include "Errors.hpp"
#include "Logger.hpp"
#include "ExecutorManager.hpp"

#include "Parser/ASTGenerator.hpp"
#include "Parser/CircuitBuilder.hpp"
#include "Circuit.hpp"
#include "CircuitCompressor.hpp"
#include "TaskScheduling/CircuitToTaskGraphConverter.hpp"
#include "TaskScheduling/BasicTaskScheduler.hpp"
#include "TaskScheduling/BasicStateStore.hpp"
#include "TaskScheduling/BasicMeasurementResultsTree.hpp"
#include "Worker/Simulator.hpp"
#include "Worker/Worker.hpp"

using namespace StateStore;
using namespace MeasurementResultsTree;

bool g_cpu_execution = false;

int main(int ac, char **av) {
  boost::program_options::options_description desc("Allowed options");
  desc.add_options()
    ("help", "help - produce help message")
    ("cpu", "cpu - force linear algebra execution on the cpu")
    ("sample", boost::program_options::value<int>(),
    "sample - set sample level (int)")
    ("input-file", boost::program_options::value<std::string>(),
    "input file - first positional argument (string)");

  boost::program_options::positional_options_description p;
  p.add("input-file", -1);

  boost::program_options::variables_map vm;
  boost::program_options::store(boost::program_options::command_line_parser(ac, av).options(desc).positional(p).run(), vm);
  boost::program_options::notify(vm);

  if (vm.count("help")) {
    std::cout << desc << std::endl;
    return EXIT_FAILURE;
  }

  if (vm.count("cpu")) {
    LOG(Logger::INFO, "Naive CPU linear algebra execution forced.");
    g_cpu_execution = true;
  }

  int sample_level = 1000;
  if (vm.count("sample")) {
    LOG(Logger::INFO, "Set sample level to " << vm["sample"].as<int>());
    sample_level = vm["sample"].as<int>();
  } else {
    LOG(Logger::INFO, "Sample level is 1000 by default");
  }

  if (vm.count("input-file")) {
    LOG(Logger::INFO, "Set " << vm["input-file"].as<std::string>()
    << " as input file");
  } else {
    LOG(Logger::ERROR, "Need at least the file argument");
    return EXIT_FAILURE;
  }

  // Matrix m1(new Tvcplxd(64*64, 1.0), 64, 64);
  // Matrix m2(new Tvcplxd(64*64, 1.0), 64, 64);
  // Matrix m3(new Tvcplxd(64*64), 64, 64);
  // Matrix v1(new Tvcplxd(1*64, 1.0), 1, 64);
  // std::cout << "NORM " << v1.normalize() << std::endl;
  // Matrix v2(new Tvcplxd(1*64), 1, 64);
  // std::cout << "TRACE " << m1.trace() << std::endl;

  // m3 = m1 * m2;
  // std::cout << "multiplication (matrix)" << m3 << std::endl;
  // v2 = m1 * v1;
  // std::cout << "multiplication (vector)" << v2 << std::endl;

  Parser::AST::t_AST ast;
  /* Reads the file and generate an AST */
  try {
    ast = Parser::ASTGenerator()(av[1]);
  } catch (const std::ios_base::failure &e) {
    LOG(Logger::ERROR, "Cannot open/parse file " << av[1]);
    return EXIT_FAILURE;
  } catch (const OpenQASMError &e) {
    LOG(Logger::ERROR, "The AST Generator encountered ill-formated OpenQASM");
    return EXIT_FAILURE;
  }

  Circuit circuit;
  /* Reads the AST and generate a Circuit */
  try {
    circuit = CircuitBuilder(av[1])(ast);
    circuit = CircuitCompressor(circuit)();
    LOG(Logger::DEBUG, "Optimized circuit:" << std::endl << circuit);
  } catch (const OpenQASMError& e) {
    LOG(Logger::ERROR, "Error while generating the circuit: " << e.what());
    return EXIT_FAILURE;
  }

  std::shared_ptr<IMeasurementResultsTree> measurementTree = std::make_shared<BasicMeasurementResultsTree>(sample_level);

  /* Convert circuit to graph of tasks */
  CircuitToTaskGraphConverter converter(circuit);
  TaskGraph::Graph graph = converter.generateTaskGraph(*measurementTree);
  LOG(Logger::INFO, "Task graph:" << graph);

  /* Creates scheduler and state store*/
  std::shared_ptr<ITaskScheduler> scheduler = std::make_shared<BasicTaskScheduler>(graph);
  std::shared_ptr<IStateStore> stateStore = std::make_shared<BasicStateStore>(graph);

  /* Start a worker */
  Worker worker = Worker(*scheduler, *stateStore, *measurementTree);
  worker();

  /* End of the simulation */
  measurementTree->printResults(circuit.creg);

  return EXIT_SUCCESS;
}


text: #include <boost/numeric/interval/compare.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/**
 * @author J Howard Johnson
 * @file sigprune_fet.cc
 * @brief Calculate Fisher's exact test significance levels
 *
 *
 * Technologies langagieres interactives / Interactive Language Technologies
 * Inst. de technologie de l'information / Institute for Information Technology
 * Conseil national de recherches Canada / National Research Council Canada
 * Copyright 2006-2011, Sa Majeste la Reine du Chef du Canada /
 * Copyright 2006-2011, Her Majesty in Right of Canada
 */

#include <iostream>
#include <fstream>
#include <cmath>
#include <boost/math/special_functions/gamma.hpp>

#include "file_utils.h"
#include "arg_reader.h"
#include "printCopyright.h"

using namespace Portage;
using namespace std;

static char help_message[] = "\n\
sigprune_fet [options] [INFILE [OUTFILE]]\n\
\n\
  Copy INFILE to OUTFILE (default stdin to stdout)\n\
  adding 3 fields to the beginning:\n\
     (1) sort key for log p level\n\
     (2) log p level\n\
     (3) flag\n\
         0 : anti-linked (p_level > 0.50)\n\
         1 : linked with log p level > alpha\n\
         2 : linked with log p level = alpha (1-1-1's)\n\
         3 : linked with log p level < alpha\n\
\n\
Options:\n\
\n\
  -v    Write progress reports to cerr.\n\
  -c    Don't cap anti-linked p_levels at 0.5. Using this\n\
        flag ensures monotonic scores as joint frequency decreases while\n\
        marginals are held constant.\n\
  -l    Minimum flag value to output (for pruning)\n\
  -n NL Copy only first NL lines [0 = all]\n\
";

// globals

static bool verbose = false;
static bool no_cap = false;
static Uint num_lines = 0;
static Uint flag_threshold = 0;
static string infile( "-" );
static string outfile( "-" );

// arg processing

void getArgs( int argc, char* argv[] )
{
   const char* switches[] = { "v", "c", "n:", "l:" };
   ArgReader arg_reader( ARRAY_SIZE( switches ), switches, 0, 2, help_message );
   arg_reader.read( argc - 1, argv + 1 );

   arg_reader.testAndSet( "v", verbose );
   arg_reader.testAndSet( "c", no_cap );
   arg_reader.testAndSet( "n", num_lines );
   arg_reader.testAndSet( "l", flag_threshold );

   arg_reader.testAndSet( 0, "infile", infile );
   arg_reader.testAndSet( 1, "outfile", outfile );
}

typedef long double quad;

quad lnfact( double x )
{
   return lgamma( (quad) x + 1.0 );
}

double ln_hyper( double C_xy, double C_x, double C_y, double nn )
{
   quad result =
      - lnfact( C_xy )
      + lnfact( C_x )
      - lnfact( C_x - C_xy )
      + lnfact( C_y )
      - lnfact( C_y - C_xy )
      + lnfact( nn - C_x )
      - lnfact( nn - C_x - C_y + C_xy )
      + lnfact( nn - C_y )
      - lnfact( nn );
   return result;
}

double lnsum( double ln_x, double ln_y )
{
   if ( ln_x < ln_y ) swap( ln_x, ln_y );
   double del = ln_y - ln_x;
   double eps = exp( del );
   if ( del < 10.0 ) return ln_x + log( 1.0 + eps );
   double last_result = 0.0;
   double result = ln_x;
   double power = eps;
   double i = 1.0;
   while ( result != last_result ) {
      last_result = result;
      result = last_result + power / i;
      power *= -eps;
      ++i;
   }
   return result;
//   return ln_x + log( exp( ln_y - ln_x ) + 1.0 );
}

double ln_p_value( double C_xy, double C_x, double C_y, double nn )
{
   double ln_p = ln_hyper( C_xy, C_x, C_y, nn );
   double result = ln_p;
   double C_xY = C_x - C_xy;
   double C_Xy = C_y - C_xy;
   double C_XY = nn - C_x - C_y + C_xy;
   double C_xy_lim = ( ( C_x < C_y ) ? C_x : C_y );
   double last_result = 0.0;
   for ( ++C_xy;
         C_xy <= C_xy_lim && result != last_result;
         ++C_xy ) {
      last_result = result;
      ln_p +=   ( log( C_Xy-- ) + log( C_xY-- ) )
              - ( log( C_xy   ) + log( ++C_XY ) );
      result = lnsum( result, ln_p );
   }
   return result;
}

string write_b64( double i )
{
   string result;
   int nd = 0;
   int digit;
   int d[ 20 ];
   if ( i > 0 ) {
      while ( nd < 20 && i > 0 ) {
         digit = fmod( i, 64.0 );
         d[ nd++ ] = digit;
         i = ( i - digit ) / 64.0;
      }
      result.push_back( 'P' + nd );
      while ( nd > 0 ) {
         result.push_back( '0' + d[ --nd ] );
      }
   } else {
      i = -i;
      while ( nd < 20 && i > 0 ) {
         digit = fmod( i, 64.0 );
         d[ nd++ ] = digit;
         i = ( i - digit ) / 64.0;
      }
      result.push_back( 'O' - nd );
      while ( nd > 0 ) {
         result.push_back( 'o' - d[ --nd ] );
      }
   }
   return result;
}

int main( int argc, char* argv[] )
{
   printCopyright(2006, "sigprune_fet");
   getArgs( argc, argv );

   iSafeMagicStream istr( infile );
   oSafeMagicStream ostr( outfile );

   Uint lineno = 0;
   string line;
   string line_copy;

   ssize_t read;

   int i;
   vector< char * > field;

   while (    getline( istr, line )
           && (    lineno++ < num_lines
                || num_lines == 0 ) ) {
      line_copy = line;
      read = line.length();
      field.resize( 0 );
      field.push_back( &line[ 0 ] );
      for ( i = 0; i < read; ++i ) {
         if (    line[ i ] == '\t'
              || line[ i ] == '\n' ) {
            line[ i ] = '\0';
            field.push_back( &line[ i + 1 ] );
         }
      }
      double C_fr_en = strtod( field[ 1 ], 0 );
      double C_fr    = strtod( field[ 2 ], 0 );
      double C_en    = strtod( field[ 3 ], 0 );
      double nn      = strtod( field[ 4 ], 0 );
      if (    0.0 > C_fr_en
           || C_fr_en > C_fr
           || C_fr_en > C_en
           || C_fr > nn
           || C_en > nn ) {
         error(ETFatal, "Illegal contingency table\n%d : %d : %d : %d : %d", lineno, C_fr_en, C_fr, C_en, nn);
      }
      double minus_ln_nn = -log( nn );
      Uint flag;
      double p_value;

// Anti-linked
      if ( C_fr_en * nn < C_fr * C_en ) {
         flag = 0;
         p_value = no_cap ? ln_p_value( C_fr_en, C_fr, C_en, nn ) : -log( 2.0 );
      }

// 1-1-1 's
      else if ( C_fr_en == 1.0 && C_fr == 1.0 && C_en == 1.0 ) {
         flag = 2;
         p_value = minus_ln_nn;
      }

// Associated less strongly than 1-1-1's
      else {
         p_value = ln_p_value( C_fr_en, C_fr, C_en, nn );
         if ( p_value > minus_ln_nn ) {
            flag = 1;
         }

// Associated more strongly than 1-1-1's
         else {
            flag = 3;
         }
      }

      if ( flag >= flag_threshold ) {
         double s_p_value = floor( p_value * 1.0e8 + 0.5 );
         ostr << write_b64( s_p_value ) << '\t';
         ostr << setprecision( 14 );
         ostr << s_p_value * 1.0e-8 << '\t';
         ostr << flag << '\t';
         ostr << line_copy << '\n';
      }
   }
}

max_stars_repo_name: nrc-cnrc/Portage-SMT-TAS

max_issues_repo_name: nrc-cnrc/Portage-SMT-TAS

max_forks_repo_name: nrc-cnrc/Portage-SMT-TAS


text:
#include "omnicore/version.h"

#include "config/bitcoin-config.h"
#include "test/test_bitcoin.h"

#include <boost/test/unit_test.hpp>

#include <string>

BOOST_FIXTURE_TEST_SUITE(omnicore_version_tests, BasicTestingSetup)

BOOST_AUTO_TEST_CASE(version_comparison)
{
    BOOST_CHECK(OMNICORE_VERSION > 1000000); // Omni Core v0.0.10.0
}

/**
 * The following tests are very unhandy, because any version bump
 * breaks the tests.
 *
 * TODO: might be removed completely.
 */

BOOST_AUTO_TEST_CASE(version_string)
{
    BOOST_CHECK_EQUAL(OmniCoreVersion(), "0.3.1");
}

BOOST_AUTO_TEST_CASE(version_number)
{
    BOOST_CHECK_EQUAL(OMNICORE_VERSION, 30001000);
}

BOOST_AUTO_TEST_CASE(config_package_version)
{
    // the package version is used in the file names:
    BOOST_CHECK_EQUAL(PACKAGE_VERSION, "0.3.1");
}

BOOST_AUTO_TEST_SUITE_END()

max_forks_repo_name: yinzhiqing/bitcoin-omni


text:
//
// Copyright (c) 2009-2013 Mart Haitjema, Charlie Wiseman, Jyoti Parwatikar, John DeHart
// and Washington University in St. Louis
//
// 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/shared_ptr.hpp>
#include "nmd_includes.h"

add_vlan_req::add_vlan_req(uint8_t *mbuf, uint32_t size) : add_vlan(mbuf, size)
{
}

add_vlan_req::add_vlan_req() : add_vlan("")
{
}

add_vlan_req::~add_vlan_req()
{
}

bool add_vlan_req::handle()
{
  ostringstream msg;
  NCCP_StatusType status = NCCP_Status_Fine;

  switch_vlan vlan;

  if (!vlans->add_vlan(vlan, getSessionID())) status = NCCP_Status_Failed;

  msg << "add_vlan_req::handle() allocated vlan " << vlan << " for session " << getSessionID();
  write_log(msg.str());

  add_vlan_response* resp = new add_vlan_response(this, status, vlan);
  resp->send();
  delete resp;

  return true;
}

delete_vlan_req::delete_vlan_req(uint8_t *mbuf, uint32_t size) : delete_vlan(mbuf, size)
{
}

delete_vlan_req::delete_vlan_req(switch_vlan vlan_id) : delete_vlan(vlan_id, "")
{
}

delete_vlan_req::~delete_vlan_req()
{
}

bool delete_vlan_req::handle()
{
  ostringstream msg;
  NCCP_StatusType status = NCCP_Status_Fine;

  msg << "delete_vlan_req::handle() deleting vlan " << vlanid << " for session: " << getSessionID();
  write_log(msg.str());

  if (!vlans->delete_vlan(vlanid, getSessionID())) status = NCCP_Status_Failed;

  // SNMP message to delete VLAN

  switch_response* resp = new switch_response(this, status);
  resp->send();
  delete resp;

  return true;
}

add_to_vlan_req::add_to_vlan_req(uint8_t *mbuf, uint32_t size) : add_to_vlan(mbuf, size)
{
}

add_to_vlan_req::add_to_vlan_req(switch_vlan vlan_id, switch_port &p) : add_to_vlan(vlan_id, p, "")
{
}

add_to_vlan_req::~add_to_vlan_req()
{
}

bool add_to_vlan_req::handle()
{
  ostringstream msg;
  NCCP_StatusType status = NCCP_Status_Fine;

  msg << "add_to_vlan_req::handle() adding " << port
      << " to vlan " << vlanid << " for session: " << getSessionID() ;
  write_log(msg.str());

  if (!vlans->add_to_vlan(vlanid, port, getSessionID()))
  //if (!vlans->add_to_vlan(this, getSessionID()))
    {
      status = NCCP_Status_Failed;
      // SNMP message to add port to VLAN
    }

  switch_response* resp = new switch_response(this, status);
  resp->send();
  delete resp;

  return true;
  //return false; //don't delete request since it will be handled later by the session
}

void add_to_vlan_req::send_response(bool fine)
{
  ostringstream msg;
  NCCP_StatusType status = NCCP_Status_Fine;
  msg << "add_to_vlan_req::send_response(";
  if (!fine)
    {
      msg << "failed";
      status = NCCP_Status_Failed;
    }
  else msg << "succeeded";
  msg << ") adding " << port
      << " to vlan " << vlanid << " for session: " << getSessionID() ;
  write_log(msg.str());

  switch_response* resp = new switch_response(this, status);
  resp->send();
  delete resp;
}

delete_from_vlan_req::delete_from_vlan_req(uint8_t *mbuf, uint32_t size) : delete_from_vlan(mbuf, size)
{
}

delete_from_vlan_req::delete_from_vlan_req(switch_vlan vlan, switch_port &p) : delete_from_vlan(vlan, p, "")
{
}

delete_from_vlan_req::~delete_from_vlan_req()
{
}

bool delete_from_vlan_req::handle()
{
  ostringstream msg;
  NCCP_StatusType status = NCCP_Status_Fine;

  msg << "delete_from_vlan_req::handle() removing " << port
      << " from vlan " << vlanid << " for session: " << getSessionID();
  write_log(msg.str());
  // SNMP message to remove port from VLAN

  // if (!vlans->delete_from_vlan(vlanid, port, getSessionID())) status = NCCP_Status_Failed;
  //just wait for vlan removal to clear whole vlan
  switch_response* resp = new switch_response(this, status);
  resp->send();
  delete resp;

  return true;
}

start_session_req::start_session_req(uint8_t *mbuf, uint32_t size) : start_session(mbuf, size)
{
}

start_session_req::start_session_req() : start_session("")
{
}

start_session_req::~start_session_req()
{
}

bool start_session_req::handle()
{
  ostringstream msg;
  NCCP_StatusType status = NCCP_Status_Fine;

  if (!vlans->create_session_vlans(getSessionID()))
    {
      status = NCCP_Status_Failed;
      msg << "start_session_req::handle() failed creating vlans for session " << getSessionID();
    }
  else
    msg << "start_session_req::handle() created vlans for session " << getSessionID();
  write_log(msg.str());

  switch_response* resp = new switch_response(this, status);
  resp->send();
  delete resp;

  return true;
}

end_session_req::end_session_req(uint8_t *mbuf, uint32_t size) : end_session(mbuf, size)
{
}

end_session_req::end_session_req() : end_session("")
{
}

end_session_req::~end_session_req()
{
}

bool end_session_req::handle()
{
  ostringstream msg;
  NCCP_StatusType status = NCCP_Status_Fine;

  if (!vlans->clear_session(getSessionID()))
    {
      status = NCCP_Status_Failed;
      msg << "end_session_req::handle() failed for session " << getSessionID();
    }
  else
    msg << "end_session_req::handle() cleared session " << getSessionID();
  write_log(msg.str());

  switch_response* resp = new switch_response(this, status);
  resp->send();
  delete resp;

  return true;
}

initialize_req::initialize_req(uint8_t *mbuf, uint32_t size) : initialize(mbuf, size)
{
}

initialize_req::initialize_req() : initialize()
{
}

initialize_req::~initialize_req()
{
}

// Mart: 6/17/10
struct parms {
  std::string switch_id;
  unsigned int ret_status;
};

void *initialize_switch_thread(void *arg)
{
  struct parms *p = (struct parms *)arg;
  p->ret_status = NCCP_Status_Fine;
  ostringstream msg;
  msg << "initialize_req::handle() initializing " << p->switch_id;
  write_log(msg.str());

  if (!initialize_switch(p->switch_id)) p->ret_status = NCCP_Status_Failed;

  pthread_exit((void *)p);
  return NULL;
}

bool initialize_req::handle()
{
  NCCP_StatusType status = NCCP_Status_Fine;

  // Mart: 6/17/10
  // Lets spawn a thread to initialize each switch
  pthread_t *threads;
  struct parms *p;
  int n, i = 0;
  n = switches.size();
  threads = new pthread_t[n];
  p = new parms[n];
  // remember set of switches
  eth_switches->set_switches(switches);

  // loop through set of switches
  for (list<switch_info>::iterator iter = switches.begin();
       iter != switches.end(); iter++) {
    p[i].switch_id = iter->getSwitchId();
    i++;
  }

  // launch a new thread to initialize each switch
  for (i = 0; i < n; i++) {
    pthread_create(&threads[i], NULL, initialize_switch_thread, (void*)(&p[i]));
  }

  // wait for all threads to complete and clean up
  for (i = 0; i < n; i++) {
    struct parms *pp;
    pthread_join(threads[i], (void**)&pp);
    if (pp->ret_status != NCCP_Status_Fine) {
      status = NCCP_Status_Failed;
      ostringstream msg;
      msg << "initialize_req:handle() failed to initialize switch " << pp->switch_id;
      write_log(msg.str());
    }
  }
  delete [] threads;
  delete [] p;

  if (status == NCCP_Status_Fine)//only initialize vlans if switch initialization was successful
    vlans->initialize_vlans();

  switch_response* resp = new switch_response(this, status);
  resp->send();
  delete resp;

  return true;

}

max_stars_repo_name: WU-ARL/ONLdaemons

max_issues_repo_name: WU-ARL/ONLdaemons

max_forks_repo_name: WU-ARL/ONLdaemons


text:
#include "Day11-HexEd.h"

#include <AdventOfCodeCommon/DisableLibraryWarningsMacros.h>

__BEGIN_LIBRARIES_DISABLE_WARNINGS
#include <boost/algorithm/string.hpp>

#include <fstream>
#include <iostream>
__END_LIBRARIES_DISABLE_WARNINGS

int main()
{
    namespace CurrentDay = AdventOfCode::Year2017::Day11;

    std::fstream fileIn("input.txt");

    std::string commaSeparatedPath;
    fileIn >> commaSeparatedPath;

    std::vector<std::string> inputPath;
    boost::split(inputPath, commaSeparatedPath, boost::is_any_of(","));

    std::cout << "First part: " << CurrentDay::numStepsFromStartAtEnd(inputPath) << std::endl;
    std::cout << "Second part: " << CurrentDay::maxNumStepsFromStart(inputPath) << std::endl;
}

max_stars_repo_name: dbartok/advent-of-code-cpp

max_issues_repo_name: dbartok/advent-of-code-cpp

max_forks_repo_name: dbartok/advent-of-code-cpp


text:
//
// Copyright RIME Developers
// Distributed under the BSD License
//

#include <boost/format.hpp>
#include <gtest/gtest.h>
#include <rime/component.h>
#include <rime/config.h>

using namespace rime;

class RimeConfigCompilerTestBase : public ::testing::Test {
 protected:
  RimeConfigCompilerTestBase() = default;

  virtual string test_config_id() const = 0;

  virtual void SetUp() {
    component_.reset(new ConfigComponent<ConfigBuilder>);
    config_.reset(component_->Create(test_config_id()));
  }

  the<Config::Component> component_;
  the<Config> config_;
};

class RimeConfigCompilerTest : public RimeConfigCompilerTestBase {
 protected:
  string test_config_id() const override {
    return "config_compiler_test";
  }
};

TEST_F(RimeConfigCompilerTest, IncludeLocalReference) {
  for (size_t i = 0; i < 4; ++i) {
    auto prefix = boost::str(boost::format("include_local_reference/@%u/") % i);
    EXPECT_TRUE(config_->IsNull(prefix + "__include"));
    string actual;
    EXPECT_TRUE(config_->GetString(prefix + "terrans/player", &actual));
    EXPECT_EQ("slayers_boxer", actual);
    EXPECT_TRUE(config_->GetString(prefix + "protoss/player", &actual));
    EXPECT_EQ("grrrr", actual);
    EXPECT_TRUE(config_->GetString(prefix + "zerg/player", &actual));
    EXPECT_EQ("yellow", actual);
  }
}

TEST_F(RimeConfigCompilerTest, IncludeExternalReference) {
  const string& prefix = "include_external_reference/";
  EXPECT_TRUE(config_->IsNull(prefix + "terrans/__include"));
  int mineral = 0;
  EXPECT_TRUE(config_->GetInt(prefix + "terrans/tank/cost/mineral", &mineral));
  EXPECT_EQ(150, mineral);
  int gas = 0;
  EXPECT_TRUE(config_->GetInt(prefix + "terrans/tank/cost/gas", &gas));
  EXPECT_EQ(100, gas);
  EXPECT_TRUE(config_->IsNull(prefix + "protoss"));
  EXPECT_TRUE(config_->IsNull(prefix + "zerg"));
}

TEST_F(RimeConfigCompilerTest, IncludeExternalFile) {
  const string& prefix = "include_external_file/";
  EXPECT_TRUE(config_->IsNull(prefix + "__include"));
  EXPECT_TRUE(config_->IsMap(prefix + "terrans"));
  EXPECT_TRUE(config_->IsMap(prefix + "protoss"));
  EXPECT_TRUE(config_->IsMap(prefix + "zerg"));
  int number = 0;
  EXPECT_TRUE(config_->GetInt(prefix + "terrans/supply/produced", &number));
  EXPECT_EQ(28, number);
  EXPECT_TRUE(config_->IsList(prefix + "protoss/air_force"));
  string name;
  EXPECT_TRUE(config_->GetString(prefix + "zerg/queen", &name));
  EXPECT_EQ("Kerrigan", name);
}

TEST_F(RimeConfigCompilerTest, PatchReference) {
  const string& prefix = "patch_reference/";
  EXPECT_TRUE(config_->IsNull(prefix + "__patch"));
  EXPECT_EQ(4, config_->GetListSize(prefix + "battlefields"));
  string map;
  EXPECT_TRUE(config_->GetString(prefix + "battlefields/@3", &map));
  EXPECT_EQ("match point", map);
}

TEST_F(RimeConfigCompilerTest, PatchLiteral) {
  const string& prefix = "patch_literal/";
  EXPECT_TRUE(config_->IsNull(prefix + "__patch"));
  EXPECT_EQ(6, config_->GetListSize(prefix + "zerg/ground_units"));
  string unit;
  EXPECT_TRUE(config_->GetString(prefix + "zerg/ground_units/@5", &unit));
  EXPECT_EQ("lurker", unit);
  // assert that we patched on a copy of the included node
  EXPECT_EQ(5, config_->GetListSize("/starcraft/zerg/ground_units"));
}

TEST_F(RimeConfigCompilerTest, PatchList) {
  const string& prefix = "patch_list/";
  EXPECT_TRUE(config_->IsNull(prefix + "protoss/__patch"));
  EXPECT_EQ(8, config_->GetListSize(prefix + "protoss/ground_units"));
  string unit;
  EXPECT_TRUE(config_->GetString(prefix + "protoss/ground_units/@6", &unit));
  EXPECT_EQ("dark templar", unit);
  EXPECT_TRUE(config_->GetString(prefix + "protoss/ground_units/@7", &unit));
  EXPECT_EQ("dark archon", unit);
  // assert that we patched on a copy of the included node
  EXPECT_EQ(6, config_->GetListSize("/starcraft/protoss/ground_units"));
}

class RimeConfigDependencyTest : public RimeConfigCompilerTestBase {
 protected:
  string test_config_id() const override {
    return "config_dependency_test";
  }
};

TEST_F(RimeConfigDependencyTest, DependencyChaining) {
  const string& prefix = "dependency_chaining/";
  EXPECT_TRUE(config_->IsNull(prefix + "alpha/__include"));
  EXPECT_TRUE(config_->IsNull(prefix + "beta/__include"));
  EXPECT_TRUE(config_->IsNull(prefix + "delta/__include"));
  string value;
  EXPECT_TRUE(config_->GetString(prefix + "alpha", &value));
  EXPECT_EQ("success", value);
  EXPECT_TRUE(config_->GetString(prefix + "beta", &value));
  EXPECT_EQ("success", value);
  EXPECT_TRUE(config_->GetString(prefix + "delta", &value));
  EXPECT_EQ("success", value);
}

// Unit test for https://github.com/rime/librime/issues/141
TEST_F(RimeConfigDependencyTest, DependencyPriorities) {
  const string& prefix = "dependency_priorities/";
  EXPECT_TRUE(config_->IsNull(prefix + "terrans/__include"));
  EXPECT_TRUE(config_->IsNull(prefix + "terrans/__patch"));
  EXPECT_TRUE(config_->IsNull(prefix + "protoss/__include"));
  EXPECT_TRUE(config_->IsNull(prefix + "protoss/__patch"));
  string player;
  EXPECT_TRUE(config_->GetString(prefix + "terrans/player", &player));
  EXPECT_EQ("nada", player);
  EXPECT_TRUE(config_->GetString(prefix + "protoss/player", &player));
  EXPECT_EQ("bisu", player);
}

class RimeConfigOptionalReferenceTest : public RimeConfigCompilerTestBase {
 protected:
  string test_config_id() const override {
    return "config_optional_reference_test";
  }
};

TEST_F(RimeConfigOptionalReferenceTest, OptionalReference) {
  const string& prefix = "/";
  EXPECT_TRUE(config_->IsNull(prefix + "__include"));
  EXPECT_TRUE(config_->IsNull(prefix + "__patch"));
  bool untouched;
  EXPECT_TRUE(config_->GetBool(prefix + "untouched", &untouched));
  EXPECT_TRUE(untouched);
}

class RimeConfigMergeTest : public RimeConfigCompilerTestBase {
 protected:
  string test_config_id() const override {
    return "config_merge_test";
  }
};

TEST_F(RimeConfigMergeTest, AppendWithInclude) {
  const string& prefix = "append_with_include/";
  EXPECT_TRUE(config_->IsNull(prefix + "list/__include"));
  EXPECT_TRUE(config_->IsNull(prefix + "list/__append"));

  EXPECT_TRUE(config_->IsList(prefix + "list"));
  EXPECT_EQ(6 + 2, config_->GetListSize(prefix + "list"));
  string unit;
  EXPECT_TRUE(config_->GetString(prefix + "list/@6", &unit));
  EXPECT_EQ("dark templar", unit);
  EXPECT_TRUE(config_->GetString(prefix + "list/@7", &unit));
  EXPECT_EQ("dark archon", unit);

  // verify that we append to a copy and the original list is untouched
  EXPECT_EQ(6, config_->GetListSize("/starcraft/protoss/ground_units"));
}

TEST_F(RimeConfigMergeTest, AppendWithPatch) {
  const string& prefix = "append_with_patch/";
  EXPECT_TRUE(config_->IsNull(prefix + "__include"));
  EXPECT_TRUE(config_->IsNull(prefix + "__patch"));

  string player;
  EXPECT_TRUE(config_->GetString(prefix + "terrans/player", &player));
  EXPECT_EQ("slayers_boxer, nada", player);

  EXPECT_EQ(2, config_->GetListSize(prefix + "terrans/air_units"));
  string unit;
  EXPECT_TRUE(config_->GetString(prefix + "terrans/air_units/@0", &unit));
  EXPECT_EQ("wraith", unit);
  EXPECT_TRUE(config_->GetString(prefix + "terrans/air_units/@1", &unit));
  EXPECT_EQ("battlecruiser", unit);

  EXPECT_EQ(6 + 2, config_->GetListSize(prefix + "protoss/ground_units"));

  // verify that we append to a copy and the original list is untouched
  EXPECT_TRUE(config_->GetString("/starcraft/terrans/player", &player));
  EXPECT_EQ("slayers_boxer", player);
  EXPECT_TRUE(config_->IsNull("/starcraft/terrans/air_units"));
  EXPECT_EQ(6, config_->GetListSize("/starcraft/protoss/ground_units"));
}

TEST_F(RimeConfigMergeTest, MergeTree) {
  const string& prefix = "merge_tree/";
  EXPECT_TRUE(config_->IsNull(prefix + "__include"));

  string player;
  EXPECT_TRUE(config_->GetString(prefix + "terrans/player", &player));
  EXPECT_EQ("slayers_boxer", player);
  EXPECT_TRUE(config_->IsNull(prefix + "terrans/air_units"));
  EXPECT_TRUE(config_->IsList(prefix + "terrans/ground_units"));
  EXPECT_EQ(5 + 2, config_->GetListSize(prefix + "terrans/ground_units"));
  string unit;
  EXPECT_TRUE(config_->GetString(prefix + "terrans/ground_units/@5", &unit));
  EXPECT_EQ("medic", unit);
  EXPECT_TRUE(config_->GetString(prefix + "terrans/ground_units/@6", &unit));
  EXPECT_EQ("goliath", unit);

  EXPECT_TRUE(config_->GetString(prefix + "protoss/player", &player));
  EXPECT_EQ("grrrr", player);
  EXPECT_TRUE(config_->IsNull(prefix + "protoss/ground_units/__append"));
  EXPECT_TRUE(config_->IsList(prefix + "protoss/ground_units"));
  EXPECT_EQ(6 + 2, config_->GetListSize(prefix + "protoss/ground_units"));
  EXPECT_TRUE(config_->GetString(prefix + "protoss/ground_units/@6", &unit));
  EXPECT_EQ("dark templar", unit);
  EXPECT_TRUE(config_->GetString(prefix + "protoss/ground_units/@7", &unit));
  EXPECT_EQ("dark archon", unit);

  EXPECT_TRUE(config_->GetString(prefix + "zerg/player", &player));
  EXPECT_EQ("yellow", player);
  EXPECT_TRUE(config_->IsList(prefix + "zerg/ground_units"));
  EXPECT_EQ(0, config_->GetListSize(prefix + "zerg/ground_units"));

  // verify that we merge to a copy and the original list is untouched
  EXPECT_TRUE(config_->IsNull("/starcraft/terrans/ground_units"));
  EXPECT_EQ(6, config_->GetListSize("/starcraft/protoss/ground_units"));
  EXPECT_EQ(5, config_->GetListSize("/starcraft/zerg/ground_units"));
}

class RimeConfigCircularDependencyTest : public RimeConfigCompilerTestBase {
 protected:
  string test_config_id() const override {
    return "config_circular_dependency_test";
  }
};

TEST_F(RimeConfigMergeTest, CreateListWithInplacePatch) {
  const string& prefix = "create_list_with_inplace_patch/";
  EXPECT_TRUE(config_->IsList(prefix + "all_ground_units"));
  EXPECT_EQ(16, config_->GetListSize(prefix + "all_ground_units"));
}

TEST_F(RimeConfigCircularDependencyTest, BestEffortResolution) {
  const string& prefix = "test/";
  EXPECT_TRUE(config_->IsNull(prefix + "__patch"));
  EXPECT_TRUE(config_->IsNull(prefix + "work/__include"));
  string home;
  EXPECT_TRUE(config_->GetString(prefix + "home", &home));
  EXPECT_EQ("naive", home);
  string work;
  EXPECT_TRUE(config_->GetString(prefix + "work", &work));
  EXPECT_EQ("excited", work);
}

max_stars_repo_name: mengzhisuoliu/librime


text:
#define CATCH_CONFIG_MAIN

#include <filesystem>
#include "hash.hpp"
#include "packagecmd.hpp"
#include <boost/format.hpp>
#include <catch2/catch.hpp>

using namespace buildsys;
namespace filesystem = std::filesystem;

class HashTestsFixture
{
protected:
	std::string cwd{"hash_test_dir"};
	std::streambuf *coutbuf{nullptr};
	std::stringstream stdout_buffer;

public:
	HashTestsFixture()
	{
		hash_setup();
		// Ensure that we restore std::cout at the end of each test.
		this->coutbuf = std::cout.rdbuf();
		// Redirect std::cout so we can verify what is printed.
		std::cout.rdbuf(this->stdout_buffer.rdbuf());
		filesystem::create_directories(this->cwd);
	}
	~HashTestsFixture()
	{
		hash_shutdown();
		std::cout.rdbuf(this->coutbuf);
		filesystem::remove_all(this->cwd);
	}
};

TEST_CASE_METHOD(HashTestsFixture, "Test hash_file() function for non-existent file", "")
{
	std::string file_path("qwekjh123.txt");
	REQUIRE(!filesystem::exists(file_path));
	REQUIRE(hash_file(file_path) == "");
	auto expected = boost::format{"BuildSys: Failed opening: %1%\n"} % file_path;
	REQUIRE(this->stdout_buffer.str() == expected.str());
}

TEST_CASE_METHOD(HashTestsFixture, "Test hash_file() function for existent file", "")
{
	std::string file_path = this->cwd + "/test_file.txt";
	std::ofstream test_file;
	test_file.open(file_path);
	test_file << "This is some test data.\n";
	test_file.close();

	std::string hash = hash_file(file_path);
	// REQUIRE(hash_file(file_path) ==
	// "524d7edddd0f6e364120af132ce1100d4200246aecb2540519d8280c648f026b");
	REQUIRE(!hash.empty());
	// We don't expect any output
	REQUIRE(this->stdout_buffer.str() == "");

	PackageCmd pc(".", "sha256sum");
	pc.addArg(file_path);
	Logger logger;
	bool ret = pc.Run(&logger);
	REQUIRE(ret);

	// The first part of the packagecmd (sha256sum) output in stdout
	// should match the hash we got via the hash_file function
	std::string output = this->stdout_buffer.str();
	std::string expected_hash = output.substr(0, output.find(' '));
	REQUIRE(expected_hash == hash);
}

max_stars_repo_name: sparlane/buildsyspp

max_issues_repo_name: sparlane/buildsyspp

max_forks_repo_name: sparlane/buildsyspp


text:
/**
 *  @file
 *  @copyright defined in eos/LICENSE.txt
 */
#include <eosio/chain/chain_config.hpp>
#include <eosio/chain/authority_checker.hpp>
#include <eosio/chain/authority.hpp>
#include <eosio/chain/types.hpp>
#include <eosio/chain/asset.hpp>
#include <eosio/testing/tester.hpp>

#include <eosio/utilities/key_conversion.hpp>
#include <eosio/utilities/rand.hpp>

#include <fc/io/json.hpp>

#include <boost/test/unit_test.hpp>

#ifdef NON_VALIDATING_TEST
#define TESTER tester
#else
#define TESTER validating_tester
#endif

using namespace eosio::chain;
using namespace eosio::testing;

#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>

namespace eosio
{
using namespace chain;
using namespace std;

static constexpr uint64_t name_suffix( uint64_t n ) {
   uint32_t remaining_bits_after_last_actual_dot = 0;
   uint32_t tmp = 0;
   for( int32_t remaining_bits = 59; remaining_bits >= 4; remaining_bits -= 5 ) { // Note: remaining_bits must remain signed integer
      // Get characters one-by-one in name in order from left to right (not including the 13th character)
      auto c = (n >> remaining_bits) & 0x1Full;
      if( !c ) { // if this character is a dot
         tmp = static_cast<uint32_t>(remaining_bits);
      } else { // if this character is not a dot
         remaining_bits_after_last_actual_dot = tmp;
      }
   }

   uint64_t thirteenth_character = n & 0x0Full;
   if( thirteenth_character ) { // if 13th character is not a dot
      remaining_bits_after_last_actual_dot = tmp;
   }

   if( remaining_bits_after_last_actual_dot == 0 ) // there is no actual dot in the name other than potentially leading dots
      return n;

   // At this point remaining_bits_after_last_actual_dot has to be within the range of 4 to 59 (and restricted to increments of 5).

   // Mask for remaining bits corresponding to characters after last actual dot, except for 4 least significant bits (corresponds to 13th character).
   uint64_t mask = (1ull << remaining_bits_after_last_actual_dot) - 16;
   uint32_t shift = 64 - remaining_bits_after_last_actual_dot;

   return ( ((n & mask) << shift) + (thirteenth_character << (shift-1)) );
}

BOOST_AUTO_TEST_SUITE(misc_tests)

BOOST_AUTO_TEST_CASE(name_suffix_tests)
{
   BOOST_CHECK_EQUAL( name{name_suffix(0)}, name{0} );
   BOOST_CHECK_EQUAL( name{name_suffix(N(abcdehijklmn))}, name{N(abcdehijklmn)} );
   BOOST_CHECK_EQUAL( name{name_suffix(N(abcdehijklmn1))}, name{N(abcdehijklmn1)} );
   BOOST_CHECK_EQUAL( name{name_suffix(N(abc.def))}, name{N(def)} );
   BOOST_CHECK_EQUAL( name{name_suffix(N(.abc.def))}, name{N(def)} );
   BOOST_CHECK_EQUAL( name{name_suffix(N(..abc.def))}, name{N(def)} );
   BOOST_CHECK_EQUAL( name{name_suffix(N(abc..def))}, name{N(def)} );
   BOOST_CHECK_EQUAL( name{name_suffix(N(abc.def.ghi))}, name{N(ghi)} );
   BOOST_CHECK_EQUAL( name{name_suffix(N(.abcdefghij))}, name{N(abcdefghij)} );
   BOOST_CHECK_EQUAL( name{name_suffix(N(.abcdefghij.1))}, name{N(1)} );
   BOOST_CHECK_EQUAL( name{name_suffix(N(a.bcdefghij))}, name{N(bcdefghij)} );
   BOOST_CHECK_EQUAL( name{name_suffix(N(a.bcdefghij.1))}, name{N(1)} );
   BOOST_CHECK_EQUAL( name{name_suffix(N(......a.b.c))}, name{N(c)} );
   BOOST_CHECK_EQUAL( name{name_suffix(N(abcdefhi.123))}, name{N(123)} );
   BOOST_CHECK_EQUAL( name{name_suffix(N(abcdefhij.123))}, name{N(123)} );
}

/// Test processing of unbalanced strings
BOOST_AUTO_TEST_CASE(json_from_string_test)
{
  bool exc_found = false;
  try {
    auto val = fc::json::from_string("{\"}");
  } catch(...) {
    exc_found = true;
  }
  BOOST_CHECK_EQUAL(exc_found, true);

  exc_found = false;
  try {
    auto val = fc::json::from_string("{\"block_num_or_id\":5");
  } catch(...) {
    exc_found = true;
  }
  BOOST_CHECK_EQUAL(exc_found, true);
}

// Test overflow handling in asset::from_string
BOOST_AUTO_TEST_CASE(asset_from_string_overflow)
{
   asset a;

   // precision = 19, magnitude < 2^61
   BOOST_CHECK_EXCEPTION( asset::from_string("0.1000000000000000000 CUR") , symbol_type_exception, [](const auto& e) {
      return expect_assert_message(e, "precision 19 should be <= 18");
   });
   BOOST_CHECK_EXCEPTION( asset::from_string("-0.1000000000000000000 CUR") , symbol_type_exception, [](const auto& e) {
      return expect_assert_message(e, "precision 19 should be <= 18");
   });
   BOOST_CHECK_EXCEPTION( asset::from_string("1.0000000000000000000 CUR") , symbol_type_exception, [](const auto& e) {
      return expect_assert_message(e, "precision 19 should be <= 18");
   });
   BOOST_CHECK_EXCEPTION( asset::from_string("-1.0000000000000000000 CUR") , symbol_type_exception, [](const auto& e) {
      return expect_assert_message(e, "precision 19 should be <= 18");
   });

   // precision = 18, magnitude < 2^58
   a = asset::from_string("0.100000000000000000 CUR");
   BOOST_CHECK_EQUAL(a.get_amount(), 100000000000000000L);
   a = asset::from_string("-0.100000000000000000 CUR");
   BOOST_CHECK_EQUAL(a.get_amount(), -100000000000000000L);

   // precision = 18, magnitude = 2^62
   BOOST_CHECK_EXCEPTION( asset::from_string("4.611686018427387904 CUR") , asset_type_exception, [](const asset_type_exception& e) {
      return expect_assert_message(e, "magnitude of asset amount must be less than 2^62");
   });
   BOOST_CHECK_EXCEPTION( asset::from_string("-4.611686018427387904 CUR") , asset_type_exception, [](const asset_type_exception& e) {
      return expect_assert_message(e, "magnitude of asset amount must be less than 2^62");
   });
   BOOST_CHECK_EXCEPTION( asset::from_string("4611686018427387.904 CUR") , asset_type_exception, [](const asset_type_exception& e) {
      return expect_assert_message(e, "magnitude of asset amount must be less than 2^62");
   });
   BOOST_CHECK_EXCEPTION( asset::from_string("-4611686018427387.904 CUR") , asset_type_exception, [](const asset_type_exception& e) {
      return expect_assert_message(e, "magnitude of asset amount must be less than 2^62");
   });

   // precision = 18, magnitude = 2^62-1
   a = asset::from_string("4.611686018427387903 CUR");
   BOOST_CHECK_EQUAL(a.get_amount(), 4611686018427387903L);
   a = asset::from_string("-4.611686018427387903 CUR");
   BOOST_CHECK_EQUAL(a.get_amount(), -4611686018427387903L);

   // precision = 0, magnitude = 2^62
   BOOST_CHECK_EXCEPTION( asset::from_string("4611686018427387904 CUR") , asset_type_exception, [](const asset_type_exception& e) {
      return expect_assert_message(e, "magnitude of asset amount must be less than 2^62");
   });
   BOOST_CHECK_EXCEPTION( asset::from_string("-4611686018427387904 CUR") , asset_type_exception, [](const asset_type_exception& e) {
      return expect_assert_message(e, "magnitude of asset amount must be less than 2^62");
   });

   // precision = 0, magnitude = 2^62-1
   a = asset::from_string("4611686018427387903 CUR");
   BOOST_CHECK_EQUAL(a.get_amount(), 4611686018427387903L);
   a = asset::from_string("-4611686018427387903 CUR");
   BOOST_CHECK_EQUAL(a.get_amount(), -4611686018427387903L);

   // precision = 18, magnitude = 2^65
   BOOST_CHECK_EXCEPTION( asset::from_string("36.893488147419103232 CUR") , overflow_exception, [](const overflow_exception& e) {
      return true;
   });
   BOOST_CHECK_EXCEPTION( asset::from_string("-36.893488147419103232 CUR") , underflow_exception, [](const underflow_exception& e) {
      return true;
   });

   // precision = 14, magnitude > 2^76
   BOOST_CHECK_EXCEPTION( asset::from_string("1000000000.00000000000000 CUR") , overflow_exception, [](const overflow_exception& e) {
      return true;
   });
   BOOST_CHECK_EXCEPTION( asset::from_string("-1000000000.00000000000000 CUR") , underflow_exception, [](const underflow_exception& e) {
      return true;
   });

   // precision = 0, magnitude > 2^76
   BOOST_CHECK_EXCEPTION( asset::from_string("100000000000000000000000 CUR") , parse_error_exception, [](const parse_error_exception& e) {
      return expect_assert_message(e, "Couldn't parse int64_t");
   });
   BOOST_CHECK_EXCEPTION( asset::from_string("-100000000000000000000000 CUR") , parse_error_exception, [](const parse_error_exception& e) {
      return expect_assert_message(e, "Couldn't parse int64_t");
   });

   // precision = 20, magnitude > 2^142
   BOOST_CHECK_EXCEPTION( asset::from_string("100000000000000000000000.00000000000000000000 CUR") , symbol_type_exception, [](const auto& e) {
      return expect_assert_message(e, "precision 20 should be <= 18");
   });
   BOOST_CHECK_EXCEPTION( asset::from_string("-100000000000000000000000.00000000000000000000 CUR") , symbol_type_exception, [](const auto& e) {
      return expect_assert_message(e, "precision 20 should be <= 18");
   });
}

/// Test that our deterministic random shuffle algorithm gives the same results in all environments
BOOST_AUTO_TEST_CASE(deterministic_randomness)
{ try {
   utilities::rand::random rng(123454321);
   vector<string> words = {"infamy", "invests", "estimated", "potters", "memorizes", "hal9000"};
   rng.shuffle(words);
   BOOST_TEST(fc::json::to_string(words) ==
                     fc::json::to_string(vector<string>{"hal9000","infamy","invests","estimated","memorizes","potters"}));
   rng.shuffle(words);
   BOOST_TEST(fc::json::to_string(words) ==
                     fc::json::to_string(vector<string>{"memorizes","infamy","hal9000","potters","estimated","invests"}));
} FC_LOG_AND_RETHROW() }

BOOST_AUTO_TEST_CASE(deterministic_distributions)
{ try {
   utilities::rand::random rng(123454321);

   BOOST_TEST(rng.next() == UINT64_C(13636622732572118961));
   BOOST_TEST(rng.next() == UINT64_C(8049736256506128729));
   BOOST_TEST(rng.next() ==  UINT64_C(1224405983932261174));

   std::vector<int> nums = {0, 1, 2};

   rng.shuffle(nums);
   std::vector<int> a{2, 0, 1};
   BOOST_TEST(std::equal(nums.begin(), nums.end(), a.begin()));
   rng.shuffle(nums);
   std::vector<int> b{0, 2, 1};
   BOOST_TEST(std::equal(nums.begin(), nums.end(), b.begin()));
   rng.shuffle(nums);
   std::vector<int> c{1, 0, 2};
   BOOST_TEST(std::equal(nums.begin(), nums.end(), c.begin()));
} FC_LOG_AND_RETHROW() }

struct permission_visitor {
   std::vector<permission_level> permissions;
   std::vector<size_t> size_stack;
   bool _log;

   permission_visitor(bool log = false) : _log(log) {}

   void operator()(const permission_level& permission) {
      permissions.push_back(permission);
   }

   void operator()(const permission_level& permission, bool repeat ) {}

   void push_undo() {
      if( _log )
         ilog("push_undo called");
      size_stack.push_back(permissions.size());
   }

   void pop_undo() {
      if( _log )
         ilog("pop_undo called");
      FC_ASSERT( size_stack.back() <= permissions.size() && size_stack.size() >= 1,
                 "invariant failure in test permission_visitor" );
      permissions.erase( permissions.begin() + size_stack.back(), permissions.end() );
      size_stack.pop_back();
   }

   void squash_undo() {
      if( _log )
         ilog("squash_undo called");
      FC_ASSERT( size_stack.size() >= 1, "invariant failure in test permission_visitor" );
      size_stack.pop_back();
   }

};

BOOST_AUTO_TEST_CASE(authority_checker)
{ try {
   testing::TESTER test;
   auto a = test.get_public_key("a", "active");
   auto b = test.get_public_key("b", "active");
   auto c = test.get_public_key("c", "active");

   auto GetNullAuthority = [](auto){abort(); return authority();};

   auto A = authority(2, {key_weight{a, 1}, key_weight{b, 1}});
   {
      auto checker = make_auth_checker(GetNullAuthority, 2, {a, b});
      BOOST_TEST(checker.satisfied(A));
      BOOST_TEST(checker.all_keys_used());
      BOOST_TEST(checker.used_keys().size() == 2);
      BOOST_TEST(checker.unused_keys().size() == 0);
   }
   {
      auto checker = make_auth_checker(GetNullAuthority, 2, {a, c});
      BOOST_TEST(!checker.satisfied(A));
      BOOST_TEST(!checker.all_keys_used());
      BOOST_TEST(checker.used_keys().size() == 0);
      BOOST_TEST(checker.unused_keys().size() == 2);
   }
   {
      auto checker = make_auth_checker(GetNullAuthority, 2, {a, b, c});
      BOOST_TEST(checker.satisfied(A));
      BOOST_TEST(!checker.all_keys_used());
      BOOST_TEST(checker.used_keys().size() == 2);
      BOOST_TEST(checker.used_keys().count(a) == 1);
      BOOST_TEST(checker.used_keys().count(b) == 1);
      BOOST_TEST(checker.unused_keys().size() == 1);
      BOOST_TEST(checker.unused_keys().count(c) == 1);
   }
   {
      auto checker = make_auth_checker(GetNullAuthority, 2, {b, c});
      BOOST_TEST(!checker.satisfied(A));
      BOOST_TEST(!checker.all_keys_used());
      BOOST_TEST(checker.used_keys().size() == 0);
   }

   A = authority(3, {key_weight{a, 1}, key_weight{b, 1}, key_weight{c, 1}});
   BOOST_TEST(make_auth_checker(GetNullAuthority, 2, {c, b, a}).satisfied(A));
   BOOST_TEST(!make_auth_checker(GetNullAuthority, 2, {a, b}).satisfied(A));
   BOOST_TEST(!make_auth_checker(GetNullAuthority, 2, {a, c}).satisfied(A));
   BOOST_TEST(!make_auth_checker(GetNullAuthority, 2, {b, c}).satisfied(A));

   A = authority(1, {key_weight{a, 1}, key_weight{b, 1}});
   BOOST_TEST(make_auth_checker(GetNullAuthority, 2, {a}).satisfied(A));
   BOOST_TEST(make_auth_checker(GetNullAuthority, 2, {b}).satisfied(A));
   BOOST_TEST(!make_auth_checker(GetNullAuthority, 2, {c}).satisfied(A));

   A = authority(1, {key_weight{a, 2}, key_weight{b, 1}});
   BOOST_TEST(make_auth_checker(GetNullAuthority, 2, {a}).satisfied(A));
   BOOST_TEST(make_auth_checker(GetNullAuthority, 2, {b}).satisfied(A));
   BOOST_TEST(!make_auth_checker(GetNullAuthority, 2, {c}).satisfied(A));

   auto GetCAuthority = [c](auto){
      return authority(1, {key_weight{c, 1}});
   };

   A = authority(2, {key_weight{a, 2}, key_weight{b, 1}}, {permission_level_weight{{"hello",  "world"}, 1}});
   {
      auto checker = make_auth_checker(GetCAuthority, 2, {a});
      BOOST_TEST(checker.satisfied(A));
      BOOST_TEST(checker.all_keys_used());
   }
   {
      auto checker = make_auth_checker(GetCAuthority, 2, {b});
      BOOST_TEST(!checker.satisfied(A));
      BOOST_TEST(checker.used_keys().size() == 0);
      BOOST_TEST(checker.unused_keys().size() == 1);
      BOOST_TEST(checker.unused_keys().count(b) == 1);
   }
   {
      auto checker = make_auth_checker(GetCAuthority, 2, {c});
      BOOST_TEST(!checker.satisfied(A));
      BOOST_TEST(checker.used_keys().size() == 0);
      BOOST_TEST(checker.unused_keys().size() == 1);
      BOOST_TEST(checker.unused_keys().count(c) == 1);
   }
   {
      auto checker = make_auth_checker(GetCAuthority, 2, {b, c});
      BOOST_TEST(checker.satisfied(A));
      BOOST_TEST(checker.all_keys_used());
      BOOST_TEST(checker.used_keys().size() == 2);
      BOOST_TEST(checker.unused_keys().size() == 0);
      BOOST_TEST(checker.used_keys().count(b) == 1);
      BOOST_TEST(checker.used_keys().count(c) == 1);
   }
   {
      auto checker = make_auth_checker(GetCAuthority, 2, {b, c, a});
      BOOST_TEST(checker.satisfied(A));
      BOOST_TEST(!checker.all_keys_used());
      BOOST_TEST(checker.used_keys().size() == 1);
      BOOST_TEST(checker.used_keys().count(a) == 1);
      BOOST_TEST(checker.unused_keys().size() == 2);
      BOOST_TEST(checker.unused_keys().count(b) == 1);
      BOOST_TEST(checker.unused_keys().count(c) == 1);
   }

   A = authority(3, {key_weight{a, 2}, key_weight{b, 1}}, {permission_level_weight{{"hello",  "world"}, 3}});
   {
      auto checker = make_auth_checker(GetCAuthority, 2, {a, b});
      BOOST_TEST(checker.satisfied(A));
      BOOST_TEST(checker.all_keys_used());
   }
   {
      auto checker = make_auth_checker(GetCAuthority, 2, {a, b, c});
      BOOST_TEST(checker.satisfied(A));
      BOOST_TEST(!checker.all_keys_used());
      BOOST_TEST(checker.used_keys().size() == 1);
      BOOST_TEST(checker.used_keys().count(c) == 1);
      BOOST_TEST(checker.unused_keys().size() == 2);
      BOOST_TEST(checker.unused_keys().count(a) == 1);
      BOOST_TEST(checker.unused_keys().count(b) == 1);
   }

   A = authority(2, {key_weight{a, 1}, key_weight{b, 1}}, {permission_level_weight{{"hello",  "world"}, 1}});
   BOOST_TEST(!make_auth_checker(GetCAuthority, 2, {a}).satisfied(A));
   BOOST_TEST(!make_auth_checker(GetCAuthority, 2, {b}).satisfied(A));
   BOOST_TEST(!make_auth_checker(GetCAuthority, 2, {c}).satisfied(A));
   BOOST_TEST(make_auth_checker(GetCAuthority, 2, {a, b}).satisfied(A));
   BOOST_TEST(make_auth_checker(GetCAuthority, 2, {b, c}).satisfied(A));
   BOOST_TEST(make_auth_checker(GetCAuthority, 2, {a, c}).satisfied(A));
   {
      auto checker = make_auth_checker(GetCAuthority, 2, {a, b, c});
      BOOST_TEST(checker.satisfied(A));
      BOOST_TEST(!checker.all_keys_used());
      BOOST_TEST(checker.used_keys().size() == 2);
      BOOST_TEST(checker.unused_keys().size() == 1);
      BOOST_TEST(checker.unused_keys().count(c) == 1);
   }

   A = authority(2, {key_weight{a, 1}, key_weight{b, 1}}, {permission_level_weight{{"hello",  "world"}, 2}});
   BOOST_TEST(make_auth_checker(GetCAuthority, 2, {a, b}).satisfied(A));
   BOOST_TEST(make_auth_checker(GetCAuthority, 2, {c}).satisfied(A));
   BOOST_TEST(!make_auth_checker(GetCAuthority, 2, {a}).satisfied(A));
   BOOST_TEST(!make_auth_checker(GetCAuthority, 2, {b}).satisfied(A));
   {
      auto checker = make_auth_checker(GetCAuthority, 2, {a, b, c});
      BOOST_TEST(checker.satisfied(A));
      BOOST_TEST(!checker.all_keys_used());
      BOOST_TEST(checker.used_keys().size() == 1);
      BOOST_TEST(checker.unused_keys().size() == 2);
      BOOST_TEST(checker.used_keys().count(c) == 1);
   }

   auto d = test.get_public_key("d", "active");
   auto e = test.get_public_key("e", "active");

   auto GetAuthority = [d, e] (const permission_level& perm) {
      if (perm.actor == "top")
         return authority(2, {key_weight{d, 1}}, {permission_level_weight{{"bottom",  "bottom"}, 1}});
      return authority{1, {{e, 1}}, {}};
   };

   A = authority(5, {key_weight{a, 2}, key_weight{b, 2}, key_weight{c, 2}}, {permission_level_weight{{"top",  "top"}, 5}});
   {
      auto checker = make_auth_checker(GetAuthority, 2, {d, e});
      BOOST_TEST(checker.satisfied(A));
      BOOST_TEST(checker.all_keys_used());
   }
   {
      auto checker = make_auth_checker(GetAuthority, 2, {a, b, c, d, e});
      BOOST_TEST(checker.satisfied(A));
      BOOST_TEST(!checker.all_keys_used());
      BOOST_TEST(checker.used_keys().size() == 2);
      BOOST_TEST(checker.unused_keys().size() == 3);
      BOOST_TEST(checker.used_keys().count(d) == 1);
      BOOST_TEST(checker.used_keys().count(e) == 1);
   }
   {
      auto checker = make_auth_checker(GetAuthority, 2, {a, b, c, e});
      BOOST_TEST(checker.satisfied(A));
      BOOST_TEST(!checker.all_keys_used());
      BOOST_TEST(checker.used_keys().size() == 3);
      BOOST_TEST(checker.unused_keys().size() == 1);
      BOOST_TEST(checker.used_keys().count(a) == 1);
      BOOST_TEST(checker.used_keys().count(b) == 1);
      BOOST_TEST(checker.used_keys().count(c) == 1);
   }
   BOOST_TEST(make_auth_checker(GetAuthority, 1, {a, b, c}).satisfied(A));
   // Fails due to short recursion depth limit
   BOOST_TEST(!make_auth_checker(GetAuthority, 1, {d, e}).satisfied(A));

   BOOST_TEST(b < a);
   BOOST_TEST(b < c);
   BOOST_TEST(a < c);
   {
      // valid key order: b < a < c
      A = authority(2, {key_weight{b, 1}, key_weight{a, 1}, key_weight{c, 1}});
      // valid key order: b < c
      auto B = authority(1, {key_weight{b, 1}, key_weight{c, 1}});
      // invalid key order: c > b
      auto C = authority(1, {key_weight{b, 1}, key_weight{c, 1}, key_weight{b, 1}});
      // invalid key order: duplicate c
      auto D = authority(1, {key_weight{b, 1}, key_weight{c, 1}, key_weight{c, 1}});
      // invalid key order: duplicate b
      auto E = authority(1, {key_weight{b, 1}, key_weight{b, 1}, key_weight{c, 1}});
      // unvalid: insufficient weight
      auto F = authority(4, {key_weight{b, 1}, key_weight{a, 1}, key_weight{c, 1}});

      auto checker = make_auth_checker(GetNullAuthority, 2, {a, b, c});
      BOOST_TEST(validate(A));
      BOOST_TEST(validate(B));
      BOOST_TEST(!validate(C));
      BOOST_TEST(!validate(D));
      BOOST_TEST(!validate(E));
      BOOST_TEST(!validate(F));

      BOOST_TEST(!checker.all_keys_used());
      BOOST_TEST(checker.unused_keys().count(b) == 1);
      BOOST_TEST(checker.unused_keys().count(a) == 1);
      BOOST_TEST(checker.unused_keys().count(c) == 1);
      BOOST_TEST(checker.satisfied(A));
      BOOST_TEST(checker.satisfied(B));
      BOOST_TEST(!checker.all_keys_used());
      BOOST_TEST(checker.unused_keys().count(b) == 0);
      BOOST_TEST(checker.unused_keys().count(a) == 0);
      BOOST_TEST(checker.unused_keys().count(c) == 1);
   }
   {
      auto A2 = authority(4, {key_weight{b, 1}, key_weight{a, 1}, key_weight{c, 1}},
                          { permission_level_weight{{"a",  "world"},     1},
                            permission_level_weight{{"hello",  "world"}, 1},
                            permission_level_weight{{"hi",  "world"},    1}
                          });
      auto B2 = authority(4, {key_weight{b, 1}, key_weight{a, 1}, key_weight{c, 1}},
                          {permission_level_weight{{"hello",  "world"}, 1}
                          });
      auto C2 = authority(4, {key_weight{b, 1}, key_weight{a, 1}, key_weight{c, 1}},
                          { permission_level_weight{{"hello",  "there"}, 1},
                            permission_level_weight{{"hello",  "world"}, 1}
                          });
      // invalid: duplicate
      auto D2 = authority(4, {key_weight{b, 1}, key_weight{a, 1}, key_weight{c, 1}},
                          { permission_level_weight{{"hello",  "world"}, 1},
                            permission_level_weight{{"hello",  "world"}, 2}
                          });
      // invalid: wrong order
      auto E2 = authority(4, {key_weight{b, 1}, key_weight{a, 1}, key_weight{c, 1}},
                          { permission_level_weight{{"hello",  "world"}, 2},
                            permission_level_weight{{"hello",  "there"}, 1}
                          });
      // invalid: wrong order
      auto F2 = authority(4, {key_weight{b, 1}, key_weight{a, 1}, key_weight{c, 1}},
                          { permission_level_weight{{"hi",  "world"}, 2},
                            permission_level_weight{{"hello",  "world"}, 1}
                          });

      // invalid: insufficient weight
      auto G2 = authority(7, {key_weight{b, 1}, key_weight{a, 1}, key_weight{c, 1}},
                             { permission_level_weight{{"a",  "world"},     1},
                               permission_level_weight{{"hello",  "world"}, 1},
                               permission_level_weight{{"hi",  "world"},    1}
                             });

      BOOST_TEST(validate(A2));
      BOOST_TEST(validate(B2));
      BOOST_TEST(validate(C2));
      BOOST_TEST(!validate(D2));
      BOOST_TEST(!validate(E2));
      BOOST_TEST(!validate(F2));
      BOOST_TEST(!validate(G2));
   }
} FC_LOG_AND_RETHROW() }

BOOST_AUTO_TEST_CASE(alphabetic_sort)
{ try {

  vector<string> words = {
    "com.o",
    "te",
    "a.....5",
    "a...4",
    ".va.ku",
    "gh",
    "1ho.la",
    "g1",
    "g",
    "a....2",
    "gg",
    "va",
    "lale.....12b",
    "a....3",
    "a....1",
    "..g",
    ".g",
    "....g",
    "a....y",
    "...g",
    "lale.....333",
  };

  std::sort(words.begin(), words.end(), std::less<string>());

  vector<uint64_t> uwords;
  for(const auto w: words) {
    auto n = name(w.c_str());
    uwords.push_back(n.value);
  }

  std::sort(uwords.begin(), uwords.end(), std::less<uint64_t>());

  vector<string> tmp;
  for(const auto uw: uwords) {
    auto str = name(uw).to_string();
    tmp.push_back(str);
  }

  for(int i = 0; i < words.size(); ++i ) {
    BOOST_TEST(tmp[i] == words[i]);
  }

} FC_LOG_AND_RETHROW() }

BOOST_AUTO_TEST_CASE(transaction_test) { try {

   testing::TESTER test;
   signed_transaction trx;

   variant pretty_trx = fc::mutable_variant_object()
      ("actions", fc::variants({
         fc::mutable_variant_object()
            ("account", "eosio")
            ("name", "reqauth")
            ("authorization", fc::variants({
               fc::mutable_variant_object()
                  ("actor", "eosio")
                  ("permission", "active")
            }))
            ("data", fc::mutable_variant_object()
               ("from", "eosio")
            )
         })
      )
      // lets also push a context free action, the multi chain test will then also include a context free action
      ("context_free_actions", fc::variants({
         fc::mutable_variant_object()
            ("account", "eosio")
            ("name", "nonce")
            ("data", fc::raw::pack(std::string("dummy")))
         })
      );

   abi_serializer::from_variant(pretty_trx, trx, test.get_resolver(), test.abi_serializer_max_time);

   test.set_transaction_headers(trx);

   trx.expiration = fc::time_point::now();
   trx.validate();
   BOOST_CHECK_EQUAL(0, trx.signatures.size());
   ((const signed_transaction &)trx).sign( test.get_private_key( N(eosio), "active" ), test.control->get_chain_id());
   BOOST_CHECK_EQUAL(0, trx.signatures.size());
   trx.sign( test.get_private_key( N(eosio), "active" ), test.control->get_chain_id()  );
   BOOST_CHECK_EQUAL(1, trx.signatures.size());
   trx.validate();

   packed_transaction pkt;
   pkt.set_transaction(trx, packed_transaction::none);

   packed_transaction pkt2;
   pkt2.set_transaction(trx, packed_transaction::zlib);

   BOOST_CHECK_EQUAL(true, trx.expiration ==  pkt.expiration());
   BOOST_CHECK_EQUAL(true, trx.expiration == pkt2.expiration());

   BOOST_CHECK_EQUAL(trx.id(), pkt.id());
   BOOST_CHECK_EQUAL(trx.id(), pkt2.id());

   bytes raw = pkt.get_raw_transaction();
   bytes raw2 = pkt2.get_raw_transaction();
   BOOST_CHECK_EQUAL(raw.size(), raw2.size());

} FC_LOG_AND_RETHROW() }

BOOST_AUTO_TEST_SUITE_END()

} // namespace eosio


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

/**************************************************************************************************/

#ifndef STLAB_CONCURRENCY_OPTIONAL_HPP
#define STLAB_CONCURRENCY_OPTIONAL_HPP

#include <stlab/concurrency/config.hpp>

#define STLAB_STD_OPTIONAL 1
#define STLAB_STD_EXPERIMENTAL_OPTIONAL 2
#define STLAB_BOOST_OPTIONAL 3

// The library can be used with boost::optinal, std::experimental::optional or std::optional.
// Without any additional define, it uses the versions from the standard, if it is available.
//
// If using of boost::optional shall be enforced, set the define STLAB_FORCE_BOOST_OPTIONAL

#ifdef STLAB_FORCE_BOOST_OPTIONAL
#include <boost/optional.hpp>
#define STLAB_OPTIONAL STLAB_BOOST_OPTIONAL
#endif

#ifndef STLAB_OPTIONAL
#ifdef __has_include                                     // Check if __has_include is present
#if __has_include(<optional>) && STLAB_CPP_VERSION == 17 // Check for a standard library
#include <optional>
#define STLAB_OPTIONAL STLAB_STD_OPTIONAL
#elif __has_include(<experimental/optional>) // Check for an experimental version
#include <experimental/optional>
#define STLAB_OPTIONAL STLAB_STD_EXPERIMENTAL_OPTIONAL
#endif
#endif
#endif

#ifndef STLAB_OPTIONAL
#include <boost/optional.hpp>
#define STLAB_OPTIONAL STLAB_BOOST_OPTIONAL
#endif

namespace stlab {

#if STLAB_OPTIONAL == STLAB_STD_OPTIONAL

template <typename T>
using optional = std::optional<T>;

constexpr std::nullopt_t nullopt{std::nullopt};

#elif STLAB_OPTIONAL == STLAB_STD_EXPERIMENTAL_OPTIONAL

template <typename T>
using optional = std::experimental::optional<T>;

constexpr std::experimental::nullopt_t nullopt{std::experimental::nullopt};

#elif STLAB_OPTIONAL == STLAB_BOOST_OPTIONAL

template <typename T>
using optional = boost::optional<T>;

const boost::none_t nullopt((boost::none_t::init_tag()));

#else
#error "No optional!"
#endif

} // namespace stlab

#endif

max_stars_repo_name: olnrao/libraries

max_issues_repo_name: olnrao/libraries

max_forks_repo_name: olnrao/libraries


text:
//==============================================================================
//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_SWAR_FUNCTIONS_SIMD_COMMON_ENUMERATE_HPP_INCLUDED
#define BOOST_SIMD_SWAR_FUNCTIONS_SIMD_COMMON_ENUMERATE_HPP_INCLUDED

#include <boost/simd/swar/functions/enumerate.hpp>
#include <boost/simd/include/functions/simd/splat.hpp>
#include <boost/simd/include/functions/simd/plus.hpp>
#include <boost/simd/include/functions/simd/multiplies.hpp>
#include <boost/simd/sdk/meta/as_arithmetic.hpp>

namespace boost { namespace simd { namespace ext
{
  BOOST_SIMD_FUNCTOR_IMPLEMENTATION ( boost::simd::tag::enumerate_, tag::cpu_
                                    , (A0)(X)(T)
                                    , (scalar_< arithmetic_<A0> >)
                                      ((target_< simd_< arithmetic_<T>,X> >))
                                    )
  {
    typedef typename T::type result_type;

    result_type operator()(A0 const& a0, T const& ) const
    {
      typedef typename meta::scalar_of<result_type>::type s_t;
      result_type that;
      for(std::size_t i=0;i<result_type::static_size;++i)
        that[i] = a0 + i;
      return that;
    }
  };

  BOOST_SIMD_FUNCTOR_IMPLEMENTATION ( boost::simd::tag::enumerate_, tag::cpu_
                                    , (A0)(A1)(X)(Y)
                                    , ((simd_< arithmetic_<A0>, X >))
                                      ((target_< simd_< arithmetic_<A1>, Y> >))
                                    )
  {
    typedef typename A1::type result_type;
    result_type operator()(A0 const& a0, A1 const& ) const
    {
      return splat<result_type>(a0);
    }
  };

  BOOST_SIMD_FUNCTOR_IMPLEMENTATION ( boost::simd::tag::enumerate_, tag::cpu_
                                    , (A0)(X)(T)
                                    , ((generic_< arithmetic_<A0> >))
                                      ((target_< simd_< logical_<T>,X> >))
                                    )
  {
    typedef typename meta::as_arithmetic<typename T::type>::type result_type;

    result_type operator()(A0 const& a0, T const& ) const
    {
      return enumerate<result_type>(a0);
    }
  };

  BOOST_SIMD_FUNCTOR_IMPLEMENTATION ( boost::simd::tag::enumerate_, tag::cpu_
                                      , (A0)(A1)(X)(T)
                                    , (scalar_< arithmetic_<A0> >)
                                      (scalar_< arithmetic_<A1> >)
                                      ((target_< simd_< arithmetic_<T>,X> >))
                                    )
  {
    typedef typename T::type result_type;
      typedef typename meta::scalar_of<result_type>::type s_t;
    result_type operator()(A0 const& a0, A1 const& a1, T const& ) const
    {
      result_type that;
      for(std::size_t i=0;i<result_type::static_size;++i)
        that[i] = a0 + a1*i;
      return that;
    }
  };

  BOOST_SIMD_FUNCTOR_IMPLEMENTATION ( boost::simd::tag::enumerate_, tag::cpu_
                                    , (A0)(A1)(X)(T)
                                    , ((simd_< arithmetic_<A0>, X >))
                                      (generic_< arithmetic_<A1> >)
                                      ((target_< simd_< arithmetic_<T>,X> >))
                                    )
  {
    typedef typename T::type result_type;

    result_type operator()(A0 const& a0, A1 const& a1, T const& ) const
    {
      return plus(a0, a1);
    }
  };

  BOOST_SIMD_FUNCTOR_IMPLEMENTATION ( boost::simd::tag::enumerate_, tag::cpu_
                                    , (A0)(A1)(X)(T)
                                    , ((simd_< arithmetic_<A0>, X >))
                                      (generic_< arithmetic_<A1> >)
                                      ((target_< simd_< logical_<T>,X> >))
                                    )
  {
    typedef typename meta::as_arithmetic<typename T::type>::type result_type;

    result_type operator()(A0 const& a0, A1 const& a1, T const& ) const
    {
      return enumerate<result_type>(a0, a1);
    }
  };
} } }

#endif