text:
/*
Copyright (c) 2014, Trail of Bits
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 the name of Trail of Bits nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <string>
#include <vector>
#include <list>

#include <LExcn.h>
#include <algorithm>
#include <boost/filesystem.hpp>

#include "llvm/Support/TargetRegistry.h"
#include "PETarget.h"
#include "bincomm.h"

using namespace llvm;
using namespace std;
using namespace boost;

PeTarget::PeTarget(string f, const Target *T) {
  this->mod_name = filesystem::path(f).stem().string();
  this->pe = ParsePEFromFile(f.c_str());
  return;
}

PeTarget::~PeTarget(void) {
  if(this->pe != NULL) {
    DestructParsedPE(this->pe);
    this->pe = NULL;
  }
  return;
}

bool PeTarget::is_open(void) {
  return this->pe != NULL;
}

//helper visitor for find_import_name
struct visit_imps_ctx {
  string  foundStr;
  VA      addrSearch;
};

static
int visit_imps(void *ctx, VA addr, string &module, string &symbol) {
  visit_imps_ctx  *c = (visit_imps_ctx *)ctx;

  if(c->addrSearch == addr) {
    //c->foundStr = module + "!" + symbol;
    c->foundStr = symbol;
    return 1;
  }

  return 0;
}

struct visit_exp_ctx {
  list<pair<string, VA> > &lst;
};

static
int visit_exp(void *ctx, VA addr, string &module, string &symbol) {
  visit_exp_ctx *c = (visit_exp_ctx *)ctx;

  c->lst.push_back(pair<string, VA>(symbol, addr));

  return 0;
}

bool PeTarget::get_exports(list<pair<string, VA> > &l) {
  //start with the PE entry point symbol
  if(this->pe == NULL) {
    return false;
  }

  VA  t;
  if(GetEntryPoint(this->pe, t)) {
    l.push_back(pair<string, ::uint64_t>("entry", t));
  }

  visit_exp_ctx c = { l };

  //enumerate over the EAT of the supplied module
  IterExpVA(this->pe, visit_exp, &c);

  return true;
}

bool PeTarget::find_import_name(uint32_t location, string &impname) {
  if(this->pe == NULL) {
    return false;
  }

  visit_imps_ctx  c;

  uint8_t   a1,a2,a3,a4;

  if(ReadByteAtVA(this->pe, location, a1) == false) {
    return false;
  }

  if(ReadByteAtVA(this->pe, location+1, a2) == false) {
    return false;
  }

  if(ReadByteAtVA(this->pe, location+2, a3) == false) {
    return false;
  }

  if(ReadByteAtVA(this->pe, location+3, a4) == false) {
    return false;
  }

  c.foundStr = "";
  c.addrSearch = (a4 << 24) + (a3 << 16) + (a2 << 8) + a1;
  IterImpVAString(this->pe, visit_imps, &c);

  if(c.foundStr.size() > 0) {
    impname = c.foundStr;
    return true;
  }

  return false;
}

//helper visitor for is_addr_relocated

struct visit_rels_ctx {
  VA    addr;
  bool  found;
};

static
int visit_rels(void *ctx, VA addr, reloc_type t) {
  visit_rels_ctx *c = (visit_rels_ctx *)ctx;

  if(c->addr == addr) {
    c->found = true;
    return 1;
  }

  return 0;
}

bool PeTarget::is_addr_relocated(uint32_t addr) {
  if(this->pe == NULL) {
    return false;
  }

  visit_rels_ctx  c;

  c.found = false;
  c.addr = addr;

  IterRelocs(this->pe, visit_rels, &c);

  return c.found;
}

bool PeTarget::relocate_addr(VA addr, VA &toaddr, VA &relocSize) {
  //doesn't really need to do anything...
  if(!this->is_addr_relocated(addr)) {
      return false;
  }

  uint8_t b[4];

  for(int i = 0; i < 4; i++) {
      if( !ReadByteAtVA(this->pe, addr+i, b[i]) ) {
          return false;
      }
  }

  toaddr =  (VA)  (((uint32_t)b[3] << 24) |
                  ((uint32_t)b[2] << 16) |
                  ((uint32_t)b[1] <<  8) |
                  ((uint32_t)b[0] <<  0));

  return true;
}

struct get_sects_ctx {
  vector<ExecutableContainer::SectionDesc> &s;
  parsed_pe *pe;
};

struct add_rels_to_vector_ctx {
  VA base;
  VA size;
  vector<VA> &rels;
};

static
int add_rels_to_vector(void *ctx, VA addr, reloc_type t) {
  add_rels_to_vector_ctx *c = (add_rels_to_vector_ctx *)ctx;

  VA base = c->base;
  VA limit = c->base + c->size;
  if(addr >= base && addr < limit) {
      c->rels.push_back(addr);
  }

  return 0;
}

int get_secs_cb(void                  *ctx,
                VA                    base,
                string                &secName,
                image_section_header  s,
                bounded_buffer        *B)
{
  get_sects_ctx                     *C = (get_sects_ctx *)ctx;
  ExecutableContainer::SectionDesc  d;

  d.secName = secName;
  d.base = base;

  // section is code if it is executable OR if it is code
  if( (s.Characteristics & IMAGE_SCN_MEM_EXECUTE) != 0 ||
      (s.Characteristics & IMAGE_SCN_CNT_CODE) != 0 ) {
    d.type = ExecutableContainer::CodeSection;
  } else {
    d.type = ExecutableContainer::DataSection;
  }

  d.read_only = (s.Characteristics & IMAGE_SCN_MEM_WRITE) == 0;

  for(::uint64_t i = 0; i < bufLen(B); i++) {
    uint8_t b;

    bool res = readByte(B, i, b);
    LASSERT(res, "Failed to read");
    d.contents.push_back(b);
  }

  add_rels_to_vector_ctx adrv =
    { d.base,
      d.contents.size(),
      d.reloc_addrs
    };

  IterRelocs(C->pe, add_rels_to_vector, &adrv);

  std::sort(d.reloc_addrs.begin(), d.reloc_addrs.end());
  C->s.push_back(d);

  return 0;
}

bool PeTarget::get_sections(vector<SectionDesc>  &secs) {
  if(this->pe == NULL) {
    return false;
  }

  get_sects_ctx c = {secs, this->pe};
  IterSec(this->pe, get_secs_cb, &c);

  return true;
}

struct visit_sec_ctx {
  ::uint64_t  curLowest;
  bool      curLowestClear;
};

static
int visit_sec(void                  *ctx,
              VA                    secBase,
              string                &secName,
              image_section_header  s,
              bounded_buffer        *B)
{
  visit_sec_ctx *c = (visit_sec_ctx *)ctx;

  if(c->curLowestClear == true) {
    c->curLowestClear = false;
    c->curLowest = secBase;
  } else {
    if(secBase < c->curLowest ) {
      c->curLowest = secBase;
    }
  }

  return 0;
}

::uint64_t PeTarget::getBase(void) const {
  assert(this->pe != NULL);

  //get the lowest base address for any section
  visit_sec_ctx c;

  c.curLowest = 0;
  c.curLowestClear = true;

  IterSec(this->pe, visit_sec, &c);

  return c.curLowest;
}

static
int visit_sec_len(void                  *ctx,
                  VA                    secBase,
                  string                &secName,
                  image_section_header  s,
                  bounded_buffer        *B)
{
  ::uint64_t  *len = (::uint64_t *)ctx;

  *len += bufLen(B);

  return 0;
}

::uint64_t PeTarget::getExtent(void) const {
  assert(this->pe != NULL);

  //count the sizes of all of the sections
  //this kind of assumes that they are contiguous
  //with no gaps, but, whatever. it is an imperfect
  //fit for an imperfect problem
  ::uint64_t  len = 0;
  IterSec(this->pe, visit_sec_len, &len);

  return len;
}

int PeTarget::readByte(::uint64_t addr, uint8_t *byte) const {
  assert(this->pe != NULL);
  uint8_t b;

  //just shell out to our API that does this from PE lib
  if(ReadByteAtVA(this->pe, addr, b)) {
    *byte = b;
    return 0;
  }

  return -1;
}

bool PeTarget::getEntryPoint(::uint64_t &entry) const {
  VA ep;
  bool did_it = GetEntryPoint(this->pe, ep);

  if( did_it ) {
      entry = static_cast< ::uint64_t >(ep);
  }

  return did_it;
}

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
/**
    test_busaobll.hpp
    Purpose: Unit Tests for the BusaoBLL class.

    @author Matheus Peschke
    @version 1.0.0 2021-05-09
*/
#pragma once
#include <boost/test/included/unit_test.hpp>
#include "stdafx.h"

/*
## 1. Nome da classe é Onibus

## 2. Deve haver um método inicial que instancie a classe Onibus

## 3. A classe Onibus deve inicializar com o número de pontos, a capacidade para pessoas sentadas e a capacidade para pessoas em pé
*/
BOOST_AUTO_TEST_SUITE(suite_onibus_inicializacao)

BOOST_AUTO_TEST_CASE(test_onibus_inicializa_sucesso)
{
    BOOST_TEST_MESSAGE( "TEST CENÁRIO 2. Deve haver um método inicial que instancie a classe Onibus" );
    BOOST_TEST_MESSAGE( "TEST CENÁRIO 3. A classe Onibus deve inicializar com o número de pontos, a capacidade para pessoas sentadas e a capacidade para pessoas em pé" );
    Onibus onibus = Onibus::Inicializar(2U, 1U, 1U);
    BOOST_TEST ( true );
}

BOOST_AUTO_TEST_CASE(test_onibus_inicializa_numero_pontos_falha)
{
    BOOST_TEST_MESSAGE( "TEST CENÁRIO 3. A classe Onibus deve inicializar com o número de pontos, a capacidade para pessoas sentadas e a capacidade para pessoas em pé" );
    BOOST_REQUIRE_THROW(Onibus::Inicializar(0U, 2U, 2U), CExcecao);
}

BOOST_AUTO_TEST_CASE(test_onibus_inicializa_capacidade_sentadas_falha)
{
    BOOST_TEST_MESSAGE( "TEST CENÁRIO 3. A classe Onibus deve inicializar com o número de pontos, a capacidade para pessoas sentadas e a capacidade para pessoas em pé" );
    BOOST_REQUIRE_THROW(Onibus::Inicializar(2U, 0U, 2U), CExcecao);
}

BOOST_AUTO_TEST_CASE(test_onibus_inicializa_capacidade_empe_falha)
{
    BOOST_TEST_MESSAGE( "TEST CENÁRIO 3. A classe Onibus deve inicializar com o número de pontos, a capacidade para pessoas sentadas e a capacidade para pessoas em pé" );
    BOOST_REQUIRE_THROW(Onibus::Inicializar(2U, 2U, 0U), CExcecao);
}

BOOST_AUTO_TEST_SUITE_END()

/*
## 4. A classe deve armazenar o número de passageiros no Ônibus

## 5. A classe deve identificar o tipo de passagem de cada passageiro
*/

BOOST_AUTO_TEST_SUITE(suite_onibus_passageiros_get_set)

BOOST_AUTO_TEST_CASE(test_onibus_passageiros_get_set_sem_passageiros)
{
    Onibus onibus = Onibus::Inicializar(2U, 1U, 1U);
    BOOST_TEST_MESSAGE( "TEST CENÁRIO 4. Onibus inicia primeira volta sem passageiros." );
    BOOST_TEST ( onibus.get_passageiros().size() == 0U );
}

BOOST_AUTO_TEST_CASE(test_onibus_passageiros_get_set_passageiro_normal)
{
    Onibus onibus = Onibus::Inicializar(2U, 1U, 1U);
    Bilhete bilhete = Bilhete::Normal;
    Passageiro passageiro = Passageiro::instantiate(bilhete);
    onibus.Entrar(passageiro);
    BOOST_TEST_MESSAGE( "TEST CENÁRIO 4. Onibus pega passageiro com bilhete Normal." );
    BOOST_TEST ( onibus.get_passageiros().size() == 1U );
    BOOST_TEST_MESSAGE( "TEST CENÁRIO 5. A classe deve identificar o tipo de passagem de cada passageiro (Normal)." );
    BOOST_TEST ( onibus.get_passageiros()[0].get_bilhete() == Bilhete::Normal );
}

BOOST_AUTO_TEST_CASE(test_onibus_passageiros_get_set_passageiro_idoso)
{
    Onibus onibus = Onibus::Inicializar(2U, 1U, 1U);
    Bilhete bilhete = Bilhete::Idoso;
    Passageiro passageiro = Passageiro::instantiate(bilhete);
    onibus.Entrar(passageiro);
    BOOST_TEST_MESSAGE( "TEST CENÁRIO 4. Onibus pega passageiro com bilhete Idoso." );
    BOOST_TEST ( onibus.get_passageiros().size() == 1U );
    BOOST_TEST_MESSAGE( "TEST CENÁRIO 5. A classe deve identificar o tipo de passagem de cada passageiro (Idoso)." );
    BOOST_TEST ( onibus.get_passageiros()[0].get_bilhete() == Bilhete::Idoso );
}

BOOST_AUTO_TEST_CASE(test_onibus_passageiros_get_set_passageiro_estudante)
{
    Onibus onibus = Onibus::Inicializar(2U, 1U, 1U);
    Bilhete bilhete = Bilhete::Estudante;
    Passageiro passageiro = Passageiro::instantiate(bilhete);
    onibus.Entrar(passageiro);
    BOOST_TEST_MESSAGE( "TEST CENÁRIO 4. Onibus pega passageiro com bilhete Estudante." );
    BOOST_TEST ( onibus.get_passageiros().size() == 1U );
    BOOST_TEST ( onibus.get_passageiros()[0].get_bilhete() == Bilhete::Estudante );
}

BOOST_AUTO_TEST_SUITE_END()

/*
## 6. Os testes devem mostrar todos os atributos da classe ônibus no ponto final
*/

BOOST_AUTO_TEST_SUITE(suite_onibus_atributos_ponto_final)

BOOST_AUTO_TEST_CASE(test_onibus_atributos_ponto_inicial)
{
    Onibus onibus = Onibus::Inicializar(2U, 1U, 1U);
    Bilhete bilhete = Bilhete::Estudante;
    Passageiro passageiro = Passageiro::instantiate(bilhete);
    onibus.Entrar(passageiro);
    onibus.Entrar(passageiro);
    BOOST_TEST_MESSAGE( "TEST CENÁRIO 6. Os testes devem mostrar todos os atributos da classe ônibus no ponto final" );
    BOOST_TEST ( onibus.ContarTipoBilhetes(Bilhete::Estudante) == 2U );
    BOOST_TEST ( onibus.ContarTipoBilhetes(Bilhete::Idoso) == 0U );
    BOOST_TEST ( onibus.ContarTipoBilhetes(Bilhete::Normal) == 0U );
}

BOOST_AUTO_TEST_CASE(test_onibus_atributos_ponto_final)
{
    const unsigned int pontos = 2U;
    const unsigned int bancos = 1U;
    const unsigned int empe = 1U;

    Onibus onibus = Onibus::Inicializar(pontos, bancos, empe);
    Bilhete bilhete = Bilhete::Estudante;
    Passageiro passageiro = Passageiro::instantiate(bilhete);
    onibus.Entrar(passageiro);
    onibus.Entrar(passageiro);
    BOOST_TEST_MESSAGE( "TEST CENÁRIO 6. Os testes devem mostrar todos os atributos da classe ônibus no ponto final" );
    BOOST_TEST ( onibus.ContarTipoBilhetes(Bilhete::Estudante) == 2U );
    BOOST_TEST ( onibus.ContarTipoBilhetes(Bilhete::Idoso) == 0U );
    BOOST_TEST ( onibus.ContarTipoBilhetes(Bilhete::Normal) == 0U );
    BOOST_TEST ( onibus.PassageirosEmPe() == 1U );
    BOOST_TEST ( onibus.PassageirosSentados() == 1U );
    BOOST_TEST ( onibus.Numerodeviagens() == 0U );
    BOOST_TEST ( onibus.get_pontos() == pontos );
    BOOST_TEST ( onibus.get_bancos() == bancos );
    BOOST_TEST ( onibus.get_empe() == empe );
    BOOST_TEST ( onibus.get_voltas() == 0U );
    BOOST_TEST ( onibus.get_ponto() == 1U );
}

BOOST_AUTO_TEST_SUITE_END()

/*
## 7. Os testes devem mostrar quantos passageiros estão em pé, em todos os pontos
*/

BOOST_AUTO_TEST_SUITE(suite_onibus_atributos_pontos)

BOOST_AUTO_TEST_CASE(test_onibus_passageiros_empe_ponto_n)
{
    Onibus onibus = Onibus::Inicializar(2U, 1U, 1U);
    Bilhete bilhete = Bilhete::Estudante;
    Passageiro passageiro = Passageiro::instantiate(bilhete);
    onibus.Entrar(passageiro);
    onibus.Entrar(passageiro);
    BOOST_TEST_MESSAGE( "TEST CENÁRIO 7. Os testes devem mostrar quantos passageiros estão em pé, em todos os pontos" );
    BOOST_TEST ( onibus.ContarTipoBilhetes(Bilhete::Estudante) == 2U );
    BOOST_TEST ( onibus.ContarTipoBilhetes(Bilhete::Idoso) == 0U );
    BOOST_TEST ( onibus.ContarTipoBilhetes(Bilhete::Normal) == 0U );
    BOOST_TEST ( onibus.PassageirosEmPe() == 1U );
    BOOST_TEST ( onibus.PassageirosSentados() == 1U );
    onibus.Pedirparadescer(1U);
    onibus.Passarnoproximoponto();
    BOOST_TEST ( onibus.PassageirosEmPe() == 0U );
    BOOST_TEST ( onibus.PassageirosSentados() == 1U );
    BOOST_TEST ( onibus.Numerodeviagens() == 0U );
    onibus.Pedirparadescer(1U);
    onibus.Passarnoproximoponto();
    BOOST_TEST ( onibus.PassageirosEmPe() == 0U );
    BOOST_TEST ( onibus.PassageirosSentados() == 0U );
    BOOST_TEST ( onibus.Numerodeviagens() == 1U );
}

BOOST_AUTO_TEST_SUITE_END()

/*
## 8. O ônibus só deve aceitar um novo passageiro, ao parar num ponto, se houver espaço

## 9. O ônibus só deve descer um passageiro, ao parar num ponto, se houver pelo menos 1 passageiro a bordo
*/

BOOST_AUTO_TEST_SUITE(suite_onibus_passageiros_subir_descer)

BOOST_AUTO_TEST_CASE(test_onibus_passageiros_subir_passageiro_empe_nao_disponiveis)
{
    Onibus onibus = Onibus::Inicializar(2U, 1U, 1U);
    Bilhete bilhete = Bilhete::Estudante;
    Passageiro passageiro = Passageiro::instantiate(bilhete);
    onibus.Entrar(passageiro);
    onibus.Entrar(passageiro);
    BOOST_TEST_MESSAGE( "TEST CENÁRIO 8. O ônibus só deve aceitar um novo passageiro, ao parar num ponto, se houver espaço" );
    BOOST_TEST ( onibus.PassageirosEmPe() == 1U );
    BOOST_TEST ( onibus.PassageirosSentados() == 1U );
    BOOST_REQUIRE_THROW(onibus.Entrar(passageiro), CExcecao);
}

BOOST_AUTO_TEST_CASE(test_onibus_passageiros_descer_passageiro_onibus_vazio)
{
    Onibus onibus = Onibus::Inicializar(2U, 1U, 1U);
    BOOST_TEST_MESSAGE( "TEST CENÁRIO 9. O ônibus só deve descer um passageiro, ao parar num ponto, se houver pelo menos 1 passageiro a bordo" );
    BOOST_TEST ( onibus.PassageirosEmPe() == 0U );
    BOOST_TEST ( onibus.PassageirosSentados() == 0U );
    onibus.Pedirparadescer(1U);
    BOOST_REQUIRE_THROW(onibus.Passarnoproximoponto(), CExcecao);
}

BOOST_AUTO_TEST_SUITE_END()

ext: hpp


text:
#include <crete/cluster/trace_pool.h>

#include <algorithm>
#include <iostream>
#include <iterator>
#include <iomanip>
#include <sstream>

#include <boost/filesystem.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/foreach.hpp>
#include <boost/regex.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/random/uniform_int_distribution.hpp>
#include <boost/random/variate_generator.hpp>

using namespace std;
using namespace boost;
namespace fs = boost::filesystem;

namespace crete
{
namespace cluster
{

TracePool::TracePool(const option::Dispatch& options)
    : options_(options), trace_count_(0) {}

auto TracePool::insert(const TracePath& trace) -> bool
{
    // TODO: xxx disabled as a part of cleanup for transmitting traces
//    if(options_.trace.print_elf_info)
//    {
//        print_elf_info(trace);
//    }

    ++trace_count_;
    next_.push_front(trace);

    return true;
}

auto TracePool::next() -> optional<TracePath>
{
    if(next_.empty())
    {
        return boost::optional<TracePath>{};
    }

    optional<TracePath> trace = optional<TracePath>(next_.back());
    next_.pop_back();

    return trace;
}

auto TracePool::count_all_unique() const -> size_t
{
    return trace_count_;
}

auto TracePool::count_next() const -> size_t
{
    return next_.size();
}

void TracePool::set(const std::map<AddressRange, Entry>& entries)
{
    elf_entries_ = entries;

    for(std::map<AddressRange, Entry>::const_iterator it = entries.begin();
        it != entries.end();
        ++it)
    {
        if(elf_entry_set_.insert(it->second).second == false)
        {
            throw std::runtime_error("found duplicate elf entry: " + it->second.name);
        }
    }
}

// TODO: xxx From trace_analyzer.cpp
static Trace parse_trace(const boost::filesystem::path& path)
{
    filesystem::ifstream ifs(path, ios_base::in | ios_base::binary);
    if(!ifs.good())
        throw runtime_error("failed to open file: " + path.generic_string());

    Trace::Blocks blocks;

    auto block_addr = uint64_t{0};
    while(ifs.read(reinterpret_cast<char*>(&block_addr), sizeof(uint64_t)))
        blocks.push_back(block_addr);

    return Trace{path.parent_path().generic_string(), blocks};
}

void TracePool::print_elf_info(const filesystem::path& trace_path)
{
    fs::path bin_seq = trace_path / "tb-seq.bin";
    fs::path elf_seq = trace_path / "tb-seq-elf.txt";

    fs::path pm_path = "guest-data/proc_maps.log";

    if(!fs::exists(pm_path))
    {
        throw runtime_error("failed to open file: " + pm_path.string());
    }

    ProcReader pr(pm_path);
    ProcMaps pms = condense(pr.find_all());

    Trace trace = parse_trace(bin_seq);

    fs::ofstream ofs(elf_seq);

    ofs << std::hex;
    ofs << std::left;

    if(!ofs.good())
        throw std::runtime_error("failed to open file: " + elf_seq.string());

    const Trace::Blocks& blocks = trace.get_blocks();

    size_t block_counter = 0;
    for(Trace::Blocks::const_iterator it = blocks.begin();
        it != blocks.end();
        ++it)
    {
        const Trace::Block& block = *it;

        uint64_t offset = 0;
        std::string lib_path;

        for(ProcMaps::const_iterator pit = pms.begin();
            pit != pms.end();
            ++pit)
        {
            const ProcMap& pm = *pit;

            if(is_in(AddressRange(pm.address().first, pm.address().second),
                     block))
            {
                if(pm.path() == pr.get_executable())
                {
                    offset = block;
                }
                else
                {
                    offset = block - pm.address().first;
                }

                lib_path = pm.path();

                break;
            }
        }

        std::string func_name;

        Entry entry;
        entry.addr = block;
        std::set<Entry>::const_iterator eit = elf_entry_set_.find(entry);
        if(eit != elf_entry_set_.end())
        {
            func_name = eit->name;
        }
        else
        {
            for(std::map<AddressRange, Entry>::const_iterator it = elf_entries_.begin();
                it != elf_entries_.end();
                ++it)
            {
                if(is_in(it->first, block))
                {
                    func_name = it->second.name;
                    break;

                }
            }
        }

        stringstream ssblock_counter;
        ssblock_counter << block_counter << ": ";

        ofs << setw(6)  << ssblock_counter.str()
            << setw(14) << block
            << " -> "
            << setw(14) << offset
            << " -> "
            << setw(35) << func_name
            << " -> "
            << setw(45) << lib_path
            << '\n';

        ++block_counter;
    }
}
} // namespace cluster
} // namespace crete

ext: cpp


text:
//////////////////////////////////////////////////////////////////////////////
// distribution::toolkit::distributions::normal::include.hpp                 //
//                                                                          //
//  (C) Copyright 2009 Erwann Rogard                                        //
//  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)        //
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_NORMAL_INCLUDE_HPP_ER_2009
#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_NORMAL_INCLUDE_HPP_ER_2009

#include <boost/math/distributions/normal.hpp>

#include <boost/statistics/detail/distribution_toolkit/distributions/normal/description.hpp>
#include <boost/statistics/detail/distribution_toolkit/distributions/normal/derivative_log_unnormalized_pdf.hpp>
#include <boost/statistics/detail/distribution_toolkit/distributions/normal/log_unnormalized_pdf.hpp>
#include <boost/statistics/detail/distribution_toolkit/distributions/normal/is_math_distribution.hpp>
#include <boost/statistics/detail/distribution_toolkit/distributions/normal/normalizing_constant.hpp>
#include <boost/statistics/detail/distribution_toolkit/distributions/normal/random.hpp>
#include <boost/statistics/detail/distribution_toolkit/distributions/normal/os.hpp>

#endif


text:
/*
 * N-DISE: NDN for Data Intensive Science Experiments
 * Author: Catalin Iordache <catalin.iordache@cern.ch>
 *
 * MIT License
 *
 * Copyright (c) 2021 California Institute of Technology
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <fstream>
#include <iostream>
#include <signal.h>
#include <unistd.h>

#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>

#include "ft-server.hpp"
#include "logger/logger.hpp"

using namespace std;
namespace po = boost::program_options;

static ndnc::Face *face;
static ndnc::benchmark::ft::Runner *server;
static bool shouldRun = true;

void handler(sig_atomic_t) {
    shouldRun = false;
}

static void usage(ostream &os, const po::options_description &desc) {
    os << desc;
}

int main(int argc, char **argv) {
    signal(SIGINT, handler);
    signal(SIGABRT, handler);

    ndnc::benchmark::ft::ServerOptions opts;

    po::options_description description("Options", 120);
    description.add_options()(
        "gqlserver",
        po::value<string>(&opts.gqlserver)->default_value(opts.gqlserver),
        "GraphQL server address");
    description.add_options()(
        "mtu", po::value<size_t>(&opts.mtu)->default_value(opts.mtu),
        "Dataroom size. Specify a positive integer between 64 and 9000");
    description.add_options()(
        "segment-size",
        po::value<size_t>(&opts.segmentSize)->default_value(opts.segmentSize),
        string("The maximum segment size of each Data packet that has "
               "content from a file. Specify a positive integer smaller or "
               "equal to " +
               to_string(ndn::MAX_NDN_PACKET_SIZE))
            .c_str());
    description.add_options()("help,h", "Print this help message and exit");

    po::variables_map vm;
    try {
        po::store(
            po::command_line_parser(argc, argv).options(description).run(), vm);
        po::notify(vm);
    } catch (const po::error &e) {
        cerr << "ERROR: " << e.what() << "\n";
        return 2;
    } catch (const boost::bad_any_cast &e) {
        cerr << "ERROR: " << e.what() << "\n";
        return 2;
    }

    if (vm.count("help") > 0) {
        usage(cout, description);
        return 0;
    }

    if (vm.count("mtu") > 0) {
        if (opts.mtu < 64 || opts.mtu > 9000) {
            cerr << "ERROR: invalid MTU size. please specify a positive "
                    "integer between 64 and 9000\n\n";
            usage(cout, description);
            return 2;
        }
    }

    if (vm.count("gqlserver") > 0) {
        if (opts.gqlserver.empty()) {
            cerr << "ERROR: empty gqlserver argument value\n\n";
            usage(cout, description);
            return 2;
        }
    }

    if (vm.count("segment-size") > 0) {
        if (opts.segmentSize > ndn::MAX_NDN_PACKET_SIZE) {
            cerr << "ERROR: invalid segment size value\n\n";
            usage(cout, description);
            return 2;
        }
    }

    face = new ndnc::Face();
#ifndef __APPLE__
    if (!face->openMemif(opts.mtu, opts.gqlserver, "ndncft-server"))
        return 2;
#endif
    if (!face->isValid()) {
        cerr << "ERROR: invalid face\n";
        return 2;
    }

    server = new ndnc::benchmark::ft::Runner(*face, opts);

    if (!face->advertise(ndnc::benchmark::namePrefixUri)) {
        cerr << "ERROR: unable to advertise prefix on face\n";
        return 2;
    }

    LOG_INFO("running... ");
    while (shouldRun && face->isValid()) {
        face->loop();
    }

#ifndef NDEBUG
    cout << "\n--- face statistics --\n"
         << face->readCounters()->nTxPackets << " packets transmitted, "
         << face->readCounters()->nRxPackets << " packets received\n"
         << face->readCounters()->nTxBytes << " bytes transmitted, "
         << face->readCounters()->nRxBytes << " bytes received "
         << "with " << face->readCounters()->nErrors << " errors\n";
#endif // DEBUG
    cout << endl;

    if (server != nullptr) {
        delete server;
    }

    if (face != nullptr) {
        delete face;
    }

    return 0;
}

max_stars_repo_name: cmscaltech/sandie-ndn

max_issues_repo_name: cmscaltech/sandie-ndn

max_forks_repo_name: cmscaltech/sandie-ndn


text:
#include "../../src/shared/state.h"

#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_CASE(TestStaticAssert)
{
    BOOST_CHECK(1);
}

BOOST_AUTO_TEST_CASE(TestPlayerGettersEmptyConstrutors)
{
    state::Player player;
    BOOST_CHECK_EQUAL(player.getId(), 0);
    BOOST_CHECK_EQUAL(player.getUnits().empty(), 1);
    BOOST_CHECK_EQUAL(player.getTowers().empty(), 1);
    BOOST_CHECK_EQUAL(player.getApparitionAreas().empty(), 1);
}

BOOST_AUTO_TEST_CASE(TestPlayerSettersEmptyConstrutors)
{
    state::Player player;

    state::Character character1, character2, character3;
    state::Tower tower1, tower2;
    state::ApparitionArea apparitionArea1;

    std::vector<state::Character> units;
    units.push_back(character1);
    units.push_back(character2);
    units.push_back(character3);
    std::vector<state::Tower> towers;
    towers.push_back(tower1);
    towers.push_back(tower2);
    std::vector<state::ApparitionArea> apparitionAreas;
    apparitionAreas.push_back(apparitionArea1);

    player.setUnits(units);
    player.setTowers(towers);
    player.setApparitionAreas(apparitionAreas);

    BOOST_CHECK_EQUAL(player.getUnits().size(), 3);
    BOOST_CHECK_EQUAL(player.getTowers().size(), 2);
    BOOST_CHECK_EQUAL(player.getApparitionAreas().size(), 1);
}

BOOST_AUTO_TEST_CASE(TestPlayerConstrutorsWithParameters)
{
    state::Character character1, character2, character3;
    state::Tower tower1, tower2;
    state::ApparitionArea apparitionArea1;

    std::vector<state::Character> units;
    units.push_back(character1);
    units.push_back(character2);
    units.push_back(character3);
    std::vector<state::Tower> towers;
    towers.push_back(tower1);
    towers.push_back(tower2);
    std::vector<state::ApparitionArea> apparitionAreas;
    apparitionAreas.push_back(apparitionArea1);

    state::Player player{0, units, towers, apparitionAreas};

    BOOST_CHECK_EQUAL(player.getUnits().size(), 3);
    BOOST_CHECK_EQUAL(player.getTowers().size(), 2);
    BOOST_CHECK_EQUAL(player.getApparitionAreas().size(), 1);
}

max_stars_repo_name: Welteam/Projet-IS

max_issues_repo_name: Welteam/Projet-IS

max_forks_repo_name: Welteam/Projet-IS


text:
#pragma once

#include "../option.hh"
#include "../../stats/movingaverage.hh"
#include "../../util/Maybe.hh"

#include <Eigen/Core>

namespace bold
{
  template<typename> class Setting;

  /** Terminates only when the opponent's kick-off time elapses, or the ball is moved away from its initial position. */
  class AwaitTheirKickOff : public Option
  {
  public:
    AwaitTheirKickOff(std::string id);

    std::vector<std::shared_ptr<Option>> runPolicy(rapidjson::Writer<rapidjson::StringBuffer>& writer) override;

    double hasTerminated() override;

    void reset() override;

  private:
    /// Smoothed ball position estimate
    MovingAverage<Eigen::Vector2d> d_ballPosition;
    /// Mature estimate of the ball's initial position, against which later mature estimates will be compared
    Maybe<Eigen::Vector2d> d_ballInitialPosition;
    /// Setting that specifies the distance the ball must move in order to terminate this option
    Setting<double>* d_requiredMoveDistance;
  };
}

ext: hh

max_stars_repo_name: drewnoakes/bold-humanoid

max_issues_repo_name: drewnoakes/bold-humanoid

max_forks_repo_name: drewnoakes/bold-humanoid


text:
#include <boost/python.hpp>

#include "OpenPGP/verify.h"

void verify_init()
{
boost::python::def("verify_message", static_cast<bool(*)(const Tag6::Ptr &, const PGPMessage &)>(&verify_message));
boost::python::def("verify_message", static_cast<bool(*)(const PGPPublicKey &, const PGPMessage &)>(&verify_message));
boost::python::def("verify_message", static_cast<bool(*)(const PGPSecretKey &, const PGPMessage &)>(&verify_message));
boost::python::def("verify_detachedsig", static_cast<bool(*)(const PGPPublicKey &, const std::string &, const PGPDetachedSignature &)>(&verify_detachedsig));
boost::python::def("verify_detachedsig", static_cast<bool(*)(const PGPSecretKey &, const std::string &, const PGPDetachedSignature &)>(&verify_detachedsig));
boost::python::def("verify_detachedsig", static_cast<bool(*)(const PGPPublicKey &, std::ifstream &, const PGPDetachedSignature &)>(&verify_detachedsig));
boost::python::def("verify_detachedsig", static_cast<bool(*)(const PGPSecretKey &, std::ifstream &, const PGPDetachedSignature &)>(&verify_detachedsig));
boost::python::def("verify_revoke", static_cast<bool(*)(const Tag6::Ptr &, const Tag2::Ptr &)>(&verify_revoke));
boost::python::def("verify_revoke", static_cast<bool(*)(const PGPPublicKey &, const PGPPublicKey &)>(&verify_revoke));
boost::python::def("verify_revoke", static_cast<bool(*)(const PGPSecretKey &, const PGPPublicKey &)>(&verify_revoke));
boost::python::def("verify_key", static_cast<bool(*)(const PGPPublicKey &, const PGPPublicKey &)>(&verify_key));
boost::python::def("verify_key", static_cast<bool(*)(const PGPSecretKey &, const PGPPublicKey &)>(&verify_key));
boost::python::def("verify_cleartext_signature", static_cast<bool(*)(const PGPPublicKey &, const PGPCleartextSignature &)>(&verify_cleartext_signature));
boost::python::def("verify_cleartext_signature", static_cast<bool(*)(const PGPSecretKey &, const PGPCleartextSignature &)>(&verify_cleartext_signature));
boost::python::def("pka_verify", static_cast<bool(*)(const std::string &, const uint8_t, const uint8_t, const std::vector<PGPMPI> &, const std::vector<PGPMPI> &)>(&pka_verify));
boost::python::def("pka_verify", static_cast<bool(*)(const std::string &, const Tag6::Ptr, const Tag2::Ptr &)>(&pka_verify));
}

max_stars_repo_name: mugwort-rc/pyOpenPGP

max_issues_repo_name: mugwort-rc/pyOpenPGP

max_forks_repo_name: mugwort-rc/pyOpenPGP


text:
/*! \file helium_hf.cpp
    \brief Hartree-Fock法で、ヘリウム原子のエネルギーを計算する
    Copyright © 2017 @dc1394 All Rights Reserved.
    (but this is originally adapted by Paolo Giannozzi for helium_hf_gauss.c from http://www.fisica.uniud.it/~giannozz/Corsi/MQ/Software/C/helium_hf_gauss.c )
    This software is released under the BSD 2-Clause License.
*/

#include <chrono>                               // for std::chrono
#include <cmath>                                // for std::pow, std::sqrt
#include <cstdint>                              // for std::int32_t
#include <iostream>                             // for std::cerr, std::cin, std::cout
#include <optional>                             // for std::make_optional, std::optional, std::nullopt
#include <valarray>                             // for std::valarray
#include <boost/assert.hpp>                     // for BOOST_ASSERT
#include <boost/format.hpp>                     // for boost::format
#include <boost/math/constants/constants.hpp>   // for boost::math::constants::pi
#include <boost/multi_array.hpp>                // for boost::multi_array
#include <Eigen/Core>                           // for Eigen::MatrixXd, Eigen::VectorXd
#include <Eigen/Eigenvalues>                    // for Eigen::GeneralizedSelfAdjointEigenSolver

namespace {
    //! A global variable (constant expression).
    /*!
        バッファサイズの上限
    */
    static auto constexpr MAXBUFSIZE = 32;

    //! A global variable (constant expression).
    /*!
        SCF計算のループの上限
    */
	static auto constexpr MAXITER = 1000;

    //! A global variable (constant expression).
    /*!
        SCF計算のループから抜ける際のエネルギーの差の閾値
    */
	static auto constexpr SCFTHRESHOLD = 1.0E-15;

    //! A global function.
    /*!
        SCF計算を行う
        \return SCF計算が正常に終了した場合はエネルギーを、しなかった場合はstd::nulloptを返す
    */
    std::optional<double> do_scfloop();

    //! A global function.
    /*!
        nalpha個のGTOによるヘリウム原子のエネルギーを計算する
        \param c 固有ベクトルC
        \param ep 一般化固有値問題のエネルギー固有値E'
        \param h 1電子積分
        \return ヘリウム原子のエネルギー
    */
    double getenergy(Eigen::VectorXd const & c, double ep, boost::multi_array<double, 2> const & h);

    //! A global function.
    /*!
        使用するGTOの数をユーザに入力させる
        \return 使用するGTOの数
    */
    std::int32_t input_nalpha();

    //! A global function.
    /*!
        GTOの肩の係数が格納された配列を生成する
        \param nalpha 使用するGTOの個数
        \return GTOの肩の係数が格納されたstd::vector
    */
    std::valarray<double> make_alpha(std::int32_t nalpha);

    //! A global function.
    /*!
        全ての要素が、引数で指定された値で埋められたnalpha次元ベクトルを生成する
        \param nalpha 使用するGTOの個数
        \param val 要素を埋める値
        \return 引数で指定された値で埋められたベクトル (Eigen::VectorXd)
    */
    Eigen::VectorXd make_c(std::int32_t nalpha, double val);

    //! A global function.
    /*!
        nalphaの数で、固有ベクトル、1電子積分および2電子積分からFock行列を生成する
        \param c 固有ベクトルC
        \param h 1電子積分hpq
        \param q 2電子積分Qprqs
        \return Fock行列 (Eigen::MatrixXd)
    */
    Eigen::MatrixXd make_fockmatrix(Eigen::VectorXd const & c, boost::multi_array<double, 2> const & h, boost::multi_array<double, 4> const & q);

    //! A global function.
    /*!
        1電子積分が格納された、nalpha×nalphaの2次元配列を生成する
        \param alpha GTOの肩の係数が格納されたstd::vector
        \return 1電子積分が格納された2次元配列 (boost::multi_array)
    */
    boost::multi_array<double, 2> make_oneelectroninteg(std::valarray<double> const & alpha);

    //! A global function.
    /*!
        nalpha次正方行列の重なり行列を生成する
        \param alpha GTOの肩の係数が格納されたstd::vector
        \return 重なり行列 (Eigen::MatrixXd)
    */
    Eigen::MatrixXd make_overlapmatrix(std::valarray<double> const & alpha);

    //! A global function.
    /*!
        2電子積分が格納されたnalpha×nalpha×nalpha×nalphaの4次元配列を生成する
        \param alpha GTOの肩の係数が格納されたstd::vector
        \return 2電子積分が格納された4次元配列 (boost::multi_array)
    */
    boost::multi_array<double, 4> make_twoelectroninteg(std::valarray<double> const & alpha);
}

int main()
{
    using namespace std::chrono;

    auto const start = system_clock::now();

    if (auto const res(do_scfloop()); res) {
        std::cout << boost::format("SCF計算が収束しました: energy = %.14f (Hartree)") % (*res) << std::endl;

        auto const end = system_clock::now();
        std::cout << boost::format("計算時間 = %.14f（秒）\n") % duration_cast< duration<double> >(end - start).count();

        return 0;
    }
    else {
        std::cerr << "SCF計算が収束しませんでした" << std::endl;

        return -1;
    }
}

namespace {
    std::optional<double> do_scfloop()
    {
        // 使用するGTOの数を入力
        //auto const nalpha(input_nalpha());
        int nalpha = 6;

        // GTOの肩の係数が格納された配列を生成
        auto alpha = make_alpha(nalpha);

        // 1電子積分が格納された2次元配列を生成
        auto const h(make_oneelectroninteg(alpha));

        // 2電子積分が格納された4次元配列を生成
        auto const q(make_twoelectroninteg(alpha));

        // 重なり行列を生成
        auto const s(make_overlapmatrix(alpha));

        // 全て0.0で初期化された固有ベクトルを生成
        auto c(make_c(nalpha, 0.0));

        // 新しく計算されたエネルギー
        auto enew = 0.0;

        // SCFループ
        for (auto iter = 1; iter < MAXITER; iter++) {
            // Fock行列を生成
            auto const f(make_fockmatrix(c, h, q));

            // 一般化固有値問題を解く
            Eigen::GeneralizedSelfAdjointEigenSolver<Eigen::MatrixXd> es(f, s);

            // E'を取得
            auto const ep = es.eigenvalues()[0];

            // 固有ベクトルを取得
            c = es.eigenvectors().col(0);

            // 前回のSCF計算のエネルギーを保管
            auto const eold = enew;

            // 今回のSCF計算のエネルギーを計算する
            enew = getenergy(c, ep, h);

            std::cout << boost::format("Iteration # %2d: HF eigenvalue = %.14f, energy = %.14f\n") % iter % ep % enew;

            // SCF計算が収束したかどうか
            if (std::fabs(enew - eold) < SCFTHRESHOLD) {
                // 収束したのでそのエネルギーを返す
                return std::make_optional(enew);
            }
        }

        // SCF計算が収束しなかった
        return std::nullopt;
    }

    double getenergy(Eigen::VectorXd const & c, double ep, boost::multi_array<double, 2> const & h)
    {
        auto const nalpha = static_cast<std::int32_t>(c.size());
        auto e = ep;
        for (auto p = 0; p < nalpha; p++) {
            for (auto q = 0; q < nalpha; q++) {
                // E = E' + Cp * Cq * hpq
                e += c[p] * c[q] * h[p][q];
            }
        }

        return e;
    }

    std::int32_t input_nalpha()
    {
        std::int32_t nalpha;

        while (true) {
            std::cout << "使用するGTOの個数を入力してください (3, 4 or 6): ";
            std::cin >> nalpha;

            if (!std::cin.fail() && (nalpha == 3 || nalpha == 4 || nalpha == 6)) {
                break;
            }

            std::cin.clear();
            std::cin.ignore(MAXBUFSIZE, '\n');
        }

        return nalpha;
    }

    std::valarray<double> make_alpha(std::int32_t nalpha)
    {
        switch (nalpha) {
        case 3:
            return { 0.31364978999999998, 1.1589229999999999, 6.3624213899999997 };

        case 4:
            return { 0.297104, 1.236745, 5.749982, 38.2166777 };

        case 6:
            return { 0.18595935599999999, 0.45151632200000003, 1.1627151630000001, 3.384639924, 12.09819836, 65.984568240000002 };

        default:
            BOOST_ASSERT(!"switch文のdefaultに来てしまった！");
            return std::valarray<double>();
        }
    }

    Eigen::VectorXd make_c(std::int32_t nalpha, double val)
    {
        Eigen::VectorXd c(nalpha);

        // 固有ベクトルCの要素を全てvalで初期化
        for (auto i = 0; i < nalpha; i++) {
            c[i] = val;
        }

        return c;
    }

    Eigen::MatrixXd make_fockmatrix(Eigen::VectorXd const & c, boost::multi_array<double, 2> const & h, boost::multi_array<double, 4> const & q)
    {
        auto const nalpha = static_cast<std::int32_t>(c.size());
        Eigen::MatrixXd f = Eigen::MatrixXd::Zero(nalpha, nalpha);

        for (auto p = 0; p < nalpha; p++) {
            for (auto qi = 0; qi < nalpha; qi++) {
                // Fpq = hpq + ΣCr * Cs * Qprqs
                f(p, qi) = h[p][qi];

                for (auto r = 0; r < nalpha; r++) {
                    for (auto s = 0; s < nalpha; s++) {
                        f(p, qi) += c[r] * c[s] * q[p][r][qi][s];
                    }
                }
            }
        }

        return f;
    }

    boost::multi_array<double, 2> make_oneelectroninteg(std::valarray<double> const & alpha)
    {
        using namespace boost::math::constants;

        auto const nalpha = static_cast<std::int32_t>(alpha.size());
        boost::multi_array<double, 2> h(boost::extents[nalpha][nalpha]);

        for (auto p = 0; p < nalpha; p++) {
            for (auto q = 0; q < nalpha; q++) {
                // αp + αq
                auto const appaq = alpha[p] + alpha[q];

                // hpq = 3αpαqπ^1.5 / (αp + αq)^2.5 - 4π / (αp + αq)
                h[p][q] = 3.0 * alpha[p] * alpha[q] * std::pow((pi<double>() / appaq), 1.5) / appaq -
                          4.0 * pi<double>() / appaq;
            }
        }

        return h;
    }

    Eigen::MatrixXd make_overlapmatrix(std::valarray<double> const & alpha)
    {
        using namespace boost::math::constants;

        auto const nalpha = static_cast<std::int32_t>(alpha.size());
        Eigen::MatrixXd s = Eigen::MatrixXd::Zero(nalpha, nalpha);

        for (auto p = 0; p < nalpha; p++) {
            for (auto q = 0; q < nalpha; q++) {
                // Spq = (π / (αp + αq))^1.5
                s(p, q) = std::pow((pi<double>() / (alpha[p] + alpha[q])), 1.5);
            }
        }

        return s;
    }

    boost::multi_array<double, 4> make_twoelectroninteg(std::valarray<double> const & alpha)
    {
        using namespace boost::math::constants;

        auto const nalpha = static_cast<std::int32_t>(alpha.size());
        boost::multi_array<double, 4> q(boost::extents[nalpha][nalpha][nalpha][nalpha]);

        for (auto p = 0; p < nalpha; p++) {
            for (auto qi = 0; qi < nalpha; qi++) {
                for (auto r = 0; r < nalpha; r++) {
                    for (auto s = 0; s < nalpha; s++) {
                        // Qprqs = 2π^2.5 / [(αp + αq)(αr + αs)√(αp + αq + αr + αs)]
                        q[p][r][qi][s] = 2.0 * std::pow(pi<double>(), 2.5) /
                            ((alpha[p] + alpha[qi]) * (alpha[r] + alpha[s]) *
                            std::sqrt(alpha[p] + alpha[qi] + alpha[r] + alpha[s]));
                    }
                }
            }
        }

        return q;
    }
}


text: #include <boost/preprocessor/seq/push_front.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/* Copyright 2008, 2009 (C) Nicira, Inc.
 *
 * This file is part of NOX.
 *
 * NOX is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * NOX is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with NOX.  If not, see <http://www.gnu.org/licenses/>.
 */
#ifndef MEMORY_HH
#define MEMORY_HH 1

#include <utility>

#include <boost/function.hpp>
#include <boost/shared_ptr.hpp>

#include "component.hh"
#include "dht-impl.hh"
#include "threads/cooperative.hh"

namespace vigil {
namespace applications {
namespace storage {

/**
 * A memory-based implementation of the multi key-value storage.
 */
class Async_DHT_storage
    : public Async_storage,
      public container::Component {
public:
    Async_DHT_storage(const container::Context*,
                      const json_object*);

    void create_table(const Table_name&,
                      const Column_definition_map&,
                      const Index_list&,
                      const Create_table_callback&);

    void drop_table(const Table_name&,
                    const Drop_table_callback&);

    void get(const Table_name&,
             const Query&,
             const Get_callback&);

    void get_next(const Context&,
                  const Get_callback&);

    void put(const Table_name&,
             const Row&,
             const Put_callback&);

    void modify(const Context&,
                const Row&,
                const Modify_callback&);

    void remove(const Context&,
                const Remove_callback&);

    void put_trigger(const Context&,
                     const Trigger_function&,
                     const Put_trigger_callback&);

    void put_trigger(const Table_name&,
                     const bool sticky,
                     const Trigger_function&,
                     const Put_trigger_callback&);

    void remove_trigger(const Trigger_id&,
                        const Remove_callback&);

    void debug(const Table_name&);

protected:
    void configure(const container::Configuration*);
    void install();

private:
    bool validate_column_types(const Table_name&, const Column_value_map&,
                               const Result::Code&,
                               const boost::function<void(const Result&)>&)
        const;

    /* Determines the matching index for a query. */
    Index identify_index(const Table_name&, const Query&) const;

    typedef std::list<boost::function<void(const Async_storage::Put_callback)> > Put_list;

    /* Table schemas */
    typedef hash_map<Index_name, Index> Index_map;
    typedef std::pair<Column_definition_map, Index_map> Table_definition;
    typedef hash_map<Table_name, Table_definition> Table_definition_map;
    Table_definition_map tables;

    Index_list to_list(const Index_map&);

    /* Fake DHTs */
    hash_map<DHT_name, Content_DHT_ptr> content_dhts;
    hash_map<DHT_name, Index_DHT_ptr> index_dhts;

    /* Mutex protecting the table definitions and rings */
    mutable Co_mutex mutex;
};

} // namespace storage
} // namespace applications
} // namespace vigil

#endif

max_stars_repo_name: ayjazz/OESS

max_issues_repo_name: ayjazz/OESS

max_forks_repo_name: ayjazz/OESS


text:
#pragma once

#include <boost/multiprecision/cpp_int.hpp>

#include <cryptopp/osrng.h>

namespace chratos
{
// Random pool used by RaiBlocks.
// This must be thread_local as long as the AutoSeededRandomPool implementation requires it
extern thread_local CryptoPP::AutoSeededRandomPool random_pool;
using uint128_t = boost::multiprecision::uint128_t;
using uint256_t = boost::multiprecision::uint256_t;
using uint512_t = boost::multiprecision::uint512_t;
// SI dividers
chratos::uint128_t const Gchr_ratio = chratos::uint128_t ("10000000000000000000000000000000000"); // 10^34
chratos::uint128_t const Mchr_ratio = chratos::uint128_t ("10000000000000000000000000000000"); // 10^31
chratos::uint128_t const kchr_ratio = chratos::uint128_t ("10000000000000000000000000000"); // 10^28
chratos::uint128_t const chr_ratio = chratos::uint128_t ("10000000000000000000000000"); // 10^25
chratos::uint128_t const mchr_ratio = chratos::uint128_t ("10000000000000000000000"); // 10^22
chratos::uint128_t const uchr_ratio = chratos::uint128_t ("10000000000000000000"); // 10^19
chratos::uint128_t const minimum_dividend_amount = Mchr_ratio;

union uint128_union
{
public:
	uint128_union () = default;
	/**
	 * Decode from hex string
	 * @warning Aborts at runtime if the input is invalid
	 */
	uint128_union (std::string const &);
	uint128_union (uint64_t);
	uint128_union (chratos::uint128_union const &) = default;
	uint128_union (chratos::uint128_t const &);
	bool operator== (chratos::uint128_union const &) const;
	bool operator!= (chratos::uint128_union const &) const;
	bool operator< (chratos::uint128_union const &) const;
	bool operator> (chratos::uint128_union const &) const;
	void encode_hex (std::string &) const;
	bool decode_hex (std::string const &);
	void encode_dec (std::string &) const;
	bool decode_dec (std::string const &);
	std::string format_balance (chratos::uint128_t scale, int precision, bool group_digits);
	std::string format_balance (chratos::uint128_t scale, int precision, bool group_digits, const std::locale & locale);
	chratos::uint128_t number () const;
	void clear ();
	bool is_zero () const;
	std::string to_string () const;
	std::string to_string_dec () const;
	std::array<uint8_t, 16> bytes;
	std::array<char, 16> chars;
	std::array<uint32_t, 4> dwords;
	std::array<uint64_t, 2> qwords;
};
// Balances are 128 bit.
using amount = uint128_union;
class raw_key;
union uint256_union
{
	uint256_union () = default;
	/**
	 * Decode from hex string
	 * @warning Aborts at runtime if the input is invalid
	 */
	uint256_union (std::string const &);
	uint256_union (uint64_t);
	uint256_union (chratos::uint256_t const &);
	void encrypt (chratos::raw_key const &, chratos::raw_key const &, uint128_union const &);
	uint256_union & operator^= (chratos::uint256_union const &);
	uint256_union operator^ (chratos::uint256_union const &) const;
	bool operator== (chratos::uint256_union const &) const;
	bool operator!= (chratos::uint256_union const &) const;
	bool operator< (chratos::uint256_union const &) const;
	void encode_hex (std::string &) const;
	bool decode_hex (std::string const &);
	void encode_dec (std::string &) const;
	bool decode_dec (std::string const &);
	void encode_account (std::string &) const;
	std::string to_account () const;
	bool decode_account (std::string const &);
	std::array<uint8_t, 32> bytes;
	std::array<char, 32> chars;
	std::array<uint32_t, 8> dwords;
	std::array<uint64_t, 4> qwords;
	std::array<uint128_union, 2> owords;
	void clear ();
	bool is_zero () const;
	std::string to_string () const;
	chratos::uint256_t number () const;
};
// All keys and hashes are 256 bit.
using block_hash = uint256_union;
using account = uint256_union;
using public_key = uint256_union;
using private_key = uint256_union;
using secret_key = uint256_union;
using checksum = uint256_union;
class raw_key
{
public:
	raw_key () = default;
	~raw_key ();
	void decrypt (chratos::uint256_union const &, chratos::raw_key const &, uint128_union const &);
	bool operator== (chratos::raw_key const &) const;
	bool operator!= (chratos::raw_key const &) const;
	chratos::uint256_union data;
};
union uint512_union
{
	uint512_union () = default;
	uint512_union (chratos::uint512_t const &);
	bool operator== (chratos::uint512_union const &) const;
	bool operator!= (chratos::uint512_union const &) const;
	chratos::uint512_union & operator^= (chratos::uint512_union const &);
	void encode_hex (std::string &) const;
	bool decode_hex (std::string const &);
	std::array<uint8_t, 64> bytes;
	std::array<uint32_t, 16> dwords;
	std::array<uint64_t, 8> qwords;
	std::array<uint256_union, 2> uint256s;
	void clear ();
	chratos::uint512_t number () const;
	std::string to_string () const;
};
// Only signatures are 512 bit.
using signature = uint512_union;

chratos::uint512_union sign_message (chratos::raw_key const &, chratos::public_key const &, chratos::uint256_union const &);
bool validate_message (chratos::public_key const &, chratos::uint256_union const &, chratos::uint512_union const &);
bool validate_message_batch (const unsigned char **, size_t *, const unsigned char **, const unsigned char **, size_t, int *);
void deterministic_key (chratos::uint256_union const &, uint32_t, chratos::uint256_union &);
chratos::public_key pub_key (chratos::private_key const &);
}

namespace std
{
template <>
struct hash<chratos::uint256_union>
{
	size_t operator() (chratos::uint256_union const & data_a) const
	{
		return *reinterpret_cast<size_t const *> (data_a.bytes.data ());
	}
};
template <>
struct hash<chratos::uint256_t>
{
	size_t operator() (chratos::uint256_t const & number_a) const
	{
		return number_a.convert_to<size_t> ();
	}
};
}

max_stars_repo_name: chratos-system/chratos

max_issues_repo_name: chratos-system/chratos

max_forks_repo_name: chratos-system/chratos


text:
#include <bunsan/pm/cache.hpp>

#include <bunsan/config/cast.hpp>
#include <bunsan/filesystem/operations.hpp>

#include <boost/assert.hpp>
#include <boost/thread/lock_types.hpp>

namespace bunsan {
namespace pm {

namespace {
const boost::filesystem::path installation_subdir = ".install";
const boost::filesystem::path installation_data = "data";

pm::config update_config_data(pm::config config) {
  if (!config.extract) BOOST_THROW_EXCEPTION(null_extractor_error());
  config.extract->installation.data = installation_data;
  return config;
}
}  // namespace

cache::cache(const config &config_)
    : m_repository(update_config_data(config_.repository)),
      m_config(config_.cache) {
  clean_();
}

cache::cache(const boost::property_tree::ptree &config_)
    : cache(bunsan::config::load<cache::config>(config_)) {}

cache::entry cache::get(const pm::entry &package) {
  const boost::filesystem::path root =
      m_config.root / package.location() / installation_subdir;
  if (m_repository.need_update(package, root, m_config.lifetime)) {
    const boost::unique_lock<boost::shared_mutex> lk(m_lock);
    const boost::filesystem::file_status status =
        boost::filesystem::symlink_status(root);
    switch (status.type()) {
      default:
        clean_();
      case boost::filesystem::file_not_found:
        boost::filesystem::create_directories(root);
      case boost::filesystem::directory_file:
        m_repository.update(package, root, m_config.lifetime);
    }
  }
  return entry(&m_lock, root / installation_data);
}

void cache::clean() {
  const boost::unique_lock<boost::shared_mutex> lk(m_lock);
  clean_();
}

void cache::clean_() {
  // requires lock
  bunsan::filesystem::reset_dir(m_config.root);
}

const boost::filesystem::path &cache::entry::root() const {
  BOOST_ASSERT(*this);
  return m_root;
}

cache::entry::entry(boost::shared_mutex *lock_,
                    const boost::filesystem::path &root)
    : m_lock(lock_), m_root(root) {
  BOOST_ASSERT(*this);
  lock();
}

void cache::entry::lock() {
  if (*this) m_lock->lock_shared();
}

void cache::entry::unlock() {
  if (m_lock) m_lock->unlock_shared();
  m_lock = nullptr;
}

}  // namespace pm
}  // namespace bunsan

max_stars_repo_name: bunsanorg/pm

max_issues_repo_name: bunsanorg/pm

max_forks_repo_name: bunsanorg/pm