text stringlengths 54 60.6k |
|---|
<commit_before>cee08702-2e4d-11e5-9284-b827eb9e62be<commit_msg>cee57f5a-2e4d-11e5-9284-b827eb9e62be<commit_after>cee57f5a-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>4679e34e-2e4e-11e5-9284-b827eb9e62be<commit_msg>467ef12c-2e4e-11e5-9284-b827eb9e62be<commit_after>467ef12c-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>b0f0b9c4-2e4d-11e5-9284-b827eb9e62be<commit_msg>b0f5b032-2e4d-11e5-9284-b827eb9e62be<commit_after>b0f5b032-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>/*
* Copyright 2008-2009 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*! \file scan.inl
* \brief Inline file for scan.h.
*/
#include <thrust/detail/device/cuda/dispatch/scan.h>
namespace thrust
{
namespace detail
{
namespace device
{
namespace cuda
{
template<typename InputIterator,
typename OutputIterator,
typename AssociativeOperator>
OutputIterator inclusive_scan(InputIterator first,
InputIterator last,
OutputIterator result,
AssociativeOperator binary_op)
{
typedef typename thrust::iterator_value<OutputIterator>::type OutputType;
// whether to use fast_scan or safe_scan
static const bool use_fast_scan = sizeof(OutputType) <= 16; // TODO profile this threshold
return thrust::detail::device::cuda::dispatch::inclusive_scan
(first, last, result, binary_op,
thrust::detail::integral_constant<bool, use_fast_scan>());
}
template<typename InputIterator,
typename OutputIterator,
typename T,
typename AssociativeOperator>
OutputIterator exclusive_scan(InputIterator first,
InputIterator last,
OutputIterator result,
T init,
AssociativeOperator binary_op)
{
typedef typename thrust::iterator_value<OutputIterator>::type OutputType;
// whether to use fast_scan or safe_scan
static const bool use_fast_scan = sizeof(OutputType) <= 16; // TODO profile this threshold
return thrust::detail::device::cuda::dispatch::exclusive_scan
(first, last, result, init, binary_op,
thrust::detail::integral_constant<bool, use_fast_scan>());
}
} // end namespace cuda
} // end namespace device
} // end namespace detail
} // end namespace thrust
<commit_msg>dispatch fast scan only for POD types<commit_after>/*
* Copyright 2008-2009 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*! \file scan.inl
* \brief Inline file for scan.h.
*/
#include <thrust/detail/device/cuda/dispatch/scan.h>
namespace thrust
{
namespace detail
{
namespace device
{
namespace cuda
{
template<typename InputIterator,
typename OutputIterator,
typename AssociativeOperator>
OutputIterator inclusive_scan(InputIterator first,
InputIterator last,
OutputIterator result,
AssociativeOperator binary_op)
{
typedef typename thrust::iterator_value<OutputIterator>::type OutputType;
// whether to use fast_scan or safe_scan
// TODO profile this threshold
static const bool use_fast_scan = sizeof(OutputType) <= 16 && thrust::detail::is_pod<OutputType>::value;
return thrust::detail::device::cuda::dispatch::inclusive_scan
(first, last, result, binary_op,
thrust::detail::integral_constant<bool, use_fast_scan>());
}
template<typename InputIterator,
typename OutputIterator,
typename T,
typename AssociativeOperator>
OutputIterator exclusive_scan(InputIterator first,
InputIterator last,
OutputIterator result,
T init,
AssociativeOperator binary_op)
{
typedef typename thrust::iterator_value<OutputIterator>::type OutputType;
// whether to use fast_scan or safe_scan
// TODO profile this threshold
static const bool use_fast_scan = sizeof(OutputType) <= 16 && thrust::detail::is_pod<OutputType>::value;
return thrust::detail::device::cuda::dispatch::exclusive_scan
(first, last, result, init, binary_op,
thrust::detail::integral_constant<bool, use_fast_scan>());
}
} // end namespace cuda
} // end namespace device
} // end namespace detail
} // end namespace thrust
<|endoftext|> |
<commit_before>8fe6263c-2e4e-11e5-9284-b827eb9e62be<commit_msg>8feb1e30-2e4e-11e5-9284-b827eb9e62be<commit_after>8feb1e30-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>ed6b5e04-2e4d-11e5-9284-b827eb9e62be<commit_msg>ed765822-2e4d-11e5-9284-b827eb9e62be<commit_after>ed765822-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>71d41f2e-2e4d-11e5-9284-b827eb9e62be<commit_msg>71d929d8-2e4d-11e5-9284-b827eb9e62be<commit_after>71d929d8-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>85580ba4-2e4e-11e5-9284-b827eb9e62be<commit_msg>855d3e1c-2e4e-11e5-9284-b827eb9e62be<commit_after>855d3e1c-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>ab94485a-2e4e-11e5-9284-b827eb9e62be<commit_msg>ab993e64-2e4e-11e5-9284-b827eb9e62be<commit_after>ab993e64-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>770ca678-2e4d-11e5-9284-b827eb9e62be<commit_msg>77119eee-2e4d-11e5-9284-b827eb9e62be<commit_after>77119eee-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>ea28dd76-2e4c-11e5-9284-b827eb9e62be<commit_msg>ea2dce58-2e4c-11e5-9284-b827eb9e62be<commit_after>ea2dce58-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>ead1573e-2e4d-11e5-9284-b827eb9e62be<commit_msg>ead64988-2e4d-11e5-9284-b827eb9e62be<commit_after>ead64988-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>af84c5d0-2e4d-11e5-9284-b827eb9e62be<commit_msg>af89bfd6-2e4d-11e5-9284-b827eb9e62be<commit_after>af89bfd6-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>270a0340-2e4e-11e5-9284-b827eb9e62be<commit_msg>270f1dbc-2e4e-11e5-9284-b827eb9e62be<commit_after>270f1dbc-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>908b4496-2e4e-11e5-9284-b827eb9e62be<commit_msg>90904432-2e4e-11e5-9284-b827eb9e62be<commit_after>90904432-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>29a706ce-2e4f-11e5-9284-b827eb9e62be<commit_msg>29abfe68-2e4f-11e5-9284-b827eb9e62be<commit_after>29abfe68-2e4f-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>f22a53a4-2e4e-11e5-9284-b827eb9e62be<commit_msg>f22f521e-2e4e-11e5-9284-b827eb9e62be<commit_after>f22f521e-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>935ceb16-2e4e-11e5-9284-b827eb9e62be<commit_msg>9361e9fe-2e4e-11e5-9284-b827eb9e62be<commit_after>9361e9fe-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>5fc6fa0e-2e4d-11e5-9284-b827eb9e62be<commit_msg>5fcc49be-2e4d-11e5-9284-b827eb9e62be<commit_after>5fcc49be-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>4e6a9b70-2e4e-11e5-9284-b827eb9e62be<commit_msg>4e6fad0e-2e4e-11e5-9284-b827eb9e62be<commit_after>4e6fad0e-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>2ec8c540-2e4d-11e5-9284-b827eb9e62be<commit_msg>2ecdbdca-2e4d-11e5-9284-b827eb9e62be<commit_after>2ecdbdca-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>71225c44-2e4d-11e5-9284-b827eb9e62be<commit_msg>71276fea-2e4d-11e5-9284-b827eb9e62be<commit_after>71276fea-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>c717fcb2-2e4d-11e5-9284-b827eb9e62be<commit_msg>c71cfa5a-2e4d-11e5-9284-b827eb9e62be<commit_after>c71cfa5a-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>c50a41ea-2e4e-11e5-9284-b827eb9e62be<commit_msg>c50f3da8-2e4e-11e5-9284-b827eb9e62be<commit_after>c50f3da8-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
/**
* Copyright (C) 2013 Regents of the University of California.
* @author: Jeff Thompson <jefft0@remap.ucla.edu>
* See COPYING for copyright and distribution information.
*/
#include <stdexcept>
#include <ndn-cpp/common.hpp>
#include <ndn-cpp/interest.hpp>
#if __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wreorder"
#pragma clang diagnostic ignored "-Wtautological-compare"
#pragma clang diagnostic ignored "-Wunused-variable"
#pragma clang diagnostic ignored "-Wunused-function"
#elif __GNUC__
#pragma GCC diagnostic ignored "-Wreorder"
#pragma GCC diagnostic ignored "-Wunused-variable"
#pragma GCC diagnostic ignored "-Wunused-function"
#endif
#include <cryptopp/osrng.h>
using namespace std;
namespace ndn {
const uint32_t&
Interest::getNonce() const
{
static CryptoPP::AutoSeededRandomPool rng;
if (nonce_ == 0)
nonce_ = rng.GenerateWord32();
return nonce_;
}
bool
Interest::matchesName(const Name &name) const
{
if (!name_.isPrefixOf(name))
return false;
if (minSuffixComponents_ >= 0 &&
// Add 1 for the implicit digest.
!(name.size() + 1 - name_.size() >= minSuffixComponents_))
return false;
if (maxSuffixComponents_ >= 0 &&
// Add 1 for the implicit digest.
!(name.size() + 1 - name_.size() <= maxSuffixComponents_))
return false;
if (!exclude_.empty() && name.size() > name_.size() &&
exclude_.isExcluded(name[name_.size()]))
return false;
return true;
}
std::ostream &
operator << (std::ostream &os, const Interest &interest)
{
os << interest.getName();
char delim = '?';
if (interest.getMinSuffixComponents() >= 0) {
os << delim << "ndn.MinSuffixComponents=" << interest.getMinSuffixComponents();
delim = '&';
}
if (interest.getMaxSuffixComponents() >= 0) {
os << delim << "ndn.MaxSuffixComponents=" << interest.getMaxSuffixComponents();
delim = '&';
}
if (interest.getChildSelector() >= 0) {
os << delim << "ndn.ChildSelector=" << interest.getChildSelector();
delim = '&';
}
if (interest.getMustBeFresh()) {
os << delim << "ndn.MustBeFresh=" << interest.getMustBeFresh();
delim = '&';
}
if (interest.getScope() >= 0) {
os << delim << "ndn.Scope=" << interest.getScope();
delim = '&';
}
if (interest.getInterestLifetime() >= 0) {
os << delim << "ndn.InterestLifetime=" << interest.getInterestLifetime();
delim = '&';
}
if (interest.getNonce() > 0) {
os << delim << "ndn.Nonce=" << interest.getNonce();
delim = '&';
}
if (!interest.getExclude().empty()) {
os << delim << "ndn.Exclude=" << interest.getExclude();
delim = '&';
}
return os;
}
const Block&
Interest::wireEncode() const
{
if (wire_.hasWire())
return wire_;
// Interest ::= INTEREST-TYPE TLV-LENGTH
// Name
// Selectors?
// Nonce
// Scope?
// InterestLifetime?
wire_ = Block(Tlv::Interest);
wire_.push_back(getName().wireEncode());
// selectors
{
Block selectors(Tlv::Selectors);
if (getMinSuffixComponents() >= 0) {
selectors.push_back
(nonNegativeIntegerBlock(Tlv::MinSuffixComponents, getMinSuffixComponents()));
}
if (getMaxSuffixComponents() >= 0) {
selectors.push_back
(nonNegativeIntegerBlock(Tlv::MaxSuffixComponents, getMaxSuffixComponents()));
}
if (!getExclude().empty()) {
selectors.push_back
(getExclude().wireEncode());
}
if (getChildSelector() >= 0) {
selectors.push_back
(nonNegativeIntegerBlock(Tlv::ChildSelector, getChildSelector()));
}
if (getMustBeFresh()) {
selectors.push_back
(booleanBlock(Tlv::MustBeFresh));
}
if (!selectors.getAll().empty())
{
selectors.encode();
wire_.push_back(selectors);
}
}
// Nonce
{
wire_.push_back
(nonNegativeIntegerBlock(Tlv::Nonce, getNonce()));
}
if (getScope() >= 0) {
wire_.push_back
(nonNegativeIntegerBlock(Tlv::Scope, getScope()));
}
if (getInterestLifetime() >= 0) {
wire_.push_back
(nonNegativeIntegerBlock(Tlv::InterestLifetime, getInterestLifetime()));
}
wire_.encode();
return wire_;
}
void
Interest::wireDecode(const Block &wire)
{
wire_ = wire;
wire_.parse();
// Interest ::= INTEREST-TYPE TLV-LENGTH
// Name
// Selectors?
// Nonce
// Scope?
// InterestLifetime?
// Name
name_.wireDecode(wire_.get(Tlv::Name));
// Selectors
Block::element_iterator selectors = wire_.find(Tlv::Selectors);
if (selectors != wire_.getAll().end())
{
selectors->parse();
// MinSuffixComponents
Block::element_iterator val = selectors->find(Tlv::MinSuffixComponents);
if (val != selectors->getAll().end())
{
minSuffixComponents_ = readNonNegativeInteger(*val);
}
// MaxSuffixComponents
val = selectors->find(Tlv::MaxSuffixComponents);
if (val != selectors->getAll().end())
{
maxSuffixComponents_ = readNonNegativeInteger(*val);
}
// Exclude
val = selectors->find(Tlv::Exclude);
if (val != selectors->getAll().end())
{
exclude_.wireDecode(*val);
}
// ChildSelector
val = selectors->find(Tlv::ChildSelector);
if (val != selectors->getAll().end())
{
childSelector_ = readNonNegativeInteger(*val);
}
//MustBeFresh aka AnswerOriginKind
val = selectors->find(Tlv::MustBeFresh);
if (val != selectors->getAll().end())
{
mustBeFresh_ = true;
}
}
// Nonce
Block::element_iterator val = wire_.find(Tlv::Nonce);
if (val != wire_.getAll().end())
{
nonce_ = readNonNegativeInteger(*val);
}
// Scope
val = wire_.find(Tlv::Scope);
if (val != wire_.getAll().end())
{
scope_ = readNonNegativeInteger(*val);
}
// InterestLifetime
val = wire_.find(Tlv::InterestLifetime);
if (val != wire_.getAll().end())
{
interestLifetime_ = readNonNegativeInteger(*val);
}
}
}
<commit_msg>interest/tlv: Do not encode InterestLifetime if it has default value (4sec)<commit_after>/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
/**
* Copyright (C) 2013 Regents of the University of California.
* @author: Jeff Thompson <jefft0@remap.ucla.edu>
* See COPYING for copyright and distribution information.
*/
#include <stdexcept>
#include <ndn-cpp/common.hpp>
#include <ndn-cpp/interest.hpp>
#if __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wreorder"
#pragma clang diagnostic ignored "-Wtautological-compare"
#pragma clang diagnostic ignored "-Wunused-variable"
#pragma clang diagnostic ignored "-Wunused-function"
#elif __GNUC__
#pragma GCC diagnostic ignored "-Wreorder"
#pragma GCC diagnostic ignored "-Wunused-variable"
#pragma GCC diagnostic ignored "-Wunused-function"
#endif
#include <cryptopp/osrng.h>
using namespace std;
namespace ndn {
const Milliseconds DEFAULT_INTEREST_LIFETIME = 4000;
const uint32_t&
Interest::getNonce() const
{
static CryptoPP::AutoSeededRandomPool rng;
if (nonce_ == 0)
nonce_ = rng.GenerateWord32();
return nonce_;
}
bool
Interest::matchesName(const Name &name) const
{
if (!name_.isPrefixOf(name))
return false;
if (minSuffixComponents_ >= 0 &&
// Add 1 for the implicit digest.
!(name.size() + 1 - name_.size() >= minSuffixComponents_))
return false;
if (maxSuffixComponents_ >= 0 &&
// Add 1 for the implicit digest.
!(name.size() + 1 - name_.size() <= maxSuffixComponents_))
return false;
if (!exclude_.empty() && name.size() > name_.size() &&
exclude_.isExcluded(name[name_.size()]))
return false;
return true;
}
std::ostream &
operator << (std::ostream &os, const Interest &interest)
{
os << interest.getName();
char delim = '?';
if (interest.getMinSuffixComponents() >= 0) {
os << delim << "ndn.MinSuffixComponents=" << interest.getMinSuffixComponents();
delim = '&';
}
if (interest.getMaxSuffixComponents() >= 0) {
os << delim << "ndn.MaxSuffixComponents=" << interest.getMaxSuffixComponents();
delim = '&';
}
if (interest.getChildSelector() >= 0) {
os << delim << "ndn.ChildSelector=" << interest.getChildSelector();
delim = '&';
}
if (interest.getMustBeFresh()) {
os << delim << "ndn.MustBeFresh=" << interest.getMustBeFresh();
delim = '&';
}
if (interest.getScope() >= 0) {
os << delim << "ndn.Scope=" << interest.getScope();
delim = '&';
}
if (interest.getInterestLifetime() >= 0 && interest.getInterestLifetime() != DEFAULT_INTEREST_LIFETIME) {
os << delim << "ndn.InterestLifetime=" << interest.getInterestLifetime();
delim = '&';
}
if (interest.getNonce() > 0) {
os << delim << "ndn.Nonce=" << interest.getNonce();
delim = '&';
}
if (!interest.getExclude().empty()) {
os << delim << "ndn.Exclude=" << interest.getExclude();
delim = '&';
}
return os;
}
const Block&
Interest::wireEncode() const
{
if (wire_.hasWire())
return wire_;
// Interest ::= INTEREST-TYPE TLV-LENGTH
// Name
// Selectors?
// Nonce
// Scope?
// InterestLifetime?
wire_ = Block(Tlv::Interest);
wire_.push_back(getName().wireEncode());
// selectors
{
Block selectors(Tlv::Selectors);
if (getMinSuffixComponents() >= 0) {
selectors.push_back
(nonNegativeIntegerBlock(Tlv::MinSuffixComponents, getMinSuffixComponents()));
}
if (getMaxSuffixComponents() >= 0) {
selectors.push_back
(nonNegativeIntegerBlock(Tlv::MaxSuffixComponents, getMaxSuffixComponents()));
}
if (!getExclude().empty()) {
selectors.push_back
(getExclude().wireEncode());
}
if (getChildSelector() >= 0) {
selectors.push_back
(nonNegativeIntegerBlock(Tlv::ChildSelector, getChildSelector()));
}
if (getMustBeFresh()) {
selectors.push_back
(booleanBlock(Tlv::MustBeFresh));
}
if (!selectors.getAll().empty())
{
selectors.encode();
wire_.push_back(selectors);
}
}
// Nonce
{
wire_.push_back
(nonNegativeIntegerBlock(Tlv::Nonce, getNonce()));
}
// Scope
if (getScope() >= 0) {
wire_.push_back
(nonNegativeIntegerBlock(Tlv::Scope, getScope()));
}
// InterestLifetime
if (getInterestLifetime() >= 0 && getInterestLifetime() != DEFAULT_INTEREST_LIFETIME) {
wire_.push_back
(nonNegativeIntegerBlock(Tlv::InterestLifetime, getInterestLifetime()));
}
wire_.encode();
return wire_;
}
void
Interest::wireDecode(const Block &wire)
{
wire_ = wire;
wire_.parse();
// Interest ::= INTEREST-TYPE TLV-LENGTH
// Name
// Selectors?
// Nonce
// Scope?
// InterestLifetime?
// Name
name_.wireDecode(wire_.get(Tlv::Name));
// Selectors
Block::element_iterator selectors = wire_.find(Tlv::Selectors);
if (selectors != wire_.getAll().end())
{
selectors->parse();
// MinSuffixComponents
Block::element_iterator val = selectors->find(Tlv::MinSuffixComponents);
if (val != selectors->getAll().end())
{
minSuffixComponents_ = readNonNegativeInteger(*val);
}
// MaxSuffixComponents
val = selectors->find(Tlv::MaxSuffixComponents);
if (val != selectors->getAll().end())
{
maxSuffixComponents_ = readNonNegativeInteger(*val);
}
// Exclude
val = selectors->find(Tlv::Exclude);
if (val != selectors->getAll().end())
{
exclude_.wireDecode(*val);
}
// ChildSelector
val = selectors->find(Tlv::ChildSelector);
if (val != selectors->getAll().end())
{
childSelector_ = readNonNegativeInteger(*val);
}
//MustBeFresh aka AnswerOriginKind
val = selectors->find(Tlv::MustBeFresh);
if (val != selectors->getAll().end())
{
mustBeFresh_ = true;
}
}
// Nonce
Block::element_iterator val = wire_.find(Tlv::Nonce);
if (val != wire_.getAll().end())
{
nonce_ = readNonNegativeInteger(*val);
}
// Scope
val = wire_.find(Tlv::Scope);
if (val != wire_.getAll().end())
{
scope_ = readNonNegativeInteger(*val);
}
// InterestLifetime
val = wire_.find(Tlv::InterestLifetime);
if (val != wire_.getAll().end())
{
interestLifetime_ = readNonNegativeInteger(*val);
}
else
{
interestLifetime_ = DEFAULT_INTEREST_LIFETIME;
}
}
}
<|endoftext|> |
<commit_before>#include <cstring>
/*
* Member function definitions of IQHandler template class.
* See iqhandler.h for template class declaration.
*/
template <typename T, size_t M, size_t N>
IQHandler<T, M, N>::IQHandler(iqcond_t cond_func) :
m_cond(cond_func) {
static_assert(M < N, "Input queue must be smaller than circular buffer.");
chSysLock();
m_thread = chThdCreateI(m_wa_iqueue_handler_thread,
sizeof(m_wa_iqueue_handler_thread), NORMALPRIO + 1,
iqueue_handler, this);
chSysUnlock();
ibqObjectInit(&m_iqueue, false, m_iqueue_buffer, sizeof(T), M, nullptr, nullptr);
chBSemObjectInit(&m_sem, false); /* set to not taken */
}
template <typename T, size_t M, size_t N>
void IQHandler<T, M, N>::start() {
chSysLock();
ibqResetI(&m_iqueue);
chBSemResetI(&m_sem, false); /* set to not taken*/
chThdStartI(m_thread);
chSchRescheduleS();
chSysUnlock();
}
template <typename T, size_t M, size_t N>
void IQHandler<T, M, N>::stop() {
chThdTerminate(m_thread);
chSysLock();
ibqResetI(&m_iqueue);
chBSemResetI(&m_sem, true); /* set to taken */
chSysUnlock();
chThdWait(m_thread);
}
template <typename T, size_t M, size_t N>
void IQHandler<T, M, N>::wait() {
chBSemWait(&m_sem);
}
template <typename T, size_t M, size_t N>
void IQHandler<T, M, N>::signal() {
chBSemSignal(&m_sem);
}
template <typename T, size_t M, size_t N>
void IQHandler<T, M, N>::insertI(T* element) {
chDbgCheckClassI();
uint8_t* buf = ibqGetEmptyBufferI(&m_iqueue);
if (buf == nullptr) {
/* queue elements not consumed quickly enough */
chSysHalt("input queue full");
// TODO: handle this case
}
std::memcpy(buf, element, sizeof(T));
ibqPostFullBufferI(&m_iqueue, sizeof(T));
}
template <typename T, size_t M, size_t N>
const std::array<T, N>& IQHandler<T, M, N>::circular_buffer() const {
return m_circular_buffer;
}
template <typename T, size_t M, size_t N>
size_t IQHandler<T, M, N>::index() const {
return m_buffer_index;
}
template <typename T, size_t M, size_t N>
void IQHandler<T, M, N>::iqueue_handler(void* p) {
auto obj = static_cast<IQHandler<T, M, N>*>(p);
while (!chThdShouldTerminateX()) {
if (ibqGetFullBufferTimeout(&obj->m_iqueue, TIME_INFINITE) == MSG_OK) {
iqcond_t condition = obj->m_cond; /* get condition to check if element should be inserted */
if ((condition == nullptr) || (condition(p))) {
if (chBSemWait(&obj->m_sem) == MSG_RESET) { /* wait for algorithm calculation to finish */
/* Sem reset due to start/stop */
ibqReleaseEmptyBuffer(&obj->m_iqueue);
chThdYield();
continue;
}
obj->insert_circular_buffer(reinterpret_cast<T*>(obj->m_iqueue.ptr));
chBSemSignal(&obj->m_sem);
}
ibqReleaseEmptyBuffer(&obj->m_iqueue);
}
chThdYield();
}
}
template <typename T, size_t M, size_t N>
void IQHandler<T, M, N>::insert_circular_buffer(T* element) {
std::memcpy(&m_circular_buffer[m_buffer_index++], element, sizeof(T));
if (m_buffer_index == N) {
m_buffer_index = 0;
}
}
<commit_msg>Set IQHandler thread name<commit_after>#include <cstring>
/*
* Member function definitions of IQHandler template class.
* See iqhandler.h for template class declaration.
*/
template <typename T, size_t M, size_t N>
IQHandler<T, M, N>::IQHandler(iqcond_t cond_func) :
m_cond(cond_func) {
static_assert(M < N, "Input queue must be smaller than circular buffer.");
chSysLock();
m_thread = chThdCreateI(m_wa_iqueue_handler_thread,
sizeof(m_wa_iqueue_handler_thread), NORMALPRIO + 1,
iqueue_handler, this);
chSysUnlock();
ibqObjectInit(&m_iqueue, false, m_iqueue_buffer, sizeof(T), M, nullptr, nullptr);
chBSemObjectInit(&m_sem, false); /* set to not taken */
}
template <typename T, size_t M, size_t N>
void IQHandler<T, M, N>::start() {
chSysLock();
ibqResetI(&m_iqueue);
chBSemResetI(&m_sem, false); /* set to not taken*/
chThdStartI(m_thread);
chSchRescheduleS();
chSysUnlock();
}
template <typename T, size_t M, size_t N>
void IQHandler<T, M, N>::stop() {
chThdTerminate(m_thread);
chSysLock();
ibqResetI(&m_iqueue);
chBSemResetI(&m_sem, true); /* set to taken */
chSysUnlock();
chThdWait(m_thread);
}
template <typename T, size_t M, size_t N>
void IQHandler<T, M, N>::wait() {
chBSemWait(&m_sem);
}
template <typename T, size_t M, size_t N>
void IQHandler<T, M, N>::signal() {
chBSemSignal(&m_sem);
}
template <typename T, size_t M, size_t N>
void IQHandler<T, M, N>::insertI(T* element) {
chDbgCheckClassI();
uint8_t* buf = ibqGetEmptyBufferI(&m_iqueue);
if (buf == nullptr) {
/* queue elements not consumed quickly enough */
chSysHalt("input queue full");
// TODO: handle this case
}
std::memcpy(buf, element, sizeof(T));
ibqPostFullBufferI(&m_iqueue, sizeof(T));
}
template <typename T, size_t M, size_t N>
const std::array<T, N>& IQHandler<T, M, N>::circular_buffer() const {
return m_circular_buffer;
}
template <typename T, size_t M, size_t N>
size_t IQHandler<T, M, N>::index() const {
return m_buffer_index;
}
template <typename T, size_t M, size_t N>
void IQHandler<T, M, N>::iqueue_handler(void* p) {
auto obj = static_cast<IQHandler<T, M, N>*>(p);
chRegSetThreadName("iqhandler");
while (!chThdShouldTerminateX()) {
if (ibqGetFullBufferTimeout(&obj->m_iqueue, TIME_INFINITE) == MSG_OK) {
iqcond_t condition = obj->m_cond; /* get condition to check if element should be inserted */
if ((condition == nullptr) || (condition(p))) {
if (chBSemWait(&obj->m_sem) == MSG_RESET) { /* wait for algorithm calculation to finish */
/* Sem reset due to start/stop */
ibqReleaseEmptyBuffer(&obj->m_iqueue);
chThdYield();
continue;
}
obj->insert_circular_buffer(reinterpret_cast<T*>(obj->m_iqueue.ptr));
chBSemSignal(&obj->m_sem);
}
ibqReleaseEmptyBuffer(&obj->m_iqueue);
}
chThdYield();
}
}
template <typename T, size_t M, size_t N>
void IQHandler<T, M, N>::insert_circular_buffer(T* element) {
std::memcpy(&m_circular_buffer[m_buffer_index++], element, sizeof(T));
if (m_buffer_index == N) {
m_buffer_index = 0;
}
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "job.hh"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <boost/ptr_container/ptr_map.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/scoped_array.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/uuid/string_generator.hpp>
#include <boost/uuid/uuid_io.hpp>
#include "lo.pb.h"
#include "bc/index.h"
#include "db/statement-driver.h"
#include "lo/layout_loader.h"
using std::cerr;
using std::endl;
using std::fclose;
using std::fopen;
using std::fread;
using std::fseek;
using std::make_pair;
using std::perror;
using std::printf;
using std::sscanf;
using std::string;
using std::strlen;
namespace job {
namespace {
class FormatLoader : db::StatementDriver {
public:
// Note that db is for read only.
explicit FormatLoader(sqlite3 *db)
: db::StatementDriver(db, "SELECT format FROM model")
{}
// the return value should be freed by caller.
char *Load()
{
int e;
e = sqlite3_step(stmt());
if (e != SQLITE_ROW) {
cerr << "failed to step statement: " << e << endl;
return NULL;
}
const char *f = (const char *)sqlite3_column_text(stmt(), 0);
size_t len = strlen(f);
char *format = new char[len+1];
strcpy(format, f);
return format;
}
};
typedef std::map<int, int> TargetMap;
class SourceLayout : boost::noncopyable {
public:
void AddTrack(lo::Track *track) {
tv_.push_back(track);
}
void AddSector(lo::Sector *sector) {
(void)sector; // nothing to do
}
void AddData(lo::Data *data) {
dv_.push_back(data);
}
int CollectTargets(TargetMap *tm) const {
int si = 0;
int di = 0;
int pos = kOffsetBase;
for (TrackVector::const_iterator it=tv_.begin();it!=tv_.end();++it) {
int nos = it->nos();
int nod = it->nod();
int sie = si + nos;
int dib = di;
int die = di + nod;
while (si++ < sie) {
di = dib;
while (di < die) {
const lo::Data &d = dv_.at(di++);
switch (d.type()) {
case lo::S:
if (std::strncmp(d.name().c_str(), "phsp:target", 11) == 0) {
const char *nstr = d.name().c_str();
int target_id = std::atoi(&nstr[11]);
tm->insert(make_pair(target_id, pos));
}
break;
default:
cerr << "unexpected data type: " << d.type() << endl;
return -1;
}
pos += d.size();
}
}
}
return pos;
}
private:
typedef boost::ptr_vector<lo::Track> TrackVector;
typedef boost::ptr_vector<lo::Data> DataVector;
TrackVector tv_;
DataVector dv_;
};
typedef boost::ptr_map<string, std::map<string, double> > TargetValueMap;
class TargetLoader : db::StatementDriver {
public:
// Note that db is for read only.
explicit TargetLoader(sqlite3 *db)
: db::StatementDriver(db, "SELECT uuid, id FROM phsp_targets WHERE rowid = ?")
{}
bool Load(const TargetMap &tm, const double *data, TargetValueMap *tvm) {
boost::uuids::uuid u;
boost::uuids::string_generator gen;
for (TargetMap::const_iterator it=tm.begin();it!=tm.end();++it) {
int e = sqlite3_bind_int(stmt(), 1, it->first);
if (e != SQLITE_OK) {
cerr << "failed to bind rowid: " << e << endl;
return false;
}
e = sqlite3_step(stmt());
if (e != SQLITE_ROW) {
cerr << "missing row with rowid " << it->first << " in phsp_targets" << endl;
return false;
}
u = gen((const char *)sqlite3_column_text(stmt(), 0));
(*tvm)[string((const char *)u.data, 16)].insert(make_pair((const char *)sqlite3_column_text(stmt(), 1), data[it->second]));
sqlite3_reset(stmt());
}
return true;
}
};
class TargetLayout : boost::noncopyable {
public:
void AddTrack(lo::Track *track) {
tv_.push_back(track);
}
void AddSector(lo::Sector *sector) {
sv_.push_back(sector);
}
void AddData(lo::Data *data) {
dv_.push_back(data);
}
bool Rewrite(const char *format, const TargetValueMap &tvm, FILE *fp) const {
boost::scoped_array<char> buf(new char[32]); // FIXME
int si = 0;
int di = 0;
if (fseek(fp, kOffsetBase*sizeof(double), SEEK_SET) != 0) {
return false;
}
for (TrackVector::const_iterator it=tv_.begin();it!=tv_.end();++it) {
int nos = it->nos();
int nod = it->nod();
int sie = si + nos;
int dib = di;
int die = di + nod;
while (si < sie) {
const lo::Sector &s = sv_.at(si++);
di = dib;
while (di < die) {
const lo::Data &d = dv_.at(di++);
switch (d.type()) {
case lo::S:
case lo::X:
{
TargetValueMap::const_iterator it = tvm.find(s.id());
if (it == tvm.end()) {
if (fseek(fp, d.size()*sizeof(double), SEEK_CUR) != 0) {
return false;
}
} else {
std::map<string, double>::const_iterator mit;
if (strcmp("phml", format) == 0) {
sprintf(buf.get(), "%d", d.id());
mit = it->second->find(buf.get());
} else {
mit = it->second->find(d.name());
}
if (mit == it->second->end()) {
if (fseek(fp, d.size()*sizeof(double), SEEK_CUR) != 0) {
return false;
}
} else {
double value = mit->second;
if (std::fwrite(&value, sizeof(double), d.size(), fp) != static_cast<size_t>(d.size())) {
// TODO
return false;
}
}
}
}
break;
default:
if (fseek(fp, d.size()*sizeof(double), SEEK_CUR) != 0) {
return false;
}
break;
}
}
}
}
return true;
}
private:
typedef boost::ptr_vector<lo::Track> TrackVector;
typedef boost::ptr_vector<lo::Sector> SectorVector;
typedef boost::ptr_vector<lo::Data> DataVector;
TrackVector tv_;
SectorVector sv_;
DataVector dv_;
};
}
bool Store(sqlite3 *db,
const char *source_layout_file, const char *source_data_file,
const char *target_layout_file, const char *target_data_file)
{
SourceLayout source_layout;
{
boost::scoped_ptr<LayoutLoader> loader(new LayoutLoader(source_layout_file));
if (!loader->Load(&source_layout)) return false;
}
TargetMap tm;
int source_layer_size = source_layout.CollectTargets(&tm);
if (source_layer_size <= 0) {
return false;
}
boost::scoped_array<double> data(new double[source_layer_size]);
FILE *fp = fopen(source_data_file, "rb");
if (!fp) {
perror(source_data_file);
return false;
}
if (fread(data.get(), sizeof(double), source_layer_size, fp) != static_cast<size_t>(source_layer_size)) {
cerr << "could not read data with size: " << source_layer_size << endl;
fclose(fp);
return false;
}
fclose(fp);
boost::scoped_array<char> format;
TargetValueMap tvm;
{
// check model's format
{
FormatLoader loader(db);
format.reset(loader.Load());
if (!format) return false;
}
{
TargetLoader loader(db);
if (!loader.Load(tm, data.get(), &tvm))
return false;
}
}
fp = fopen(target_data_file, "r+b");
if (!fp) {
perror(target_data_file);
return false;
}
TargetLayout target_layout;
{
boost::scoped_ptr<LayoutLoader> loader(new LayoutLoader(target_layout_file));
if (!loader->Load(&target_layout)) return false;
}
if (!target_layout.Rewrite(format.get(), tvm, fp)) {
fclose(fp);
return false;
}
fclose(fp);
return true;
}
}
<commit_msg>fix a resource leak<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "job.hh"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <boost/ptr_container/ptr_map.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/scoped_array.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/uuid/string_generator.hpp>
#include <boost/uuid/uuid_io.hpp>
#include "lo.pb.h"
#include "bc/index.h"
#include "db/statement-driver.h"
#include "lo/layout_loader.h"
using std::cerr;
using std::endl;
using std::fclose;
using std::fopen;
using std::fread;
using std::fseek;
using std::make_pair;
using std::perror;
using std::printf;
using std::sscanf;
using std::string;
using std::strlen;
namespace job {
namespace {
class FormatLoader : db::StatementDriver {
public:
// Note that db is for read only.
explicit FormatLoader(sqlite3 *db)
: db::StatementDriver(db, "SELECT format FROM model")
{}
// the return value should be freed by caller.
char *Load()
{
int e;
e = sqlite3_step(stmt());
if (e != SQLITE_ROW) {
cerr << "failed to step statement: " << e << endl;
return NULL;
}
const char *f = (const char *)sqlite3_column_text(stmt(), 0);
size_t len = strlen(f);
char *format = new char[len+1];
strcpy(format, f);
return format;
}
};
typedef std::map<int, int> TargetMap;
class SourceLayout : boost::noncopyable {
public:
void AddTrack(lo::Track *track) {
tv_.push_back(track);
}
void AddSector(lo::Sector *sector) {
(void)sector; // nothing to do
}
void AddData(lo::Data *data) {
dv_.push_back(data);
}
int CollectTargets(TargetMap *tm) const {
int si = 0;
int di = 0;
int pos = kOffsetBase;
for (TrackVector::const_iterator it=tv_.begin();it!=tv_.end();++it) {
int nos = it->nos();
int nod = it->nod();
int sie = si + nos;
int dib = di;
int die = di + nod;
while (si++ < sie) {
di = dib;
while (di < die) {
const lo::Data &d = dv_.at(di++);
switch (d.type()) {
case lo::S:
if (std::strncmp(d.name().c_str(), "phsp:target", 11) == 0) {
const char *nstr = d.name().c_str();
int target_id = std::atoi(&nstr[11]);
tm->insert(make_pair(target_id, pos));
}
break;
default:
cerr << "unexpected data type: " << d.type() << endl;
return -1;
}
pos += d.size();
}
}
}
return pos;
}
private:
typedef boost::ptr_vector<lo::Track> TrackVector;
typedef boost::ptr_vector<lo::Data> DataVector;
TrackVector tv_;
DataVector dv_;
};
typedef boost::ptr_map<string, std::map<string, double> > TargetValueMap;
class TargetLoader : db::StatementDriver {
public:
// Note that db is for read only.
explicit TargetLoader(sqlite3 *db)
: db::StatementDriver(db, "SELECT uuid, id FROM phsp_targets WHERE rowid = ?")
{}
bool Load(const TargetMap &tm, const double *data, TargetValueMap *tvm) {
boost::uuids::uuid u;
boost::uuids::string_generator gen;
for (TargetMap::const_iterator it=tm.begin();it!=tm.end();++it) {
int e = sqlite3_bind_int(stmt(), 1, it->first);
if (e != SQLITE_OK) {
cerr << "failed to bind rowid: " << e << endl;
return false;
}
e = sqlite3_step(stmt());
if (e != SQLITE_ROW) {
cerr << "missing row with rowid " << it->first << " in phsp_targets" << endl;
return false;
}
u = gen((const char *)sqlite3_column_text(stmt(), 0));
(*tvm)[string((const char *)u.data, 16)].insert(make_pair((const char *)sqlite3_column_text(stmt(), 1), data[it->second]));
sqlite3_reset(stmt());
}
return true;
}
};
class TargetLayout : boost::noncopyable {
public:
void AddTrack(lo::Track *track) {
tv_.push_back(track);
}
void AddSector(lo::Sector *sector) {
sv_.push_back(sector);
}
void AddData(lo::Data *data) {
dv_.push_back(data);
}
bool Rewrite(const char *format, const TargetValueMap &tvm, FILE *fp) const {
boost::scoped_array<char> buf(new char[32]); // FIXME
int si = 0;
int di = 0;
if (fseek(fp, kOffsetBase*sizeof(double), SEEK_SET) != 0) {
return false;
}
for (TrackVector::const_iterator it=tv_.begin();it!=tv_.end();++it) {
int nos = it->nos();
int nod = it->nod();
int sie = si + nos;
int dib = di;
int die = di + nod;
while (si < sie) {
const lo::Sector &s = sv_.at(si++);
di = dib;
while (di < die) {
const lo::Data &d = dv_.at(di++);
switch (d.type()) {
case lo::S:
case lo::X:
{
TargetValueMap::const_iterator it = tvm.find(s.id());
if (it == tvm.end()) {
if (fseek(fp, d.size()*sizeof(double), SEEK_CUR) != 0) {
return false;
}
} else {
std::map<string, double>::const_iterator mit;
if (strcmp("phml", format) == 0) {
sprintf(buf.get(), "%d", d.id());
mit = it->second->find(buf.get());
} else {
mit = it->second->find(d.name());
}
if (mit == it->second->end()) {
if (fseek(fp, d.size()*sizeof(double), SEEK_CUR) != 0) {
return false;
}
} else {
double value = mit->second;
if (std::fwrite(&value, sizeof(double), d.size(), fp) != static_cast<size_t>(d.size())) {
// TODO
return false;
}
}
}
}
break;
default:
if (fseek(fp, d.size()*sizeof(double), SEEK_CUR) != 0) {
return false;
}
break;
}
}
}
}
return true;
}
private:
typedef boost::ptr_vector<lo::Track> TrackVector;
typedef boost::ptr_vector<lo::Sector> SectorVector;
typedef boost::ptr_vector<lo::Data> DataVector;
TrackVector tv_;
SectorVector sv_;
DataVector dv_;
};
}
bool Store(sqlite3 *db,
const char *source_layout_file, const char *source_data_file,
const char *target_layout_file, const char *target_data_file)
{
SourceLayout source_layout;
{
boost::scoped_ptr<LayoutLoader> loader(new LayoutLoader(source_layout_file));
if (!loader->Load(&source_layout)) return false;
}
TargetMap tm;
int source_layer_size = source_layout.CollectTargets(&tm);
if (source_layer_size <= 0) {
return false;
}
boost::scoped_array<double> data(new double[source_layer_size]);
FILE *fp = fopen(source_data_file, "rb");
if (!fp) {
perror(source_data_file);
return false;
}
if (fread(data.get(), sizeof(double), source_layer_size, fp) != static_cast<size_t>(source_layer_size)) {
cerr << "could not read data with size: " << source_layer_size << endl;
fclose(fp);
return false;
}
fclose(fp);
boost::scoped_array<char> format;
TargetValueMap tvm;
{
// check model's format
{
FormatLoader loader(db);
format.reset(loader.Load());
if (!format) return false;
}
{
TargetLoader loader(db);
if (!loader.Load(tm, data.get(), &tvm))
return false;
}
}
TargetLayout target_layout;
{
boost::scoped_ptr<LayoutLoader> loader(new LayoutLoader(target_layout_file));
if (!loader->Load(&target_layout)) return false;
}
fp = fopen(target_data_file, "r+b");
if (!fp) {
perror(target_data_file);
return false;
}
if (!target_layout.Rewrite(format.get(), tvm, fp)) {
fclose(fp);
return false;
}
fclose(fp);
return true;
}
}
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2011-2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Author : Christian Potthast
* Email : potthast@usc.edu
*
*/
#include <pcl/io/pcd_io.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>
#include <pcl/segmentation/unary_classifier.h>
using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;
double default_feature_threshold = 5.0;
double default_normal_radius_search = 0.01;
double default_fpfh_radius_search = 0.05;
typedef PointXYZRGBA PointT;
typedef PointCloud<PointT> CloudT;
typedef PointCloud<PointXYZRGBL> CloudLT;
typedef PointCloud<FPFHSignature33> FeatureT;
void
printHelp (int, char **argv)
{
print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]);
print_info (" where options are:\n");
print_info (" -d = trained features directory \n");
print_info (" -threshold X = feature threshold (default: ");
print_value ("%f", default_feature_threshold); print_info (")\n");
print_info (" -normal-search X = Normal radius search (default: ");
print_value ("%f", default_normal_radius_search); print_info (")\n");
print_info (" -fpfh-search X = FPFH radius search (default: ");
print_value ("%f", default_fpfh_radius_search); print_info (")\n");
}
bool
loadTrainedFeatures (std::vector<FeatureT::Ptr> &out,
const boost::filesystem::path &base_dir)
{
if (!boost::filesystem::exists (base_dir) && !boost::filesystem::is_directory (base_dir))
return false;
for (boost::filesystem::directory_iterator it (base_dir); it != boost::filesystem::directory_iterator (); ++it)
{
if (!boost::filesystem::is_directory (it->status ()) &&
boost::filesystem::extension (it->path ()) == ".pcd")
{
std::stringstream ss;
ss << it->path ().filename ();
print_highlight ("Loading %s \n", ss.str ().c_str ());
FeatureT::Ptr features (new FeatureT);
loadPCDFile (it->path ().filename (), *features);
out.push_back (features);
}
}
return true;
}
bool
loadCloud (const std::string &filename, CloudT::Ptr &cloud)
{
TicToc tt;
print_highlight ("Loading "); print_value ("%s ", filename.c_str ());
tt.tic ();
if (loadPCDFile (filename, *cloud) < 0)
return (false);
print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", cloud->width * cloud->height); print_info (" points]\n");
return (true);
}
void
compute (const CloudT::Ptr &input, std::vector<FeatureT::Ptr> &trained_features,
CloudLT::Ptr &out,
float normal_radius_search,
float fpfh_radius_search,
float feature_threshold)
{
TicToc tt;
tt.tic ();
print_highlight ("Computing ");
UnaryClassifier<PointT> classifier;
classifier.setInputCloud (input);
classifier.setTrainedFeatures (trained_features);
classifier.setNormalRadiusSearch (normal_radius_search);
classifier.setFPFHRadiusSearch (fpfh_radius_search);
classifier.setFeatureThreshold (feature_threshold);
classifier.segment (out);
print_info ("[done, ");
print_value ("%g", tt.toc ());
print_info (" ms : "); print_value ("%d", out->width * out->height);
print_info (" points]\n");
}
void
saveCloud (const std::string &filename, CloudLT::Ptr &output)
{
TicToc tt;
tt.tic ();
print_highlight ("Saving "); print_value ("%s ", filename.c_str ());
PCDWriter w;
w.write (filename, *output);
print_info ("[done, ");
print_value ("%g", tt.toc ()); print_info (" ms : ");
print_value ("%d", output->width * output->height); print_info (" points]\n");
}
/* ---[ */
int
main (int argc, char** argv)
{
print_info ("Train unary classifier using FPFH. For more information, use: %s -h\n", argv[0]);
if (argc < 4)
{
printHelp (argc, argv);
return (-1);
}
// Parse the command line arguments for .pcd files
std::vector<int> p_file_indices;
p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
if (p_file_indices.size () != 2)
{
print_error ("Need one input PCD file and one output PCD file to continue.\n");
return (-1);
}
// Load the input file
CloudT::Ptr cloud (new CloudT);
if (!loadCloud (argv[p_file_indices[0]], cloud))
return (-1);
// TODO:: make this as an optional argument ??
std::vector<int> tmp_indices;
pcl::removeNaNFromPointCloud (*cloud, *cloud, tmp_indices);
// parse optional input arguments from the command line
float normal_radius_search = static_cast<float> (default_normal_radius_search);
float fpfh_radius_search = static_cast<float> (default_fpfh_radius_search);
float feature_threshold = static_cast<float> (default_feature_threshold);
std::string dir_name;
parse_argument (argc, argv, "-d", dir_name);
parse_argument (argc, argv, "-threshold", feature_threshold);
parse_argument (argc, argv, "-normal-radius-search", normal_radius_search);
parse_argument (argc, argv, "-fpfh-radius-search", fpfh_radius_search);
print_info ("trained feature directory: %s \n", dir_name.c_str ());
// load the trained features
std::vector<FeatureT::Ptr> trained_features;
loadTrainedFeatures (trained_features, dir_name.c_str ());
print_info ("feature_threshold: %f \n", feature_threshold);
print_info ("normal-radius-search: %f \n", normal_radius_search);
print_info ("fpfh-radius-search: %f \n\n", fpfh_radius_search);
CloudLT::Ptr out (new CloudLT);
compute (cloud, trained_features, out, normal_radius_search, fpfh_radius_search, feature_threshold);
saveCloud (argv[p_file_indices[1]], out);
}
<commit_msg>Follow-up fix to r7110, hopefully this is portable across different OS and Boost versions.<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2011-2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Author : Christian Potthast
* Email : potthast@usc.edu
*
*/
#include <pcl/io/pcd_io.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>
#include <pcl/segmentation/unary_classifier.h>
using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;
double default_feature_threshold = 5.0;
double default_normal_radius_search = 0.01;
double default_fpfh_radius_search = 0.05;
typedef PointXYZRGBA PointT;
typedef PointCloud<PointT> CloudT;
typedef PointCloud<PointXYZRGBL> CloudLT;
typedef PointCloud<FPFHSignature33> FeatureT;
void
printHelp (int, char **argv)
{
print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]);
print_info (" where options are:\n");
print_info (" -d = trained features directory \n");
print_info (" -threshold X = feature threshold (default: ");
print_value ("%f", default_feature_threshold); print_info (")\n");
print_info (" -normal-search X = Normal radius search (default: ");
print_value ("%f", default_normal_radius_search); print_info (")\n");
print_info (" -fpfh-search X = FPFH radius search (default: ");
print_value ("%f", default_fpfh_radius_search); print_info (")\n");
}
bool
loadTrainedFeatures (std::vector<FeatureT::Ptr> &out,
const boost::filesystem::path &base_dir)
{
if (!boost::filesystem::exists (base_dir) && !boost::filesystem::is_directory (base_dir))
return false;
for (boost::filesystem::directory_iterator it (base_dir); it != boost::filesystem::directory_iterator (); ++it)
{
if (!boost::filesystem::is_directory (it->status ()) &&
boost::filesystem::extension (it->path ()) == ".pcd")
{
std::stringstream ss;
ss << it->path ().filename ();
print_highlight ("Loading %s \n", ss.str ().c_str ());
FeatureT::Ptr features (new FeatureT);
loadPCDFile (ss.str (), *features);
out.push_back (features);
}
}
return true;
}
bool
loadCloud (const std::string &filename, CloudT::Ptr &cloud)
{
TicToc tt;
print_highlight ("Loading "); print_value ("%s ", filename.c_str ());
tt.tic ();
if (loadPCDFile (filename, *cloud) < 0)
return (false);
print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", cloud->width * cloud->height); print_info (" points]\n");
return (true);
}
void
compute (const CloudT::Ptr &input, std::vector<FeatureT::Ptr> &trained_features,
CloudLT::Ptr &out,
float normal_radius_search,
float fpfh_radius_search,
float feature_threshold)
{
TicToc tt;
tt.tic ();
print_highlight ("Computing ");
UnaryClassifier<PointT> classifier;
classifier.setInputCloud (input);
classifier.setTrainedFeatures (trained_features);
classifier.setNormalRadiusSearch (normal_radius_search);
classifier.setFPFHRadiusSearch (fpfh_radius_search);
classifier.setFeatureThreshold (feature_threshold);
classifier.segment (out);
print_info ("[done, ");
print_value ("%g", tt.toc ());
print_info (" ms : "); print_value ("%d", out->width * out->height);
print_info (" points]\n");
}
void
saveCloud (const std::string &filename, CloudLT::Ptr &output)
{
TicToc tt;
tt.tic ();
print_highlight ("Saving "); print_value ("%s ", filename.c_str ());
PCDWriter w;
w.write (filename, *output);
print_info ("[done, ");
print_value ("%g", tt.toc ()); print_info (" ms : ");
print_value ("%d", output->width * output->height); print_info (" points]\n");
}
/* ---[ */
int
main (int argc, char** argv)
{
print_info ("Train unary classifier using FPFH. For more information, use: %s -h\n", argv[0]);
if (argc < 4)
{
printHelp (argc, argv);
return (-1);
}
// Parse the command line arguments for .pcd files
std::vector<int> p_file_indices;
p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
if (p_file_indices.size () != 2)
{
print_error ("Need one input PCD file and one output PCD file to continue.\n");
return (-1);
}
// Load the input file
CloudT::Ptr cloud (new CloudT);
if (!loadCloud (argv[p_file_indices[0]], cloud))
return (-1);
// TODO:: make this as an optional argument ??
std::vector<int> tmp_indices;
pcl::removeNaNFromPointCloud (*cloud, *cloud, tmp_indices);
// parse optional input arguments from the command line
float normal_radius_search = static_cast<float> (default_normal_radius_search);
float fpfh_radius_search = static_cast<float> (default_fpfh_radius_search);
float feature_threshold = static_cast<float> (default_feature_threshold);
std::string dir_name;
parse_argument (argc, argv, "-d", dir_name);
parse_argument (argc, argv, "-threshold", feature_threshold);
parse_argument (argc, argv, "-normal-radius-search", normal_radius_search);
parse_argument (argc, argv, "-fpfh-radius-search", fpfh_radius_search);
print_info ("trained feature directory: %s \n", dir_name.c_str ());
// load the trained features
std::vector<FeatureT::Ptr> trained_features;
loadTrainedFeatures (trained_features, dir_name.c_str ());
print_info ("feature_threshold: %f \n", feature_threshold);
print_info ("normal-radius-search: %f \n", normal_radius_search);
print_info ("fpfh-radius-search: %f \n\n", fpfh_radius_search);
CloudLT::Ptr out (new CloudLT);
compute (cloud, trained_features, out, normal_radius_search, fpfh_radius_search, feature_threshold);
saveCloud (argv[p_file_indices[1]], out);
}
<|endoftext|> |
<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2013 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include "save_load.hpp"
#include <ctime>
#include <fstream>
#include <string>
#include <vector>
#include <glog/logging.h>
#include "jubatus/util/lang/cast.h"
#include "jubatus/core/common/exception.hpp"
#include "jubatus/core/common/big_endian.hpp"
#include "jubatus/core/common/crc32.hpp"
#include "jubatus/core/framework/mixable.hpp"
#include "jubatus/core/framework/stream_writer.hpp"
using jubatus::core::common::write_big_endian;
using jubatus::core::common::read_big_endian;
using std::string;
using jubatus::util::lang::lexical_cast;
namespace jubatus {
namespace server {
namespace framework {
namespace {
const char magic_number[8] = "jubatus";
const uint64_t format_version = 1;
uint32_t jubatus_version_major = -1;
uint32_t jubatus_version_minor = -1;
uint32_t jubatus_version_maintenance = -1;
// TODO(gintenlabo): remove sscanf
void init_versions() {
if (jubatus_version_major == static_cast<uint32_t>(-1)) {
int major, minor, maintenance;
std::sscanf(JUBATUS_VERSION, "%d.%d.%d", &major, &minor, &maintenance); // NOLINT
jubatus_version_major = major;
jubatus_version_minor = minor;
jubatus_version_maintenance = maintenance;
}
}
const uint64_t system_data_container_version = 1;
struct system_data_container {
uint64_t version;
time_t timestamp;
std::string type;
std::string id;
std::string config;
system_data_container()
: version(), timestamp(), type(), id(), config() {
}
system_data_container(const server_base& server, const std::string& id_)
: version(system_data_container_version),
timestamp(std::time(NULL)),
type(server.argv().type), id(id_),
config(server.get_config()) {
}
MSGPACK_DEFINE(version, timestamp, type, id, config);
};
uint32_t calc_crc32(const char* header, // header size is 28 (fixed)
const char* system_data, uint64_t system_data_size,
const char* user_data, uint64_t user_data_size) {
uint32_t crc32 = core::common::calc_crc32(header, 28);
crc32 = core::common::calc_crc32(&header[32], 16, crc32);
crc32 = core::common::calc_crc32(system_data, system_data_size, crc32);
crc32 = core::common::calc_crc32(user_data, user_data_size, crc32);
return crc32;
}
} // namespace
void save_server(std::ostream& os,
const server_base& server, const std::string& id) {
if (id == "") {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error("empty id is not allowed"));
}
init_versions();
msgpack::sbuffer system_data_buf;
msgpack::pack(&system_data_buf, system_data_container(server, id));
msgpack::sbuffer user_data_buf;
{
core::framework::stream_writer<msgpack::sbuffer> st(user_data_buf);
core::framework::jubatus_packer jp(st);
core::framework::packer packer(jp);
packer.pack_array(2);
uint64_t user_data_version = server.user_data_version();
packer.pack(user_data_version);
server.get_driver()->pack(packer);
}
char header_buf[48];
std::memcpy(header_buf, magic_number, 8);
write_big_endian(format_version, &header_buf[8]);
write_big_endian(jubatus_version_major, &header_buf[16]);
write_big_endian(jubatus_version_minor, &header_buf[20]);
write_big_endian(jubatus_version_maintenance, &header_buf[24]);
// write_big_endian(crc32, &header_buf[28]); // skipped
write_big_endian(static_cast<uint64_t>(system_data_buf.size()),
&header_buf[32]);
write_big_endian(static_cast<uint64_t>(user_data_buf.size()),
&header_buf[40]);
uint32_t crc32 = calc_crc32(header_buf,
system_data_buf.data(), system_data_buf.size(),
user_data_buf.data(), user_data_buf.size());
write_big_endian(crc32, &header_buf[28]);
os.write(header_buf, 48);
os.write(system_data_buf.data(), system_data_buf.size());
os.write(user_data_buf.data(), user_data_buf.size());
}
void load_server(std::istream& is,
server_base& server, const std::string& id) {
init_versions();
char header_buf[48];
is.read(header_buf, 48);
if (std::memcmp(header_buf, magic_number, 8) != 0) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error("invalid file format"));
}
uint64_t format_version_read = read_big_endian<uint64_t>(&header_buf[8]);
if (format_version_read != format_version) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"invalid format version: " +
lexical_cast<string>(format_version_read) +
", expected " +
lexical_cast<string>(format_version)));
}
uint32_t jubatus_major_read = read_big_endian<uint32_t>(&header_buf[16]);
uint32_t jubatus_minor_read = read_big_endian<uint32_t>(&header_buf[20]);
uint32_t jubatus_maintenance_read =
read_big_endian<uint32_t>(&header_buf[24]);
if (jubatus_major_read != jubatus_version_major ||
jubatus_minor_read != jubatus_version_minor ||
jubatus_maintenance_read != jubatus_version_maintenance) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"jubatus version mismatched: current version: " JUBATUS_VERSION
", saved version: " +
lexical_cast<std::string>(jubatus_major_read) + "." +
lexical_cast<std::string>(jubatus_minor_read) + "." +
lexical_cast<std::string>(jubatus_maintenance_read)));
}
uint32_t crc32_expected = read_big_endian<uint32_t>(&header_buf[28]);
uint64_t system_data_size = read_big_endian<uint64_t>(&header_buf[32]);
uint64_t user_data_size = read_big_endian<uint64_t>(&header_buf[40]);
std::vector<char> system_data_buf(system_data_size);
is.read(&system_data_buf[0], system_data_size);
std::vector<char> user_data_buf(user_data_size);
is.read(&user_data_buf[0], user_data_size);
uint32_t crc32_actual = calc_crc32(header_buf,
&system_data_buf[0], system_data_size,
&user_data_buf[0], user_data_size);
if (crc32_actual != crc32_expected) {
std::ostringstream ss;
ss << "invalid crc32 checksum: " << std::hex << crc32_actual;
ss << ", read " << crc32_expected;
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(ss.str()));
}
system_data_container system_data_actual;
try {
msgpack::unpacked unpacked;
msgpack::unpack(&unpacked, &system_data_buf[0], system_data_size);
unpacked.get().convert(&system_data_actual);
} catch (msgpack::type_error) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"system data is broken"));
}
system_data_container system_data_expected(server, id);
if (system_data_actual.version != system_data_expected.version) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"invalid system data version: saved version: " +
lexical_cast<string>(system_data_actual.version) +
", expected " +
lexical_cast<string>(system_data_expected.version)));
}
if (system_data_actual.type != system_data_expected.type) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"server type mismatched: " + system_data_actual.type +
", expected " + system_data_expected.type));
}
if (system_data_actual.config != system_data_expected.config) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"server config mismatched" + system_data_actual.config +
", expected " + system_data_expected.config));
}
try {
msgpack::unpacked unpacked;
msgpack::unpack(&unpacked, &user_data_buf[0], user_data_size);
std::vector<msgpack::object> objs;
unpacked.get().convert(&objs);
if (objs.size() != 2) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error("invalid user container"));
}
uint64_t user_data_version_expected = server.user_data_version();
uint64_t user_data_version_actual;
objs[0].convert(&user_data_version_actual);
if (user_data_version_actual != user_data_version_expected) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"user data version mismatched: " +
lexical_cast<string>(user_data_version_actual) +
", expected " +
lexical_cast<string>(user_data_version_expected)));
}
server.get_driver()->unpack(objs[1]);
} catch (msgpack::type_error) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"user data is broken"));
}
}
} // namespace framework
} // namespace server
} // namespace jubatus
<commit_msg>Add const reference<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2013 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include "save_load.hpp"
#include <ctime>
#include <fstream>
#include <string>
#include <vector>
#include <glog/logging.h>
#include "jubatus/util/lang/cast.h"
#include "jubatus/core/common/exception.hpp"
#include "jubatus/core/common/big_endian.hpp"
#include "jubatus/core/common/crc32.hpp"
#include "jubatus/core/framework/mixable.hpp"
#include "jubatus/core/framework/stream_writer.hpp"
using jubatus::core::common::write_big_endian;
using jubatus::core::common::read_big_endian;
using std::string;
using jubatus::util::lang::lexical_cast;
namespace jubatus {
namespace server {
namespace framework {
namespace {
const char magic_number[8] = "jubatus";
const uint64_t format_version = 1;
uint32_t jubatus_version_major = -1;
uint32_t jubatus_version_minor = -1;
uint32_t jubatus_version_maintenance = -1;
// TODO(gintenlabo): remove sscanf
void init_versions() {
if (jubatus_version_major == static_cast<uint32_t>(-1)) {
int major, minor, maintenance;
std::sscanf(JUBATUS_VERSION, "%d.%d.%d", &major, &minor, &maintenance); // NOLINT
jubatus_version_major = major;
jubatus_version_minor = minor;
jubatus_version_maintenance = maintenance;
}
}
const uint64_t system_data_container_version = 1;
struct system_data_container {
uint64_t version;
time_t timestamp;
std::string type;
std::string id;
std::string config;
system_data_container()
: version(), timestamp(), type(), id(), config() {
}
system_data_container(const server_base& server, const std::string& id_)
: version(system_data_container_version),
timestamp(std::time(NULL)),
type(server.argv().type), id(id_),
config(server.get_config()) {
}
MSGPACK_DEFINE(version, timestamp, type, id, config);
};
uint32_t calc_crc32(const char* header, // header size is 28 (fixed)
const char* system_data, uint64_t system_data_size,
const char* user_data, uint64_t user_data_size) {
uint32_t crc32 = core::common::calc_crc32(header, 28);
crc32 = core::common::calc_crc32(&header[32], 16, crc32);
crc32 = core::common::calc_crc32(system_data, system_data_size, crc32);
crc32 = core::common::calc_crc32(user_data, user_data_size, crc32);
return crc32;
}
} // namespace
void save_server(std::ostream& os,
const server_base& server, const std::string& id) {
if (id == "") {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error("empty id is not allowed"));
}
init_versions();
msgpack::sbuffer system_data_buf;
msgpack::pack(&system_data_buf, system_data_container(server, id));
msgpack::sbuffer user_data_buf;
{
core::framework::stream_writer<msgpack::sbuffer> st(user_data_buf);
core::framework::jubatus_packer jp(st);
core::framework::packer packer(jp);
packer.pack_array(2);
uint64_t user_data_version = server.user_data_version();
packer.pack(user_data_version);
server.get_driver()->pack(packer);
}
char header_buf[48];
std::memcpy(header_buf, magic_number, 8);
write_big_endian(format_version, &header_buf[8]);
write_big_endian(jubatus_version_major, &header_buf[16]);
write_big_endian(jubatus_version_minor, &header_buf[20]);
write_big_endian(jubatus_version_maintenance, &header_buf[24]);
// write_big_endian(crc32, &header_buf[28]); // skipped
write_big_endian(static_cast<uint64_t>(system_data_buf.size()),
&header_buf[32]);
write_big_endian(static_cast<uint64_t>(user_data_buf.size()),
&header_buf[40]);
uint32_t crc32 = calc_crc32(header_buf,
system_data_buf.data(), system_data_buf.size(),
user_data_buf.data(), user_data_buf.size());
write_big_endian(crc32, &header_buf[28]);
os.write(header_buf, 48);
os.write(system_data_buf.data(), system_data_buf.size());
os.write(user_data_buf.data(), user_data_buf.size());
}
void load_server(std::istream& is,
server_base& server, const std::string& id) {
init_versions();
char header_buf[48];
is.read(header_buf, 48);
if (std::memcmp(header_buf, magic_number, 8) != 0) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error("invalid file format"));
}
uint64_t format_version_read = read_big_endian<uint64_t>(&header_buf[8]);
if (format_version_read != format_version) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"invalid format version: " +
lexical_cast<string>(format_version_read) +
", expected " +
lexical_cast<string>(format_version)));
}
uint32_t jubatus_major_read = read_big_endian<uint32_t>(&header_buf[16]);
uint32_t jubatus_minor_read = read_big_endian<uint32_t>(&header_buf[20]);
uint32_t jubatus_maintenance_read =
read_big_endian<uint32_t>(&header_buf[24]);
if (jubatus_major_read != jubatus_version_major ||
jubatus_minor_read != jubatus_version_minor ||
jubatus_maintenance_read != jubatus_version_maintenance) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"jubatus version mismatched: current version: " JUBATUS_VERSION
", saved version: " +
lexical_cast<std::string>(jubatus_major_read) + "." +
lexical_cast<std::string>(jubatus_minor_read) + "." +
lexical_cast<std::string>(jubatus_maintenance_read)));
}
uint32_t crc32_expected = read_big_endian<uint32_t>(&header_buf[28]);
uint64_t system_data_size = read_big_endian<uint64_t>(&header_buf[32]);
uint64_t user_data_size = read_big_endian<uint64_t>(&header_buf[40]);
std::vector<char> system_data_buf(system_data_size);
is.read(&system_data_buf[0], system_data_size);
std::vector<char> user_data_buf(user_data_size);
is.read(&user_data_buf[0], user_data_size);
uint32_t crc32_actual = calc_crc32(header_buf,
&system_data_buf[0], system_data_size,
&user_data_buf[0], user_data_size);
if (crc32_actual != crc32_expected) {
std::ostringstream ss;
ss << "invalid crc32 checksum: " << std::hex << crc32_actual;
ss << ", read " << crc32_expected;
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(ss.str()));
}
system_data_container system_data_actual;
try {
msgpack::unpacked unpacked;
msgpack::unpack(&unpacked, &system_data_buf[0], system_data_size);
unpacked.get().convert(&system_data_actual);
} catch (const msgpack::type_error&) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"system data is broken"));
}
system_data_container system_data_expected(server, id);
if (system_data_actual.version != system_data_expected.version) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"invalid system data version: saved version: " +
lexical_cast<string>(system_data_actual.version) +
", expected " +
lexical_cast<string>(system_data_expected.version)));
}
if (system_data_actual.type != system_data_expected.type) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"server type mismatched: " + system_data_actual.type +
", expected " + system_data_expected.type));
}
if (system_data_actual.config != system_data_expected.config) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"server config mismatched" + system_data_actual.config +
", expected " + system_data_expected.config));
}
try {
msgpack::unpacked unpacked;
msgpack::unpack(&unpacked, &user_data_buf[0], user_data_size);
std::vector<msgpack::object> objs;
unpacked.get().convert(&objs);
if (objs.size() != 2) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error("invalid user container"));
}
uint64_t user_data_version_expected = server.user_data_version();
uint64_t user_data_version_actual;
objs[0].convert(&user_data_version_actual);
if (user_data_version_actual != user_data_version_expected) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"user data version mismatched: " +
lexical_cast<string>(user_data_version_actual) +
", expected " +
lexical_cast<string>(user_data_version_expected)));
}
server.get_driver()->unpack(objs[1]);
} catch (const msgpack::type_error&) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"user data is broken"));
}
}
} // namespace framework
} // namespace server
} // namespace jubatus
<|endoftext|> |
<commit_before>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
* Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file process_density.hpp
* \date June 2015
* \author Jan Issac (jan.issac@gmail.com)
* \author Manuel Wuthrich (manuel.wuthrich@gmail.com)
*/
#ifndef FL__MODEL__PROCESS__STATE_TRANSITION_DENSITY_HPP
#define FL__MODEL__PROCESS__STATE_TRANSITION_DENSITY_HPP
#include <fl/util/types.hpp>
#include <fl/util/traits.hpp>
namespace fl
{
template <
typename State,
typename Input,
int BatchSize = Eigen::Dynamic
>
class StateTransitionDensity
{
public:
typedef Eigen::Array<State, BatchSize, 1 > StateArray;
typedef Eigen::Array<Input, BatchSize, 1 > InputArray;
typedef Eigen::Array<FloatingPoint, BatchSize, 1 > ValueArray;
public:
/// \todo should add the unnormalized log probability interface
virtual FloatingPoint log_probability(const State& state,
const State& cond_state,
const Input& cond_input,
FloatingPoint dt) const = 0;
/**
* \return Dimension of the state variable $\f$x_t\f$
*/
virtual int state_dimension() const = 0;
/**
* \return Dimension of the input \f$u_t\f$
*/
virtual int input_dimension() const = 0;
virtual FloatingPoint probability(const State& state,
const State& cond_state,
const Input& cond_input,
FloatingPoint dt) const
{
return std::exp(log_probability(state, cond_state, cond_input, dt));
}
virtual ValueArray log_probabilities(const StateArray& states,
const StateArray& cond_states,
const InputArray& cond_inputs,
FloatingPoint dt) const
{
assert(states.size() == cond_inputs.size());
auto probs = ValueArray(states.size());
for (int i = 0; i < states.size(); ++i)
{
probs[i] = log_probability(states[i],
cond_states[i],
cond_inputs[i],
dt);
}
return probs;
}
virtual ValueArray probabilities(const StateArray& states,
const StateArray& cond_states,
const InputArray& cond_inputs,
FloatingPoint dt)
{
return log_probabilities(states, cond_inputs, cond_inputs, dt).exp();
}
};
}
#endif
<commit_msg>fixed log_probabilities<commit_after>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
* Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file process_density.hpp
* \date June 2015
* \author Jan Issac (jan.issac@gmail.com)
* \author Manuel Wuthrich (manuel.wuthrich@gmail.com)
*/
#ifndef FL__MODEL__PROCESS__STATE_TRANSITION_DENSITY_HPP
#define FL__MODEL__PROCESS__STATE_TRANSITION_DENSITY_HPP
#include <fl/util/types.hpp>
#include <fl/util/traits.hpp>
namespace fl
{
template <
typename State,
typename Input,
int BatchSize = Eigen::Dynamic
>
class StateTransitionDensity
{
public:
typedef Eigen::Array<State, BatchSize, 1 > StateArray;
typedef Eigen::Array<Input, BatchSize, 1 > InputArray;
typedef Eigen::Array<FloatingPoint, BatchSize, 1 > ValueArray;
public:
/// \todo should add the unnormalized log probability interface
virtual FloatingPoint log_probability(const State& state,
const State& cond_state,
const Input& cond_input,
FloatingPoint dt) const = 0;
/**
* \return Dimension of the state variable $\f$x_t\f$
*/
virtual int state_dimension() const = 0;
/**
* \return Dimension of the input \f$u_t\f$
*/
virtual int input_dimension() const = 0;
virtual FloatingPoint probability(const State& state,
const State& cond_state,
const Input& cond_input,
FloatingPoint dt) const
{
return std::exp(log_probability(state, cond_state, cond_input, dt));
}
virtual ValueArray log_probabilities(const StateArray& states,
const StateArray& cond_states,
const InputArray& cond_inputs,
FloatingPoint dt) const
{
assert(states.size() == cond_inputs.size());
auto probs = ValueArray(states.size());
for (int i = 0; i < states.size(); ++i)
{
probs[i] = log_probability(states[i],
cond_states[i],
cond_inputs[i],
dt);
}
return probs;
}
virtual ValueArray probabilities(const StateArray& states,
const StateArray& cond_states,
const InputArray& cond_inputs,
FloatingPoint dt)
{
return log_probabilities(states, cond_states, cond_inputs, dt).exp();
}
};
}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2019 Tuukka Norri
* This code is licensed under MIT license (see LICENSE for details).
*/
#ifndef VCF2MULTIALIGN_VARIANT_GRAPH_VARIANT_GRAPH_GENERATOR_HH
#define VCF2MULTIALIGN_VARIANT_GRAPH_VARIANT_GRAPH_GENERATOR_HH
#include <libbio/copyable_atomic.hh>
#include <libbio/int_matrix.hh>
#include <libbio/matrix.hh>
#include <libbio/vcf/subfield.hh>
#include <libbio/vcf/variant.hh>
#include <ostream>
#include <queue>
#include <string>
#include <vcf2multialign/variant_graph/variant_graph.hh>
#include <vcf2multialign/preprocess/path_sorted_variant.hh>
#include <vcf2multialign/preprocess/sample_indexer.hh>
#include <vcf2multialign/preprocess/sample_sorter.hh>
#include <vcf2multialign/preprocess/types.hh>
#include <vcf2multialign/preprocess/variant_partitioner.hh>
#include <vcf2multialign/types.hh>
#include <vcf2multialign/variant_processor.hh>
#include <vcf2multialign/variant_processor_delegate.hh>
#include <vector>
namespace vcf2multialign { namespace variant_graphs {
class variant_graph_generator; // Fwd.
struct variant_graph_generator_delegate
{
virtual ~variant_graph_generator_delegate() {}
virtual void variant_graph_generator_will_handle_subgraph(libbio::vcf::variant const &first_var, std::size_t const variant_count, std::size_t const path_count) = 0;
};
struct variant_graph_single_pass_generator_delegate : public virtual variant_graph_generator_delegate,
public virtual variant_processor_delegate // For the case where processing was not done.
{
};
}}
namespace vcf2multialign { namespace variant_graphs { namespace detail {
struct generator_node_description
{
std::size_t node_index{};
std::size_t ref_position{};
std::size_t alt_edge_start{};
std::size_t alt_edge_count{};
generator_node_description() = default;
explicit generator_node_description(std::size_t ref_position_):
ref_position(ref_position_)
{
}
};
}}}
namespace vcf2multialign { namespace variant_graphs {
// Generate a variant graph from a set of VCF records.
class variant_graph_generator : public sample_sorter_delegate
{
protected:
typedef std::vector <libbio::vcf::variant> variant_vector;
typedef std::vector <detail::generator_node_description> node_description_vector;
typedef std::vector <std::size_t> position_vector;
protected:
libbio::vcf::info_field_end const *m_end_field{};
variant_graph m_graph;
variant_vector m_subgraph_variants;
sample_indexer m_sample_indexer;
sample_sorter m_sample_sorter;
std::vector <std::string> m_sample_names;
node_description_vector m_sorted_nodes;
position_vector m_start_positions;
position_vector m_end_positions;
position_vector m_end_positions_by_sample;
std::vector <bool> m_can_handle_alt;
std::vector <std::uint16_t> m_unhandled_alt_csum;
std::size_t m_output_lineno{};
libbio::copyable_atomic <std::size_t> m_processed_count{};
public:
variant_graph_generator() = default;
variant_graph_generator(
libbio::vcf::reader &reader,
std::size_t const donor_count,
std::uint8_t const chr_count
):
m_end_field(reader.get_end_field_ptr()),
m_sample_indexer(donor_count, chr_count), // donor_count and chr_count should be set in all cases.
m_sample_sorter(*this, reader, m_sample_indexer)
{
}
class variant_graph const &variant_graph() const { return m_graph; }
class variant_graph &variant_graph() { return m_graph; }
class sample_sorter &sample_sorter() { return m_sample_sorter; }
class sample_sorter const &sample_sorter() const { return m_sample_sorter; }
class sample_indexer &sample_indexer() { return m_sample_indexer; }
class sample_indexer const &sample_indexer() const { return m_sample_indexer; }
std::size_t processed_count() const { return m_processed_count.load(std::memory_order_relaxed); }
virtual void sample_sorter_found_overlapping_variant(
libbio::vcf::variant const &var,
std::size_t const sample_idx,
std::size_t const prev_end_pos
) override {}
virtual libbio::vcf::reader &vcf_reader() = 0;
virtual vector_type const &reference() = 0;
virtual variant_graph_generator_delegate &delegate() = 0;
protected:
void update_sample_names();
void process_subgraph(std::size_t const prev_overlap_end);
void combine_subgraph_variants_by_pos_and_ref();
void reset_genotype_values_for_samples_with_overlapping_variants();
std::tuple <std::size_t, std::size_t> create_subgraph_and_nodes();
void generate_graph_setup();
void finalize_graph();
};
class variant_graph_precalculated_generator final : public variant_graph_generator
{
protected:
variant_graph_generator_delegate *m_delegate{};
libbio::vcf::reader *m_reader{};
vector_type const *m_reference{};
preprocessing_result const *m_preprocessing_result{};
public:
variant_graph_precalculated_generator() = default;
variant_graph_precalculated_generator(
variant_graph_generator_delegate &delegate,
libbio::vcf::reader &reader,
vector_type const &reference,
preprocessing_result const &preprocessing_result
):
variant_graph_generator(reader, preprocessing_result.donor_count, preprocessing_result.chr_count),
m_delegate(&delegate),
m_reader(&reader),
m_reference(&reference),
m_preprocessing_result(&preprocessing_result)
{
}
libbio::vcf::reader &vcf_reader() override { return *m_reader; }
vector_type const &reference() override { return *m_reference; }
variant_graph_generator_delegate &delegate() override { return *m_delegate; }
void generate_graph(bool const should_start_from_current_variant);
};
class variant_graph_single_pass_generator final : public variant_graph_generator,
public variant_processor
{
protected:
variant_graph_single_pass_generator_delegate *m_delegate{};
std::size_t m_minimum_bridge_length{};
public:
variant_graph_single_pass_generator() = default;
variant_graph_single_pass_generator(
variant_graph_single_pass_generator_delegate &delegate,
libbio::vcf::reader &reader,
vector_type const &reference,
std::string const &chr_name,
std::size_t const donor_count,
std::uint8_t const chr_count,
std::size_t const minimum_bridge_length
):
variant_graph_generator(reader, donor_count, chr_count),
variant_processor(reader, reference, chr_name),
m_delegate(&delegate),
m_minimum_bridge_length(minimum_bridge_length)
{
}
libbio::vcf::reader &vcf_reader() override { return *this->m_reader; }
vector_type const &reference() override { return *this->m_reference; }
variant_graph_single_pass_generator_delegate &delegate() override { return *m_delegate; }
void generate_graph(
std::vector <std::string> const &field_names_for_filter_by_assigned,
bool const should_start_from_current_variant
);
};
}}
#endif
<commit_msg>Use std::deque for buffering variant records<commit_after>/*
* Copyright (c) 2019 Tuukka Norri
* This code is licensed under MIT license (see LICENSE for details).
*/
#ifndef VCF2MULTIALIGN_VARIANT_GRAPH_VARIANT_GRAPH_GENERATOR_HH
#define VCF2MULTIALIGN_VARIANT_GRAPH_VARIANT_GRAPH_GENERATOR_HH
#include <deque>
#include <libbio/copyable_atomic.hh>
#include <libbio/int_matrix.hh>
#include <libbio/matrix.hh>
#include <libbio/vcf/subfield.hh>
#include <libbio/vcf/variant.hh>
#include <ostream>
#include <queue>
#include <string>
#include <vcf2multialign/variant_graph/variant_graph.hh>
#include <vcf2multialign/preprocess/path_sorted_variant.hh>
#include <vcf2multialign/preprocess/sample_indexer.hh>
#include <vcf2multialign/preprocess/sample_sorter.hh>
#include <vcf2multialign/preprocess/types.hh>
#include <vcf2multialign/preprocess/variant_partitioner.hh>
#include <vcf2multialign/types.hh>
#include <vcf2multialign/variant_processor.hh>
#include <vcf2multialign/variant_processor_delegate.hh>
#include <vector>
namespace vcf2multialign { namespace variant_graphs {
class variant_graph_generator; // Fwd.
struct variant_graph_generator_delegate
{
virtual ~variant_graph_generator_delegate() {}
virtual void variant_graph_generator_will_handle_subgraph(libbio::vcf::variant const &first_var, std::size_t const variant_count, std::size_t const path_count) = 0;
};
struct variant_graph_single_pass_generator_delegate : public virtual variant_graph_generator_delegate,
public virtual variant_processor_delegate // For the case where processing was not done.
{
};
}}
namespace vcf2multialign { namespace variant_graphs { namespace detail {
struct generator_node_description
{
std::size_t node_index{};
std::size_t ref_position{};
std::size_t alt_edge_start{};
std::size_t alt_edge_count{};
generator_node_description() = default;
explicit generator_node_description(std::size_t ref_position_):
ref_position(ref_position_)
{
}
};
}}}
namespace vcf2multialign { namespace variant_graphs {
// Generate a variant graph from a set of VCF records.
class variant_graph_generator : public sample_sorter_delegate
{
protected:
typedef std::deque <libbio::vcf::variant> variant_vector;
typedef std::vector <detail::generator_node_description> node_description_vector;
typedef std::vector <std::size_t> position_vector;
protected:
libbio::vcf::info_field_end const *m_end_field{};
variant_graph m_graph;
variant_vector m_subgraph_variants;
sample_indexer m_sample_indexer;
sample_sorter m_sample_sorter;
std::vector <std::string> m_sample_names;
node_description_vector m_sorted_nodes;
position_vector m_start_positions;
position_vector m_end_positions;
position_vector m_end_positions_by_sample;
std::vector <bool> m_can_handle_alt;
std::vector <std::uint16_t> m_unhandled_alt_csum;
std::size_t m_output_lineno{};
libbio::copyable_atomic <std::size_t> m_processed_count{};
public:
variant_graph_generator() = default;
variant_graph_generator(
libbio::vcf::reader &reader,
std::size_t const donor_count,
std::uint8_t const chr_count
):
m_end_field(reader.get_end_field_ptr()),
m_sample_indexer(donor_count, chr_count), // donor_count and chr_count should be set in all cases.
m_sample_sorter(*this, reader, m_sample_indexer)
{
}
class variant_graph const &variant_graph() const { return m_graph; }
class variant_graph &variant_graph() { return m_graph; }
class sample_sorter &sample_sorter() { return m_sample_sorter; }
class sample_sorter const &sample_sorter() const { return m_sample_sorter; }
class sample_indexer &sample_indexer() { return m_sample_indexer; }
class sample_indexer const &sample_indexer() const { return m_sample_indexer; }
std::size_t processed_count() const { return m_processed_count.load(std::memory_order_relaxed); }
virtual void sample_sorter_found_overlapping_variant(
libbio::vcf::variant const &var,
std::size_t const sample_idx,
std::size_t const prev_end_pos
) override {}
virtual libbio::vcf::reader &vcf_reader() = 0;
virtual vector_type const &reference() = 0;
virtual variant_graph_generator_delegate &delegate() = 0;
protected:
void update_sample_names();
void process_subgraph(std::size_t const prev_overlap_end);
void combine_subgraph_variants_by_pos_and_ref();
void reset_genotype_values_for_samples_with_overlapping_variants();
std::tuple <std::size_t, std::size_t> create_subgraph_and_nodes();
void generate_graph_setup();
void finalize_graph();
};
class variant_graph_precalculated_generator final : public variant_graph_generator
{
protected:
variant_graph_generator_delegate *m_delegate{};
libbio::vcf::reader *m_reader{};
vector_type const *m_reference{};
preprocessing_result const *m_preprocessing_result{};
public:
variant_graph_precalculated_generator() = default;
variant_graph_precalculated_generator(
variant_graph_generator_delegate &delegate,
libbio::vcf::reader &reader,
vector_type const &reference,
preprocessing_result const &preprocessing_result
):
variant_graph_generator(reader, preprocessing_result.donor_count, preprocessing_result.chr_count),
m_delegate(&delegate),
m_reader(&reader),
m_reference(&reference),
m_preprocessing_result(&preprocessing_result)
{
}
libbio::vcf::reader &vcf_reader() override { return *m_reader; }
vector_type const &reference() override { return *m_reference; }
variant_graph_generator_delegate &delegate() override { return *m_delegate; }
void generate_graph(bool const should_start_from_current_variant);
};
class variant_graph_single_pass_generator final : public variant_graph_generator,
public variant_processor
{
protected:
variant_graph_single_pass_generator_delegate *m_delegate{};
std::size_t m_minimum_bridge_length{};
public:
variant_graph_single_pass_generator() = default;
variant_graph_single_pass_generator(
variant_graph_single_pass_generator_delegate &delegate,
libbio::vcf::reader &reader,
vector_type const &reference,
std::string const &chr_name,
std::size_t const donor_count,
std::uint8_t const chr_count,
std::size_t const minimum_bridge_length
):
variant_graph_generator(reader, donor_count, chr_count),
variant_processor(reader, reference, chr_name),
m_delegate(&delegate),
m_minimum_bridge_length(minimum_bridge_length)
{
}
libbio::vcf::reader &vcf_reader() override { return *this->m_reader; }
vector_type const &reference() override { return *this->m_reference; }
variant_graph_single_pass_generator_delegate &delegate() override { return *m_delegate; }
void generate_graph(
std::vector <std::string> const &field_names_for_filter_by_assigned,
bool const should_start_from_current_variant
);
};
}}
#endif
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation //
// //
// 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 "scene_triangle_mesh.h"
#include "scene.h"
namespace embree
{
TriangleMesh::TriangleMesh (Scene* parent, RTCGeometryFlags flags, size_t numTriangles, size_t numVertices, size_t numTimeSteps)
: Geometry(parent,TRIANGLE_MESH,numTriangles,numTimeSteps,flags), mask(-1)
{
triangles.init(numTriangles,sizeof(Triangle));
for (size_t i=0; i<numTimeSteps; i++) {
vertices[i].init(numVertices,sizeof(Vec3fa));
}
enabling();
}
void TriangleMesh::enabling()
{
if (numTimeSteps == 1) atomic_add(&parent->numTriangles ,triangles.size());
else atomic_add(&parent->numTriangles2,triangles.size());
}
void TriangleMesh::disabling()
{
if (numTimeSteps == 1) atomic_add(&parent->numTriangles ,-(ssize_t)triangles.size());
else atomic_add(&parent->numTriangles2,-(ssize_t)triangles.size());
}
void TriangleMesh::setMask (unsigned mask)
{
if (parent->isStatic() && parent->isBuild())
throw_RTCError(RTC_INVALID_OPERATION,"static scenes cannot get modified");
this->mask = mask;
}
void TriangleMesh::setBuffer(RTCBufferType type, void* ptr, size_t offset, size_t stride)
{
if (parent->isStatic() && parent->isBuild())
throw_RTCError(RTC_INVALID_OPERATION,"static scenes cannot get modified");
/* verify that all accesses are 4 bytes aligned */
if (((size_t(ptr) + offset) & 0x3) || (stride & 0x3))
throw_RTCError(RTC_INVALID_OPERATION,"data must be 4 bytes aligned");
switch (type) {
case RTC_INDEX_BUFFER :
triangles.set(ptr,offset,stride);
break;
case RTC_VERTEX_BUFFER0:
vertices[0].set(ptr,offset,stride);
if (vertices[0].size()) {
/* test if array is properly padded */
volatile int w = *((int*)vertices[0].getPtr(vertices[0].size()-1)+3); // FIXME: is failing hard avoidable?
}
break;
case RTC_VERTEX_BUFFER1:
vertices[1].set(ptr,offset,stride);
if (vertices[1].size()) {
/* test if array is properly padded */
volatile int w = *((int*)vertices[1].getPtr(vertices[1].size()-1)+3); // FIXME: is failing hard avoidable?
}
break;
default:
throw_RTCError(RTC_INVALID_ARGUMENT,"unknown buffer type");
}
}
void* TriangleMesh::map(RTCBufferType type)
{
if (parent->isStatic() && parent->isBuild())
throw_RTCError(RTC_INVALID_OPERATION,"static scenes cannot get modified");
switch (type) {
case RTC_INDEX_BUFFER : return triangles .map(parent->numMappedBuffers);
case RTC_VERTEX_BUFFER0: return vertices[0].map(parent->numMappedBuffers);
case RTC_VERTEX_BUFFER1: return vertices[1].map(parent->numMappedBuffers);
default : throw_RTCError(RTC_INVALID_ARGUMENT,"unknown buffer type"); return nullptr;
}
}
void TriangleMesh::unmap(RTCBufferType type)
{
if (parent->isStatic() && parent->isBuild())
throw_RTCError(RTC_INVALID_OPERATION,"static scenes cannot get modified");
switch (type) {
case RTC_INDEX_BUFFER : triangles .unmap(parent->numMappedBuffers); break;
case RTC_VERTEX_BUFFER0: vertices[0].unmap(parent->numMappedBuffers); break;
case RTC_VERTEX_BUFFER1: vertices[1].unmap(parent->numMappedBuffers); break;
default : throw_RTCError(RTC_INVALID_ARGUMENT,"unknown buffer type"); break;
}
}
void TriangleMesh::immutable ()
{
bool freeTriangles = !parent->needTriangles;
bool freeVertices = !parent->needTriangleVertices;
if (freeTriangles) triangles.free();
if (freeVertices ) vertices[0].free();
if (freeVertices ) vertices[1].free();
}
bool TriangleMesh::verify ()
{
if (numTimeSteps == 2 && vertices[0].size() != vertices[1].size())
return false;
for (size_t i=0; i<triangles.size(); i++) {
if (triangles[i].v[0] >= numVertices()) return false;
if (triangles[i].v[1] >= numVertices()) return false;
if (triangles[i].v[2] >= numVertices()) return false;
}
for (size_t j=0; j<numTimeSteps; j++) {
BufferT<Vec3fa>& verts = vertices[j];
for (size_t i=0; i<verts.size(); i++) {
if (!isvalid(verts[i]))
return false;
}
}
return true;
}
void TriangleMesh::write(std::ofstream& file)
{
int type = TRIANGLE_MESH;
file.write((char*)&type,sizeof(int));
file.write((char*)&numTimeSteps,sizeof(int));
int numVerts = numVertices();
file.write((char*)&numVerts,sizeof(int));
int numTriangles = triangles.size();
file.write((char*)&numTriangles,sizeof(int));
for (size_t j=0; j<numTimeSteps; j++) {
while ((file.tellp() % 16) != 0) { char c = 0; file.write(&c,1); }
for (size_t i=0; i<numVerts; i++) file.write((char*)vertexPtr(i,j),sizeof(Vec3fa));
}
while ((file.tellp() % 16) != 0) { char c = 0; file.write(&c,1); }
for (size_t i=0; i<numTriangles; i++) file.write((char*)&triangle(i),sizeof(Triangle));
while ((file.tellp() % 16) != 0) { char c = 0; file.write(&c,1); }
for (size_t i=0; i<numTriangles; i++) file.write((char*)&triangle(i),sizeof(Triangle)); // FIXME: why is this written twice?
}
}
<commit_msg>cleanups to trianglemesh<commit_after>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation //
// //
// 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 "scene_triangle_mesh.h"
#include "scene.h"
namespace embree
{
TriangleMesh::TriangleMesh (Scene* parent, RTCGeometryFlags flags, size_t numTriangles, size_t numVertices, size_t numTimeSteps)
: Geometry(parent,TRIANGLE_MESH,numTriangles,numTimeSteps,flags), mask(-1)
{
triangles.init(numTriangles,sizeof(Triangle));
for (size_t i=0; i<numTimeSteps; i++) {
vertices[i].init(numVertices,sizeof(Vec3fa));
}
enabling();
}
void TriangleMesh::enabling()
{
if (numTimeSteps == 1) atomic_add(&parent->numTriangles ,triangles.size());
else atomic_add(&parent->numTriangles2,triangles.size());
}
void TriangleMesh::disabling()
{
if (numTimeSteps == 1) atomic_add(&parent->numTriangles ,-(ssize_t)triangles.size());
else atomic_add(&parent->numTriangles2,-(ssize_t)triangles.size());
}
void TriangleMesh::setMask (unsigned mask)
{
if (parent->isStatic() && parent->isBuild())
throw_RTCError(RTC_INVALID_OPERATION,"static scenes cannot get modified");
this->mask = mask;
}
void TriangleMesh::setBuffer(RTCBufferType type, void* ptr, size_t offset, size_t stride)
{
if (parent->isStatic() && parent->isBuild())
throw_RTCError(RTC_INVALID_OPERATION,"static scenes cannot get modified");
/* verify that all accesses are 4 bytes aligned */
if (((size_t(ptr) + offset) & 0x3) || (stride & 0x3))
throw_RTCError(RTC_INVALID_OPERATION,"data must be 4 bytes aligned");
switch (type) {
case RTC_INDEX_BUFFER :
triangles.set(ptr,offset,stride);
break;
case RTC_VERTEX_BUFFER0:
vertices[0].set(ptr,offset,stride);
/* test if array is properly padded */
if (vertices[0].size())
volatile int w = *((int*)vertices[0].getPtr(vertices[0].size()-1)+3); // FIXME: is failing hard avoidable?
break;
case RTC_VERTEX_BUFFER1:
vertices[1].set(ptr,offset,stride);
/* test if array is properly padded */
if (vertices[1].size())
volatile int w = *((int*)vertices[1].getPtr(vertices[1].size()-1)+3); // FIXME: is failing hard avoidable?
break;
default:
throw_RTCError(RTC_INVALID_ARGUMENT,"unknown buffer type");
}
}
void* TriangleMesh::map(RTCBufferType type)
{
if (parent->isStatic() && parent->isBuild())
throw_RTCError(RTC_INVALID_OPERATION,"static scenes cannot get modified");
switch (type) {
case RTC_INDEX_BUFFER : return triangles .map(parent->numMappedBuffers);
case RTC_VERTEX_BUFFER0: return vertices[0].map(parent->numMappedBuffers);
case RTC_VERTEX_BUFFER1: return vertices[1].map(parent->numMappedBuffers);
default : throw_RTCError(RTC_INVALID_ARGUMENT,"unknown buffer type"); return nullptr;
}
}
void TriangleMesh::unmap(RTCBufferType type)
{
if (parent->isStatic() && parent->isBuild())
throw_RTCError(RTC_INVALID_OPERATION,"static scenes cannot get modified");
switch (type) {
case RTC_INDEX_BUFFER : triangles .unmap(parent->numMappedBuffers); break;
case RTC_VERTEX_BUFFER0: vertices[0].unmap(parent->numMappedBuffers); break;
case RTC_VERTEX_BUFFER1: vertices[1].unmap(parent->numMappedBuffers); break;
default : throw_RTCError(RTC_INVALID_ARGUMENT,"unknown buffer type"); break;
}
}
void TriangleMesh::immutable ()
{
bool freeTriangles = !parent->needTriangles;
bool freeVertices = !parent->needTriangleVertices;
if (freeTriangles) triangles.free();
if (freeVertices ) vertices[0].free();
if (freeVertices ) vertices[1].free();
}
bool TriangleMesh::verify ()
{
/*! verify consistent size of vertex arrays */
if (numTimeSteps == 2 && vertices[0].size() != vertices[1].size())
return false;
/*! verify proper triangle indices */
for (size_t i=0; i<triangles.size(); i++) {
if (triangles[i].v[0] >= numVertices()) return false;
if (triangles[i].v[1] >= numVertices()) return false;
if (triangles[i].v[2] >= numVertices()) return false;
}
/*! verify proper triangle vertices */
for (size_t j=0; j<numTimeSteps; j++)
{
BufferT<Vec3fa>& verts = vertices[j];
for (size_t i=0; i<verts.size(); i++) {
if (!isvalid(verts[i]))
return false;
}
}
return true;
}
void TriangleMesh::write(std::ofstream& file)
{
int type = TRIANGLE_MESH;
file.write((char*)&type,sizeof(int));
file.write((char*)&numTimeSteps,sizeof(int));
int numVerts = numVertices();
file.write((char*)&numVerts,sizeof(int));
int numTriangles = triangles.size();
file.write((char*)&numTriangles,sizeof(int));
for (size_t j=0; j<numTimeSteps; j++) {
while ((file.tellp() % 16) != 0) { char c = 0; file.write(&c,1); }
for (size_t i=0; i<numVerts; i++) file.write((char*)vertexPtr(i,j),sizeof(Vec3fa));
}
while ((file.tellp() % 16) != 0) { char c = 0; file.write(&c,1); }
for (size_t i=0; i<numTriangles; i++) file.write((char*)&triangle(i),sizeof(Triangle));
while ((file.tellp() % 16) != 0) { char c = 0; file.write(&c,1); }
for (size_t i=0; i<numTriangles; i++) file.write((char*)&triangle(i),sizeof(Triangle)); // FIXME: why is this written twice?
}
}
<|endoftext|> |
<commit_before>/*
Copyright 2007 Google Inc.
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 "image.h"
#include "canvas_interface.h"
#include "graphics_interface.h"
#include "file_manager_interface.h"
namespace ggadget {
class Image::Impl {
public:
Impl(const GraphicsInterface *graphics,
FileManagerInterface *file_manager,
const char *filename, bool is_mask)
: graphics_(graphics),
file_manager_(file_manager),
filename_(filename),
is_mask_(is_mask),
canvas_(NULL),
failed_(false) {
ASSERT(graphics);
ASSERT(file_manager);
ASSERT(filename);
// canvas_ will be lazy initialized when it is used.
}
Impl(const GraphicsInterface *graphics,
const char *data, size_t data_size, bool is_mask)
: graphics_(graphics),
file_manager_(NULL),
is_mask_(is_mask),
canvas_(NULL),
failed_(false) {
ASSERT(graphics);
ASSERT(data);
// TODO: Remove IMG_JPEG.
canvas_ = is_mask_ ?
graphics->NewMask(data, data_size) :
graphics->NewImage(data, data_size);
}
Impl(const Impl &another)
: graphics_(another.graphics_),
filename_(another.filename_),
is_mask_(another.is_mask_),
canvas_(NULL),
failed_(another.failed_) {
if (!failed_ && another.canvas_) {
canvas_ = graphics_->NewCanvas(another.canvas_->GetWidth(),
another.canvas_->GetHeight());
canvas_->DrawCanvas(0, 0, another.canvas_);
}
}
Impl::~Impl() {
if (canvas_) {
canvas_->Destroy();
canvas_ = NULL;
}
}
const CanvasInterface *GetCanvas() {
if (!failed_ && !canvas_ && !filename_.empty() && file_manager_) {
std::string data;
std::string real_path;
failed_ = !file_manager_->GetFileContents(filename_.c_str(),
&data, &real_path);
if (!failed_) {
canvas_ = is_mask_ ?
graphics_->NewMask(data.c_str(), data.size()) :
graphics_->NewImage(data.c_str(), data.size());
}
}
return canvas_;
}
const GraphicsInterface *graphics_;
FileManagerInterface *file_manager_;
std::string filename_;
bool is_mask_;
CanvasInterface *canvas_;
bool failed_;
};
Image::Image(const GraphicsInterface *graphics,
FileManagerInterface *file_manager,
const char *filename, bool is_mask)
: impl_(new Impl(graphics, file_manager, filename, is_mask)) {
}
Image::Image(const GraphicsInterface *graphics,
const char *data, size_t data_size, bool is_mask)
: impl_(new Impl(graphics, data, data_size, is_mask)) {
}
Image::Image(const Image &another)
: impl_(new Impl(*another.impl_)) {
}
const CanvasInterface *Image::GetCanvas() {
return impl_->GetCanvas();
}
} // namespace ggadget
<commit_msg>Fixed the build break under Debian Lenny.<commit_after>/*
Copyright 2007 Google Inc.
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 "image.h"
#include "canvas_interface.h"
#include "graphics_interface.h"
#include "file_manager_interface.h"
namespace ggadget {
class Image::Impl {
public:
Impl(const GraphicsInterface *graphics,
FileManagerInterface *file_manager,
const char *filename, bool is_mask)
: graphics_(graphics),
file_manager_(file_manager),
filename_(filename),
is_mask_(is_mask),
canvas_(NULL),
failed_(false) {
ASSERT(graphics);
ASSERT(file_manager);
ASSERT(filename);
// canvas_ will be lazy initialized when it is used.
}
Impl(const GraphicsInterface *graphics,
const char *data, size_t data_size, bool is_mask)
: graphics_(graphics),
file_manager_(NULL),
is_mask_(is_mask),
canvas_(NULL),
failed_(false) {
ASSERT(graphics);
ASSERT(data);
// TODO: Remove IMG_JPEG.
canvas_ = is_mask_ ?
graphics->NewMask(data, data_size) :
graphics->NewImage(data, data_size);
}
Impl(const Impl &another)
: graphics_(another.graphics_),
filename_(another.filename_),
is_mask_(another.is_mask_),
canvas_(NULL),
failed_(another.failed_) {
if (!failed_ && another.canvas_) {
canvas_ = graphics_->NewCanvas(another.canvas_->GetWidth(),
another.canvas_->GetHeight());
canvas_->DrawCanvas(0, 0, another.canvas_);
}
}
~Impl() {
if (canvas_) {
canvas_->Destroy();
canvas_ = NULL;
}
}
const CanvasInterface *GetCanvas() {
if (!failed_ && !canvas_ && !filename_.empty() && file_manager_) {
std::string data;
std::string real_path;
failed_ = !file_manager_->GetFileContents(filename_.c_str(),
&data, &real_path);
if (!failed_) {
canvas_ = is_mask_ ?
graphics_->NewMask(data.c_str(), data.size()) :
graphics_->NewImage(data.c_str(), data.size());
}
}
return canvas_;
}
const GraphicsInterface *graphics_;
FileManagerInterface *file_manager_;
std::string filename_;
bool is_mask_;
CanvasInterface *canvas_;
bool failed_;
};
Image::Image(const GraphicsInterface *graphics,
FileManagerInterface *file_manager,
const char *filename, bool is_mask)
: impl_(new Impl(graphics, file_manager, filename, is_mask)) {
}
Image::Image(const GraphicsInterface *graphics,
const char *data, size_t data_size, bool is_mask)
: impl_(new Impl(graphics, data, data_size, is_mask)) {
}
Image::Image(const Image &another)
: impl_(new Impl(*another.impl_)) {
}
const CanvasInterface *Image::GetCanvas() {
return impl_->GetCanvas();
}
} // namespace ggadget
<|endoftext|> |
<commit_before>#ifndef GLHPP_OPENGL_HPP
#define GLHPP_OPENGL_HPP
#include "Exception.hpp"
#include "Formats.hpp"
#include "Object.hpp"
#include "Sync.hpp"
#include "Query.hpp"
#include "Buffer.hpp"
#include "Shader.hpp"
#include "Program.hpp"
#include "ProgramPipeline.hpp"
#include "Texture.hpp"
#include "Sampler.hpp"
#include "Framebuffer.hpp"
#include "Renderbuffer.hpp"
#include "VertexAttrib.hpp"
namespace gl
{
};
#endif
<commit_msg>Fix temporary bug<commit_after>#ifndef GLHPP_OPENGL_HPP
#define GLHPP_OPENGL_HPP
#include "Exception.hpp"
#include "Formats.hpp"
#include "Object.hpp"
#include "Sync.hpp"
#include "Query.hpp"
#include "Buffer.hpp"
#include "Shader.hpp"
#include "Program.hpp"
#include "ProgramPipeline.hpp"
#include "Texture.hpp"
#include "Sampler.hpp"
#include "Framebuffer.hpp"
#include "Renderbuffer.hpp"
//#include "VertexAttrib.hpp"
namespace gl
{
};
#endif
<|endoftext|> |
<commit_before>/* Max Flow Problem, by Abreto<m@abreto.net> */
#define MAXV (100000)
#define MAXE (1000000)
struct edge
{
static int N;
int v, w;
edge *n;
edge(void):v(0),w(0),n(NULL){}
edge(int vv, int ww, edge *nn):v(vv),w(ww),n(nn){}
};
int nE;
edge E[MAXE];
edge *front[MAXV];
void add_edge(int u, int v, int w)
{
int ne = ++nE;
E[ne] = edge(v, w, u[front]);
u[front] = &(E[ne]);
}
edge *find_edge(int u, int v)
{
for(edge *e = u[front];e != NULL;e = e->n)
if(e->v == v)
return e;
return NULL;
}
void grant_e(int u, int v, int w)
{
edge *e = find_edge(u, v);
if(NULL == e) add_edge(u,v,w);
else e->w += w;
}
int vis[MAXV];
int path[MAXV];
int dfs(int u, int t)
{
vis[u] = 1;
if(u == t) return 1;
for(edge *e = u[front];e != NULL;e = e->n)
{
int v = e->v;
if(!vis[v] && e->w && dfs(v,t))
{
path[u] = v;
return 1;
}
}
return 0;
}
int find_path(int s, int t)
{
memset(vis, 0, sizeof(vis));
return dfs(s,t);
}
int max_flow(int s, int t)
{
int flow = 0;
while(find_path(s,t))
{
int i = 0;
int minf = find_edge(s,path[s])->w;
for(i = path[s];i != t;i = path[i])
minf = min(minf, find_edge(i,path[i])->w);
for(i = s;i != t;i = path[i])
{
grant_e(i, path[i], -minf);
grant_e(path[i], i, minf);
}
flow += minf;
}
return flow;
}
<commit_msg>maxflow Dinic<commit_after>/* Max Flow Problem, by Abreto<m@abreto.net> */
#define MAXV (100000)
#define MAXE (1000000)
struct edge
{
static int N;
int v, w;
edge *n;
edge(void):v(0),w(0),n(NULL){}
edge(int vv, int ww, edge *nn):v(vv),w(ww),n(nn){}
};
int nE;
edge E[MAXE];
edge *front[MAXV];
void add_edge(int u, int v, int w)
{
int ne = ++nE;
E[ne] = edge(v, w, u[front]);
u[front] = &(E[ne]);
}
edge *find_edge(int u, int v)
{
for(edge *e = u[front];e != NULL;e = e->n)
if(e->v == v)
return e;
return NULL;
}
void grant_e(int u, int v, int w)
{
edge *e = find_edge(u, v);
if(NULL == e) add_edge(u,v,w);
else e->w += w;
}
int vis[MAXV];
int path[MAXV];
int dfs(int u, int t)
{
vis[u] = 1;
if(u == t) return 1;
for(edge *e = u[front];e != NULL;e = e->n)
{
int v = e->v;
if(!vis[v] && e->w && dfs(v,t))
{
path[u] = v;
return 1;
}
}
return 0;
}
int find_path(int s, int t)
{
memset(vis, 0, sizeof(vis));
return dfs(s,t);
}
int max_flow(int s, int t)
{
int flow = 0;
while(find_path(s,t))
{
int i = 0;
int minf = find_edge(s,path[s])->w;
for(i = path[s];i != t;i = path[i])
minf = min(minf, find_edge(i,path[i])->w);
for(i = s;i != t;i = path[i])
{
grant_e(i, path[i], -minf);
grant_e(path[i], i, minf);
}
flow += minf;
}
return flow;
}
/* Dinic */
#define N 1000
#define INF 100000000
struct Edge
{
int from,to,cap,flow;
Edge(int u,int v,int c,int f):from(u),to(v),cap(c),flow(f){}
};
struct Dinic
{
int n,m,s,t;//结点数,边数(包括反向弧),源点编号,汇点编号
vector<Edge>edges;//边表,dges[e]和dges[e^1]互为反向弧
vector<int>G[N];//邻接表,G[i][j]表示结点i的第j条边在e数组中的编号
bool vis[N]; //BFS的使用
int d[N]; //从起点到i的距离
int cur[N]; //当前弧下标
void addedge(int from,int to,int cap)
{
edges.push_back(Edge(from,to,cap,0));
edges.push_back(Edge(to,from,0,0));
int m=edges.size();
G[from].push_back(m-2);
G[to].push_back(m-1);
}
bool bfs()
{
memset(vis,0,sizeof(vis));
queue<int>Q;
Q.push(s);
d[s]=0;
vis[s]=1;
while(!Q.empty())
{
int x=Q.front();Q.pop();
for(int i=0;i<G[x].size();i++)
{
Edge&e=edges[G[x][i]];
if(!vis[e.to]&&e.cap>e.flow)//只考虑残量网络中的弧
{
vis[e.to]=1;
d[e.to]=d[x]+1;
Q.push(e.to);
}
}
}
return vis[t];
}
int dfs(int x,int a)//x表示当前结点,a表示目前为止的最小残量
{
if(x==t||a==0)return a;//a等于0时及时退出,此时相当于断路了
int flow=0,f;
for(int&i=cur[x];i<G[x].size();i++)//从上次考虑的弧开始,注意要使用引用,同时修改cur[x]
{
Edge&e=edges[G[x][i]];//e是一条边
if(d[x]+1==d[e.to]&&(f=dfs(e.to,min(a,e.cap-e.flow)))>0)
{
e.flow+=f;
edges[G[x][i]^1].flow-=f;
flow+=f;
a-=f;
if(!a)break;//a等于0及时退出,当a!=0,说明当前节点还存在另一个曾广路分支。
}
}
return flow;
}
int Maxflow(int s,int t)//主过程
{
this->s=s,this->t=t;
int flow=0;
while(bfs())//不停地用bfs构造分层网络,然后用dfs沿着阻塞流增广
{
memset(cur,0,sizeof(cur));
flow+=dfs(s,INF);
}
return flow;
}
};
/* ISAP */
<|endoftext|> |
<commit_before>// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/eval/tensor/default_tensor_engine.h>
#include <vespa/eval/tensor/dense/dense_tensor.h>
#include <vespa/eval/tensor/tensor.h>
#include <vespa/searchlib/common/feature.h>
#include <vespa/searchlib/fef/matchdata.h>
#include <vespa/searchlib/queryeval/nearest_neighbor_iterator.h>
#include <vespa/searchlib/queryeval/simpleresult.h>
#include <vespa/searchlib/tensor/dense_tensor_attribute.h>
#include <vespa/vespalib/test/insertion_operators.h>
#include <vespa/log/log.h>
LOG_SETUP("nearest_neighbor_test");
using search::feature_t;
using search::tensor::DenseTensorAttribute;
using search::AttributeVector;
using vespalib::eval::ValueType;
using vespalib::eval::TensorSpec;
using vespalib::tensor::Tensor;
using vespalib::tensor::DenseTensorView;
using vespalib::tensor::DefaultTensorEngine;
using namespace search::fef;
using namespace search::queryeval;
vespalib::string denseSpec("tensor(x[2])");
std::unique_ptr<DenseTensorView> createTensor(const TensorSpec &spec) {
auto value = DefaultTensorEngine::ref().from_spec(spec);
DenseTensorView *tensor = dynamic_cast<DenseTensorView*>(value.get());
ASSERT_TRUE(tensor != nullptr);
value.release();
return std::unique_ptr<DenseTensorView>(tensor);
}
struct Fixture
{
using BasicType = search::attribute::BasicType;
using CollectionType = search::attribute::CollectionType;
using Config = search::attribute::Config;
Config _cfg;
vespalib::string _name;
vespalib::string _typeSpec;
std::shared_ptr<DenseTensorAttribute> _tensorAttr;
std::shared_ptr<AttributeVector> _attr;
Fixture(const vespalib::string &typeSpec)
: _cfg(BasicType::TENSOR, CollectionType::SINGLE),
_name("test"),
_typeSpec(typeSpec),
_tensorAttr(),
_attr()
{
_cfg.setTensorType(ValueType::from_spec(typeSpec));
_tensorAttr = makeAttr();
_attr = _tensorAttr;
_attr->addReservedDoc();
}
~Fixture() {}
std::shared_ptr<DenseTensorAttribute> makeAttr() {
return std::make_shared<DenseTensorAttribute>(_name, _cfg);
}
void ensureSpace(uint32_t docId) {
while (_attr->getNumDocs() <= docId) {
uint32_t newDocId = 0u;
_attr->addDoc(newDocId);
_attr->commit();
}
}
void setTensor(uint32_t docId, const Tensor &tensor) {
ensureSpace(docId);
_tensorAttr->setTensor(docId, tensor);
_attr->commit();
}
void setTensor(uint32_t docId, double v1, double v2) {
auto t = createTensor(TensorSpec(denseSpec)
.add({{"x", 0}}, v1)
.add({{"x", 1}}, v2));
setTensor(docId, *t);
}
};
template <bool strict>
SimpleResult find_matches(Fixture &env) {
auto md = MatchData::makeTestInstance(2, 2);
auto qt = createTensor(TensorSpec(denseSpec));
auto &tfmd = *(md->resolveTermField(0));
const DenseTensorView &qtv = *qt;
auto &attr = *(env._tensorAttr);
NearestNeighborDistanceHeap dh(2);
auto search = NearestNeighborIteratorFactory::createIterator(strict, tfmd, qtv, attr, dh);
if (strict) {
return SimpleResult().searchStrict(*search, attr.getNumDocs());
} else {
return SimpleResult().search(*search, attr.getNumDocs());
}
}
TEST("require that NearestNeighborIterator returns expected results") {
Fixture fixture(denseSpec);
fixture.ensureSpace(6);
fixture.setTensor(1, 3.0, 4.0);
fixture.setTensor(2, 6.0, 8.0);
fixture.setTensor(3, 5.0, 12.0);
fixture.setTensor(4, 4.0, 3.0);
fixture.setTensor(5, 8.0, 6.0);
fixture.setTensor(6, 4.0, 3.0);
SimpleResult result = find_matches<true>(fixture);
SimpleResult expect({1,2,4,6});
EXPECT_EQUAL(result, expect);
result = find_matches<false>(fixture);
EXPECT_EQUAL(result, expect);
}
template <bool strict>
std::vector<feature_t> get_rawscores(Fixture &env) {
auto md = MatchData::makeTestInstance(2, 2);
auto qt = createTensor(TensorSpec(denseSpec));
auto &tfmd = *(md->resolveTermField(0));
const DenseTensorView &qtv = *qt;
auto &attr = *(env._tensorAttr);
NearestNeighborDistanceHeap dh(2);
auto search = NearestNeighborIteratorFactory::createIterator(strict, tfmd, qtv, attr, dh);
uint32_t limit = attr.getNumDocs();
uint32_t docid = 1;
search->initRange(docid, limit);
std::vector<feature_t> rv;
while (docid < limit) {
if (strict) {
search->seek(docid);
if (search->isAtEnd()) break;
docid = search->getDocId();
search->unpack(docid);
rv.push_back(tfmd.getRawScore());
} else {
if (search->seek(docid)) {
search->unpack(docid);
rv.push_back(tfmd.getRawScore());
}
}
++docid;
}
return rv;
}
TEST("require that NearestNeighborIterator sets expected rawscore") {
Fixture fixture(denseSpec);
fixture.ensureSpace(6);
fixture.setTensor(1, 3.0, 4.0);
fixture.setTensor(2, 5.0, 12.0);
fixture.setTensor(3, 6.0, 8.0);
fixture.setTensor(4, 5.0, 12.0);
fixture.setTensor(5, 8.0, 6.0);
fixture.setTensor(6, 4.0, 3.0);
std::vector<feature_t> got = get_rawscores<true>(fixture);
std::vector<feature_t> expected{5.0, 13.0, 10.0, 10.0, 5.0};
EXPECT_EQUAL(got, expected);
got = get_rawscores<false>(fixture);
EXPECT_EQUAL(got, expected);
}
TEST_MAIN() { TEST_RUN_ALL(); }
<commit_msg>refactor and check with non-null tensor<commit_after>// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/eval/tensor/default_tensor_engine.h>
#include <vespa/eval/tensor/dense/dense_tensor.h>
#include <vespa/eval/tensor/tensor.h>
#include <vespa/searchlib/common/feature.h>
#include <vespa/searchlib/fef/matchdata.h>
#include <vespa/searchlib/queryeval/nearest_neighbor_iterator.h>
#include <vespa/searchlib/queryeval/simpleresult.h>
#include <vespa/searchlib/tensor/dense_tensor_attribute.h>
#include <vespa/vespalib/test/insertion_operators.h>
#include <vespa/log/log.h>
LOG_SETUP("nearest_neighbor_test");
using search::feature_t;
using search::tensor::DenseTensorAttribute;
using search::AttributeVector;
using vespalib::eval::ValueType;
using vespalib::eval::TensorSpec;
using vespalib::tensor::Tensor;
using vespalib::tensor::DenseTensorView;
using vespalib::tensor::DefaultTensorEngine;
using namespace search::fef;
using namespace search::queryeval;
vespalib::string denseSpec("tensor(x[2])");
std::unique_ptr<DenseTensorView> createTensor(const TensorSpec &spec) {
auto value = DefaultTensorEngine::ref().from_spec(spec);
DenseTensorView *tensor = dynamic_cast<DenseTensorView*>(value.get());
ASSERT_TRUE(tensor != nullptr);
value.release();
return std::unique_ptr<DenseTensorView>(tensor);
}
std::unique_ptr<DenseTensorView> createTensor(double v1, double v2) {
return createTensor(TensorSpec(denseSpec).add({{"x", 0}}, v1)
.add({{"x", 1}}, v2));
}
struct Fixture
{
using BasicType = search::attribute::BasicType;
using CollectionType = search::attribute::CollectionType;
using Config = search::attribute::Config;
Config _cfg;
vespalib::string _name;
vespalib::string _typeSpec;
std::shared_ptr<DenseTensorAttribute> _tensorAttr;
std::shared_ptr<AttributeVector> _attr;
Fixture(const vespalib::string &typeSpec)
: _cfg(BasicType::TENSOR, CollectionType::SINGLE),
_name("test"),
_typeSpec(typeSpec),
_tensorAttr(),
_attr()
{
_cfg.setTensorType(ValueType::from_spec(typeSpec));
_tensorAttr = makeAttr();
_attr = _tensorAttr;
_attr->addReservedDoc();
}
~Fixture() {}
std::shared_ptr<DenseTensorAttribute> makeAttr() {
return std::make_shared<DenseTensorAttribute>(_name, _cfg);
}
void ensureSpace(uint32_t docId) {
while (_attr->getNumDocs() <= docId) {
uint32_t newDocId = 0u;
_attr->addDoc(newDocId);
_attr->commit();
}
}
void setTensor(uint32_t docId, const Tensor &tensor) {
ensureSpace(docId);
_tensorAttr->setTensor(docId, tensor);
_attr->commit();
}
void setTensor(uint32_t docId, double v1, double v2) {
auto t = createTensor(v1, v2);
setTensor(docId, *t);
}
};
template <bool strict>
SimpleResult find_matches(Fixture &env, const DenseTensorView &qtv) {
auto md = MatchData::makeTestInstance(2, 2);
auto &tfmd = *(md->resolveTermField(0));
auto &attr = *(env._tensorAttr);
NearestNeighborDistanceHeap dh(2);
auto search = NearestNeighborIteratorFactory::createIterator(strict, tfmd, qtv, attr, dh);
if (strict) {
return SimpleResult().searchStrict(*search, attr.getNumDocs());
} else {
return SimpleResult().search(*search, attr.getNumDocs());
}
}
TEST("require that NearestNeighborIterator returns expected results") {
Fixture fixture(denseSpec);
fixture.ensureSpace(6);
fixture.setTensor(1, 3.0, 4.0);
fixture.setTensor(2, 6.0, 8.0);
fixture.setTensor(3, 5.0, 12.0);
fixture.setTensor(4, 4.0, 3.0);
fixture.setTensor(5, 8.0, 6.0);
fixture.setTensor(6, 4.0, 3.0);
auto nullTensor = createTensor(0.0, 0.0);
SimpleResult result = find_matches<true>(fixture, *nullTensor);
SimpleResult nullExpect({1,2,4,6});
EXPECT_EQUAL(result, nullExpect);
result = find_matches<false>(fixture, *nullTensor);
EXPECT_EQUAL(result, nullExpect);
auto farTensor = createTensor(9.0, 9.0);
SimpleResult farExpect({1,2,3,5});
result = find_matches<true>(fixture, *farTensor);
EXPECT_EQUAL(result, farExpect);
result = find_matches<false>(fixture, *farTensor);
EXPECT_EQUAL(result, farExpect);
}
template <bool strict>
std::vector<feature_t> get_rawscores(Fixture &env, const DenseTensorView &qtv) {
auto md = MatchData::makeTestInstance(2, 2);
auto &tfmd = *(md->resolveTermField(0));
auto &attr = *(env._tensorAttr);
NearestNeighborDistanceHeap dh(2);
auto search = NearestNeighborIteratorFactory::createIterator(strict, tfmd, qtv, attr, dh);
uint32_t limit = attr.getNumDocs();
uint32_t docid = 1;
search->initRange(docid, limit);
std::vector<feature_t> rv;
while (docid < limit) {
if (strict) {
search->seek(docid);
if (search->isAtEnd()) break;
docid = search->getDocId();
search->unpack(docid);
rv.push_back(tfmd.getRawScore());
} else {
if (search->seek(docid)) {
search->unpack(docid);
rv.push_back(tfmd.getRawScore());
}
}
++docid;
}
return rv;
}
TEST("require that NearestNeighborIterator sets expected rawscore") {
Fixture fixture(denseSpec);
fixture.ensureSpace(6);
fixture.setTensor(1, 3.0, 4.0);
fixture.setTensor(2, 5.0, 12.0);
fixture.setTensor(3, 6.0, 8.0);
fixture.setTensor(4, 5.0, 12.0);
fixture.setTensor(5, 8.0, 6.0);
fixture.setTensor(6, 4.0, 3.0);
auto nullTensor = createTensor(0.0, 0.0);
std::vector<feature_t> got = get_rawscores<true>(fixture, *nullTensor);
std::vector<feature_t> expected{5.0, 13.0, 10.0, 10.0, 5.0};
EXPECT_EQUAL(got, expected);
got = get_rawscores<false>(fixture, *nullTensor);
EXPECT_EQUAL(got, expected);
}
TEST_MAIN() { TEST_RUN_ALL(); }
<|endoftext|> |
<commit_before><commit_msg>fix mem leak; fixes #3<commit_after><|endoftext|> |
<commit_before>
#include <iostream>
#ifdef __cplusplus
extern "C"
{
#endif
int xerbla_(const char * msg, int *info, int)
{
std::cerr << "Eigen BLAS ERROR #" << *info << ": " << msg << "\n";
return 0;
}
#ifdef __cplusplus
}
#endif
<commit_msg>enforce weak linking of xerbla<commit_after>
#include <iostream>
#if (defined __GNUC__)
#define EIGEN_WEAK_LINKING __attribute__ ((weak))
#else
#define EIGEN_WEAK_LINKING
#endif
#ifdef __cplusplus
extern "C"
{
#endif
EIGEN_WEAK_LINKING int xerbla_(const char * msg, int *info, int)
{
std::cerr << "Eigen BLAS ERROR #" << *info << ": " << msg << "\n";
return 0;
}
#ifdef __cplusplus
}
#endif
<|endoftext|> |
<commit_before>#include "StdAfx.h"
#include "CameraMetaData.h"
/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
http://www.klauspost.com
*/
namespace RawSpeed {
CameraMetaData::CameraMetaData() {
}
CameraMetaData::CameraMetaData(const char *docname) {
xml_document doc;
xml_parse_result result = doc.load_file(docname);
if (!result) {
ThrowCME("CameraMetaData: XML Document could not be parsed successfully. Error was: %s in %s",
result.description(), doc.child("node").attribute("attr").value());
}
xml_node cameras = doc.child("Cameras");
for (xml_node camera = cameras.child("Camera"); camera; camera = camera.next_sibling("Camera")) {
Camera *cam = new Camera(camera);
if(!addCamera(cam)) continue;
// Create cameras for aliases.
for (uint32 i = 0; i < cam->aliases.size(); i++) {
addCamera(new Camera(cam, i));
}
}
}
CameraMetaData::~CameraMetaData(void) {
map<string, Camera*>::iterator i = cameras.begin();
for (; i != cameras.end(); ++i) {
delete((*i).second);
}
}
Camera* CameraMetaData::getCamera(string make, string model, string mode) {
string id = string(make).append(model).append(mode);
if (cameras.end() == cameras.find(id))
return NULL;
return cameras[id];
}
bool CameraMetaData::hasCamera(string make, string model, string mode) {
string id = string(make).append(model).append(mode);
if (cameras.end() == cameras.find(id))
return FALSE;
return TRUE;
}
Camera* CameraMetaData::getChdkCamera(uint32 filesize) {
if (chdkCameras.end() == chdkCameras.find(filesize))
return NULL;
return chdkCameras[filesize];
}
bool CameraMetaData::hasChdkCamera(uint32 filesize) {
return chdkCameras.end() != chdkCameras.find(filesize);
}
bool CameraMetaData::addCamera( Camera* cam )
{
string id = string(cam->make).append(cam->model).append(cam->mode);
if (cameras.end() != cameras.find(id)) {
writeLog(DEBUG_PRIO_WARNING, "CameraMetaData: Duplicate entry found for camera: %s %s, Skipping!\n", cam->make.c_str(), cam->model.c_str());
delete(cam);
return false;
} else {
cameras[id] = cam;
}
if (string::npos != cam->mode.find("chdk")) {
if (cam->hints.find("filesize") == cam->hints.end()) {
writeLog(DEBUG_PRIO_WARNING, "CameraMetaData: CHDK camera: %s %s, no \"filesize\" hint set!\n", cam->make.c_str(), cam->model.c_str());
} else {
uint32 size;
stringstream fsize(cam->hints.find("filesize")->second);
fsize >> size;
chdkCameras[size] = cam;
// writeLog(DEBUG_PRIO_WARNING, "CHDK camera: %s %s size:%u\n", cam->make.c_str(), cam->model.c_str(), size);
}
}
return true;
}
void CameraMetaData::disableMake( string make )
{
map<string, Camera*>::iterator i = cameras.begin();
for (; i != cameras.end(); ++i) {
Camera* cam = (*i).second;
if (0 == cam->make.compare(make)) {
cam->supported = FALSE;
}
}
}
void CameraMetaData::disableCamera( string make, string model )
{
map<string, Camera*>::iterator i = cameras.begin();
for (; i != cameras.end(); ++i) {
Camera* cam = (*i).second;
if (0 == cam->make.compare(make) && 0 == cam->model.compare(model)) {
cam->supported = FALSE;
}
}
}
} // namespace RawSpeed
<commit_msg>CameraMetaData(): properly compute "id"<commit_after>#include "StdAfx.h"
#include "CameraMetaData.h"
/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
http://www.klauspost.com
*/
namespace RawSpeed {
CameraMetaData::CameraMetaData() {
}
CameraMetaData::CameraMetaData(const char *docname) {
xml_document doc;
xml_parse_result result = doc.load_file(docname);
if (!result) {
ThrowCME("CameraMetaData: XML Document could not be parsed successfully. Error was: %s in %s",
result.description(), doc.child("node").attribute("attr").value());
}
xml_node cameras = doc.child("Cameras");
for (xml_node camera = cameras.child("Camera"); camera; camera = camera.next_sibling("Camera")) {
Camera *cam = new Camera(camera);
if(!addCamera(cam)) continue;
// Create cameras for aliases.
for (uint32 i = 0; i < cam->aliases.size(); i++) {
addCamera(new Camera(cam, i));
}
}
}
CameraMetaData::~CameraMetaData(void) {
map<string, Camera*>::iterator i = cameras.begin();
for (; i != cameras.end(); ++i) {
delete((*i).second);
}
}
static inline string getId(string make, string model, string mode)
{
TrimSpaces(make);
TrimSpaces(model);
TrimSpaces(mode);
return string(make).append(model).append(mode);
}
static inline string getId(Camera* cam)
{
return getId(cam->make, cam->model, cam->mode);
}
Camera* CameraMetaData::getCamera(string make, string model, string mode) {
string id = getId(make, model, mode);
if (cameras.end() == cameras.find(id))
return NULL;
return cameras[id];
}
bool CameraMetaData::hasCamera(string make, string model, string mode) {
string id = getId(make, model, mode);
if (cameras.end() == cameras.find(id))
return FALSE;
return TRUE;
}
Camera* CameraMetaData::getChdkCamera(uint32 filesize) {
if (chdkCameras.end() == chdkCameras.find(filesize))
return NULL;
return chdkCameras[filesize];
}
bool CameraMetaData::hasChdkCamera(uint32 filesize) {
return chdkCameras.end() != chdkCameras.find(filesize);
}
bool CameraMetaData::addCamera( Camera* cam )
{
string id = getId(cam);
if (cameras.end() != cameras.find(id)) {
writeLog(DEBUG_PRIO_WARNING, "CameraMetaData: Duplicate entry found for camera: %s %s, Skipping!\n", cam->make.c_str(), cam->model.c_str());
delete(cam);
return false;
} else {
cameras[id] = cam;
}
if (string::npos != cam->mode.find("chdk")) {
if (cam->hints.find("filesize") == cam->hints.end()) {
writeLog(DEBUG_PRIO_WARNING, "CameraMetaData: CHDK camera: %s %s, no \"filesize\" hint set!\n", cam->make.c_str(), cam->model.c_str());
} else {
uint32 size;
stringstream fsize(cam->hints.find("filesize")->second);
fsize >> size;
chdkCameras[size] = cam;
// writeLog(DEBUG_PRIO_WARNING, "CHDK camera: %s %s size:%u\n", cam->make.c_str(), cam->model.c_str(), size);
}
}
return true;
}
void CameraMetaData::disableMake( string make )
{
map<string, Camera*>::iterator i = cameras.begin();
for (; i != cameras.end(); ++i) {
Camera* cam = (*i).second;
if (0 == cam->make.compare(make)) {
cam->supported = FALSE;
}
}
}
void CameraMetaData::disableCamera( string make, string model )
{
map<string, Camera*>::iterator i = cameras.begin();
for (; i != cameras.end(); ++i) {
Camera* cam = (*i).second;
if (0 == cam->make.compare(make) && 0 == cam->model.compare(model)) {
cam->supported = FALSE;
}
}
}
} // namespace RawSpeed
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2013-2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <types.hpp>
#include <unique_ptr.hpp>
#include <algorithms.hpp>
#include <errors.hpp>
#include "fs/sysfs.hpp"
#include "console.hpp"
#include "rtc.hpp"
namespace {
struct sys_value {
std::string name;
std::string value;
};
struct sys_folder {
std::string name;
std::vector<sys_folder> folders;
std::vector<sys_value> values;
};
std::vector<sys_folder> root_folders;
} //end of anonymous namespace
sysfs::sysfs_file_system::sysfs_file_system(std::string mp) : mount_point(mp) {
//Nothing to init
}
sysfs::sysfs_file_system::~sysfs_file_system(){
//Nothing to delete
}
size_t sysfs::sysfs_file_system::get_file(const std::vector<std::string>& file_path, vfs::file& file){
//TODO
return std::ERROR_NOT_EXISTS;
}
size_t sysfs::sysfs_file_system::read(const std::vector<std::string>& file_path, std::string& content){
//TODO
return 0;
}
size_t sysfs::sysfs_file_system::ls(const std::vector<std::string>& file_path, std::vector<vfs::file>& contents){
//TODO
return 0;
}
size_t sysfs::sysfs_file_system::touch(const std::vector<std::string>& file_path){
return std::ERROR_PERMISSION_DENIED;
}
size_t sysfs::sysfs_file_system::mkdir(const std::vector<std::string>& file_path){
return std::ERROR_PERMISSION_DENIED;
}
size_t sysfs::sysfs_file_system::rm(const std::vector<std::string>& file_path){
return std::ERROR_PERMISSION_DENIED;
}
size_t sysfs::sysfs_file_system::statfs(statfs_info& file){
file.total_size = 0;
file.free_size = 0;
return 0;
}
void set_value(const std::string& mount_point, const std::string& path, const std::string& value){
//TODO
}
void delete_value(const std::string& mount_point, const std::string& path){
//TODO
}
<commit_msg>Add a way for the system to set values<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2013-2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <types.hpp>
#include <unique_ptr.hpp>
#include <algorithms.hpp>
#include <errors.hpp>
#include "fs/sysfs.hpp"
#include "console.hpp"
#include "rtc.hpp"
namespace {
struct sys_value {
std::string name;
std::string value;
sys_value(){}
sys_value(std::string name, std::string value) : name(name), value(value){
//Nothing else to init
}
};
struct sys_folder {
std::string name;
std::vector<sys_folder> folders;
std::vector<sys_value> values;
sys_folder(){}
sys_folder(std::string name) : name(name) {
//Nothing else to init
}
};
std::vector<sys_folder> root_folders;
sys_folder& find_root_folder(const std::string& mount_point){
for(auto& sys_folder : root_folders){
if(sys_folder.name == mount_point){
return sys_folder;
}
}
root_folders.emplace_back(mount_point);
return root_folders.back();
}
sys_folder& find_folder(sys_folder& root, const std::vector<std::string>& path, size_t i = 0){
auto& name = path[i];
for(auto& folder : root.folders){
if(folder.name == name){
if(i == path.size() - 1){
return folder;
} else {
return find_folder(folder, path, i + 1);
}
}
}
root.folders.emplace_back(name);
if(i == path.size() - 1){
return root.folders.back();
} else {
return find_folder(root.folders.back(), path, i + 1);
}
}
} //end of anonymous namespace
sysfs::sysfs_file_system::sysfs_file_system(std::string mp) : mount_point(mp) {
//Nothing to init
}
sysfs::sysfs_file_system::~sysfs_file_system(){
//Nothing to delete
}
size_t sysfs::sysfs_file_system::get_file(const std::vector<std::string>& file_path, vfs::file& file){
//TODO
return std::ERROR_NOT_EXISTS;
}
size_t sysfs::sysfs_file_system::read(const std::vector<std::string>& file_path, std::string& content){
//TODO
return 0;
}
size_t sysfs::sysfs_file_system::ls(const std::vector<std::string>& file_path, std::vector<vfs::file>& contents){
//TODO
return 0;
}
size_t sysfs::sysfs_file_system::touch(const std::vector<std::string>& ){
return std::ERROR_PERMISSION_DENIED;
}
size_t sysfs::sysfs_file_system::mkdir(const std::vector<std::string>& ){
return std::ERROR_PERMISSION_DENIED;
}
size_t sysfs::sysfs_file_system::rm(const std::vector<std::string>& ){
return std::ERROR_PERMISSION_DENIED;
}
size_t sysfs::sysfs_file_system::statfs(statfs_info& file){
file.total_size = 0;
file.free_size = 0;
return 0;
}
void set_value(const std::string& mount_point, const std::string& path, const std::string& value){
auto& root_folder = find_root_folder(mount_point);
auto file_path = std::split(path, '/');
auto last = file_path.back();
file_path.pop_back();
auto& folder = find_folder(root_folder, file_path);
for(auto& v : folder.values){
if(v.name == last){
v.value = value;
return;
}
}
folder.values.emplace_back(last, value);
}
void delete_value(const std::string& mount_point, const std::string& path){
//TODO
}
<|endoftext|> |
<commit_before>// <insert copyright>
/*! \mainpage CAMP C++ library documentation
*
* \image html logo_camp.png
*
* \section overview Overview
*
* CAMP is a C++ library which provides runtime reflection for types.
* It provides an abstraction for most of the high-level concepts of C++:
*
* \li Classes
* \li Enumerations
* \li Properties
* \li Functions
* \li Objects
* \li Variables
*
* By wrapping all these concepts into abstract structures, CAMP provides an extra layer of
* flexibility to programs, and allow them to fully expose their data structures at runtime.
*
* Many applications can take advantage of CAMP, in order to automate tasks which would
* otherwise require a huge amount of work. For example, CAMP can be used to expose and edit
* objects' attributes into a graphical user interface. It can also be used to do
* automatic binding of C++ classes to script languages such as Python or Lua.
* Another possible application would be the serialization of objects to XML, text or
* binary formats. Or you can even combine all these examples to provide a powerful
* and consistent interface for manipulating your objects outside C++ code.
*
* \section example Quick example
*
* Here is a simple example of how to use CAMP:
*
* \code
* #include <camp/camptype.hpp>
* #include <camp/class.hpp>
* #include <string>
* #include <iostream>
*
* // Let's define a class for handling persons
* class Person
* {
* public:
*
* // Construct a person from its name
* Person(const std::string& name) : m_name(name), m_age(0)
* {
* }
*
* // Retrieve the name of a person
* std::string name() const
* {
* return m_name;
* }
*
* // Retrieve the age of a person
* unsigned int age() const
* {
* return m_age;
* }
*
* // Set the age of a person
* void setAge(unsigned int age)
* {
* m_age = age;
* }
*
* // Make a person speak (tell about its name and age)
* void speak()
* {
* std::cout << "Hi! My name is " << m_name << " and I'm " << m_age << " years old." << std::endl;
* }
*
* private:
*
* std::string m_name;
* unsigned int m_age;
* };
*
* // Make the Person type available to CAMP
* CAMP_TYPE(Person);
*
*
* int main()
* {
* // Bind our Person class to CAMP
* camp::Class::declare<Person>("Person")
* .constructor1<std::string>()
* .property("name", &Person::name)
* .property("age", &Person::age, &Person::setAge)
* .function("speak", &Person::speak);
*
* // Retrieve it by its name
* const camp::Class& metaclass = camp::classByName("Person");
*
* // Construct a new person named John
* Person* john = metaclass.construct<Person>(camp::Args("John"));
*
* // Print its name
* std::string name = metaclass.property("name").get(john);
* std::cout << "John's name is: " << name << std::endl;
*
* // Set its age to 24
* metaclass.property("age").set(john, 24);
*
* // Make John say something
* metaclass.function("speak").call(john);
*
* // Kill John
* metaclass.destroy(john);
*
* return 0;
* }
* \endcode
*
* \section licence Licence
*
* CAMP is distributed under the terms of the GPL v3 licence:
*
* \verbatim
* CAMP - dynamic reflexion C++ library
* Copyright (C) 2009 TechnoGerma Systems France
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
* \endverbatim
*
* \section contact Contact
*
* Blah blah Tegesoft...
*
*/
<commit_msg>Updated API documentation<commit_after>// <insert copyright>
/*! \mainpage CAMP C++ library documentation
*
* \image html logo_camp.png
*
* \section overview Overview
*
* CAMP is a C++ library which provides runtime reflection for types.
* It provides an abstraction for most of the high-level concepts of C++:
*
* \li Classes
* \li Enumerations
* \li Properties
* \li Functions
* \li Objects
* \li Variables
*
* By wrapping all these concepts into abstract structures, CAMP provides an extra layer of
* flexibility to programs, and allow them to fully expose their data structures at runtime.
*
* Many applications can take advantage of CAMP, in order to automate tasks which would
* otherwise require a huge amount of work. For example, CAMP can be used to expose and edit
* objects' attributes into a graphical user interface. It can also be used to do
* automatic binding of C++ classes to script languages such as Python or Lua.
* Another possible application would be the serialization of objects to XML, text or
* binary formats. Or you can even combine all these examples to provide a powerful
* and consistent interface for manipulating your objects outside C++ code.
*
* \section example Quick example
*
* Here is a simple example of how to use CAMP:
*
* \code
* #include <camp/camptype.hpp>
* #include <camp/class.hpp>
* #include <string>
* #include <iostream>
*
* // Let's define a class for handling persons
* class Person
* {
* public:
*
* // Construct a person from its name
* Person(const std::string& name) : m_name(name), m_age(0)
* {
* }
*
* // Retrieve the name of a person
* std::string name() const
* {
* return m_name;
* }
*
* // Retrieve the age of a person
* unsigned int age() const
* {
* return m_age;
* }
*
* // Set the age of a person
* void setAge(unsigned int age)
* {
* m_age = age;
* }
*
* // Make a person speak (tell about its name and age)
* void speak()
* {
* std::cout << "Hi! My name is " << m_name << " and I'm " << m_age << " years old." << std::endl;
* }
*
* private:
*
* std::string m_name;
* unsigned int m_age;
* };
*
* // Make the Person type available to CAMP
* CAMP_TYPE(Person);
*
*
* int main()
* {
* // Bind our Person class to CAMP
* camp::Class::declare<Person>("Person")
* .constructor1<std::string>()
* .property("name", &Person::name)
* .property("age", &Person::age, &Person::setAge)
* .function("speak", &Person::speak);
*
* // Retrieve it by its name
* const camp::Class& metaclass = camp::classByName("Person");
*
* // Construct a new person named John
* Person* john = metaclass.construct<Person>(camp::Args("John"));
*
* // Print its name
* std::string name = metaclass.property("name").get(john);
* std::cout << "John's name is: " << name << std::endl;
*
* // Set its age to 24
* metaclass.property("age").set(john, 24);
*
* // Make John say something
* metaclass.function("speak").call(john);
*
* // Kill John
* metaclass.destroy(john);
*
* return 0;
* }
* \endcode
*
* \section licence Licence
*
* CAMP is distributed under the terms of the GPL v3 licence:
*
* \verbatim
* CAMP - dynamic reflexion C++ library
* Copyright (C) 2009 TechnoGerma Systems France
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
* \endverbatim
*
*/
<|endoftext|> |
<commit_before>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
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 "tensorflow/core/platform/error.h"
#include <errno.h>
#include <string.h>
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/platform/strcat.h"
namespace tensorflow {
error::Code ErrnoToCode(int err_number) {
error::Code code;
switch (err_number) {
case 0:
code = error::OK;
break;
case EINVAL: // Invalid argument
case ENAMETOOLONG: // Filename too long
case E2BIG: // Argument list too long
case EDESTADDRREQ: // Destination address required
case EDOM: // Mathematics argument out of domain of function
case EFAULT: // Bad address
case EILSEQ: // Illegal byte sequence
case ENOPROTOOPT: // Protocol not available
case ENOSTR: // Not a STREAM
case ENOTSOCK: // Not a socket
case ENOTTY: // Inappropriate I/O control operation
case EPROTOTYPE: // Protocol wrong type for socket
case ESPIPE: // Invalid seek
code = error::INVALID_ARGUMENT;
break;
case ETIMEDOUT: // Connection timed out
case ETIME: // Timer expired
code = error::DEADLINE_EXCEEDED;
break;
case ENODEV: // No such device
case ENOENT: // No such file or directory
case ENXIO: // No such device or address
case ESRCH: // No such process
code = error::NOT_FOUND;
break;
case EEXIST: // File exists
case EADDRNOTAVAIL: // Address not available
case EALREADY: // Connection already in progress
code = error::ALREADY_EXISTS;
break;
case EPERM: // Operation not permitted
case EACCES: // Permission denied
case EROFS: // Read only file system
code = error::PERMISSION_DENIED;
break;
case ENOTEMPTY: // Directory not empty
case EISDIR: // Is a directory
case ENOTDIR: // Not a directory
case EADDRINUSE: // Address already in use
case EBADF: // Invalid file descriptor
case EBUSY: // Device or resource busy
case ECHILD: // No child processes
case EISCONN: // Socket is connected
#if !defined(_WIN32) && !defined(__HAIKU__)
case ENOTBLK: // Block device required
#endif
case ENOTCONN: // The socket is not connected
case EPIPE: // Broken pipe
#if !defined(_WIN32)
case ESHUTDOWN: // Cannot send after transport endpoint shutdown
#endif
case ETXTBSY: // Text file busy
code = error::FAILED_PRECONDITION;
break;
case ENOSPC: // No space left on device
#if !defined(_WIN32)
case EDQUOT: // Disk quota exceeded
#endif
case EMFILE: // Too many open files
case EMLINK: // Too many links
case ENFILE: // Too many open files in system
case ENOBUFS: // No buffer space available
case ENODATA: // No message is available on the STREAM read queue
case ENOMEM: // Not enough space
case ENOSR: // No STREAM resources
#if !defined(_WIN32) && !defined(__HAIKU__)
case EUSERS: // Too many users
#endif
code = error::RESOURCE_EXHAUSTED;
break;
case EFBIG: // File too large
case EOVERFLOW: // Value too large to be stored in data type
case ERANGE: // Result too large
code = error::OUT_OF_RANGE;
break;
case ENOSYS: // Function not implemented
case ENOTSUP: // Operation not supported
case EAFNOSUPPORT: // Address family not supported
#if !defined(_WIN32)
case EPFNOSUPPORT: // Protocol family not supported
#endif
case EPROTONOSUPPORT: // Protocol not supported
#if !defined(_WIN32) && !defined(__HAIKU__)
case ESOCKTNOSUPPORT: // Socket type not supported
#endif
case EXDEV: // Improper link
code = error::UNIMPLEMENTED;
break;
case EAGAIN: // Resource temporarily unavailable
case ECONNREFUSED: // Connection refused
case ECONNABORTED: // Connection aborted
case ECONNRESET: // Connection reset
case EINTR: // Interrupted function call
#if !defined(_WIN32)
case EHOSTDOWN: // Host is down
#endif
case EHOSTUNREACH: // Host is unreachable
case ENETDOWN: // Network is down
case ENETRESET: // Connection aborted by network
case ENETUNREACH: // Network unreachable
case ENOLCK: // No locks available
case ENOLINK: // Link has been severed
#if !(defined(__APPLE__) || defined(__FreeBSD__) || defined(_WIN32) || \
defined(__HAIKU__))
case ENONET: // Machine is not on the network
#endif
code = error::UNAVAILABLE;
break;
case EDEADLK: // Resource deadlock avoided
#if !defined(_WIN32)
case ESTALE: // Stale file handle
#endif
code = error::ABORTED;
break;
case ECANCELED: // Operation cancelled
code = error::CANCELLED;
break;
// NOTE: If you get any of the following (especially in a
// reproducible way) and can propose a better mapping,
// please email the owners about updating this mapping.
case EBADMSG: // Bad message
case EIDRM: // Identifier removed
case EINPROGRESS: // Operation in progress
case EIO: // I/O error
case ELOOP: // Too many levels of symbolic links
case ENOEXEC: // Exec format error
case ENOMSG: // No message of the desired type
case EPROTO: // Protocol error
#if !defined(_WIN32) && !defined(__HAIKU__)
case EREMOTE: // Object is remote
#endif
code = error::UNKNOWN;
break;
default: {
code = error::UNKNOWN;
break;
}
}
return code;
}
Status IOError(const string& context, int err_number) {
auto code = ErrnoToCode(err_number);
return Status(code, strings::StrCat(context, "; ", strerror(err_number)));
}
#if defined(_WIN32)
namespace internal {
std::string GetWindowsErrorMessage(DWORD err) {
LPSTR buffer = NULL;
DWORD flags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS;
FormatMessageA(flags, NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
reinterpret_cast<LPSTR>(&buffer), 0, NULL);
std::string message = buffer;
LocalFree(buffer);
return message;
}
} // namespace internal
#endif
} // namespace tensorflow
<commit_msg>tensorflow::ErrornoToCode should only have internal linkage.<commit_after>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
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 "tensorflow/core/platform/error.h"
#include <errno.h>
#include <string.h>
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/platform/strcat.h"
namespace tensorflow {
namespace {
error::Code ErrnoToCode(int err_number) {
error::Code code;
switch (err_number) {
case 0:
code = error::OK;
break;
case EINVAL: // Invalid argument
case ENAMETOOLONG: // Filename too long
case E2BIG: // Argument list too long
case EDESTADDRREQ: // Destination address required
case EDOM: // Mathematics argument out of domain of function
case EFAULT: // Bad address
case EILSEQ: // Illegal byte sequence
case ENOPROTOOPT: // Protocol not available
case ENOSTR: // Not a STREAM
case ENOTSOCK: // Not a socket
case ENOTTY: // Inappropriate I/O control operation
case EPROTOTYPE: // Protocol wrong type for socket
case ESPIPE: // Invalid seek
code = error::INVALID_ARGUMENT;
break;
case ETIMEDOUT: // Connection timed out
case ETIME: // Timer expired
code = error::DEADLINE_EXCEEDED;
break;
case ENODEV: // No such device
case ENOENT: // No such file or directory
case ENXIO: // No such device or address
case ESRCH: // No such process
code = error::NOT_FOUND;
break;
case EEXIST: // File exists
case EADDRNOTAVAIL: // Address not available
case EALREADY: // Connection already in progress
code = error::ALREADY_EXISTS;
break;
case EPERM: // Operation not permitted
case EACCES: // Permission denied
case EROFS: // Read only file system
code = error::PERMISSION_DENIED;
break;
case ENOTEMPTY: // Directory not empty
case EISDIR: // Is a directory
case ENOTDIR: // Not a directory
case EADDRINUSE: // Address already in use
case EBADF: // Invalid file descriptor
case EBUSY: // Device or resource busy
case ECHILD: // No child processes
case EISCONN: // Socket is connected
#if !defined(_WIN32) && !defined(__HAIKU__)
case ENOTBLK: // Block device required
#endif
case ENOTCONN: // The socket is not connected
case EPIPE: // Broken pipe
#if !defined(_WIN32)
case ESHUTDOWN: // Cannot send after transport endpoint shutdown
#endif
case ETXTBSY: // Text file busy
code = error::FAILED_PRECONDITION;
break;
case ENOSPC: // No space left on device
#if !defined(_WIN32)
case EDQUOT: // Disk quota exceeded
#endif
case EMFILE: // Too many open files
case EMLINK: // Too many links
case ENFILE: // Too many open files in system
case ENOBUFS: // No buffer space available
case ENODATA: // No message is available on the STREAM read queue
case ENOMEM: // Not enough space
case ENOSR: // No STREAM resources
#if !defined(_WIN32) && !defined(__HAIKU__)
case EUSERS: // Too many users
#endif
code = error::RESOURCE_EXHAUSTED;
break;
case EFBIG: // File too large
case EOVERFLOW: // Value too large to be stored in data type
case ERANGE: // Result too large
code = error::OUT_OF_RANGE;
break;
case ENOSYS: // Function not implemented
case ENOTSUP: // Operation not supported
case EAFNOSUPPORT: // Address family not supported
#if !defined(_WIN32)
case EPFNOSUPPORT: // Protocol family not supported
#endif
case EPROTONOSUPPORT: // Protocol not supported
#if !defined(_WIN32) && !defined(__HAIKU__)
case ESOCKTNOSUPPORT: // Socket type not supported
#endif
case EXDEV: // Improper link
code = error::UNIMPLEMENTED;
break;
case EAGAIN: // Resource temporarily unavailable
case ECONNREFUSED: // Connection refused
case ECONNABORTED: // Connection aborted
case ECONNRESET: // Connection reset
case EINTR: // Interrupted function call
#if !defined(_WIN32)
case EHOSTDOWN: // Host is down
#endif
case EHOSTUNREACH: // Host is unreachable
case ENETDOWN: // Network is down
case ENETRESET: // Connection aborted by network
case ENETUNREACH: // Network unreachable
case ENOLCK: // No locks available
case ENOLINK: // Link has been severed
#if !(defined(__APPLE__) || defined(__FreeBSD__) || defined(_WIN32) || \
defined(__HAIKU__))
case ENONET: // Machine is not on the network
#endif
code = error::UNAVAILABLE;
break;
case EDEADLK: // Resource deadlock avoided
#if !defined(_WIN32)
case ESTALE: // Stale file handle
#endif
code = error::ABORTED;
break;
case ECANCELED: // Operation cancelled
code = error::CANCELLED;
break;
// NOTE: If you get any of the following (especially in a
// reproducible way) and can propose a better mapping,
// please email the owners about updating this mapping.
case EBADMSG: // Bad message
case EIDRM: // Identifier removed
case EINPROGRESS: // Operation in progress
case EIO: // I/O error
case ELOOP: // Too many levels of symbolic links
case ENOEXEC: // Exec format error
case ENOMSG: // No message of the desired type
case EPROTO: // Protocol error
#if !defined(_WIN32) && !defined(__HAIKU__)
case EREMOTE: // Object is remote
#endif
code = error::UNKNOWN;
break;
default: {
code = error::UNKNOWN;
break;
}
}
return code;
}
} // namespace
Status IOError(const string& context, int err_number) {
auto code = ErrnoToCode(err_number);
return Status(code, strings::StrCat(context, "; ", strerror(err_number)));
}
#if defined(_WIN32)
namespace internal {
std::string GetWindowsErrorMessage(DWORD err) {
LPSTR buffer = NULL;
DWORD flags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS;
FormatMessageA(flags, NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
reinterpret_cast<LPSTR>(&buffer), 0, NULL);
std::string message = buffer;
LocalFree(buffer);
return message;
}
} // namespace internal
#endif
} // namespace tensorflow
<|endoftext|> |
<commit_before>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved
#include "InteriorEntityHighlightController.h"
#include "ISearchService.h"
#include "ISearchQueryPerformer.h"
#include "ISearchResultRepository.h"
#include "InteriorInteractionModel.h"
#include "InteriorsModel.h"
#include "InteriorsFloorModel.h"
#include "IInteriorsLabelController.h"
#include "VectorMath.h"
#include "InteriorHighlightRenderable.h"
#include "InteriorsLabelParser.h"
#include "InteriorsFloorCells.h"
#include "InteriorsFloorCell.h"
#include "PlaceNameModel.h"
#include "InteriorsCellResource.h"
#include "InteriorsCellResourceObserver.h"
#include "LabelAnchorFilterModel.h"
#include "IAnchoredLabel.h"
#include "document.h"
#include "IInteriorsHighlightService.h"
namespace ExampleApp
{
namespace InteriorsExplorer
{
namespace SdkModel
{
namespace Highlights
{
std::vector<std::string> GetEntityIdsFromJsonArray(const rapidjson::Value& jsonArray)
{
assert(jsonArray.IsArray());
std::vector<std::string> entities;
for (int i = 0; i < jsonArray.Size(); i++)
{
assert(jsonArray[i].IsString());
entities.push_back(jsonArray[i].GetString());
}
return entities;
}
std::vector<std::string> GetEntityIdsFromSearchResultModel(const Search::SdkModel::SearchResultModel& selectedSearchResult)
{
rapidjson::Document json;
std::vector<std::string> entities;
if (!json.Parse<0>(selectedSearchResult.GetJsonData().c_str()).HasParseError())
{
if( json.HasMember("highlight") )
{
const rapidjson::Value& area_highlight = json["highlight"];
if(area_highlight.IsString())
{
entities.push_back(json["highlight"].GetString());
}
else
{
std::vector<std::string> areaHighlights = GetEntityIdsFromJsonArray(area_highlight);
entities.insert(std::end(entities), std::begin(areaHighlights), std::end(areaHighlights));
}
}
if( json.HasMember("entity_highlight") )
{
std::vector<std::string> entityHighlights = GetEntityIdsFromJsonArray(json["entity_highlight"]);
entities.insert(std::end(entities), std::begin(entityHighlights), std::end(entityHighlights));
}
}
return entities;
}
InteriorEntityHighlightController::InteriorEntityHighlightController(Eegeo::Resources::Interiors::InteriorInteractionModel& interiorInteractionModel,
Eegeo::Resources::Interiors::InteriorsCellResourceObserver& interiorsCellResourceObserver,
Search::SdkModel::ISearchService& searchService,
Search::SdkModel::ISearchQueryPerformer& searchQueryPerformer, Eegeo::Resources::Interiors::Entities::IInteriorsLabelController& legacyLabelController,
Eegeo::Labels::ILabelAnchorFilterModel& labelHiddenFilterModel,
const Eegeo::Labels::LabelLayer::IdType interiorLabelLayer,
ExampleAppMessaging::TMessageBus& messageBus,
IHighlightColorMapper& highlightColorMapper,
Eegeo::Resources::Interiors::Highlights::IInteriorsHighlightService& interiorsHighlightService)
: m_interiorInteractionModel(interiorInteractionModel)
, m_interiorsCellResourceObserver(interiorsCellResourceObserver)
, m_interiorLabelLayer(interiorLabelLayer)
, m_labelHiddenFilterModel(labelHiddenFilterModel)
, m_searchQueryPerformer(searchQueryPerformer)
, m_highlightColorMapper(highlightColorMapper)
, m_searchResultsIndex(-1)
, m_searchQueryResponseHandler(this, &InteriorEntityHighlightController::OnSearchQueryResponseReceived)
, m_searchResultsClearedHandler(this, &InteriorEntityHighlightController::OnSearchResultCleared)
, m_handleSearchResultSectionItemSelectedMessageBinding(this, &InteriorEntityHighlightController::OnSearchItemSelected)
, m_interiorInteractionModelChangedHandler(this, &InteriorEntityHighlightController::OnInteriorChanged)
, m_interiorCellAddedHandler(this, &InteriorEntityHighlightController::OnInteriorAddedToSceneGraph)
, m_availabilityChangedHandlerBinding(this, &InteriorEntityHighlightController::OnAvailabilityChanged)
, m_interiorLabelsBuiltHandler(this, &InteriorEntityHighlightController::OnInteriorLabelsBuilt)
, m_interiorsHighlightService(interiorsHighlightService)
, m_messageBus(messageBus)
, m_hideLabelAlwaysFilter(this, &InteriorEntityHighlightController::HideLabelAlwaysPredicate)
, m_hideLabelByNameFilter(this, &InteriorEntityHighlightController::HideLabelByNamePredicate)
{
m_messageBus.SubscribeUi(m_searchQueryResponseHandler);
m_searchQueryPerformer.InsertOnSearchResultsClearedCallback(m_searchResultsClearedHandler);
m_interiorInteractionModel.RegisterModelChangedCallback(m_interiorInteractionModelChangedHandler);
m_interiorsCellResourceObserver.RegisterAddedToSceneGraphCallback(m_interiorCellAddedHandler);
m_messageBus.SubscribeNative(m_handleSearchResultSectionItemSelectedMessageBinding);
m_labelHiddenFilterModel.SetFilter(m_interiorLabelLayer, &m_hideLabelAlwaysFilter);
}
InteriorEntityHighlightController::~InteriorEntityHighlightController()
{
m_interiorsCellResourceObserver.UnregisterAddedToSceneGraphCallback(m_interiorCellAddedHandler);
m_messageBus.UnsubscribeUi(m_searchQueryResponseHandler);
m_searchQueryPerformer.RemoveOnSearchResultsClearedCallback(m_searchResultsClearedHandler);
m_interiorInteractionModel.UnregisterModelChangedCallback(m_interiorInteractionModelChangedHandler);
m_messageBus.UnsubscribeNative(m_handleSearchResultSectionItemSelectedMessageBinding);
}
void InteriorEntityHighlightController::OnAvailabilityChanged()
{
}
void InteriorEntityHighlightController::RemoveHighlights()
{
m_interiorsHighlightService.ClearAllHighlights();
}
void InteriorEntityHighlightController::ActivateLabels(bool active)
{
m_labelHiddenFilterModel.SetFilter(m_interiorLabelLayer, active ? NULL : &m_hideLabelByNameFilter);
}
void InteriorEntityHighlightController::OnInteriorLabelsBuilt()
{
ApplyHighlightsForCurrentResults();
bool hasResults = m_searchResults.size() > 0;
ActivateLabels(!hasResults);
}
void InteriorEntityHighlightController::OnSearchResultCleared()
{
m_searchResultsIndex = -1;
m_searchResults.clear();
RemoveHighlights();
ApplyHighlightsForCurrentResults();
ActivateLabels(true);
}
void InteriorEntityHighlightController::OnSearchItemSelected(const SearchResultSection::SearchResultSectionItemSelectedMessage& message)
{
if (message.ItemIndex() >= m_searchResults.size())
{
m_searchResultsIndex = -1;
}
else
{
m_searchResultsIndex = message.ItemIndex();
}
ApplyHighlightsForCurrentResults();
}
void InteriorEntityHighlightController::OnInteriorChanged()
{
namespace EegeoInteriors = Eegeo::Resources::Interiors;
namespace EegeoRenderables = Eegeo::Rendering::Renderables;
RemoveHighlights();
m_currentHighlightRenderables.clear();
if (m_interiorInteractionModel.HasInteriorModel())
{
const EegeoInteriors::InteriorsModel& model = *m_interiorInteractionModel.GetInteriorModel();
for (EegeoInteriors::TFloorModelVector::const_iterator floors = model.GetFloors().begin();
floors != model.GetFloors().end();
++floors)
{
const EegeoInteriors::InteriorsFloorCells* floorCells = model.GetFloorCells((*floors)->GetFloorNumber());
for (int cellIndex = 0; cellIndex < floorCells->GetCellCount(); ++cellIndex)
{
const EegeoInteriors::InteriorsFloorCell* cell = floorCells->GetFloorCells()[cellIndex];
std::vector<EegeoRenderables::InteriorHighlightRenderable*> renderables = cell->GetHighlightRenderables();
for (std::vector<EegeoRenderables::InteriorHighlightRenderable*>::iterator renderableIterator = renderables.begin();
renderableIterator != renderables.end();
++renderableIterator)
{
AddHighlight(**renderableIterator);
}
}
}
RemoveHighlights();
bool hasResults = m_searchResults.size() > 0;
ActivateLabels(!hasResults);
}
else
{
RemoveHighlights();
m_currentHighlightRenderables.clear();
}
}
void InteriorEntityHighlightController::OnInteriorAddedToSceneGraph(const Eegeo::Resources::Interiors::InteriorsCellResource& resource)
{
if (m_interiorInteractionModel.HasInteriorModel())
{
const Eegeo::Resources::Interiors::InteriorsModel& model = *m_interiorInteractionModel.GetInteriorModel();
if (model.GetId() == resource.GetInteriorId())
{
OnInteriorChanged();
}
}
}
void InteriorEntityHighlightController::AddHighlight(Eegeo::Rendering::Renderables::InteriorHighlightRenderable& renderable)
{
static const std::string highlightPrefix = "entity_highlight ";
const std::string& id = renderable.GetRenderableId();
if (id.compare(0, highlightPrefix.length(), highlightPrefix) == 0)
{
std::string highlightId = id.substr(highlightPrefix.length());
if (m_currentHighlightRenderables.find(highlightId) == m_currentHighlightRenderables.end())
{
std::vector<Eegeo::Rendering::Renderables::InteriorHighlightRenderable*> highlights;
m_currentHighlightRenderables.insert(std::make_pair(highlightId, highlights));
}
m_currentHighlightRenderables[highlightId].push_back(&renderable);
}
}
void InteriorEntityHighlightController::OnSearchQueryResponseReceived(const Search::SearchQueryResponseReceivedMessage& message)
{
auto results = message.GetResults();
RemoveHighlights();
if (m_searchResultsIndex >= 0)
{
const Search::SdkModel::SearchResultModel& selectedSearchResult = m_searchResults.at(m_searchResultsIndex);
const std::vector<Search::SdkModel::SearchResultModel>& newSearchResults = results;
std::vector<Search::SdkModel::SearchResultModel>::const_iterator iter = std::find(newSearchResults.begin(), newSearchResults.end(), selectedSearchResult);
if (iter == newSearchResults.end())
{
m_searchResultsIndex = -1;
}
else
{
m_searchResultsIndex = static_cast<int>(std::distance(newSearchResults.begin(), iter));
}
}
m_searchResults = results;
ApplyHighlightsForCurrentResults();
bool hasResults = results.size() > 0;
ActivateLabels(!hasResults);
}
std::vector<Search::SdkModel::SearchResultModel> InteriorEntityHighlightController::GetCurrentSearchResults()
{
std::vector<Search::SdkModel::SearchResultModel> results;
results.reserve(m_searchResults.size());
for (int i = 0; i < m_searchResults.size(); i++)
{
Search::SdkModel::SearchResultModel pResult = m_searchResults.at(i);
results.push_back(pResult);
}
return results;
}
void InteriorEntityHighlightController::ApplyHighlightsForCurrentResults()
{
std::vector<Search::SdkModel::SearchResultModel> results = GetCurrentSearchResults();
ApplyHighlights(results);
}
void InteriorEntityHighlightController::HighlightSearchResult(const Search::SdkModel::SearchResultModel &searchResult)
{
if (!searchResult.IsInterior())
{
return;
}
rapidjson::Document json;
std::string highlightedRoomId = "";
std::vector<std::string> filteredEntityIds = GetEntityIdsFromSearchResultModel(searchResult);
std::vector<Eegeo::v4> highlightColors = m_highlightColorMapper.GetColors(searchResult);
if (m_interiorInteractionModel.HasInteriorModel())
{
const std::string& interiorId = m_interiorInteractionModel.GetInteriorModel()->GetId().Value();
m_interiorsHighlightService.SetHighlights(interiorId, filteredEntityIds, highlightColors.front());
}
}
void InteriorEntityHighlightController::ApplyHighlights(const std::vector<Search::SdkModel::SearchResultModel> &results)
{
RemoveHighlights();
if (m_interiorInteractionModel.HasInteriorModel() && m_currentHighlightRenderables.size() == 0)
{
OnInteriorChanged();
}
rapidjson::Document json;
std::string highlightedRoomId = "";
if (m_searchResultsIndex >= 0)
{
const Search::SdkModel::SearchResultModel& resultsItt = m_searchResults.at(m_searchResultsIndex);
HighlightSearchResult(resultsItt);
}
else
{
for (std::vector<Search::SdkModel::SearchResultModel>::const_iterator resultsItt = results.begin(); resultsItt != results.end(); ++resultsItt)
{
HighlightSearchResult(*resultsItt);
}
}
}
bool InteriorEntityHighlightController::HideLabelAlwaysPredicate(const Eegeo::Labels::IAnchoredLabel& anchoredLabel) const
{
return true;
}
bool InteriorEntityHighlightController::HideLabelByNamePredicate(const Eegeo::Labels::IAnchoredLabel& anchoredLabel) const
{
const std::string& labelCategoryName = anchoredLabel.GetLabelAnchorCategory().GetId();
bool shouldHide = labelCategoryName != "interior_facility_escalator"
&& labelCategoryName != "interior_facility_stairs"
&& labelCategoryName != "interior_facility_elevator"
&& labelCategoryName != "interior_facility_toilets";
return shouldHide;
}
}
}
}
}
<commit_msg>Add re-highlight after re-render, buddy Salvador G<commit_after>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved
#include "InteriorEntityHighlightController.h"
#include "ISearchService.h"
#include "ISearchQueryPerformer.h"
#include "ISearchResultRepository.h"
#include "InteriorInteractionModel.h"
#include "InteriorsModel.h"
#include "InteriorsFloorModel.h"
#include "IInteriorsLabelController.h"
#include "VectorMath.h"
#include "InteriorHighlightRenderable.h"
#include "InteriorsLabelParser.h"
#include "InteriorsFloorCells.h"
#include "InteriorsFloorCell.h"
#include "PlaceNameModel.h"
#include "InteriorsCellResource.h"
#include "InteriorsCellResourceObserver.h"
#include "LabelAnchorFilterModel.h"
#include "IAnchoredLabel.h"
#include "document.h"
#include "IInteriorsHighlightService.h"
namespace ExampleApp
{
namespace InteriorsExplorer
{
namespace SdkModel
{
namespace Highlights
{
std::vector<std::string> GetEntityIdsFromJsonArray(const rapidjson::Value& jsonArray)
{
assert(jsonArray.IsArray());
std::vector<std::string> entities;
for (int i = 0; i < jsonArray.Size(); i++)
{
assert(jsonArray[i].IsString());
entities.push_back(jsonArray[i].GetString());
}
return entities;
}
std::vector<std::string> GetEntityIdsFromSearchResultModel(const Search::SdkModel::SearchResultModel& selectedSearchResult)
{
rapidjson::Document json;
std::vector<std::string> entities;
if (!json.Parse<0>(selectedSearchResult.GetJsonData().c_str()).HasParseError())
{
if( json.HasMember("highlight") )
{
const rapidjson::Value& area_highlight = json["highlight"];
if(area_highlight.IsString())
{
entities.push_back(json["highlight"].GetString());
}
else
{
std::vector<std::string> areaHighlights = GetEntityIdsFromJsonArray(area_highlight);
entities.insert(std::end(entities), std::begin(areaHighlights), std::end(areaHighlights));
}
}
if( json.HasMember("entity_highlight") )
{
std::vector<std::string> entityHighlights = GetEntityIdsFromJsonArray(json["entity_highlight"]);
entities.insert(std::end(entities), std::begin(entityHighlights), std::end(entityHighlights));
}
}
return entities;
}
InteriorEntityHighlightController::InteriorEntityHighlightController(Eegeo::Resources::Interiors::InteriorInteractionModel& interiorInteractionModel,
Eegeo::Resources::Interiors::InteriorsCellResourceObserver& interiorsCellResourceObserver,
Search::SdkModel::ISearchService& searchService,
Search::SdkModel::ISearchQueryPerformer& searchQueryPerformer, Eegeo::Resources::Interiors::Entities::IInteriorsLabelController& legacyLabelController,
Eegeo::Labels::ILabelAnchorFilterModel& labelHiddenFilterModel,
const Eegeo::Labels::LabelLayer::IdType interiorLabelLayer,
ExampleAppMessaging::TMessageBus& messageBus,
IHighlightColorMapper& highlightColorMapper,
Eegeo::Resources::Interiors::Highlights::IInteriorsHighlightService& interiorsHighlightService)
: m_interiorInteractionModel(interiorInteractionModel)
, m_interiorsCellResourceObserver(interiorsCellResourceObserver)
, m_interiorLabelLayer(interiorLabelLayer)
, m_labelHiddenFilterModel(labelHiddenFilterModel)
, m_searchQueryPerformer(searchQueryPerformer)
, m_highlightColorMapper(highlightColorMapper)
, m_searchResultsIndex(-1)
, m_searchQueryResponseHandler(this, &InteriorEntityHighlightController::OnSearchQueryResponseReceived)
, m_searchResultsClearedHandler(this, &InteriorEntityHighlightController::OnSearchResultCleared)
, m_handleSearchResultSectionItemSelectedMessageBinding(this, &InteriorEntityHighlightController::OnSearchItemSelected)
, m_interiorInteractionModelChangedHandler(this, &InteriorEntityHighlightController::OnInteriorChanged)
, m_interiorCellAddedHandler(this, &InteriorEntityHighlightController::OnInteriorAddedToSceneGraph)
, m_availabilityChangedHandlerBinding(this, &InteriorEntityHighlightController::OnAvailabilityChanged)
, m_interiorLabelsBuiltHandler(this, &InteriorEntityHighlightController::OnInteriorLabelsBuilt)
, m_interiorsHighlightService(interiorsHighlightService)
, m_messageBus(messageBus)
, m_hideLabelAlwaysFilter(this, &InteriorEntityHighlightController::HideLabelAlwaysPredicate)
, m_hideLabelByNameFilter(this, &InteriorEntityHighlightController::HideLabelByNamePredicate)
{
m_messageBus.SubscribeUi(m_searchQueryResponseHandler);
m_searchQueryPerformer.InsertOnSearchResultsClearedCallback(m_searchResultsClearedHandler);
m_interiorInteractionModel.RegisterModelChangedCallback(m_interiorInteractionModelChangedHandler);
m_interiorsCellResourceObserver.RegisterAddedToSceneGraphCallback(m_interiorCellAddedHandler);
m_messageBus.SubscribeNative(m_handleSearchResultSectionItemSelectedMessageBinding);
m_labelHiddenFilterModel.SetFilter(m_interiorLabelLayer, &m_hideLabelAlwaysFilter);
}
InteriorEntityHighlightController::~InteriorEntityHighlightController()
{
m_interiorsCellResourceObserver.UnregisterAddedToSceneGraphCallback(m_interiorCellAddedHandler);
m_messageBus.UnsubscribeUi(m_searchQueryResponseHandler);
m_searchQueryPerformer.RemoveOnSearchResultsClearedCallback(m_searchResultsClearedHandler);
m_interiorInteractionModel.UnregisterModelChangedCallback(m_interiorInteractionModelChangedHandler);
m_messageBus.UnsubscribeNative(m_handleSearchResultSectionItemSelectedMessageBinding);
}
void InteriorEntityHighlightController::OnAvailabilityChanged()
{
}
void InteriorEntityHighlightController::RemoveHighlights()
{
m_interiorsHighlightService.ClearAllHighlights();
}
void InteriorEntityHighlightController::ActivateLabels(bool active)
{
m_labelHiddenFilterModel.SetFilter(m_interiorLabelLayer, active ? NULL : &m_hideLabelByNameFilter);
}
void InteriorEntityHighlightController::OnInteriorLabelsBuilt()
{
ApplyHighlightsForCurrentResults();
bool hasResults = m_searchResults.size() > 0;
ActivateLabels(!hasResults);
}
void InteriorEntityHighlightController::OnSearchResultCleared()
{
m_searchResultsIndex = -1;
m_searchResults.clear();
RemoveHighlights();
ApplyHighlightsForCurrentResults();
ActivateLabels(true);
}
void InteriorEntityHighlightController::OnSearchItemSelected(const SearchResultSection::SearchResultSectionItemSelectedMessage& message)
{
if (message.ItemIndex() >= m_searchResults.size())
{
m_searchResultsIndex = -1;
}
else
{
m_searchResultsIndex = message.ItemIndex();
}
ApplyHighlightsForCurrentResults();
}
void InteriorEntityHighlightController::OnInteriorChanged()
{
namespace EegeoInteriors = Eegeo::Resources::Interiors;
namespace EegeoRenderables = Eegeo::Rendering::Renderables;
RemoveHighlights();
m_currentHighlightRenderables.clear();
if (m_interiorInteractionModel.HasInteriorModel())
{
const EegeoInteriors::InteriorsModel& model = *m_interiorInteractionModel.GetInteriorModel();
for (EegeoInteriors::TFloorModelVector::const_iterator floors = model.GetFloors().begin();
floors != model.GetFloors().end();
++floors)
{
const EegeoInteriors::InteriorsFloorCells* floorCells = model.GetFloorCells((*floors)->GetFloorNumber());
for (int cellIndex = 0; cellIndex < floorCells->GetCellCount(); ++cellIndex)
{
const EegeoInteriors::InteriorsFloorCell* cell = floorCells->GetFloorCells()[cellIndex];
std::vector<EegeoRenderables::InteriorHighlightRenderable*> renderables = cell->GetHighlightRenderables();
for (std::vector<EegeoRenderables::InteriorHighlightRenderable*>::iterator renderableIterator = renderables.begin();
renderableIterator != renderables.end();
++renderableIterator)
{
AddHighlight(**renderableIterator);
}
}
}
RemoveHighlights();
bool hasResults = m_searchResults.size() > 0;
ActivateLabels(!hasResults);
}
else
{
RemoveHighlights();
m_currentHighlightRenderables.clear();
}
}
void InteriorEntityHighlightController::OnInteriorAddedToSceneGraph(const Eegeo::Resources::Interiors::InteriorsCellResource& resource)
{
if (m_interiorInteractionModel.HasInteriorModel())
{
const Eegeo::Resources::Interiors::InteriorsModel& model = *m_interiorInteractionModel.GetInteriorModel();
if (model.GetId() == resource.GetInteriorId())
{
OnInteriorChanged();
ApplyHighlightsForCurrentResults();
}
}
}
void InteriorEntityHighlightController::AddHighlight(Eegeo::Rendering::Renderables::InteriorHighlightRenderable& renderable)
{
static const std::string highlightPrefix = "entity_highlight ";
const std::string& id = renderable.GetRenderableId();
if (id.compare(0, highlightPrefix.length(), highlightPrefix) == 0)
{
std::string highlightId = id.substr(highlightPrefix.length());
if (m_currentHighlightRenderables.find(highlightId) == m_currentHighlightRenderables.end())
{
std::vector<Eegeo::Rendering::Renderables::InteriorHighlightRenderable*> highlights;
m_currentHighlightRenderables.insert(std::make_pair(highlightId, highlights));
}
m_currentHighlightRenderables[highlightId].push_back(&renderable);
}
}
void InteriorEntityHighlightController::OnSearchQueryResponseReceived(const Search::SearchQueryResponseReceivedMessage& message)
{
auto results = message.GetResults();
RemoveHighlights();
if (m_searchResultsIndex >= 0)
{
const Search::SdkModel::SearchResultModel& selectedSearchResult = m_searchResults.at(m_searchResultsIndex);
const std::vector<Search::SdkModel::SearchResultModel>& newSearchResults = results;
std::vector<Search::SdkModel::SearchResultModel>::const_iterator iter = std::find(newSearchResults.begin(), newSearchResults.end(), selectedSearchResult);
if (iter == newSearchResults.end())
{
m_searchResultsIndex = -1;
}
else
{
m_searchResultsIndex = static_cast<int>(std::distance(newSearchResults.begin(), iter));
}
}
m_searchResults = results;
ApplyHighlightsForCurrentResults();
bool hasResults = results.size() > 0;
ActivateLabels(!hasResults);
}
std::vector<Search::SdkModel::SearchResultModel> InteriorEntityHighlightController::GetCurrentSearchResults()
{
std::vector<Search::SdkModel::SearchResultModel> results;
results.reserve(m_searchResults.size());
for (int i = 0; i < m_searchResults.size(); i++)
{
Search::SdkModel::SearchResultModel pResult = m_searchResults.at(i);
results.push_back(pResult);
}
return results;
}
void InteriorEntityHighlightController::ApplyHighlightsForCurrentResults()
{
std::vector<Search::SdkModel::SearchResultModel> results = GetCurrentSearchResults();
ApplyHighlights(results);
}
void InteriorEntityHighlightController::HighlightSearchResult(const Search::SdkModel::SearchResultModel &searchResult)
{
if (!searchResult.IsInterior())
{
return;
}
rapidjson::Document json;
std::string highlightedRoomId = "";
std::vector<std::string> filteredEntityIds = GetEntityIdsFromSearchResultModel(searchResult);
std::vector<Eegeo::v4> highlightColors = m_highlightColorMapper.GetColors(searchResult);
if (m_interiorInteractionModel.HasInteriorModel())
{
const std::string& interiorId = m_interiorInteractionModel.GetInteriorModel()->GetId().Value();
m_interiorsHighlightService.SetHighlights(interiorId, filteredEntityIds, highlightColors.front());
}
}
void InteriorEntityHighlightController::ApplyHighlights(const std::vector<Search::SdkModel::SearchResultModel> &results)
{
RemoveHighlights();
if (m_interiorInteractionModel.HasInteriorModel() && m_currentHighlightRenderables.size() == 0)
{
OnInteriorChanged();
}
rapidjson::Document json;
std::string highlightedRoomId = "";
if (m_searchResultsIndex >= 0)
{
const Search::SdkModel::SearchResultModel& resultsItt = m_searchResults.at(m_searchResultsIndex);
HighlightSearchResult(resultsItt);
}
else
{
for (std::vector<Search::SdkModel::SearchResultModel>::const_iterator resultsItt = results.begin(); resultsItt != results.end(); ++resultsItt)
{
HighlightSearchResult(*resultsItt);
}
}
}
bool InteriorEntityHighlightController::HideLabelAlwaysPredicate(const Eegeo::Labels::IAnchoredLabel& anchoredLabel) const
{
return true;
}
bool InteriorEntityHighlightController::HideLabelByNamePredicate(const Eegeo::Labels::IAnchoredLabel& anchoredLabel) const
{
const std::string& labelCategoryName = anchoredLabel.GetLabelAnchorCategory().GetId();
bool shouldHide = labelCategoryName != "interior_facility_escalator"
&& labelCategoryName != "interior_facility_stairs"
&& labelCategoryName != "interior_facility_elevator"
&& labelCategoryName != "interior_facility_toilets";
return shouldHide;
}
}
}
}
}
<|endoftext|> |
<commit_before>/***************************************************************************
knnntpaccount.cpp - description
-------------------
copyright : (C) 2000 by Christian Thurner
email : cthurner@freepage.de
***************************************************************************/
/***************************************************************************
* *
* This program 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 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include <ksimpleconfig.h>
#include <kstddirs.h>
#include "utilities.h"
#include "knnntpaccount.h"
KNNntpAccount::KNNntpAccount()
: KNCollection(0), KNServerInfo(), u_nsentCount(0), f_etchDescriptions(true)
{
l_astNewFetch = QDate::currentDate();
}
KNNntpAccount::~KNNntpAccount()
{
}
// trys to read information, returns false if it fails to do so
bool KNNntpAccount::readInfo(const QString &confPath)
{
KSimpleConfig conf(confPath);
n_ame = conf.readEntry("name");
u_nsentCount = conf.readNumEntry("unsentCnt", 0);
f_etchDescriptions = conf.readBoolEntry("fetchDescriptions", true);
l_astNewFetch = conf.readDateTimeEntry("lastNewFetch").date();
KNServerInfo::readConf(&conf);
return true;
if (n_ame.isEmpty() || s_erver.isEmpty() || i_d == -1)
return false;
else
return true;
}
void KNNntpAccount::saveInfo()
{
QString dir(path());
if (dir == QString::null)
return;
KSimpleConfig conf(dir+"info");
conf.writeEntry("name", n_ame);
conf.writeEntry("unsentCnt", u_nsentCount);
conf.writeEntry("fetchDescriptions", f_etchDescriptions);
conf.writeEntry("lastNewFetch", QDateTime(l_astNewFetch));
KNServerInfo::saveConf(&conf); // save not KNNntpAccount specific settings
}
void KNNntpAccount::syncInfo()
{
QString dir(path());
if (dir == QString::null)
return;
KSimpleConfig conf(dir+"info");
conf.writeEntry("unsentCnt", u_nsentCount);
}
QString KNNntpAccount::path()
{
QString dir(KGlobal::dirs()->saveLocation("appdata",QString("nntp.%1/").arg(i_d)));
if (dir==QString::null)
displayInternalFileError();
return (dir);
}
<commit_msg>arghhh, my fault, I comitted this in june. should fix the "ghost" accounts (#8846)<commit_after>/***************************************************************************
knnntpaccount.cpp - description
-------------------
copyright : (C) 2000 by Christian Thurner
email : cthurner@freepage.de
***************************************************************************/
/***************************************************************************
* *
* This program 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 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include <ksimpleconfig.h>
#include <kstddirs.h>
#include "utilities.h"
#include "knnntpaccount.h"
KNNntpAccount::KNNntpAccount()
: KNCollection(0), KNServerInfo(), u_nsentCount(0), f_etchDescriptions(true)
{
l_astNewFetch = QDate::currentDate();
}
KNNntpAccount::~KNNntpAccount()
{
}
// trys to read information, returns false if it fails to do so
bool KNNntpAccount::readInfo(const QString &confPath)
{
KSimpleConfig conf(confPath);
n_ame = conf.readEntry("name");
u_nsentCount = conf.readNumEntry("unsentCnt", 0);
f_etchDescriptions = conf.readBoolEntry("fetchDescriptions", true);
l_astNewFetch = conf.readDateTimeEntry("lastNewFetch").date();
KNServerInfo::readConf(&conf);
if (n_ame.isEmpty() || s_erver.isEmpty() || i_d == -1)
return false;
else
return true;
}
void KNNntpAccount::saveInfo()
{
QString dir(path());
if (dir == QString::null)
return;
KSimpleConfig conf(dir+"info");
conf.writeEntry("name", n_ame);
conf.writeEntry("unsentCnt", u_nsentCount);
conf.writeEntry("fetchDescriptions", f_etchDescriptions);
conf.writeEntry("lastNewFetch", QDateTime(l_astNewFetch));
KNServerInfo::saveConf(&conf); // save not KNNntpAccount specific settings
}
void KNNntpAccount::syncInfo()
{
QString dir(path());
if (dir == QString::null)
return;
KSimpleConfig conf(dir+"info");
conf.writeEntry("unsentCnt", u_nsentCount);
}
QString KNNntpAccount::path()
{
QString dir(KGlobal::dirs()->saveLocation("appdata",QString("nntp.%1/").arg(i_d)));
if (dir==QString::null)
displayInternalFileError();
return (dir);
}
<|endoftext|> |
<commit_before><commit_msg>Update BinaryTree.cpp<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/audio/mac/audio_low_latency_output_mac.h"
#include <CoreServices/CoreServices.h>
#include "base/basictypes.h"
#include "base/logging.h"
#include "media/audio/audio_util.h"
#include "media/audio/mac/audio_manager_mac.h"
using media::SwizzleCoreAudioLayout5_1;
// Overview of operation:
// 1) An object of AUAudioOutputStream is created by the AudioManager
// factory: audio_man->MakeAudioStream().
// 2) Next some thread will call Open(), at that point the underlying
// default output Audio Unit is created and configured.
// 3) Then some thread will call Start(source).
// Then the Audio Unit is started which creates its own thread which
// periodically will call the source for more data as buffers are being
// consumed.
// 4) At some point some thread will call Stop(), which we handle by directly
// stopping the default output Audio Unit.
// 6) The same thread that called stop will call Close() where we cleanup
// and notify the audio manager, which likely will destroy this object.
AUAudioOutputStream::AUAudioOutputStream(
AudioManagerMac* manager, AudioParameters params)
: manager_(manager),
source_(NULL),
output_unit_(0),
volume_(1) {
// We must have a manager.
DCHECK(manager_);
// A frame is one sample across all channels. In interleaved audio the per
// frame fields identify the set of n |channels|. In uncompressed audio, a
// packet is always one frame.
format_.mSampleRate = params.sample_rate;
format_.mFormatID = kAudioFormatLinearPCM;
format_.mFormatFlags = kLinearPCMFormatFlagIsPacked |
kLinearPCMFormatFlagIsSignedInteger;
format_.mBitsPerChannel = params.bits_per_sample;
format_.mChannelsPerFrame = params.channels;
format_.mFramesPerPacket = 1;
format_.mBytesPerPacket = (format_.mBitsPerChannel * params.channels) / 8;
format_.mBytesPerFrame = format_.mBytesPerPacket;
// Calculate the number of sample frames per callback.
number_of_frames_ = params.GetPacketSize() / format_.mBytesPerPacket;
}
AUAudioOutputStream::~AUAudioOutputStream() {
}
bool AUAudioOutputStream::Open() {
// Open and initialize the DefaultOutputUnit.
Component comp;
ComponentDescription desc;
desc.componentType = kAudioUnitType_Output;
desc.componentSubType = kAudioUnitSubType_DefaultOutput;
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
comp = FindNextComponent(0, &desc);
DCHECK(comp);
OSStatus result = OpenAComponent(comp, &output_unit_);
DCHECK_EQ(result, 0);
if (result)
return false;
result = AudioUnitInitialize(output_unit_);
DCHECK_EQ(result, 0);
if (result)
return false;
return Configure();
}
bool AUAudioOutputStream::Configure() {
// Set the render callback.
AURenderCallbackStruct input;
input.inputProc = InputProc;
input.inputProcRefCon = this;
OSStatus result = AudioUnitSetProperty(
output_unit_,
kAudioUnitProperty_SetRenderCallback,
kAudioUnitScope_Global,
0,
&input,
sizeof(input));
DCHECK_EQ(result, 0);
if (result)
return false;
// Set the stream format.
result = AudioUnitSetProperty(
output_unit_,
kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Input,
0,
&format_,
sizeof(format_));
DCHECK_EQ(result, 0);
if (result)
return false;
// Set the buffer frame size.
UInt32 buffer_size = number_of_frames_;
result = AudioUnitSetProperty(
output_unit_,
kAudioDevicePropertyBufferFrameSize,
kAudioUnitScope_Output,
0,
&buffer_size,
sizeof(buffer_size));
DCHECK_EQ(result, 0);
if (result)
return false;
return true;
}
void AUAudioOutputStream::Close() {
if (output_unit_)
CloseComponent(output_unit_);
// Inform the audio manager that we have been closed. This can cause our
// destruction.
manager_->ReleaseOutputStream(this);
}
void AUAudioOutputStream::Start(AudioSourceCallback* callback) {
DCHECK(callback);
source_ = callback;
AudioOutputUnitStart(output_unit_);
}
void AUAudioOutputStream::Stop() {
// We request a synchronous stop, so the next call can take some time. In
// the windows implementation we block here as well.
source_ = NULL;
AudioOutputUnitStop(output_unit_);
}
void AUAudioOutputStream::SetVolume(double volume) {
if (!output_unit_)
return;
volume_ = static_cast<float>(volume);
// TODO(crogers): set volume property
}
void AUAudioOutputStream::GetVolume(double* volume) {
if (!output_unit_)
return;
*volume = volume_;
}
// Pulls on our provider to get rendered audio stream.
// Note to future hackers of this function: Do not add locks here because this
// is running on a real-time thread (for low-latency).
OSStatus AUAudioOutputStream::Render(UInt32 number_of_frames,
AudioBufferList* io_data) {
AudioBuffer& buffer = io_data->mBuffers[0];
uint8* audio_data = reinterpret_cast<uint8*>(buffer.mData);
uint32 filled = source_->OnMoreData(
this, audio_data, buffer.mDataByteSize, AudioBuffersState(0, 0));
// Handle channel order for 5.1 audio.
if (format_.mChannelsPerFrame == 6) {
if (format_.mBitsPerChannel == 8) {
SwizzleCoreAudioLayout5_1(reinterpret_cast<uint8*>(audio_data), filled);
} else if (format_.mBitsPerChannel == 16) {
SwizzleCoreAudioLayout5_1(reinterpret_cast<int16*>(audio_data), filled);
} else if (format_.mBitsPerChannel == 32) {
SwizzleCoreAudioLayout5_1(reinterpret_cast<int32*>(audio_data), filled);
}
}
return noErr;
}
// DefaultOutputUnit callback
OSStatus AUAudioOutputStream::InputProc(void* user_data,
AudioUnitRenderActionFlags*,
const AudioTimeStamp*,
UInt32,
UInt32 number_of_frames,
AudioBufferList* io_data) {
AUAudioOutputStream* audio_output =
static_cast<AUAudioOutputStream*>(user_data);
DCHECK(audio_output);
if (!audio_output)
return -1;
return audio_output->Render(number_of_frames, io_data);
}
double AUAudioOutputStream::HardwareSampleRate() {
// Determine the default output device's sample-rate.
AudioDeviceID device_id = kAudioDeviceUnknown;
UInt32 info_size = sizeof(device_id);
AudioObjectPropertyAddress default_input_device_address = {
kAudioHardwarePropertyDefaultInputDevice,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
OSStatus result = AudioObjectGetPropertyData(kAudioObjectSystemObject,
&default_input_device_address,
0,
0,
&info_size,
&device_id);
DCHECK_EQ(result, 0);
if (result)
return 0.0; // error
Float64 nominal_sample_rate;
info_size = sizeof(nominal_sample_rate);
AudioObjectPropertyAddress nominal_sample_rate_address = {
kAudioDevicePropertyNominalSampleRate,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
result = AudioObjectGetPropertyData(device_id,
&nominal_sample_rate_address,
0,
0,
&info_size,
&nominal_sample_rate);
DCHECK_EQ(result, 0);
if (result)
return 0.0; // error
return nominal_sample_rate;
}
<commit_msg>Use default "output" rather than "input" device when querying hardware sample-rate BUG=none TEST=none (tested locally on Mac OS X to verify that hardware sample-rate is correctly retrieved) Review URL: http://codereview.chromium.org/6721001<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/audio/mac/audio_low_latency_output_mac.h"
#include <CoreServices/CoreServices.h>
#include "base/basictypes.h"
#include "base/logging.h"
#include "media/audio/audio_util.h"
#include "media/audio/mac/audio_manager_mac.h"
using media::SwizzleCoreAudioLayout5_1;
// Overview of operation:
// 1) An object of AUAudioOutputStream is created by the AudioManager
// factory: audio_man->MakeAudioStream().
// 2) Next some thread will call Open(), at that point the underlying
// default output Audio Unit is created and configured.
// 3) Then some thread will call Start(source).
// Then the Audio Unit is started which creates its own thread which
// periodically will call the source for more data as buffers are being
// consumed.
// 4) At some point some thread will call Stop(), which we handle by directly
// stopping the default output Audio Unit.
// 6) The same thread that called stop will call Close() where we cleanup
// and notify the audio manager, which likely will destroy this object.
AUAudioOutputStream::AUAudioOutputStream(
AudioManagerMac* manager, AudioParameters params)
: manager_(manager),
source_(NULL),
output_unit_(0),
volume_(1) {
// We must have a manager.
DCHECK(manager_);
// A frame is one sample across all channels. In interleaved audio the per
// frame fields identify the set of n |channels|. In uncompressed audio, a
// packet is always one frame.
format_.mSampleRate = params.sample_rate;
format_.mFormatID = kAudioFormatLinearPCM;
format_.mFormatFlags = kLinearPCMFormatFlagIsPacked |
kLinearPCMFormatFlagIsSignedInteger;
format_.mBitsPerChannel = params.bits_per_sample;
format_.mChannelsPerFrame = params.channels;
format_.mFramesPerPacket = 1;
format_.mBytesPerPacket = (format_.mBitsPerChannel * params.channels) / 8;
format_.mBytesPerFrame = format_.mBytesPerPacket;
// Calculate the number of sample frames per callback.
number_of_frames_ = params.GetPacketSize() / format_.mBytesPerPacket;
}
AUAudioOutputStream::~AUAudioOutputStream() {
}
bool AUAudioOutputStream::Open() {
// Open and initialize the DefaultOutputUnit.
Component comp;
ComponentDescription desc;
desc.componentType = kAudioUnitType_Output;
desc.componentSubType = kAudioUnitSubType_DefaultOutput;
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
comp = FindNextComponent(0, &desc);
DCHECK(comp);
OSStatus result = OpenAComponent(comp, &output_unit_);
DCHECK_EQ(result, 0);
if (result)
return false;
result = AudioUnitInitialize(output_unit_);
DCHECK_EQ(result, 0);
if (result)
return false;
return Configure();
}
bool AUAudioOutputStream::Configure() {
// Set the render callback.
AURenderCallbackStruct input;
input.inputProc = InputProc;
input.inputProcRefCon = this;
OSStatus result = AudioUnitSetProperty(
output_unit_,
kAudioUnitProperty_SetRenderCallback,
kAudioUnitScope_Global,
0,
&input,
sizeof(input));
DCHECK_EQ(result, 0);
if (result)
return false;
// Set the stream format.
result = AudioUnitSetProperty(
output_unit_,
kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Input,
0,
&format_,
sizeof(format_));
DCHECK_EQ(result, 0);
if (result)
return false;
// Set the buffer frame size.
UInt32 buffer_size = number_of_frames_;
result = AudioUnitSetProperty(
output_unit_,
kAudioDevicePropertyBufferFrameSize,
kAudioUnitScope_Output,
0,
&buffer_size,
sizeof(buffer_size));
DCHECK_EQ(result, 0);
if (result)
return false;
return true;
}
void AUAudioOutputStream::Close() {
if (output_unit_)
CloseComponent(output_unit_);
// Inform the audio manager that we have been closed. This can cause our
// destruction.
manager_->ReleaseOutputStream(this);
}
void AUAudioOutputStream::Start(AudioSourceCallback* callback) {
DCHECK(callback);
source_ = callback;
AudioOutputUnitStart(output_unit_);
}
void AUAudioOutputStream::Stop() {
// We request a synchronous stop, so the next call can take some time. In
// the windows implementation we block here as well.
source_ = NULL;
AudioOutputUnitStop(output_unit_);
}
void AUAudioOutputStream::SetVolume(double volume) {
if (!output_unit_)
return;
volume_ = static_cast<float>(volume);
// TODO(crogers): set volume property
}
void AUAudioOutputStream::GetVolume(double* volume) {
if (!output_unit_)
return;
*volume = volume_;
}
// Pulls on our provider to get rendered audio stream.
// Note to future hackers of this function: Do not add locks here because this
// is running on a real-time thread (for low-latency).
OSStatus AUAudioOutputStream::Render(UInt32 number_of_frames,
AudioBufferList* io_data) {
AudioBuffer& buffer = io_data->mBuffers[0];
uint8* audio_data = reinterpret_cast<uint8*>(buffer.mData);
uint32 filled = source_->OnMoreData(
this, audio_data, buffer.mDataByteSize, AudioBuffersState(0, 0));
// Handle channel order for 5.1 audio.
if (format_.mChannelsPerFrame == 6) {
if (format_.mBitsPerChannel == 8) {
SwizzleCoreAudioLayout5_1(reinterpret_cast<uint8*>(audio_data), filled);
} else if (format_.mBitsPerChannel == 16) {
SwizzleCoreAudioLayout5_1(reinterpret_cast<int16*>(audio_data), filled);
} else if (format_.mBitsPerChannel == 32) {
SwizzleCoreAudioLayout5_1(reinterpret_cast<int32*>(audio_data), filled);
}
}
return noErr;
}
// DefaultOutputUnit callback
OSStatus AUAudioOutputStream::InputProc(void* user_data,
AudioUnitRenderActionFlags*,
const AudioTimeStamp*,
UInt32,
UInt32 number_of_frames,
AudioBufferList* io_data) {
AUAudioOutputStream* audio_output =
static_cast<AUAudioOutputStream*>(user_data);
DCHECK(audio_output);
if (!audio_output)
return -1;
return audio_output->Render(number_of_frames, io_data);
}
double AUAudioOutputStream::HardwareSampleRate() {
// Determine the default output device's sample-rate.
AudioDeviceID device_id = kAudioDeviceUnknown;
UInt32 info_size = sizeof(device_id);
AudioObjectPropertyAddress default_output_device_address = {
kAudioHardwarePropertyDefaultOutputDevice,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
OSStatus result = AudioObjectGetPropertyData(kAudioObjectSystemObject,
&default_output_device_address,
0,
0,
&info_size,
&device_id);
DCHECK_EQ(result, 0);
if (result)
return 0.0; // error
Float64 nominal_sample_rate;
info_size = sizeof(nominal_sample_rate);
AudioObjectPropertyAddress nominal_sample_rate_address = {
kAudioDevicePropertyNominalSampleRate,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
result = AudioObjectGetPropertyData(device_id,
&nominal_sample_rate_address,
0,
0,
&info_size,
&nominal_sample_rate);
DCHECK_EQ(result, 0);
if (result)
return 0.0; // error
return nominal_sample_rate;
}
<|endoftext|> |
<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** 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 the ETH Zurich 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 "CppExporter.h"
#include "OOModel/src/declarations/Project.h"
#include "Export/src/writer/Exporter.h"
#include "Export/src/writer/FragmentLayouter.h"
#include "Export/src/tree/CompositeFragment.h"
#include "ModelBase/src/model/TreeManager.h"
#include "../CodeUnit.h"
#include "../CodeComposite.h"
#include "../Config.h"
namespace CppExport {
QList<Export::ExportError> CppExporter::exportTree(Model::TreeManager* treeManager,
const QString& pathToProjectContainerDirectory)
{
QList<CodeUnit*> codeUnits;
units(treeManager->root(), "", codeUnits);
QList<CodeUnitPart*> allHeaderParts;
for (auto unit : codeUnits)
{
unit->calculateSourceFragments();
allHeaderParts.append(unit->headerPart());
}
for (auto unit : codeUnits) unit->calculateDependencies(allHeaderParts);
auto directory = new Export::SourceDir(nullptr, pathToProjectContainerDirectory + "/src");
for (auto codeComposite : mergeUnits(codeUnits))
{
codeComposite->sortUnits();
createFileFromFragment(directory, codeComposite->name() + ".h", codeComposite->headerFragment());
createFileFromFragment(directory, codeComposite->name() + ".h", addPragmaOnce(codeComposite->headerFragment()));
createFileFromFragment(directory, codeComposite->name() + ".cpp", codeComposite->sourceFragment());
}
auto layout = layouter();
Export::Exporter::exportToFileSystem("", directory, &layout);
return {};
}
void CppExporter::createFileFromFragment(Export::SourceDir* directory, const QString& fileName,
Export::SourceFragment* sourceFragment)
{
auto file = &directory->file(fileName);
file->append(sourceFragment);
}
void CppExporter::units(Model::Node* current, QString namespaceName, QList<CodeUnit*>& result)
{
if (auto ooModule = DCast<OOModel::Module>(current))
{
if (ooModule->classes()->size() > 0)
namespaceName = ooModule->name();
else
{
// macro file
// TODO: handle non class units
//result.append(new CodeUnit((namespaceName.isEmpty() ? "" : namespaceName + "/") + ooModule->name(), current));
return;
}
}
else if (auto ooClass = DCast<OOModel::Class>(current))
{
result.append(new CodeUnit((namespaceName.isEmpty() ? "" : namespaceName + "/") + ooClass->name(), current));
return;
}
for (auto child : current->children())
units(child, namespaceName, result);
}
QList<CodeComposite*> CppExporter::mergeUnits(QList<CodeUnit*>& units)
{
QHash<QString, QString> mergeMap = Config::instance().dependencyUnitMergeMap();
QHash<QString, CodeComposite*> nameToCompositeMap;
for (auto unit : units)
{
auto it = mergeMap.find(unit->name());
auto compositeName = it != mergeMap.end() ? *it : unit->name();
auto cIt = nameToCompositeMap.find(compositeName);
if (cIt != nameToCompositeMap.end())
// case A: the composite that unit is a part of already exists => merge
(*cIt)->addUnit(unit);
else
{
// case B: the composite that unit is a part of does not yet exist
auto composite = new CodeComposite(compositeName);
composite->addUnit(unit);
nameToCompositeMap.insert(composite->name(), composite);
}
}
return nameToCompositeMap.values();
}
Export::FragmentLayouter CppExporter::layouter()
{
auto result = Export::FragmentLayouter{"\t"};
result.addRule("enumerators", Export::FragmentLayouter::SpaceAfterSeparator, "", ",", "");
result.addRule("vertical", Export::FragmentLayouter::NoIndentation, "", "\n", "");
result.addRule("sections", Export::FragmentLayouter::NoIndentation, "", "\n", "");
result.addRule("spacedSections", Export::FragmentLayouter::NoIndentation, "", "\n\n", "");
result.addRule("accessorSections", Export::FragmentLayouter::IndentChildFragments, "", "\n", "");
result.addRule("bodySections", Export::FragmentLayouter::NewLineBefore
| Export::FragmentLayouter::IndentChildFragments | Export::FragmentLayouter::NewLineAfterPrefix
| Export::FragmentLayouter::NewLineBeforePostfix, "{", "\n", "}");
result.addRule("space", Export::FragmentLayouter::SpaceAtEnd, "", " ", "");
result.addRule("comma", Export::FragmentLayouter::SpaceAfterSeparator, "", ",", "");
result.addRule("baseClasses", Export::FragmentLayouter::SpaceAfterSeparator, " : public ", ",", "");
result.addRule("initializerList", Export::FragmentLayouter::SpaceAfterSeparator, "{", ",", "}");
result.addRule("argsList", Export::FragmentLayouter::SpaceAfterSeparator, "(", ",", ")");
result.addRule("typeArgsList", Export::FragmentLayouter::SpaceAfterSeparator, "<", ",", ">");
result.addRule("templateArgsList", Export::FragmentLayouter::SpaceAfterSeparator
| Export::FragmentLayouter::NewLineAfterPostfix, "template<", ",", ">");
result.addRule("body", Export::FragmentLayouter::NewLineBefore | Export::FragmentLayouter::IndentChildFragments
| Export::FragmentLayouter::NewLineAfterPrefix | Export::FragmentLayouter::NewLineBeforePostfix,
"{", "\n", "}");
return result;
}
Export::ExportMapContainer& CppExporter::exportMaps()
{
static Export::ExportMapContainer* container = new Export::ExportMapContainer();
return *container;
}
}
<commit_msg>remove extra code<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** 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 the ETH Zurich 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 "CppExporter.h"
#include "OOModel/src/declarations/Project.h"
#include "Export/src/writer/Exporter.h"
#include "Export/src/writer/FragmentLayouter.h"
#include "Export/src/tree/CompositeFragment.h"
#include "ModelBase/src/model/TreeManager.h"
#include "../CodeUnit.h"
#include "../CodeComposite.h"
#include "../Config.h"
namespace CppExport {
QList<Export::ExportError> CppExporter::exportTree(Model::TreeManager* treeManager,
const QString& pathToProjectContainerDirectory)
{
QList<CodeUnit*> codeUnits;
units(treeManager->root(), "", codeUnits);
QList<CodeUnitPart*> allHeaderParts;
for (auto unit : codeUnits)
{
unit->calculateSourceFragments();
allHeaderParts.append(unit->headerPart());
}
for (auto unit : codeUnits) unit->calculateDependencies(allHeaderParts);
auto directory = new Export::SourceDir(nullptr, pathToProjectContainerDirectory + "/src");
for (auto codeComposite : mergeUnits(codeUnits))
{
codeComposite->sortUnits();
createFileFromFragment(directory, codeComposite->name() + ".h", codeComposite->headerFragment());
createFileFromFragment(directory, codeComposite->name() + ".cpp", codeComposite->sourceFragment());
}
auto layout = layouter();
Export::Exporter::exportToFileSystem("", directory, &layout);
return {};
}
void CppExporter::createFileFromFragment(Export::SourceDir* directory, const QString& fileName,
Export::SourceFragment* sourceFragment)
{
auto file = &directory->file(fileName);
file->append(sourceFragment);
}
void CppExporter::units(Model::Node* current, QString namespaceName, QList<CodeUnit*>& result)
{
if (auto ooModule = DCast<OOModel::Module>(current))
{
if (ooModule->classes()->size() > 0)
namespaceName = ooModule->name();
else
{
// macro file
// TODO: handle non class units
//result.append(new CodeUnit((namespaceName.isEmpty() ? "" : namespaceName + "/") + ooModule->name(), current));
return;
}
}
else if (auto ooClass = DCast<OOModel::Class>(current))
{
result.append(new CodeUnit((namespaceName.isEmpty() ? "" : namespaceName + "/") + ooClass->name(), current));
return;
}
for (auto child : current->children())
units(child, namespaceName, result);
}
QList<CodeComposite*> CppExporter::mergeUnits(QList<CodeUnit*>& units)
{
QHash<QString, QString> mergeMap = Config::instance().dependencyUnitMergeMap();
QHash<QString, CodeComposite*> nameToCompositeMap;
for (auto unit : units)
{
auto it = mergeMap.find(unit->name());
auto compositeName = it != mergeMap.end() ? *it : unit->name();
auto cIt = nameToCompositeMap.find(compositeName);
if (cIt != nameToCompositeMap.end())
// case A: the composite that unit is a part of already exists => merge
(*cIt)->addUnit(unit);
else
{
// case B: the composite that unit is a part of does not yet exist
auto composite = new CodeComposite(compositeName);
composite->addUnit(unit);
nameToCompositeMap.insert(composite->name(), composite);
}
}
return nameToCompositeMap.values();
}
Export::FragmentLayouter CppExporter::layouter()
{
auto result = Export::FragmentLayouter{"\t"};
result.addRule("enumerators", Export::FragmentLayouter::SpaceAfterSeparator, "", ",", "");
result.addRule("vertical", Export::FragmentLayouter::NoIndentation, "", "\n", "");
result.addRule("sections", Export::FragmentLayouter::NoIndentation, "", "\n", "");
result.addRule("spacedSections", Export::FragmentLayouter::NoIndentation, "", "\n\n", "");
result.addRule("accessorSections", Export::FragmentLayouter::IndentChildFragments, "", "\n", "");
result.addRule("bodySections", Export::FragmentLayouter::NewLineBefore
| Export::FragmentLayouter::IndentChildFragments | Export::FragmentLayouter::NewLineAfterPrefix
| Export::FragmentLayouter::NewLineBeforePostfix, "{", "\n", "}");
result.addRule("space", Export::FragmentLayouter::SpaceAtEnd, "", " ", "");
result.addRule("comma", Export::FragmentLayouter::SpaceAfterSeparator, "", ",", "");
result.addRule("baseClasses", Export::FragmentLayouter::SpaceAfterSeparator, " : public ", ",", "");
result.addRule("initializerList", Export::FragmentLayouter::SpaceAfterSeparator, "{", ",", "}");
result.addRule("argsList", Export::FragmentLayouter::SpaceAfterSeparator, "(", ",", ")");
result.addRule("typeArgsList", Export::FragmentLayouter::SpaceAfterSeparator, "<", ",", ">");
result.addRule("templateArgsList", Export::FragmentLayouter::SpaceAfterSeparator
| Export::FragmentLayouter::NewLineAfterPostfix, "template<", ",", ">");
result.addRule("body", Export::FragmentLayouter::NewLineBefore | Export::FragmentLayouter::IndentChildFragments
| Export::FragmentLayouter::NewLineAfterPrefix | Export::FragmentLayouter::NewLineBeforePostfix,
"{", "\n", "}");
return result;
}
Export::ExportMapContainer& CppExporter::exportMaps()
{
static Export::ExportMapContainer* container = new Export::ExportMapContainer();
return *container;
}
}
<|endoftext|> |
<commit_before>/*
kimifaceimpl.cpp - Kopete DCOP Interface
Copyright (c) 2004 by Will Stephenson <lists@stevello.free-online.co.uk>
Kopete (c) 2002-2004 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program 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 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <qstringlist.h>
#include <dcopclient.h>
#include <kapplication.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kplugininfo.h>
#include "kopeteaccount.h"
#include "kopeteaccountmanager.h"
#include "kopetecontactlist.h"
#include "kopetemetacontact.h"
#include "kopeteprotocol.h"
#include "kopetepluginmanager.h"
#include "kimifaceimpl.h"
KIMIfaceImpl::KIMIfaceImpl() : QObject(), DCOPObject( "KIMIface" )
{
connect( KopeteContactList::contactList(),
SIGNAL( metaContactAdded( KopeteMetaContact * ) ),
SLOT( slotMetaContactAdded( KopeteMetaContact * ) ) );
}
KIMIfaceImpl::~KIMIfaceImpl()
{
}
QStringList KIMIfaceImpl::allContacts()
{
QStringList result;
QPtrList<KopeteMetaContact> list = KopeteContactList::contactList()->metaContacts();
QPtrListIterator<KopeteMetaContact> it( list );
for( ; it.current(); ++it )
{
if ( !it.current()->metaContactId().isNull() )
result.append( it.current()->metaContactId() );
}
return result;
}
QStringList KIMIfaceImpl::reachableContacts()
{
QStringList result;
QPtrList<KopeteMetaContact> list = KopeteContactList::contactList()->metaContacts();
QPtrListIterator<KopeteMetaContact> it( list );
for( ; it.current(); ++it )
{
if ( it.current()->isReachable() && !it.current()->metaContactId().isNull() )
result.append( it.current()->metaContactId() );
}
return result;
}
QStringList KIMIfaceImpl::onlineContacts()
{
QStringList result;
QPtrList<KopeteMetaContact> list = KopeteContactList::contactList()->metaContacts();
QPtrListIterator<KopeteMetaContact> it( list );
for( ; it.current(); ++it )
{
if ( it.current()->isOnline() && !it.current()->metaContactId().isNull() )
result.append( it.current()->metaContactId() );
}
return result;
}
QStringList KIMIfaceImpl::fileTransferContacts()
{
QStringList result;
QPtrList<KopeteMetaContact> list = KopeteContactList::contactList()->metaContacts();
QPtrListIterator<KopeteMetaContact> it( list );
for( ; it.current(); ++it )
{
if ( it.current()->canAcceptFiles() && !it.current()->metaContactId().isNull() )
result.append( it.current()->metaContactId() );
}
return result;
}
bool KIMIfaceImpl::isPresent( const QString & uid )
{
KopeteMetaContact *mc;
mc = KopeteContactList::contactList()->metaContact( uid );
return ( mc != 0 );
}
int KIMIfaceImpl::presenceStatus( const QString & uid )
{
int p = -1;
KopeteMetaContact *m = KopeteContactList::contactList()->metaContact( uid );
if ( m )
{
KopeteOnlineStatus status = m->status();
switch ( status.status() )
{
case KopeteOnlineStatus::Unknown:
p = 0;
break;
case KopeteOnlineStatus::Offline:
p = 1;
break;
case KopeteOnlineStatus::Connecting:
p = 2;
break;
case KopeteOnlineStatus::Away:
p = 3;
break;
case KopeteOnlineStatus::Online:
p = 4;
break;
}
}
return p;
}
QString KIMIfaceImpl::presenceString( const QString & uid )
{
QString p;
KopeteMetaContact *m = KopeteContactList::contactList()->metaContact( uid );
if ( m )
{
KopeteOnlineStatus status = m->status();
p = status.description();
}
else
{
p = i18n("Error: could not discover presence.");
}
return p;
}
bool KIMIfaceImpl::canReceiveFiles( const QString & uid )
{
KopeteMetaContact *mc;
mc = KopeteContactList::contactList()->metaContact( uid );
if ( mc )
return mc->canAcceptFiles();
else
return false;
}
bool KIMIfaceImpl::canRespond( const QString & uid )
{
KopeteMetaContact *mc;
mc = KopeteContactList::contactList()->metaContact( uid );
if ( mc )
{
QPtrList<KopeteContact> list = mc->contacts();
QPtrListIterator<KopeteContact> it( list );
KopeteContact *contact;
while ( ( contact = it.current() ) != 0 )
{
++it;
if ( contact->isOnline() && contact->protocol()->pluginId() != "SMSProtocol" )
return true;
}
}
return false;
}
QString KIMIfaceImpl::locate( const QString & contactId, const QString & protocolId )
{
KopeteMetaContact *mc = locateProtocolContact( contactId, protocolId );
if ( mc )
return mc->metaContactId();
else
return QString();
}
KopeteMetaContact * KIMIfaceImpl::locateProtocolContact( const QString & contactId, const QString & protocolId )
{
KopeteMetaContact *mc = 0;
// find a matching protocol
KopeteProtocol *protocol = dynamic_cast<KopeteProtocol*>( KopetePluginManager::self()->plugin( protocolId ) );
if ( protocol )
{
// find its accounts
QDict<KopeteAccount> accounts = KopeteAccountManager::manager()->accounts( protocol );
QDictIterator<KopeteAccount> it( accounts );
for( ; it.current(); ++it )
{
mc = KopeteContactList::contactList()->findContact( protocolId, it.currentKey(), contactId );
if (mc)
break;
}
}
return mc;
}
QPixmap KIMIfaceImpl::icon( const QString & uid )
{
KopeteMetaContact *m = KopeteContactList::contactList()->metaContact( uid );
QPixmap p;
if ( m )
p = SmallIcon( m->statusIcon() );
return p;
}
QString KIMIfaceImpl::context( const QString & uid )
{
// TODO: support context
// shush warning
QString myUid = uid;
return QString( "Home" );
}
QStringList KIMIfaceImpl::protocols()
{
QValueList<KPluginInfo *> protocols = KopetePluginManager::self()->availablePlugins( "Protocols" );
QStringList protocolList;
for ( QValueList<KPluginInfo *>::Iterator it = protocols.begin(); it != protocols.end(); ++it )
protocolList.append( (*it)->name() );
return protocolList;
}
void KIMIfaceImpl::messageContact( const QString &uid, const QString& messageText )
{
// TODO: make it possible to specify the message here
KopeteMetaContact *m = KopeteContactList::contactList()->metaContact( uid );
if ( m )
m->sendMessage();
}
void KIMIfaceImpl::messageNewContact( const QString &protocol, const QString &contactId )
{
KopeteMetaContact *mc = locateProtocolContact( contactId, protocol );
if ( mc )
mc->sendMessage();
}
void KIMIfaceImpl::chatWithContact( const QString &uid )
{
KopeteMetaContact *m = KopeteContactList::contactList()->metaContact( uid );
if ( m )
m->execute();
}
void KIMIfaceImpl::sendFile(const QString &uid, const KURL &sourceURL,
const QString &altFileName, uint fileSize)
{
KopeteMetaContact *m = KopeteContactList::contactList()->metaContact( uid );
if ( m )
m->sendFile( sourceURL, altFileName, fileSize );
}
bool KIMIfaceImpl::addContact( const QString &protocolId, const QString &contactId )
{
// find a matching protocol
KopeteProtocol *protocol = dynamic_cast<KopeteProtocol*>( KopetePluginManager::self()->plugin( protocolId ) );
if ( protocol )
{
// find its accounts
QDict<KopeteAccount> accounts = KopeteAccountManager::manager()->accounts( protocol );
QDictIterator<KopeteAccount> it( accounts );
KopeteAccount *ac = it.toFirst();
if ( ac )
{
ac->addContact( contactId );
return true;
}
}
return false;
}
void KIMIfaceImpl::slotMetaContactAdded( KopeteMetaContact *mc )
{
connect( mc, SIGNAL( onlineStatusChanged( KopeteMetaContact *, KopeteOnlineStatus::OnlineStatus ) ),
SLOT( slotContactStatusChanged( KopeteMetaContact * ) ) );
}
void KIMIfaceImpl::slotContactStatusChanged( KopeteMetaContact *mc )
{
if ( !mc->metaContactId().isNull() )
{
// tell anyone who's listening over DCOP
QByteArray params;
QDataStream stream(params, IO_WriteOnly);
stream << mc->metaContactId();
kapp->dcopClient()->emitDCOPSignal( "contactStatusChanged(QString)", params );
}
}
<commit_msg>CVS_SILENT Include moc<commit_after>/*
kimifaceimpl.cpp - Kopete DCOP Interface
Copyright (c) 2004 by Will Stephenson <lists@stevello.free-online.co.uk>
Kopete (c) 2002-2004 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program 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 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <qstringlist.h>
#include <dcopclient.h>
#include <kapplication.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kplugininfo.h>
#include "kopeteaccount.h"
#include "kopeteaccountmanager.h"
#include "kopetecontactlist.h"
#include "kopetemetacontact.h"
#include "kopeteprotocol.h"
#include "kopetepluginmanager.h"
#include "kimifaceimpl.h"
KIMIfaceImpl::KIMIfaceImpl() : QObject(), DCOPObject( "KIMIface" )
{
connect( KopeteContactList::contactList(),
SIGNAL( metaContactAdded( KopeteMetaContact * ) ),
SLOT( slotMetaContactAdded( KopeteMetaContact * ) ) );
}
KIMIfaceImpl::~KIMIfaceImpl()
{
}
QStringList KIMIfaceImpl::allContacts()
{
QStringList result;
QPtrList<KopeteMetaContact> list = KopeteContactList::contactList()->metaContacts();
QPtrListIterator<KopeteMetaContact> it( list );
for( ; it.current(); ++it )
{
if ( !it.current()->metaContactId().isNull() )
result.append( it.current()->metaContactId() );
}
return result;
}
QStringList KIMIfaceImpl::reachableContacts()
{
QStringList result;
QPtrList<KopeteMetaContact> list = KopeteContactList::contactList()->metaContacts();
QPtrListIterator<KopeteMetaContact> it( list );
for( ; it.current(); ++it )
{
if ( it.current()->isReachable() && !it.current()->metaContactId().isNull() )
result.append( it.current()->metaContactId() );
}
return result;
}
QStringList KIMIfaceImpl::onlineContacts()
{
QStringList result;
QPtrList<KopeteMetaContact> list = KopeteContactList::contactList()->metaContacts();
QPtrListIterator<KopeteMetaContact> it( list );
for( ; it.current(); ++it )
{
if ( it.current()->isOnline() && !it.current()->metaContactId().isNull() )
result.append( it.current()->metaContactId() );
}
return result;
}
QStringList KIMIfaceImpl::fileTransferContacts()
{
QStringList result;
QPtrList<KopeteMetaContact> list = KopeteContactList::contactList()->metaContacts();
QPtrListIterator<KopeteMetaContact> it( list );
for( ; it.current(); ++it )
{
if ( it.current()->canAcceptFiles() && !it.current()->metaContactId().isNull() )
result.append( it.current()->metaContactId() );
}
return result;
}
bool KIMIfaceImpl::isPresent( const QString & uid )
{
KopeteMetaContact *mc;
mc = KopeteContactList::contactList()->metaContact( uid );
return ( mc != 0 );
}
int KIMIfaceImpl::presenceStatus( const QString & uid )
{
int p = -1;
KopeteMetaContact *m = KopeteContactList::contactList()->metaContact( uid );
if ( m )
{
KopeteOnlineStatus status = m->status();
switch ( status.status() )
{
case KopeteOnlineStatus::Unknown:
p = 0;
break;
case KopeteOnlineStatus::Offline:
p = 1;
break;
case KopeteOnlineStatus::Connecting:
p = 2;
break;
case KopeteOnlineStatus::Away:
p = 3;
break;
case KopeteOnlineStatus::Online:
p = 4;
break;
}
}
return p;
}
QString KIMIfaceImpl::presenceString( const QString & uid )
{
QString p;
KopeteMetaContact *m = KopeteContactList::contactList()->metaContact( uid );
if ( m )
{
KopeteOnlineStatus status = m->status();
p = status.description();
}
else
{
p = i18n("Error: could not discover presence.");
}
return p;
}
bool KIMIfaceImpl::canReceiveFiles( const QString & uid )
{
KopeteMetaContact *mc;
mc = KopeteContactList::contactList()->metaContact( uid );
if ( mc )
return mc->canAcceptFiles();
else
return false;
}
bool KIMIfaceImpl::canRespond( const QString & uid )
{
KopeteMetaContact *mc;
mc = KopeteContactList::contactList()->metaContact( uid );
if ( mc )
{
QPtrList<KopeteContact> list = mc->contacts();
QPtrListIterator<KopeteContact> it( list );
KopeteContact *contact;
while ( ( contact = it.current() ) != 0 )
{
++it;
if ( contact->isOnline() && contact->protocol()->pluginId() != "SMSProtocol" )
return true;
}
}
return false;
}
QString KIMIfaceImpl::locate( const QString & contactId, const QString & protocolId )
{
KopeteMetaContact *mc = locateProtocolContact( contactId, protocolId );
if ( mc )
return mc->metaContactId();
else
return QString();
}
KopeteMetaContact * KIMIfaceImpl::locateProtocolContact( const QString & contactId, const QString & protocolId )
{
KopeteMetaContact *mc = 0;
// find a matching protocol
KopeteProtocol *protocol = dynamic_cast<KopeteProtocol*>( KopetePluginManager::self()->plugin( protocolId ) );
if ( protocol )
{
// find its accounts
QDict<KopeteAccount> accounts = KopeteAccountManager::manager()->accounts( protocol );
QDictIterator<KopeteAccount> it( accounts );
for( ; it.current(); ++it )
{
mc = KopeteContactList::contactList()->findContact( protocolId, it.currentKey(), contactId );
if (mc)
break;
}
}
return mc;
}
QPixmap KIMIfaceImpl::icon( const QString & uid )
{
KopeteMetaContact *m = KopeteContactList::contactList()->metaContact( uid );
QPixmap p;
if ( m )
p = SmallIcon( m->statusIcon() );
return p;
}
QString KIMIfaceImpl::context( const QString & uid )
{
// TODO: support context
// shush warning
QString myUid = uid;
return QString( "Home" );
}
QStringList KIMIfaceImpl::protocols()
{
QValueList<KPluginInfo *> protocols = KopetePluginManager::self()->availablePlugins( "Protocols" );
QStringList protocolList;
for ( QValueList<KPluginInfo *>::Iterator it = protocols.begin(); it != protocols.end(); ++it )
protocolList.append( (*it)->name() );
return protocolList;
}
void KIMIfaceImpl::messageContact( const QString &uid, const QString& messageText )
{
// TODO: make it possible to specify the message here
KopeteMetaContact *m = KopeteContactList::contactList()->metaContact( uid );
if ( m )
m->sendMessage();
}
void KIMIfaceImpl::messageNewContact( const QString &protocol, const QString &contactId )
{
KopeteMetaContact *mc = locateProtocolContact( contactId, protocol );
if ( mc )
mc->sendMessage();
}
void KIMIfaceImpl::chatWithContact( const QString &uid )
{
KopeteMetaContact *m = KopeteContactList::contactList()->metaContact( uid );
if ( m )
m->execute();
}
void KIMIfaceImpl::sendFile(const QString &uid, const KURL &sourceURL,
const QString &altFileName, uint fileSize)
{
KopeteMetaContact *m = KopeteContactList::contactList()->metaContact( uid );
if ( m )
m->sendFile( sourceURL, altFileName, fileSize );
}
bool KIMIfaceImpl::addContact( const QString &protocolId, const QString &contactId )
{
// find a matching protocol
KopeteProtocol *protocol = dynamic_cast<KopeteProtocol*>( KopetePluginManager::self()->plugin( protocolId ) );
if ( protocol )
{
// find its accounts
QDict<KopeteAccount> accounts = KopeteAccountManager::manager()->accounts( protocol );
QDictIterator<KopeteAccount> it( accounts );
KopeteAccount *ac = it.toFirst();
if ( ac )
{
ac->addContact( contactId );
return true;
}
}
return false;
}
void KIMIfaceImpl::slotMetaContactAdded( KopeteMetaContact *mc )
{
connect( mc, SIGNAL( onlineStatusChanged( KopeteMetaContact *, KopeteOnlineStatus::OnlineStatus ) ),
SLOT( slotContactStatusChanged( KopeteMetaContact * ) ) );
}
void KIMIfaceImpl::slotContactStatusChanged( KopeteMetaContact *mc )
{
if ( !mc->metaContactId().isNull() )
{
// tell anyone who's listening over DCOP
QByteArray params;
QDataStream stream(params, IO_WriteOnly);
stream << mc->metaContactId();
kapp->dcopClient()->emitDCOPSignal( "contactStatusChanged(QString)", params );
}
}
#include "kimifaceimpl.moc"
<|endoftext|> |
<commit_before>//
// File: GraphicsAPI.cpp
// Author: Hongtae Kim (tiff2766@gmail.com)
//
// Copyright (c) 2004-2017 Hongtae Kim. All rights reserved.
//
#include <initializer_list>
#include "../DKPropertySet.h"
#include "../Interface/DKGraphicsDeviceInterface.h"
#include "GraphicsAPI.h"
namespace DKFramework
{
namespace Private
{
#if DKGL_USE_METAL
namespace Metal
{
DKGraphicsDeviceInterface* CreateInterface(void);
}
#endif
#if DKGL_USE_VULKAN
namespace Vulkan
{
DKGraphicsDeviceInterface* CreateInterface(void);
}
#endif
#if DKGL_USE_DIRECT3D
namespace Direct3D
{
DKGraphicsDeviceInterface* CreateInterface(void);
}
#endif
#if DKGL_USE_OPENGL
namespace OpenGL
{
DKGraphicsDeviceInterface* CreateInterface(void);
}
#endif
}
DKGraphicsDeviceInterface* DKGraphicsDeviceInterface::CreateInterface(void)
{
DKString defaultAPI =
#if DKGL_USE_METAL
"Metal";
#elif DKGL_USE_DIRECT3D
"Direct3D";
#elif DKGL_USE_VULKAN
"Vulkan";
#elif DKGL_USE_OPENGL
"OpenGL";
#else
"";
#endif
struct APISet
{
const char* name;
DKGraphicsDeviceInterface* (*fn)(void);
};
DKArray<APISet> apis = {
#if DKGL_USE_METAL
{ "Metal", Private::Metal::CreateInterface },
#endif
#if DKGL_USE_DIRECT3D
{ "Direct3D", Private::Direct3D::CreateInterface },
#endif
#if DKGL_USE_VULKAN
{ "Vulkan", Private::Vulkan::CreateInterface },
#endif
#if DKGL_USE_OPENGL
{ "OpenGL", Private::OpenGL::CreateInterface },
#endif
};
for (size_t i = 0; i < apis.Count(); ++i)
{
if (defaultAPI.CompareNoCase(apis.Value(i).name) == 0)
{
if (i > 0)
{
APISet api = apis.Value(i);
apis.Remove(i);
apis.Insert(api, 0);
}
break;
}
}
// get user preferred API name.
bool tryPreferredApiFirst = true;
if (tryPreferredApiFirst)
{
const char* key = "GraphicsAPI";
DKPropertySet& config = DKPropertySet::SystemConfig();
if (config.HasValue(key))
{
const DKVariant& var = config.Value(key);
if (var.ValueType() == DKVariant::TypeString)
{
DKString selectAPI = DKStringU8(var.String());
for (size_t i = 0; i < apis.Count(); ++i)
{
if (selectAPI.CompareNoCase(apis.Value(i).name) == 0)
{
if (i > 0)
{
APISet api = apis.Value(i);
apis.Remove(i);
apis.Insert(api, 0);
}
break;
}
}
}
}
}
bool printApiSet = true;
if (printApiSet)
{
int index = 0;
for (const APISet& as : apis)
{
DKLog(" GraphicsAPI[%d]: %s", index, as.name);
index++;
}
if (index == 0)
DKLog(" No Graphics API available.");
}
for (const APISet& as : apis)
{
try {
DKGraphicsDeviceInterface* device = as.fn();
if (device)
{
DKLog("Graphics API \"%s\" selected.", as.name);
return device;
}
else
{
DKLog("Graphics API \"%s\" not supported.", as.name);
}
}
catch (DKError& e)
{
DKLog("Graphics API \"%s\" Failed: %ls", as.name, (const wchar_t*)e.Description());
}
catch (std::exception& e)
{
DKLog("Graphics API \"%s\" Failed: %s", as.name, e.what());
}
}
DKLog("ERROR: No Graphics device found.");
return NULL;
}
}
<commit_msg>no message<commit_after>//
// File: GraphicsAPI.cpp
// Author: Hongtae Kim (tiff2766@gmail.com)
//
// Copyright (c) 2004-2017 Hongtae Kim. All rights reserved.
//
#include <initializer_list>
#include "../DKPropertySet.h"
#include "../Interface/DKGraphicsDeviceInterface.h"
#include "GraphicsAPI.h"
namespace DKFramework
{
namespace Private
{
#if DKGL_USE_METAL
namespace Metal
{
DKGraphicsDeviceInterface* CreateInterface(void);
}
#endif
#if DKGL_USE_VULKAN
namespace Vulkan
{
DKGraphicsDeviceInterface* CreateInterface(void);
}
#endif
#if DKGL_USE_DIRECT3D
namespace Direct3D
{
DKGraphicsDeviceInterface* CreateInterface(void);
}
#endif
#if DKGL_USE_OPENGL
namespace OpenGL
{
DKGraphicsDeviceInterface* CreateInterface(void);
}
#endif
}
DKGraphicsDeviceInterface* DKGraphicsDeviceInterface::CreateInterface(void)
{
DKString defaultAPI =
#if DKGL_USE_METAL
"Metal";
#elif DKGL_USE_DIRECT3D
"Direct3D";
#elif DKGL_USE_VULKAN
"Vulkan";
#elif DKGL_USE_OPENGL
"OpenGL";
#else
"";
#endif
struct APISet
{
const char* name;
DKGraphicsDeviceInterface* (*fn)(void);
};
DKArray<APISet> apis = {
#if DKGL_USE_METAL
{ "Metal", Private::Metal::CreateInterface },
#endif
#if DKGL_USE_DIRECT3D
{ "Direct3D", Private::Direct3D::CreateInterface },
#endif
#if DKGL_USE_VULKAN
{ "Vulkan", Private::Vulkan::CreateInterface },
#endif
#if DKGL_USE_OPENGL
{ "OpenGL", Private::OpenGL::CreateInterface },
#endif
};
for (size_t i = 0; i < apis.Count(); ++i)
{
if (defaultAPI.CompareNoCase(apis.Value(i).name) == 0)
{
if (i > 0)
{
APISet api = apis.Value(i);
apis.Remove(i);
apis.Insert(api, 0);
}
break;
}
}
// get user preferred API name.
bool tryPreferredApiFirst = true;
if (tryPreferredApiFirst)
{
const char* key = "GraphicsAPI";
DKPropertySet& config = DKPropertySet::SystemConfig();
if (config.HasValue(key))
{
const DKVariant& var = config.Value(key);
if (var.ValueType() == DKVariant::TypeString)
{
DKString selectAPI = (DKString)DKStringU8(var.String());
for (size_t i = 0; i < apis.Count(); ++i)
{
if (selectAPI.CompareNoCase(apis.Value(i).name) == 0)
{
if (i > 0)
{
APISet api = apis.Value(i);
apis.Remove(i);
apis.Insert(api, 0);
}
break;
}
}
}
}
}
bool printApiSet = true;
if (printApiSet)
{
int index = 0;
for (const APISet& as : apis)
{
DKLog(" GraphicsAPI[%d]: %s", index, as.name);
index++;
}
if (index == 0)
DKLog(" No Graphics API available.");
}
for (const APISet& as : apis)
{
try {
DKGraphicsDeviceInterface* device = as.fn();
if (device)
{
DKLog("Graphics API \"%s\" selected.", as.name);
return device;
}
else
{
DKLog("Graphics API \"%s\" not supported.", as.name);
}
}
catch (DKError& e)
{
DKLog("Graphics API \"%s\" Failed: %ls", as.name, (const wchar_t*)e.Description());
}
catch (std::exception& e)
{
DKLog("Graphics API \"%s\" Failed: %s", as.name, e.what());
}
}
DKLog("ERROR: No Graphics device found.");
return NULL;
}
}
<|endoftext|> |
<commit_before>// RUN: clang-cc -fsyntax-only -faccess-control -verify %s
namespace T1 {
class A {
virtual int f(); // expected-note{{overridden virtual function is here}}
};
class B : A {
virtual void f(); // expected-error{{virtual function 'f' has a different return type ('void') than the function it overrides (which has return type 'int')}}
};
}
namespace T2 {
struct a { };
struct b { };
class A {
virtual a* f(); // expected-note{{overridden virtual function is here}}
};
class B : A {
virtual b* f(); // expected-error{{return type of virtual function 'f' is not covariant with the return type of the function it overrrides ('struct T2::b *' is not derived from 'struct T2::a *')}}
};
}
namespace T3 {
struct a { };
struct b : private a { }; // expected-note{{'private' inheritance specifier here}}
class A {
virtual a* f(); // expected-note{{overridden virtual function is here}}
};
class B : A {
virtual b* f(); // expected-error{{return type of virtual function 'f' is not covariant with the return type of the function it overrides (conversion from 'struct T3::b' to inaccessible base class 'struct T3::a')}}
};
}
namespace T4 {
struct a { };
struct a1 : a { };
struct b : a, a1 { };
class A {
virtual a* f(); // expected-note{{overridden virtual function is here}}
};
class B : A {
virtual b* f(); // expected-error{{return type of virtual function 'f' is not covariant with the return type of the function it overrides (ambiguous conversion from derived class 'struct T4::b' to base class 'struct T4::a':\n\
struct T4::b -> struct T4::a\n\
struct T4::b -> struct T4::a1 -> struct T4::a)}}
};
}
namespace T5 {
struct a { };
class A {
virtual a* const f();
virtual a* const g(); // expected-note{{overridden virtual function is here}}
};
class B : A {
virtual a* const f();
virtual a* g(); // expected-error{{return type of virtual function 'g' is not covariant with the return type of the function it overrides ('struct T5::a *' has different qualifiers than 'struct T5::a *const')}}
};
}
namespace T6 {
struct a { };
class A {
virtual const a* f();
virtual a* g(); // expected-note{{overridden virtual function is here}}
};
class B : A {
virtual a* f();
virtual const a* g(); // expected-error{{return type of virtual function 'g' is not covariant with the return type of the function it overrides (class type 'struct T6::a const *' is more qualified than class type 'struct T6::a *'}}
};
}
<commit_msg>Fix the same speling error in the test case (Duh).<commit_after>// RUN: clang-cc -fsyntax-only -faccess-control -verify %s
namespace T1 {
class A {
virtual int f(); // expected-note{{overridden virtual function is here}}
};
class B : A {
virtual void f(); // expected-error{{virtual function 'f' has a different return type ('void') than the function it overrides (which has return type 'int')}}
};
}
namespace T2 {
struct a { };
struct b { };
class A {
virtual a* f(); // expected-note{{overridden virtual function is here}}
};
class B : A {
virtual b* f(); // expected-error{{return type of virtual function 'f' is not covariant with the return type of the function it overrides ('struct T2::b *' is not derived from 'struct T2::a *')}}
};
}
namespace T3 {
struct a { };
struct b : private a { }; // expected-note{{'private' inheritance specifier here}}
class A {
virtual a* f(); // expected-note{{overridden virtual function is here}}
};
class B : A {
virtual b* f(); // expected-error{{return type of virtual function 'f' is not covariant with the return type of the function it overrides (conversion from 'struct T3::b' to inaccessible base class 'struct T3::a')}}
};
}
namespace T4 {
struct a { };
struct a1 : a { };
struct b : a, a1 { };
class A {
virtual a* f(); // expected-note{{overridden virtual function is here}}
};
class B : A {
virtual b* f(); // expected-error{{return type of virtual function 'f' is not covariant with the return type of the function it overrides (ambiguous conversion from derived class 'struct T4::b' to base class 'struct T4::a':\n\
struct T4::b -> struct T4::a\n\
struct T4::b -> struct T4::a1 -> struct T4::a)}}
};
}
namespace T5 {
struct a { };
class A {
virtual a* const f();
virtual a* const g(); // expected-note{{overridden virtual function is here}}
};
class B : A {
virtual a* const f();
virtual a* g(); // expected-error{{return type of virtual function 'g' is not covariant with the return type of the function it overrides ('struct T5::a *' has different qualifiers than 'struct T5::a *const')}}
};
}
namespace T6 {
struct a { };
class A {
virtual const a* f();
virtual a* g(); // expected-note{{overridden virtual function is here}}
};
class B : A {
virtual a* f();
virtual const a* g(); // expected-error{{return type of virtual function 'g' is not covariant with the return type of the function it overrides (class type 'struct T6::a const *' is more qualified than class type 'struct T6::a *'}}
};
}
<|endoftext|> |
<commit_before><commit_msg>Use new startsWith() method of OString<commit_after><|endoftext|> |
<commit_before>#include "raiden.h"
#include "reflection.h"
//#include "transform.h"
#include "gtest.h"
#include "sampling.h"
TEST(FrConductor,Au){
Float air_ior[3]={1,1,1};
// float au_ior[3]={0.15557,0.42415,1.3831};
// float au_k[3] = {3.5024,2.4721,1.9155};
Float au_ior[3]={0.18299,0.42108,1.3734};
Float au_k[3] = {3.4242,2.3459,1.7704};
Spectrum air=Spectrum::FromRGB(air_ior);
Spectrum ior=Spectrum::FromRGB(au_ior);
Spectrum k=Spectrum::FromRGB(au_k);
Spectrum r=FrConductor(1,air,ior,k);
Float au[3];
r.ToRGB(au);
// EXPECT_FLOAT_EQ(au[0],1.000);
// EXPECT_FLOAT_EQ(au[1],0.766);
// EXPECT_FLOAT_EQ(au[2],0.336);
EXPECT_GE(au[0],0.9);
EXPECT_GE(au[1],0.7);
EXPECT_GE(au[2],0.3);
}
TEST(HairBSDF,WhiteFurnace){
RNG rng;
auto wo=UniformSampleSphere({rng.UniformFloat(),rng.UniformFloat()});
for(Float betam=0.1;betam<=1;betam+=0.2){
for(Float betan=0.1;betan<=1;betan+=0.2){
int count=300000;
Spectrum sigmaA(0);
Spectrum sum(0);
for(int i=0;i<count;++i){
Float h=-1+2*rng.UniformFloat();
HairBSDF bsdf(h,1.55f,sigmaA,betam,betan,0.0f);
auto wi=UniformSampleSphere({rng.UniformFloat(),rng.UniformFloat()});
sum+=bsdf.f(wo,wi)*AbsCosTheta(wi);
}
sum=sum/(count*UniformSpherePdf());
EXPECT_GT(sum.y(),0.95);
EXPECT_LT(sum.y(),1.05);
}
}
}<commit_msg>上传单元测试<commit_after>#include "raiden.h"
#include "reflection.h"
//#include "transform.h"
#include "gtest.h"
#include "sampling.h"
TEST(FrConductor,Au){
Float air_ior[3]={1,1,1};
// float au_ior[3]={0.15557,0.42415,1.3831};
// float au_k[3] = {3.5024,2.4721,1.9155};
Float au_ior[3]={0.18299,0.42108,1.3734};
Float au_k[3] = {3.4242,2.3459,1.7704};
Spectrum air=Spectrum::FromRGB(air_ior);
Spectrum ior=Spectrum::FromRGB(au_ior);
Spectrum k=Spectrum::FromRGB(au_k);
Spectrum r=FrConductor(1,air,ior,k);
Float au[3];
r.ToRGB(au);
// EXPECT_FLOAT_EQ(au[0],1.000);
// EXPECT_FLOAT_EQ(au[1],0.766);
// EXPECT_FLOAT_EQ(au[2],0.336);
EXPECT_GE(au[0],0.9);
EXPECT_GE(au[1],0.7);
EXPECT_GE(au[2],0.3);
}
TEST(HairBSDF,WhiteFurnace){
RNG rng;
auto wo=UniformSampleSphere({rng.UniformFloat(),rng.UniformFloat()});
for(Float betam=0.1;betam<=1;betam+=0.2){
for(Float betan=0.1;betan<=1;betan+=0.2){
int count=300000;
Spectrum sigmaA(0);
Spectrum sum(0);
for(int i=0;i<count;++i){
Float h=-1+2*rng.UniformFloat();
HairBSDF bsdf(h,1.55f,sigmaA,betam,betan,0.0f);
auto wi=UniformSampleSphere({rng.UniformFloat(),rng.UniformFloat()});
sum+=bsdf.f(wo,wi)*AbsCosTheta(wi);
}
sum=sum/(count*UniformSpherePdf());
EXPECT_GT(sum.y(),0.95);
EXPECT_LT(sum.y(),1.05);
}
}
}
TEST(HairBSDF,SampleWeights){
RNG rng;
auto wo=UniformSampleSphere({rng.UniformFloat(),rng.UniformFloat()});
for(Float betam=0.1;betam<=1;betam+=0.2){
for(Float betan=0.1;betan<=1;betan+=0.2){
int count=1000;
Spectrum sigmaA(0);
for(int i=0;i<count;++i){
Float h=-1+2*rng.UniformFloat();
HairBSDF bsdf(h,1.55f,sigmaA,betam,betan,0.0f);
Vector3f wi;
Float pdf;
auto f=bsdf.Sample_f(wo,&wi,{rng.UniformFloat(),rng.UniformFloat()},&pdf);
if(pdf>0){
EXPECT_EQ(f.y()*AbsCosTheta(wi),pdf);
}
}
}
}
}<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/bubble/bubble_frame_view.h"
#include <algorithm>
#include "grit/ui_resources.h"
#include "ui/base/hit_test.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/path.h"
#include "ui/gfx/screen.h"
#include "ui/views/bubble/bubble_border.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/window/client_view.h"
namespace {
// Padding, in pixels, for the title view, when it exists.
const int kTitleTopInset = 12;
const int kTitleLeftInset = 19;
const int kTitleBottomInset = 12;
// Get the |vertical| or horizontal screen overflow of the |window_bounds|.
int GetOffScreenLength(const gfx::Rect& monitor_bounds,
const gfx::Rect& window_bounds,
bool vertical) {
if (monitor_bounds.IsEmpty() || monitor_bounds.Contains(window_bounds))
return 0;
// window_bounds
// +-------------------------------+
// | top |
// | +----------------+ |
// | left | monitor_bounds | right |
// | +----------------+ |
// | bottom |
// +-------------------------------+
if (vertical)
return std::max(0, monitor_bounds.y() - window_bounds.y()) +
std::max(0, window_bounds.bottom() - monitor_bounds.bottom());
return std::max(0, monitor_bounds.x() - window_bounds.x()) +
std::max(0, window_bounds.right() - monitor_bounds.right());
}
} // namespace
namespace views {
BubbleFrameView::BubbleFrameView(const gfx::Insets& content_margins)
: bubble_border_(NULL),
content_margins_(content_margins),
title_(NULL),
close_(NULL),
titlebar_extra_view_(NULL) {
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
title_ = new Label(string16(), rb.GetFont(ui::ResourceBundle::MediumFont));
title_->SetHorizontalAlignment(gfx::ALIGN_LEFT);
AddChildView(title_);
close_ = new LabelButton(this, string16());
close_->SetImage(CustomButton::STATE_NORMAL,
*rb.GetImageNamed(IDR_CLOSE_DIALOG).ToImageSkia());
close_->SetImage(CustomButton::STATE_HOVERED,
*rb.GetImageNamed(IDR_CLOSE_DIALOG_H).ToImageSkia());
close_->SetImage(CustomButton::STATE_PRESSED,
*rb.GetImageNamed(IDR_CLOSE_DIALOG_P).ToImageSkia());
close_->SetSize(close_->GetPreferredSize());
close_->set_border(NULL);
close_->SetVisible(false);
AddChildView(close_);
}
BubbleFrameView::~BubbleFrameView() {}
gfx::Rect BubbleFrameView::GetBoundsForClientView() const {
gfx::Rect client_bounds = GetLocalBounds();
client_bounds.Inset(GetInsets());
client_bounds.Inset(bubble_border_->GetInsets());
return client_bounds;
}
gfx::Rect BubbleFrameView::GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const {
return const_cast<BubbleFrameView*>(this)->GetUpdatedWindowBounds(
gfx::Rect(), client_bounds.size(), false);
}
int BubbleFrameView::NonClientHitTest(const gfx::Point& point) {
if (!bounds().Contains(point))
return HTNOWHERE;
if (close_->visible() && close_->GetMirroredBounds().Contains(point))
return HTCLOSE;
if (!GetWidget()->widget_delegate()->CanResize())
return GetWidget()->client_view()->NonClientHitTest(point);
const int size = bubble_border_->GetBorderThickness() + 4;
const int hit = GetHTComponentForFrame(point, size, size, size, size, true);
if (hit == HTNOWHERE && point.y() < title_->bounds().bottom())
return HTCAPTION;
return hit;
}
void BubbleFrameView::GetWindowMask(const gfx::Size& size,
gfx::Path* window_mask) {
if (bubble_border_->shadow() != BubbleBorder::NO_SHADOW_OPAQUE_BORDER)
return;
// Use a window mask roughly matching the border in the image assets.
static const int kBorderStrokeSize = 1;
static const SkScalar kCornerRadius = SkIntToScalar(6);
gfx::Insets border_insets = bubble_border_->GetInsets();
const SkRect rect = { SkIntToScalar(border_insets.left() - kBorderStrokeSize),
SkIntToScalar(border_insets.top() - kBorderStrokeSize),
SkIntToScalar(size.width() - border_insets.right() +
kBorderStrokeSize),
SkIntToScalar(size.height() - border_insets.bottom() +
kBorderStrokeSize) };
window_mask->addRoundRect(rect, kCornerRadius, kCornerRadius);
}
void BubbleFrameView::ResetWindowControls() {}
void BubbleFrameView::UpdateWindowIcon() {}
void BubbleFrameView::UpdateWindowTitle() {}
gfx::Insets BubbleFrameView::GetInsets() const {
gfx::Insets insets = content_margins_;
const int title_height = title_->text().empty() ? 0 :
title_->GetPreferredSize().height() + kTitleTopInset + kTitleBottomInset;
const int close_height = close_->visible() ? close_->height() : 0;
insets += gfx::Insets(std::max(title_height, close_height), 0, 0, 0);
return insets;
}
gfx::Size BubbleFrameView::GetPreferredSize() {
const gfx::Size client(GetWidget()->client_view()->GetPreferredSize());
gfx::Size size(GetUpdatedWindowBounds(gfx::Rect(), client, false).size());
// Accommodate the width of the title bar elements.
int title_bar_width = GetInsets().width() + border()->GetInsets().width() +
kTitleLeftInset + title_->GetPreferredSize().width() +
close_->width() + 1;
if (titlebar_extra_view_ != NULL)
title_bar_width += titlebar_extra_view_->GetPreferredSize().width();
size.SetToMax(gfx::Size(title_bar_width, 0));
return size;
}
void BubbleFrameView::Layout() {
gfx::Rect bounds(GetLocalBounds());
bounds.Inset(border()->GetInsets());
// Small additional insets yield the desired 10px visual close button insets.
bounds.Inset(0, 0, close_->width() + 1, 0);
close_->SetPosition(gfx::Point(bounds.right(), bounds.y() + 2));
gfx::Rect title_bounds(bounds);
title_bounds.Inset(kTitleLeftInset, kTitleTopInset, 0, 0);
gfx::Size title_size(title_->GetPreferredSize());
const int title_width = std::max(0, close_->bounds().x() - title_bounds.x());
title_size.SetToMin(gfx::Size(title_width, title_size.height()));
title_bounds.set_size(title_size);
title_->SetBoundsRect(title_bounds);
if (titlebar_extra_view_) {
const int extra_width = close_->bounds().x() - title_->bounds().right();
gfx::Size size = titlebar_extra_view_->GetPreferredSize();
size.SetToMin(gfx::Size(std::max(0, extra_width), size.height()));
gfx::Rect titlebar_extra_view_bounds(
bounds.right() - size.width(),
title_bounds.y(),
size.width(),
title_bounds.height());
titlebar_extra_view_bounds.Subtract(title_bounds);
titlebar_extra_view_->SetBoundsRect(titlebar_extra_view_bounds);
}
}
const char* BubbleFrameView::GetClassName() const {
return "BubbleFrameView";
}
void BubbleFrameView::ChildPreferredSizeChanged(View* child) {
if (child == titlebar_extra_view_ || child == title_)
Layout();
}
void BubbleFrameView::ButtonPressed(Button* sender, const ui::Event& event) {
if (sender == close_)
GetWidget()->Close();
}
void BubbleFrameView::SetBubbleBorder(BubbleBorder* border) {
bubble_border_ = border;
set_border(bubble_border_);
// Update the background, which relies on the border.
set_background(new views::BubbleBackground(border));
}
void BubbleFrameView::SetTitle(const string16& title) {
title_->SetText(title);
}
void BubbleFrameView::SetShowCloseButton(bool show) {
close_->SetVisible(show);
}
void BubbleFrameView::SetTitlebarExtraView(View* view) {
DCHECK(view);
DCHECK(!titlebar_extra_view_);
AddChildView(view);
titlebar_extra_view_ = view;
}
gfx::Rect BubbleFrameView::GetUpdatedWindowBounds(const gfx::Rect& anchor_rect,
gfx::Size client_size,
bool adjust_if_offscreen) {
gfx::Insets insets(GetInsets());
client_size.Enlarge(insets.width(), insets.height());
const BubbleBorder::Arrow arrow = bubble_border_->arrow();
if (adjust_if_offscreen && BubbleBorder::has_arrow(arrow)) {
if (!bubble_border_->is_arrow_at_center(arrow)) {
// Try to mirror the anchoring if the bubble does not fit on the screen.
MirrorArrowIfOffScreen(true, anchor_rect, client_size);
MirrorArrowIfOffScreen(false, anchor_rect, client_size);
} else {
// Mirror as needed vertically if the arrow is on a horizontal edge and
// vice-versa.
MirrorArrowIfOffScreen(BubbleBorder::is_arrow_on_horizontal(arrow),
anchor_rect,
client_size);
OffsetArrowIfOffScreen(anchor_rect, client_size);
}
}
// Calculate the bounds with the arrow in its updated location and offset.
return bubble_border_->GetBounds(anchor_rect, client_size);
}
gfx::Rect BubbleFrameView::GetMonitorBounds(const gfx::Rect& rect) {
// TODO(scottmg): Native is wrong. http://crbug.com/133312
return gfx::Screen::GetNativeScreen()->GetDisplayNearestPoint(
rect.CenterPoint()).work_area();
}
void BubbleFrameView::MirrorArrowIfOffScreen(
bool vertical,
const gfx::Rect& anchor_rect,
const gfx::Size& client_size) {
// Check if the bounds don't fit on screen.
gfx::Rect monitor_rect(GetMonitorBounds(anchor_rect));
gfx::Rect window_bounds(bubble_border_->GetBounds(anchor_rect, client_size));
if (GetOffScreenLength(monitor_rect, window_bounds, vertical) > 0) {
BubbleBorder::Arrow arrow = bubble_border()->arrow();
// Mirror the arrow and get the new bounds.
bubble_border_->set_arrow(
vertical ? BubbleBorder::vertical_mirror(arrow) :
BubbleBorder::horizontal_mirror(arrow));
gfx::Rect mirror_bounds =
bubble_border_->GetBounds(anchor_rect, client_size);
// Restore the original arrow if mirroring doesn't show more of the bubble.
if (GetOffScreenLength(monitor_rect, mirror_bounds, vertical) >=
GetOffScreenLength(monitor_rect, window_bounds, vertical))
bubble_border_->set_arrow(arrow);
else
SchedulePaint();
}
}
void BubbleFrameView::OffsetArrowIfOffScreen(const gfx::Rect& anchor_rect,
const gfx::Size& client_size) {
BubbleBorder::Arrow arrow = bubble_border()->arrow();
DCHECK(BubbleBorder::is_arrow_at_center(arrow));
// Get the desired bubble bounds without adjustment.
bubble_border_->set_arrow_offset(0);
gfx::Rect window_bounds(bubble_border_->GetBounds(anchor_rect, client_size));
gfx::Rect monitor_rect(GetMonitorBounds(anchor_rect));
if (monitor_rect.IsEmpty() || monitor_rect.Contains(window_bounds))
return;
// Calculate off-screen adjustment.
const bool is_horizontal = BubbleBorder::is_arrow_on_horizontal(arrow);
int offscreen_adjust = 0;
if (is_horizontal) {
if (window_bounds.x() < monitor_rect.x())
offscreen_adjust = monitor_rect.x() - window_bounds.x();
else if (window_bounds.right() > monitor_rect.right())
offscreen_adjust = monitor_rect.right() - window_bounds.right();
} else {
if (window_bounds.y() < monitor_rect.y())
offscreen_adjust = monitor_rect.y() - window_bounds.y();
else if (window_bounds.bottom() > monitor_rect.bottom())
offscreen_adjust = monitor_rect.bottom() - window_bounds.bottom();
}
// For center arrows, arrows are moved in the opposite direction of
// |offscreen_adjust|, e.g. positive |offscreen_adjust| means bubble
// window needs to be moved to the right and that means we need to move arrow
// to the left, and that means negative offset.
bubble_border_->set_arrow_offset(
bubble_border_->GetArrowOffset(window_bounds.size()) - offscreen_adjust);
if (offscreen_adjust)
SchedulePaint();
}
} // namespace views
<commit_msg>Fix BubbleFrameView titlebar sizing.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/bubble/bubble_frame_view.h"
#include <algorithm>
#include "grit/ui_resources.h"
#include "ui/base/hit_test.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/path.h"
#include "ui/gfx/screen.h"
#include "ui/views/bubble/bubble_border.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/window/client_view.h"
namespace {
// Padding, in pixels, for the title view, when it exists.
const int kTitleTopInset = 12;
const int kTitleLeftInset = 19;
const int kTitleBottomInset = 12;
// Get the |vertical| or horizontal screen overflow of the |window_bounds|.
int GetOffScreenLength(const gfx::Rect& monitor_bounds,
const gfx::Rect& window_bounds,
bool vertical) {
if (monitor_bounds.IsEmpty() || monitor_bounds.Contains(window_bounds))
return 0;
// window_bounds
// +-------------------------------+
// | top |
// | +----------------+ |
// | left | monitor_bounds | right |
// | +----------------+ |
// | bottom |
// +-------------------------------+
if (vertical)
return std::max(0, monitor_bounds.y() - window_bounds.y()) +
std::max(0, window_bounds.bottom() - monitor_bounds.bottom());
return std::max(0, monitor_bounds.x() - window_bounds.x()) +
std::max(0, window_bounds.right() - monitor_bounds.right());
}
} // namespace
namespace views {
BubbleFrameView::BubbleFrameView(const gfx::Insets& content_margins)
: bubble_border_(NULL),
content_margins_(content_margins),
title_(NULL),
close_(NULL),
titlebar_extra_view_(NULL) {
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
title_ = new Label(string16(), rb.GetFont(ui::ResourceBundle::MediumFont));
title_->SetHorizontalAlignment(gfx::ALIGN_LEFT);
AddChildView(title_);
close_ = new LabelButton(this, string16());
close_->SetImage(CustomButton::STATE_NORMAL,
*rb.GetImageNamed(IDR_CLOSE_DIALOG).ToImageSkia());
close_->SetImage(CustomButton::STATE_HOVERED,
*rb.GetImageNamed(IDR_CLOSE_DIALOG_H).ToImageSkia());
close_->SetImage(CustomButton::STATE_PRESSED,
*rb.GetImageNamed(IDR_CLOSE_DIALOG_P).ToImageSkia());
close_->SetSize(close_->GetPreferredSize());
close_->set_border(NULL);
close_->SetVisible(false);
AddChildView(close_);
}
BubbleFrameView::~BubbleFrameView() {}
gfx::Rect BubbleFrameView::GetBoundsForClientView() const {
gfx::Rect client_bounds = GetLocalBounds();
client_bounds.Inset(GetInsets());
client_bounds.Inset(bubble_border_->GetInsets());
return client_bounds;
}
gfx::Rect BubbleFrameView::GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const {
return const_cast<BubbleFrameView*>(this)->GetUpdatedWindowBounds(
gfx::Rect(), client_bounds.size(), false);
}
int BubbleFrameView::NonClientHitTest(const gfx::Point& point) {
if (!bounds().Contains(point))
return HTNOWHERE;
if (close_->visible() && close_->GetMirroredBounds().Contains(point))
return HTCLOSE;
if (!GetWidget()->widget_delegate()->CanResize())
return GetWidget()->client_view()->NonClientHitTest(point);
const int size = bubble_border_->GetBorderThickness() + 4;
const int hit = GetHTComponentForFrame(point, size, size, size, size, true);
if (hit == HTNOWHERE && point.y() < title_->bounds().bottom())
return HTCAPTION;
return hit;
}
void BubbleFrameView::GetWindowMask(const gfx::Size& size,
gfx::Path* window_mask) {
if (bubble_border_->shadow() != BubbleBorder::NO_SHADOW_OPAQUE_BORDER)
return;
// Use a window mask roughly matching the border in the image assets.
static const int kBorderStrokeSize = 1;
static const SkScalar kCornerRadius = SkIntToScalar(6);
gfx::Insets border_insets = bubble_border_->GetInsets();
const SkRect rect = { SkIntToScalar(border_insets.left() - kBorderStrokeSize),
SkIntToScalar(border_insets.top() - kBorderStrokeSize),
SkIntToScalar(size.width() - border_insets.right() +
kBorderStrokeSize),
SkIntToScalar(size.height() - border_insets.bottom() +
kBorderStrokeSize) };
window_mask->addRoundRect(rect, kCornerRadius, kCornerRadius);
}
void BubbleFrameView::ResetWindowControls() {}
void BubbleFrameView::UpdateWindowIcon() {}
void BubbleFrameView::UpdateWindowTitle() {}
gfx::Insets BubbleFrameView::GetInsets() const {
gfx::Insets insets = content_margins_;
const int title_height = title_->text().empty() ? 0 :
title_->GetPreferredSize().height() + kTitleTopInset + kTitleBottomInset;
const int close_height = close_->visible() ? close_->height() : 0;
insets += gfx::Insets(std::max(title_height, close_height), 0, 0, 0);
return insets;
}
gfx::Size BubbleFrameView::GetPreferredSize() {
const gfx::Size client(GetWidget()->client_view()->GetPreferredSize());
gfx::Size size(GetUpdatedWindowBounds(gfx::Rect(), client, false).size());
// Accommodate the width of the title bar elements.
int title_bar_width = GetInsets().width() + border()->GetInsets().width();
if (!title_->text().empty())
title_bar_width += kTitleLeftInset + title_->GetPreferredSize().width();
if (close_->visible())
title_bar_width += close_->width() + 1;
if (titlebar_extra_view_ != NULL)
title_bar_width += titlebar_extra_view_->GetPreferredSize().width();
size.SetToMax(gfx::Size(title_bar_width, 0));
return size;
}
void BubbleFrameView::Layout() {
gfx::Rect bounds(GetLocalBounds());
bounds.Inset(border()->GetInsets());
// Small additional insets yield the desired 10px visual close button insets.
bounds.Inset(0, 0, close_->width() + 1, 0);
close_->SetPosition(gfx::Point(bounds.right(), bounds.y() + 2));
gfx::Rect title_bounds(bounds);
title_bounds.Inset(kTitleLeftInset, kTitleTopInset, 0, 0);
gfx::Size title_size(title_->GetPreferredSize());
const int title_width = std::max(0, close_->bounds().x() - title_bounds.x());
title_size.SetToMin(gfx::Size(title_width, title_size.height()));
title_bounds.set_size(title_size);
title_->SetBoundsRect(title_bounds);
if (titlebar_extra_view_) {
const int extra_width = close_->bounds().x() - title_->bounds().right();
gfx::Size size = titlebar_extra_view_->GetPreferredSize();
size.SetToMin(gfx::Size(std::max(0, extra_width), size.height()));
gfx::Rect titlebar_extra_view_bounds(
bounds.right() - size.width(),
title_bounds.y(),
size.width(),
title_bounds.height());
titlebar_extra_view_bounds.Subtract(title_bounds);
titlebar_extra_view_->SetBoundsRect(titlebar_extra_view_bounds);
}
}
const char* BubbleFrameView::GetClassName() const {
return "BubbleFrameView";
}
void BubbleFrameView::ChildPreferredSizeChanged(View* child) {
if (child == titlebar_extra_view_ || child == title_)
Layout();
}
void BubbleFrameView::ButtonPressed(Button* sender, const ui::Event& event) {
if (sender == close_)
GetWidget()->Close();
}
void BubbleFrameView::SetBubbleBorder(BubbleBorder* border) {
bubble_border_ = border;
set_border(bubble_border_);
// Update the background, which relies on the border.
set_background(new views::BubbleBackground(border));
}
void BubbleFrameView::SetTitle(const string16& title) {
title_->SetText(title);
}
void BubbleFrameView::SetShowCloseButton(bool show) {
close_->SetVisible(show);
}
void BubbleFrameView::SetTitlebarExtraView(View* view) {
DCHECK(view);
DCHECK(!titlebar_extra_view_);
AddChildView(view);
titlebar_extra_view_ = view;
}
gfx::Rect BubbleFrameView::GetUpdatedWindowBounds(const gfx::Rect& anchor_rect,
gfx::Size client_size,
bool adjust_if_offscreen) {
gfx::Insets insets(GetInsets());
client_size.Enlarge(insets.width(), insets.height());
const BubbleBorder::Arrow arrow = bubble_border_->arrow();
if (adjust_if_offscreen && BubbleBorder::has_arrow(arrow)) {
if (!bubble_border_->is_arrow_at_center(arrow)) {
// Try to mirror the anchoring if the bubble does not fit on the screen.
MirrorArrowIfOffScreen(true, anchor_rect, client_size);
MirrorArrowIfOffScreen(false, anchor_rect, client_size);
} else {
// Mirror as needed vertically if the arrow is on a horizontal edge and
// vice-versa.
MirrorArrowIfOffScreen(BubbleBorder::is_arrow_on_horizontal(arrow),
anchor_rect,
client_size);
OffsetArrowIfOffScreen(anchor_rect, client_size);
}
}
// Calculate the bounds with the arrow in its updated location and offset.
return bubble_border_->GetBounds(anchor_rect, client_size);
}
gfx::Rect BubbleFrameView::GetMonitorBounds(const gfx::Rect& rect) {
// TODO(scottmg): Native is wrong. http://crbug.com/133312
return gfx::Screen::GetNativeScreen()->GetDisplayNearestPoint(
rect.CenterPoint()).work_area();
}
void BubbleFrameView::MirrorArrowIfOffScreen(
bool vertical,
const gfx::Rect& anchor_rect,
const gfx::Size& client_size) {
// Check if the bounds don't fit on screen.
gfx::Rect monitor_rect(GetMonitorBounds(anchor_rect));
gfx::Rect window_bounds(bubble_border_->GetBounds(anchor_rect, client_size));
if (GetOffScreenLength(monitor_rect, window_bounds, vertical) > 0) {
BubbleBorder::Arrow arrow = bubble_border()->arrow();
// Mirror the arrow and get the new bounds.
bubble_border_->set_arrow(
vertical ? BubbleBorder::vertical_mirror(arrow) :
BubbleBorder::horizontal_mirror(arrow));
gfx::Rect mirror_bounds =
bubble_border_->GetBounds(anchor_rect, client_size);
// Restore the original arrow if mirroring doesn't show more of the bubble.
if (GetOffScreenLength(monitor_rect, mirror_bounds, vertical) >=
GetOffScreenLength(monitor_rect, window_bounds, vertical))
bubble_border_->set_arrow(arrow);
else
SchedulePaint();
}
}
void BubbleFrameView::OffsetArrowIfOffScreen(const gfx::Rect& anchor_rect,
const gfx::Size& client_size) {
BubbleBorder::Arrow arrow = bubble_border()->arrow();
DCHECK(BubbleBorder::is_arrow_at_center(arrow));
// Get the desired bubble bounds without adjustment.
bubble_border_->set_arrow_offset(0);
gfx::Rect window_bounds(bubble_border_->GetBounds(anchor_rect, client_size));
gfx::Rect monitor_rect(GetMonitorBounds(anchor_rect));
if (monitor_rect.IsEmpty() || monitor_rect.Contains(window_bounds))
return;
// Calculate off-screen adjustment.
const bool is_horizontal = BubbleBorder::is_arrow_on_horizontal(arrow);
int offscreen_adjust = 0;
if (is_horizontal) {
if (window_bounds.x() < monitor_rect.x())
offscreen_adjust = monitor_rect.x() - window_bounds.x();
else if (window_bounds.right() > monitor_rect.right())
offscreen_adjust = monitor_rect.right() - window_bounds.right();
} else {
if (window_bounds.y() < monitor_rect.y())
offscreen_adjust = monitor_rect.y() - window_bounds.y();
else if (window_bounds.bottom() > monitor_rect.bottom())
offscreen_adjust = monitor_rect.bottom() - window_bounds.bottom();
}
// For center arrows, arrows are moved in the opposite direction of
// |offscreen_adjust|, e.g. positive |offscreen_adjust| means bubble
// window needs to be moved to the right and that means we need to move arrow
// to the left, and that means negative offset.
bubble_border_->set_arrow_offset(
bubble_border_->GetArrowOffset(window_bounds.size()) - offscreen_adjust);
if (offscreen_adjust)
SchedulePaint();
}
} // namespace views
<|endoftext|> |
<commit_before>//===- llvm/unittest/Support/MathExtrasTest.cpp - math utils tests --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "gtest/gtest.h"
#include "llvm/Support/MathExtras.h"
using namespace llvm;
namespace {
TEST(MathExtras, isPowerOf2_32) {
EXPECT_TRUE(isPowerOf2_32(1 << 6));
EXPECT_TRUE(isPowerOf2_32(1 << 12));
EXPECT_FALSE(isPowerOf2_32((1 << 19) + 3));
EXPECT_FALSE(isPowerOf2_32(0xABCDEF0));
}
TEST(MathExtras, isPowerOf2_64) {
EXPECT_TRUE(isPowerOf2_64(1LL << 46));
EXPECT_TRUE(isPowerOf2_64(1LL << 12));
EXPECT_FALSE(isPowerOf2_64((1LL << 53) + 3));
EXPECT_FALSE(isPowerOf2_64(0xABCDEF0ABCDEF0LL));
}
TEST(MathExtras, ByteSwap_32) {
EXPECT_EQ(0x44332211u, ByteSwap_32(0x11223344));
EXPECT_EQ(0xDDCCBBAAu, ByteSwap_32(0xAABBCCDD));
}
TEST(MathExtras, ByteSwap_64) {
EXPECT_EQ(0x8877665544332211ULL, ByteSwap_64(0x1122334455667788LL));
EXPECT_EQ(0x1100FFEEDDCCBBAAULL, ByteSwap_64(0xAABBCCDDEEFF0011LL));
}
TEST(MathExtras, CountLeadingZeros_32) {
EXPECT_EQ(8u, CountLeadingZeros_32(0x00F000FF));
EXPECT_EQ(8u, CountLeadingZeros_32(0x00F12345));
for (unsigned i = 0; i <= 30; ++i) {
EXPECT_EQ(31 - i, CountLeadingZeros_32(1 << i));
}
}
TEST(MathExtras, CountLeadingZeros_64) {
EXPECT_EQ(8u, CountLeadingZeros_64(0x00F1234500F12345LL));
EXPECT_EQ(1u, CountLeadingZeros_64(1LL << 62));
for (unsigned i = 0; i <= 62; ++i) {
EXPECT_EQ(63 - i, CountLeadingZeros_64(1LL << i));
}
}
TEST(MathExtras, CountLeadingOnes_32) {
for (int i = 30; i >= 0; --i) {
// Start with all ones and unset some bit.
EXPECT_EQ(31u - i, CountLeadingOnes_32(0xFFFFFFFF ^ (1 << i)));
}
}
TEST(MathExtras, CountLeadingOnes_64) {
for (int i = 62; i >= 0; --i) {
// Start with all ones and unset some bit.
EXPECT_EQ(63u - i, CountLeadingOnes_64(0xFFFFFFFFFFFFFFFFLL ^ (1LL << i)));
}
for (int i = 30; i >= 0; --i) {
// Start with all ones and unset some bit.
EXPECT_EQ(31u - i, CountLeadingOnes_32(0xFFFFFFFF ^ (1 << i)));
}
}
TEST(MathExtras, FloatBits) {
static const float kValue = 5632.34;
EXPECT_FLOAT_EQ(kValue, BitsToFloat(FloatToBits(kValue)));
}
TEST(MathExtras, DoubleBits) {
static const double kValue = 87987234.983498;
EXPECT_FLOAT_EQ(kValue, BitsToDouble(DoubleToBits(kValue)));
}
TEST(MathExtras, MinAlign) {
EXPECT_EQ(1u, MinAlign(2, 3));
EXPECT_EQ(2u, MinAlign(2, 4));
EXPECT_EQ(1u, MinAlign(17, 64));
EXPECT_EQ(256u, MinAlign(256, 512));
}
TEST(MathExtras, NextPowerOf2) {
EXPECT_EQ(4u, NextPowerOf2(3));
EXPECT_EQ(16u, NextPowerOf2(15));
EXPECT_EQ(256u, NextPowerOf2(128));
}
TEST(MathExtras, RoundUpToAlignment) {
EXPECT_EQ(8u, RoundUpToAlignment(5, 8));
EXPECT_EQ(24u, RoundUpToAlignment(17, 8));
EXPECT_EQ(0u, RoundUpToAlignment(~0LL, 8));
}
}
<commit_msg>Fixed header comment.<commit_after>//===- unittests/Support/MathExtrasTest.cpp - math utils tests ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "gtest/gtest.h"
#include "llvm/Support/MathExtras.h"
using namespace llvm;
namespace {
TEST(MathExtras, isPowerOf2_32) {
EXPECT_TRUE(isPowerOf2_32(1 << 6));
EXPECT_TRUE(isPowerOf2_32(1 << 12));
EXPECT_FALSE(isPowerOf2_32((1 << 19) + 3));
EXPECT_FALSE(isPowerOf2_32(0xABCDEF0));
}
TEST(MathExtras, isPowerOf2_64) {
EXPECT_TRUE(isPowerOf2_64(1LL << 46));
EXPECT_TRUE(isPowerOf2_64(1LL << 12));
EXPECT_FALSE(isPowerOf2_64((1LL << 53) + 3));
EXPECT_FALSE(isPowerOf2_64(0xABCDEF0ABCDEF0LL));
}
TEST(MathExtras, ByteSwap_32) {
EXPECT_EQ(0x44332211u, ByteSwap_32(0x11223344));
EXPECT_EQ(0xDDCCBBAAu, ByteSwap_32(0xAABBCCDD));
}
TEST(MathExtras, ByteSwap_64) {
EXPECT_EQ(0x8877665544332211ULL, ByteSwap_64(0x1122334455667788LL));
EXPECT_EQ(0x1100FFEEDDCCBBAAULL, ByteSwap_64(0xAABBCCDDEEFF0011LL));
}
TEST(MathExtras, CountLeadingZeros_32) {
EXPECT_EQ(8u, CountLeadingZeros_32(0x00F000FF));
EXPECT_EQ(8u, CountLeadingZeros_32(0x00F12345));
for (unsigned i = 0; i <= 30; ++i) {
EXPECT_EQ(31 - i, CountLeadingZeros_32(1 << i));
}
}
TEST(MathExtras, CountLeadingZeros_64) {
EXPECT_EQ(8u, CountLeadingZeros_64(0x00F1234500F12345LL));
EXPECT_EQ(1u, CountLeadingZeros_64(1LL << 62));
for (unsigned i = 0; i <= 62; ++i) {
EXPECT_EQ(63 - i, CountLeadingZeros_64(1LL << i));
}
}
TEST(MathExtras, CountLeadingOnes_32) {
for (int i = 30; i >= 0; --i) {
// Start with all ones and unset some bit.
EXPECT_EQ(31u - i, CountLeadingOnes_32(0xFFFFFFFF ^ (1 << i)));
}
}
TEST(MathExtras, CountLeadingOnes_64) {
for (int i = 62; i >= 0; --i) {
// Start with all ones and unset some bit.
EXPECT_EQ(63u - i, CountLeadingOnes_64(0xFFFFFFFFFFFFFFFFLL ^ (1LL << i)));
}
for (int i = 30; i >= 0; --i) {
// Start with all ones and unset some bit.
EXPECT_EQ(31u - i, CountLeadingOnes_32(0xFFFFFFFF ^ (1 << i)));
}
}
TEST(MathExtras, FloatBits) {
static const float kValue = 5632.34;
EXPECT_FLOAT_EQ(kValue, BitsToFloat(FloatToBits(kValue)));
}
TEST(MathExtras, DoubleBits) {
static const double kValue = 87987234.983498;
EXPECT_FLOAT_EQ(kValue, BitsToDouble(DoubleToBits(kValue)));
}
TEST(MathExtras, MinAlign) {
EXPECT_EQ(1u, MinAlign(2, 3));
EXPECT_EQ(2u, MinAlign(2, 4));
EXPECT_EQ(1u, MinAlign(17, 64));
EXPECT_EQ(256u, MinAlign(256, 512));
}
TEST(MathExtras, NextPowerOf2) {
EXPECT_EQ(4u, NextPowerOf2(3));
EXPECT_EQ(16u, NextPowerOf2(15));
EXPECT_EQ(256u, NextPowerOf2(128));
}
TEST(MathExtras, RoundUpToAlignment) {
EXPECT_EQ(8u, RoundUpToAlignment(5, 8));
EXPECT_EQ(24u, RoundUpToAlignment(17, 8));
EXPECT_EQ(0u, RoundUpToAlignment(~0LL, 8));
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
* Copyright (c) 2012-2018 by the DataTransferKit authors *
* All rights reserved. *
* *
* This file is part of the DataTransferKit library. DataTransferKit is *
* distributed under a BSD 3-clause license. For the licensing terms see *
* the LICENSE file in the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#ifndef DTK_DISTRIBUTED_SEARCH_TREE_DECL_HPP
#define DTK_DISTRIBUTED_SEARCH_TREE_DECL_HPP
#include <DTK_Box.hpp>
#include <DTK_DetailsDistributedSearchTreeImpl.hpp>
#include <DTK_DetailsUtils.hpp> // accumulate
#include <DTK_LinearBVH.hpp>
#include <Kokkos_View.hpp>
#include <mpi.h>
namespace DataTransferKit
{
/** \brief Distributed search tree
*
* \note query() must be called as collective over all processes in the
* communicator passed to the constructor.
*/
template <typename DeviceType>
class DistributedSearchTree
{
public:
using bounding_volume_type = typename BVH<DeviceType>::bounding_volume_type;
using size_type = typename BVH<DeviceType>::size_type;
template <typename Primitives>
DistributedSearchTree( MPI_Comm comm, Primitives const &primitives );
/** Returns the smallest axis-aligned box able to contain all the objects
* stored in the tree or an invalid box if the tree is empty.
*/
bounding_volume_type bounds() const { return _top_tree.bounds(); }
/** Returns the global number of objects stored in the tree.
*/
size_type size() const { return _top_tree_size; }
/** Indicates whether the tree is empty on all processes.
*/
bool empty() const { return size() == 0; }
/** \brief Finds object satisfying the passed predicates (e.g. nearest to
* some point or overlaping with some box)
*
* This query function performs a batch of spatial or k-nearest neighbors
* searches. The results give indices of the objects that satisfy
* predicates (as given to the constructor). They are organized in a
* distributed compressed row storage format.
*
* \c indices stores the indices of the objects that satisfy the
* predicates. \c offset stores the locations in the \c indices view that
* start a predicate, that is, \c queries(q) is satisfied by \c indices(o)
* for <code>objects(q) <= o < objects(q+1)</code> that live on processes
* \c ranks(o) respectively. Following the usual convention,
* <code>offset(n) = nnz</code>, where \c n is the number of queries that
* were performed and \c nnz is the total number of collisions.
*
* \note The views \c indices, \c offset, and \c ranks are passed by
* reference because \c Kokkos::realloc() calls the assignment operator.
*
* \param[in] predicates Collection of predicates of the same type. These
* may be spatial predicates or nearest predicates.
* \param[out] args
* - \c indices Object local indices that satisfy the predicates.
* - \c offset Array of predicate offsets for one-dimensional
* storage.
* - \c ranks Process ranks that own objects.
* - \c distances Computed distances (optional and only for nearest
* predicates).
*/
template <typename Predicates, typename... Args>
void query( Predicates const &predicates, Args &&... args ) const
{
// FIXME lame placeholder for concept check
static_assert( Kokkos::is_view<Predicates>::value, "must pass a view" );
using Tag = typename Predicates::value_type::Tag;
Details::DistributedSearchTreeImpl<DeviceType>::queryDispatch(
Tag{}, *this, predicates, std::forward<Args>( args )... );
}
private:
friend struct Details::DistributedSearchTreeImpl<DeviceType>;
MPI_Comm _comm;
BVH<DeviceType> _top_tree; // replicated
BVH<DeviceType> _bottom_tree; // local
size_type _top_tree_size;
Kokkos::View<size_type *, DeviceType> _bottom_tree_sizes;
};
template <typename DeviceType>
template <typename Primitives>
DistributedSearchTree<DeviceType>::DistributedSearchTree(
MPI_Comm comm, Primitives const &primitives )
: _comm( comm )
, _bottom_tree( primitives )
{
int comm_rank;
MPI_Comm_rank( _comm, &comm_rank );
int comm_size;
MPI_Comm_size( _comm, &comm_size );
Kokkos::View<Box *, DeviceType> boxes(
Kokkos::ViewAllocateWithoutInitializing( "rank_bounding_boxes" ),
comm_size );
// FIXME: I am not sure how to do the MPI allgather with Teuchos for data
// living on the device so I copied to the host.
auto boxes_host = Kokkos::create_mirror_view( boxes );
boxes_host( comm_rank ) = _bottom_tree.bounds();
MPI_Allgather( MPI_IN_PLACE, 0, MPI_DATATYPE_NULL,
static_cast<void *>( boxes_host.data() ), sizeof( Box ),
MPI_BYTE, _comm );
Kokkos::deep_copy( boxes, boxes_host );
_top_tree = BVH<DeviceType>( boxes );
_bottom_tree_sizes = Kokkos::View<size_type *, DeviceType>(
Kokkos::ViewAllocateWithoutInitializing( "leave_count_in_local_trees" ),
comm_size );
auto bottom_tree_sizes_host =
Kokkos::create_mirror_view( _bottom_tree_sizes );
bottom_tree_sizes_host( comm_rank ) = _bottom_tree.size();
MPI_Allgather( MPI_IN_PLACE, 0, MPI_DATATYPE_NULL,
static_cast<void *>( bottom_tree_sizes_host.data() ),
sizeof( size_type ), MPI_BYTE, _comm );
Kokkos::deep_copy( _bottom_tree_sizes, bottom_tree_sizes_host );
_top_tree_size = accumulate( _bottom_tree_sizes, 0 );
}
} // namespace DataTransferKit
#endif
<commit_msg>Update outdated comment about not copying to the host when moving to MPI with CUDA support<commit_after>/****************************************************************************
* Copyright (c) 2012-2018 by the DataTransferKit authors *
* All rights reserved. *
* *
* This file is part of the DataTransferKit library. DataTransferKit is *
* distributed under a BSD 3-clause license. For the licensing terms see *
* the LICENSE file in the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#ifndef DTK_DISTRIBUTED_SEARCH_TREE_DECL_HPP
#define DTK_DISTRIBUTED_SEARCH_TREE_DECL_HPP
#include <DTK_Box.hpp>
#include <DTK_DetailsDistributedSearchTreeImpl.hpp>
#include <DTK_DetailsUtils.hpp> // accumulate
#include <DTK_LinearBVH.hpp>
#include <Kokkos_View.hpp>
#include <mpi.h>
namespace DataTransferKit
{
/** \brief Distributed search tree
*
* \note query() must be called as collective over all processes in the
* communicator passed to the constructor.
*/
template <typename DeviceType>
class DistributedSearchTree
{
public:
using bounding_volume_type = typename BVH<DeviceType>::bounding_volume_type;
using size_type = typename BVH<DeviceType>::size_type;
template <typename Primitives>
DistributedSearchTree( MPI_Comm comm, Primitives const &primitives );
/** Returns the smallest axis-aligned box able to contain all the objects
* stored in the tree or an invalid box if the tree is empty.
*/
bounding_volume_type bounds() const { return _top_tree.bounds(); }
/** Returns the global number of objects stored in the tree.
*/
size_type size() const { return _top_tree_size; }
/** Indicates whether the tree is empty on all processes.
*/
bool empty() const { return size() == 0; }
/** \brief Finds object satisfying the passed predicates (e.g. nearest to
* some point or overlaping with some box)
*
* This query function performs a batch of spatial or k-nearest neighbors
* searches. The results give indices of the objects that satisfy
* predicates (as given to the constructor). They are organized in a
* distributed compressed row storage format.
*
* \c indices stores the indices of the objects that satisfy the
* predicates. \c offset stores the locations in the \c indices view that
* start a predicate, that is, \c queries(q) is satisfied by \c indices(o)
* for <code>objects(q) <= o < objects(q+1)</code> that live on processes
* \c ranks(o) respectively. Following the usual convention,
* <code>offset(n) = nnz</code>, where \c n is the number of queries that
* were performed and \c nnz is the total number of collisions.
*
* \note The views \c indices, \c offset, and \c ranks are passed by
* reference because \c Kokkos::realloc() calls the assignment operator.
*
* \param[in] predicates Collection of predicates of the same type. These
* may be spatial predicates or nearest predicates.
* \param[out] args
* - \c indices Object local indices that satisfy the predicates.
* - \c offset Array of predicate offsets for one-dimensional
* storage.
* - \c ranks Process ranks that own objects.
* - \c distances Computed distances (optional and only for nearest
* predicates).
*/
template <typename Predicates, typename... Args>
void query( Predicates const &predicates, Args &&... args ) const
{
// FIXME lame placeholder for concept check
static_assert( Kokkos::is_view<Predicates>::value, "must pass a view" );
using Tag = typename Predicates::value_type::Tag;
Details::DistributedSearchTreeImpl<DeviceType>::queryDispatch(
Tag{}, *this, predicates, std::forward<Args>( args )... );
}
private:
friend struct Details::DistributedSearchTreeImpl<DeviceType>;
MPI_Comm _comm;
BVH<DeviceType> _top_tree; // replicated
BVH<DeviceType> _bottom_tree; // local
size_type _top_tree_size;
Kokkos::View<size_type *, DeviceType> _bottom_tree_sizes;
};
template <typename DeviceType>
template <typename Primitives>
DistributedSearchTree<DeviceType>::DistributedSearchTree(
MPI_Comm comm, Primitives const &primitives )
: _comm( comm )
, _bottom_tree( primitives )
{
int comm_rank;
MPI_Comm_rank( _comm, &comm_rank );
int comm_size;
MPI_Comm_size( _comm, &comm_size );
Kokkos::View<Box *, DeviceType> boxes(
Kokkos::ViewAllocateWithoutInitializing( "rank_bounding_boxes" ),
comm_size );
// FIXME when we move to MPI with CUDA-aware support, we will not need to
// copy from the device to the host
auto boxes_host = Kokkos::create_mirror_view( boxes );
boxes_host( comm_rank ) = _bottom_tree.bounds();
MPI_Allgather( MPI_IN_PLACE, 0, MPI_DATATYPE_NULL,
static_cast<void *>( boxes_host.data() ), sizeof( Box ),
MPI_BYTE, _comm );
Kokkos::deep_copy( boxes, boxes_host );
_top_tree = BVH<DeviceType>( boxes );
_bottom_tree_sizes = Kokkos::View<size_type *, DeviceType>(
Kokkos::ViewAllocateWithoutInitializing( "leave_count_in_local_trees" ),
comm_size );
auto bottom_tree_sizes_host =
Kokkos::create_mirror_view( _bottom_tree_sizes );
bottom_tree_sizes_host( comm_rank ) = _bottom_tree.size();
MPI_Allgather( MPI_IN_PLACE, 0, MPI_DATATYPE_NULL,
static_cast<void *>( bottom_tree_sizes_host.data() ),
sizeof( size_type ), MPI_BYTE, _comm );
Kokkos::deep_copy( _bottom_tree_sizes, bottom_tree_sizes_host );
_top_tree_size = accumulate( _bottom_tree_sizes, 0 );
}
} // namespace DataTransferKit
#endif
<|endoftext|> |
<commit_before>/***********************************************************************************************************************
* *
* SPLASH build system v0.2 *
* *
* Copyright (c) 2016 Andrew D. Zonenberg *
* 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 the author nor the names of any contributors may be used to endorse or promote products *
* derived from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL *
* THE AUTHORS BE HELD 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 "splashcore.h"
using namespace std;
Cache* g_cache = NULL;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construction / destruction
Cache::Cache(string cachename)
{
LogVerbose("Initializing cache subsystem...\n");
LogIndenter li;
//TODO: get cache path from command line arg or something?
//Hard-coding the path prevents more than one splashctl instance from running on a given server.
//This may or may not be what we want. If we DO want to limit to one instance, we need a way for multiple distinct
//projects to share the splashctl/splashbuild back end.
string home = getenv("HOME");
if(!DoesDirectoryExist(home))
LogFatal("home dir does not exist\n");
m_cachePath = home + "/.splash/cache-" + cachename;
//If the cache directory does not exist, create it
if(!DoesDirectoryExist(m_cachePath))
{
LogDebug("Cache directory does not exist, creating it\n");
MakeDirectoryRecursive(m_cachePath, 0600);
}
//It exists, load existing entries
else
{
LogDebug("Cache directory exists, loading items\n");
for(unsigned int i=0; i<256; i++)
{
//If the cache isn't very full we might not have entries in every bucket
char hex[3];
snprintf(hex, sizeof(hex), "%02x", i);
string dirname = m_cachePath + "/" + hex;
if(!DoesDirectoryExist(dirname))
continue;
//It exists, load whatever is in it
vector<string> subdirs;
FindSubdirs(dirname, subdirs);
for(auto dir : subdirs)
{
//The object ID is what goes in our table, not the file hash
string oid = GetBasenameOfFile(dir);
if(!ValidateCacheEntry(oid))
{
LogWarning("Cache entry %s is not valid\n", oid.c_str());
continue;
}
//TODO: load fail records too
//Cache entry is valid, add to the cache table
m_cacheIndex.emplace(oid);
}
}
LogVerbose("%d cache entries loaded\n", (int)m_cacheIndex.size());
}
}
Cache::~Cache()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Status queries
NodeInfo::NodeState Cache::GetState(string id)
{
lock_guard<recursive_mutex> lock(m_mutex);
if(IsCached(id))
return NodeInfo::READY;
else if(IsFailed(id))
return NodeInfo::FAILED;
//TODO: check if it's building
else
return NodeInfo::MISSING;
}
/**
@brief Determine if a particular object is in the cache.
@param id Object ID hash
*/
bool Cache::IsCached(string id)
{
lock_guard<recursive_mutex> lock(m_mutex);
if(m_cacheIndex.find(id) != m_cacheIndex.end())
return true;
return false;
}
/**
@brief Determine if a particular object is in the cache with a "fail" record.
@param id Object ID hash
*/
bool Cache::IsFailed(string id)
{
lock_guard<recursive_mutex> lock(m_mutex);
if(m_cacheFails.find(id) != m_cacheFails.end())
return true;
return false;
}
/**
@brief Stronger form of IsCached(). Checks if the internal hash is consistent
@param id Object ID hash
*/
bool Cache::ValidateCacheEntry(string id)
{
lock_guard<recursive_mutex> lock(m_mutex);
//If the directory doesn't exist, obviously we have nothing useful there
string dir = GetStoragePath(id);
if(!DoesDirectoryExist(dir))
return false;
//If we're missing the file or hash, can't possibly be valid
string fpath = dir + "/data";
string hpath = dir + "/hash";
if( !DoesFileExist(fpath) || !DoesFileExist(hpath) )
return false;
//Get the expected hash and compare to the real one
//If it's invalid, just get rid of the junk
string expected = GetFileContents(hpath);
string found = sha256_file(fpath);
if(expected != found)
{
LogWarning("Cache directory %s is corrupted (hash match failed)\n", id.c_str());
LogDebug("Expected hash: %s\n", expected.c_str());
LogDebug("Found hash: %s\n", found.c_str());
ShellCommand(string("rm -I ") + dir + "/*");
ShellCommand(string("rm -r ") + dir);
return false;
}
return true;
}
/**
@brief Gets the cache path used for storing a particular object
*/
string Cache::GetStoragePath(string id)
{
return m_cachePath + "/" + id.substr(0, 2) + "/" + id;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Cache manipulation
/**
@brief Reads a file from the cache
*/
string Cache::ReadCachedFile(string id)
{
lock_guard<recursive_mutex> lock(m_mutex);
//Sanity check
if(!IsCached(id))
{
LogError("Requested file %s is not in cache\n", id.c_str());
return "";
}
//Read the file
string ret = GetFileContents(GetStoragePath(id) + "/data");
return ret;
}
/**
@brief Reads the log from a file from the cache
*/
string Cache::ReadCachedLog(string id)
{
lock_guard<recursive_mutex> lock(m_mutex);
//Sanity check
if(!IsCached(id) && !IsFailed(id))
{
LogError("Requested log %s is not in cache\n", id.c_str());
return "";
}
//Read the file
string ret = GetFileContents(GetStoragePath(id) + "/log");
return ret;
}
/**
@brief Adds a new file's metadata to the cache, reporting that we couldn't actually make it
*/
void Cache::AddFailedFile(string basename, string id, string log)
{
lock_guard<recursive_mutex> lock(m_mutex);
//If the content is already in the cache, skip it
if(IsCached(id) || IsFailed(id))
return;
//Create the directory. If it already exists, delete whatever junk was in there
string dirname = GetStoragePath(id);
if(DoesDirectoryExist(dirname))
{
LogWarning("Cache directory %s already exists but was not loaded, removing dead files\n", id.c_str());
ShellCommand(string("rm -I ") + dirname + "/*");
}
else
MakeDirectoryRecursive(dirname, 0600);
//Create the "failed" record
if(!PutFileContents(dirname + "/failed", ""))
return;
//Write the command stdout (not integrity checked)
if(!PutFileContents(dirname + "/log", log))
return;
//Remember that we have this file cached
m_cacheFails.emplace(id);
}
/**
@brief Adds a file to the cache
@param basename Name of the file without directory information
@param id Object ID hash
@param hash SHA-256 sum of the file
@param data The data to write
@param log Standard output of the command that built this file
*/
void Cache::AddFile(string /*basename*/, string id, string hash, string data, string log)
{
lock_guard<recursive_mutex> lock(m_mutex);
//If the content is already in the cache, skip it
if(IsCached(id) || IsFailed(id))
return;
//Create the directory. If it already exists, delete whatever junk was in there
string dirname = GetStoragePath(id);
if(DoesDirectoryExist(dirname))
{
LogWarning("Cache directory %s already exists but was not loaded, removing dead files\n", id.c_str());
ShellCommand(string("rm -I ") + dirname + "/*");
}
else
MakeDirectoryRecursive(dirname, 0600);
//Write the file data to it
if(!PutFileContents(dirname + "/data", data))
return;
//Write the hash
if(!PutFileContents(dirname + "/hash", hash))
return;
//Write the command stdout (not integrity checked)
if(!PutFileContents(dirname + "/log", log))
return;
//Sanity check
string chash = sha256(data);
if(chash != hash)
{
LogWarning("Adding new cache entry for id %s:\n", id.c_str());
LogIndenter li;
LogWarning("passed: %s:\n", hash.c_str());
LogWarning("calculated: %s:\n", chash.c_str());
}
//TODO: write the atime file?
//Remember that we have this file cached
m_cacheIndex.emplace(id);
//TODO: add this file's size to the cache, if we went over the cap delete the LRU file
}
<commit_msg>splashcore: Cache now gives more useful error messages if you pass the wrong hash<commit_after>/***********************************************************************************************************************
* *
* SPLASH build system v0.2 *
* *
* Copyright (c) 2016 Andrew D. Zonenberg *
* 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 the author nor the names of any contributors may be used to endorse or promote products *
* derived from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL *
* THE AUTHORS BE HELD 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 "splashcore.h"
using namespace std;
Cache* g_cache = NULL;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construction / destruction
Cache::Cache(string cachename)
{
LogVerbose("Initializing cache subsystem...\n");
LogIndenter li;
//TODO: get cache path from command line arg or something?
//Hard-coding the path prevents more than one splashctl instance from running on a given server.
//This may or may not be what we want. If we DO want to limit to one instance, we need a way for multiple distinct
//projects to share the splashctl/splashbuild back end.
string home = getenv("HOME");
if(!DoesDirectoryExist(home))
LogFatal("home dir does not exist\n");
m_cachePath = home + "/.splash/cache-" + cachename;
//If the cache directory does not exist, create it
if(!DoesDirectoryExist(m_cachePath))
{
LogDebug("Cache directory does not exist, creating it\n");
MakeDirectoryRecursive(m_cachePath, 0600);
}
//It exists, load existing entries
else
{
LogDebug("Cache directory exists, loading items\n");
for(unsigned int i=0; i<256; i++)
{
//If the cache isn't very full we might not have entries in every bucket
char hex[3];
snprintf(hex, sizeof(hex), "%02x", i);
string dirname = m_cachePath + "/" + hex;
if(!DoesDirectoryExist(dirname))
continue;
//It exists, load whatever is in it
vector<string> subdirs;
FindSubdirs(dirname, subdirs);
for(auto dir : subdirs)
{
//The object ID is what goes in our table, not the file hash
string oid = GetBasenameOfFile(dir);
if(!ValidateCacheEntry(oid))
{
LogWarning("Cache entry %s is not valid\n", oid.c_str());
continue;
}
//TODO: load fail records too
//Cache entry is valid, add to the cache table
m_cacheIndex.emplace(oid);
}
}
LogVerbose("%d cache entries loaded\n", (int)m_cacheIndex.size());
}
}
Cache::~Cache()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Status queries
NodeInfo::NodeState Cache::GetState(string id)
{
lock_guard<recursive_mutex> lock(m_mutex);
if(IsCached(id))
return NodeInfo::READY;
else if(IsFailed(id))
return NodeInfo::FAILED;
//TODO: check if it's building
else
return NodeInfo::MISSING;
}
/**
@brief Determine if a particular object is in the cache.
@param id Object ID hash
*/
bool Cache::IsCached(string id)
{
lock_guard<recursive_mutex> lock(m_mutex);
if(m_cacheIndex.find(id) != m_cacheIndex.end())
return true;
return false;
}
/**
@brief Determine if a particular object is in the cache with a "fail" record.
@param id Object ID hash
*/
bool Cache::IsFailed(string id)
{
lock_guard<recursive_mutex> lock(m_mutex);
if(m_cacheFails.find(id) != m_cacheFails.end())
return true;
return false;
}
/**
@brief Stronger form of IsCached(). Checks if the internal hash is consistent
@param id Object ID hash
*/
bool Cache::ValidateCacheEntry(string id)
{
lock_guard<recursive_mutex> lock(m_mutex);
//If the directory doesn't exist, obviously we have nothing useful there
string dir = GetStoragePath(id);
if(!DoesDirectoryExist(dir))
return false;
//If we're missing the file or hash, can't possibly be valid
string fpath = dir + "/data";
string hpath = dir + "/hash";
if( !DoesFileExist(fpath) || !DoesFileExist(hpath) )
return false;
//Get the expected hash and compare to the real one
//If it's invalid, just get rid of the junk
string expected = GetFileContents(hpath);
string found = sha256_file(fpath);
if(expected != found)
{
LogWarning("Cache directory %s is corrupted (hash match failed)\n", id.c_str());
LogDebug("Expected hash: %s\n", expected.c_str());
LogDebug("Found hash: %s\n", found.c_str());
ShellCommand(string("rm -I ") + dir + "/*");
ShellCommand(string("rm -r ") + dir);
return false;
}
return true;
}
/**
@brief Gets the cache path used for storing a particular object
*/
string Cache::GetStoragePath(string id)
{
return m_cachePath + "/" + id.substr(0, 2) + "/" + id;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Cache manipulation
/**
@brief Reads a file from the cache
*/
string Cache::ReadCachedFile(string id)
{
lock_guard<recursive_mutex> lock(m_mutex);
//Sanity check
if(!IsCached(id))
{
LogError("Requested file %s is not in cache\n", id.c_str());
return "";
}
//Read the file
string ret = GetFileContents(GetStoragePath(id) + "/data");
return ret;
}
/**
@brief Reads the log from a file from the cache
*/
string Cache::ReadCachedLog(string id)
{
lock_guard<recursive_mutex> lock(m_mutex);
//Sanity check
if(!IsCached(id) && !IsFailed(id))
{
LogError("Requested log %s is not in cache\n", id.c_str());
return "";
}
//Read the file
string ret = GetFileContents(GetStoragePath(id) + "/log");
return ret;
}
/**
@brief Adds a new file's metadata to the cache, reporting that we couldn't actually make it
*/
void Cache::AddFailedFile(string basename, string id, string log)
{
lock_guard<recursive_mutex> lock(m_mutex);
//If the content is already in the cache, skip it
if(IsCached(id) || IsFailed(id))
return;
//Create the directory. If it already exists, delete whatever junk was in there
string dirname = GetStoragePath(id);
if(DoesDirectoryExist(dirname))
{
LogWarning("Cache directory %s already exists but was not loaded, removing dead files\n", id.c_str());
ShellCommand(string("rm -I ") + dirname + "/*");
}
else
MakeDirectoryRecursive(dirname, 0600);
//Create the "failed" record
if(!PutFileContents(dirname + "/failed", ""))
return;
//Write the command stdout (not integrity checked)
if(!PutFileContents(dirname + "/log", log))
return;
//Remember that we have this file cached
m_cacheFails.emplace(id);
}
/**
@brief Adds a file to the cache
@param basename Name of the file without directory information
@param id Object ID hash
@param hash SHA-256 sum of the file
@param data The data to write
@param log Standard output of the command that built this file
*/
void Cache::AddFile(string basename, string id, string hash, string data, string log)
{
lock_guard<recursive_mutex> lock(m_mutex);
//If the content is already in the cache, skip it
if(IsCached(id) || IsFailed(id))
return;
//Create the directory. If it already exists, delete whatever junk was in there
string dirname = GetStoragePath(id);
if(DoesDirectoryExist(dirname))
{
LogWarning("Cache directory %s already exists but was not loaded, removing dead files\n", id.c_str());
ShellCommand(string("rm -I ") + dirname + "/*");
}
else
MakeDirectoryRecursive(dirname, 0600);
//Write the file data to it
if(!PutFileContents(dirname + "/data", data))
return;
//Write the hash
if(!PutFileContents(dirname + "/hash", hash))
return;
//Write the command stdout (not integrity checked)
if(!PutFileContents(dirname + "/log", log))
return;
//Sanity check
string chash = sha256(data);
if(chash != hash)
{
LogWarning("Adding new cache entry for id %s (%s):\n", id.c_str(), basename.c_str());
LogIndenter li;
LogWarning("passed: %s:\n", hash.c_str());
LogWarning("calculated: %s:\n", chash.c_str());
}
//TODO: write the atime file?
//Remember that we have this file cached
m_cacheIndex.emplace(id);
//TODO: add this file's size to the cache, if we went over the cap delete the LRU file
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include "AliTrackReference.h"
#include "TParticle.h"
#include "AliRun.h"
#include "TLorentzVector.h"
//
// Track Reference object is created every time particle is
// crossing detector bounds. The object is created by Step Manager
//
// The class stores the following informations:
// track label,
// track position: X,Y,X
// track momentum px, py, pz
// track length and time of fligth: both in cm
// status bits from Monte Carlo
//
ClassImp(AliTrackReference)
//_______________________________________________________________________
AliTrackReference::AliTrackReference():
fTrack(0),
fX(0),
fY(0),
fZ(0),
fPx(0),
fPy(0),
fPz(0),
fLength(0)
{
//
// Default constructor
// Creates empty object
for(Int_t i=0; i<16; i++) ResetBit(BIT(i));
}
//_______________________________________________________________________
AliTrackReference::AliTrackReference(Int_t label, TVirtualMC *vMC) {
//
// Create Reference object out of label and
// data in TVirtualMC object
//
// Creates an object and fill all parameters
// from data in VirtualMC
//
// Sylwester Radomski, (S.Radomski@gsi.de)
// GSI, Jan 31, 2003
//
TLorentzVector vec;
fTrack = label;
fLength = vMC->TrackLength();
fTime = vMC->TrackTime();
vMC->TrackPosition(vec);
fX = vec[0];
fY = vec[1];
fZ = vec[2];
vMC->TrackMomentum(vec);
fPx = vec[0];
fPy = vec[1];
fPy = vec[2];
// Set Up status code
// Copy Bits from virtual MC
for(Int_t i=0; i<16; i++) ResetBit(BIT(i));
SetBit(BIT(0), vMC->IsNewTrack());
SetBit(BIT(1), vMC->IsTrackAlive());
SetBit(BIT(2), vMC->IsTrackDisappeared());
SetBit(BIT(3), vMC->IsTrackEntering());
SetBit(BIT(4), vMC->IsTrackExiting());
SetBit(BIT(5), vMC->IsTrackInside());
SetBit(BIT(6), vMC->IsTrackOut());
SetBit(BIT(7), vMC->IsTrackStop());
}
//_______________________________________________________________________
<commit_msg>Correcting typo<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include "AliTrackReference.h"
#include "TParticle.h"
#include "AliRun.h"
#include "TLorentzVector.h"
//
// Track Reference object is created every time particle is
// crossing detector bounds. The object is created by Step Manager
//
// The class stores the following informations:
// track label,
// track position: X,Y,X
// track momentum px, py, pz
// track length and time of fligth: both in cm
// status bits from Monte Carlo
//
ClassImp(AliTrackReference)
//_______________________________________________________________________
AliTrackReference::AliTrackReference():
fTrack(0),
fX(0),
fY(0),
fZ(0),
fPx(0),
fPy(0),
fPz(0),
fLength(0)
{
//
// Default constructor
// Creates empty object
for(Int_t i=0; i<16; i++) ResetBit(BIT(i));
}
//_______________________________________________________________________
AliTrackReference::AliTrackReference(Int_t label, TVirtualMC *vMC) {
//
// Create Reference object out of label and
// data in TVirtualMC object
//
// Creates an object and fill all parameters
// from data in VirtualMC
//
// Sylwester Radomski, (S.Radomski@gsi.de)
// GSI, Jan 31, 2003
//
TLorentzVector vec;
fTrack = label;
fLength = vMC->TrackLength();
fTime = vMC->TrackTime();
vMC->TrackPosition(vec);
fX = vec[0];
fY = vec[1];
fZ = vec[2];
vMC->TrackMomentum(vec);
fPx = vec[0];
fPy = vec[1];
fPz = vec[2];
// Set Up status code
// Copy Bits from virtual MC
for(Int_t i=0; i<16; i++) ResetBit(BIT(i));
SetBit(BIT(0), vMC->IsNewTrack());
SetBit(BIT(1), vMC->IsTrackAlive());
SetBit(BIT(2), vMC->IsTrackDisappeared());
SetBit(BIT(3), vMC->IsTrackEntering());
SetBit(BIT(4), vMC->IsTrackExiting());
SetBit(BIT(5), vMC->IsTrackInside());
SetBit(BIT(6), vMC->IsTrackOut());
SetBit(BIT(7), vMC->IsTrackStop());
}
//_______________________________________________________________________
<|endoftext|> |
<commit_before>#pragma once
#include <optional>
#include "Runtime/Collision/CCollidableAABox.hpp"
#include "Runtime/World/CActor.hpp"
#include <zeus/CAxisAngle.hpp>
#include <zeus/CQuaternion.hpp>
#include <zeus/CTransform.hpp>
#include <zeus/CVector3f.hpp>
namespace urde {
class CCollisionInfoList;
struct SMoverData;
struct SMoverData {
zeus::CVector3f x0_velocity;
zeus::CAxisAngle xc_angularVelocity;
zeus::CVector3f x18_momentum;
zeus::CAxisAngle x24_;
float x30_mass;
SMoverData(float mass) : x30_mass(mass) {}
};
struct CMotionState {
zeus::CVector3f x0_translation;
zeus::CNUQuaternion xc_orientation;
zeus::CVector3f x1c_velocity;
zeus::CAxisAngle x28_angularMomentum;
CMotionState(const zeus::CVector3f& origin, const zeus::CNUQuaternion& orientation, const zeus::CVector3f& velocity,
const zeus::CAxisAngle& angle)
: x0_translation(origin), xc_orientation(orientation), x1c_velocity(velocity), x28_angularMomentum(angle) {}
CMotionState(const zeus::CVector3f& origin, const zeus::CNUQuaternion& orientation)
: x0_translation(origin), xc_orientation(orientation) {}
};
class CPhysicsState {
zeus::CVector3f x0_translation;
zeus::CQuaternion xc_orientation;
zeus::CVector3f x1c_constantForce;
zeus::CAxisAngle x28_angularMomentum;
zeus::CVector3f x34_momentum;
zeus::CVector3f x40_force;
zeus::CVector3f x4c_impulse;
zeus::CAxisAngle x58_torque;
zeus::CAxisAngle x64_angularImpulse;
public:
CPhysicsState(const zeus::CVector3f& translation, const zeus::CQuaternion& orient, const zeus::CVector3f& v2,
const zeus::CAxisAngle& a1, const zeus::CVector3f& v3, const zeus::CVector3f& v4,
const zeus::CVector3f& v5, const zeus::CAxisAngle& a2, const zeus::CAxisAngle& a3)
: x0_translation(translation)
, xc_orientation(orient)
, x1c_constantForce(v2)
, x28_angularMomentum(a1)
, x34_momentum(v3)
, x40_force(v4)
, x4c_impulse(v5)
, x58_torque(a2)
, x64_angularImpulse(a3) {}
void SetTranslation(const zeus::CVector3f& tr) { x0_translation = tr; }
void SetOrientation(const zeus::CQuaternion& orient) { xc_orientation = orient; }
const zeus::CQuaternion& GetOrientation() const { return xc_orientation; }
const zeus::CVector3f& GetTranslation() const { return x0_translation; }
const zeus::CVector3f& GetConstantForceWR() const { return x1c_constantForce; }
const zeus::CAxisAngle& GetAngularMomentumWR() const { return x28_angularMomentum; }
const zeus::CVector3f& GetMomentumWR() const { return x34_momentum; }
const zeus::CVector3f& GetForceWR() const { return x40_force; }
const zeus::CVector3f& GetImpulseWR() const { return x4c_impulse; }
const zeus::CAxisAngle& GetTorque() const { return x58_torque; }
const zeus::CAxisAngle& GetAngularImpulseWR() const { return x64_angularImpulse; }
};
class CPhysicsActor : public CActor {
friend class CGroundMovement;
protected:
float xe8_mass;
float xec_massRecip;
float xf0_inertiaTensor;
float xf4_inertiaTensorRecip;
union {
struct {
bool xf8_24_movable : 1;
bool xf8_25_angularEnabled : 1;
};
u8 _dummy = 0;
};
bool xf9_standardCollider = false;
zeus::CVector3f xfc_constantForce;
zeus::CAxisAngle x108_angularMomentum;
zeus::CMatrix3f x114_;
zeus::CVector3f x138_velocity;
zeus::CAxisAngle x144_angularVelocity;
zeus::CVector3f x150_momentum;
zeus::CVector3f x15c_force;
zeus::CVector3f x168_impulse;
zeus::CAxisAngle x174_torque;
zeus::CAxisAngle x180_angularImpulse;
zeus::CVector3f x18c_moveImpulse;
zeus::CAxisAngle x198_moveAngularImpulse;
zeus::CAABox x1a4_baseBoundingBox;
CCollidableAABox x1c0_collisionPrimitive;
zeus::CVector3f x1e8_primitiveOffset;
CMotionState x1f4_lastNonCollidingState;
std::optional<zeus::CVector3f> x228_lastFloorPlaneNormal;
float x238_maximumCollisionVelocity = 1000000.0f;
float x23c_stepUpHeight;
float x240_stepDownHeight;
float x244_restitutionCoefModifier = 0.f;
float x248_collisionAccuracyModifier = 1.f;
u32 x24c_numTicksStuck = 0;
u32 x250_numTicksPartialUpdate = 0;
public:
CPhysicsActor(TUniqueId uid, bool active, std::string_view name, const CEntityInfo& info, const zeus::CTransform& xf,
CModelData&& mData, const CMaterialList& matList, const zeus::CAABox& box, const SMoverData& moverData,
const CActorParameters& actorParms, float stepUp, float stepDown);
void Render(const CStateManager& mgr) const override;
zeus::CVector3f GetOrbitPosition(const CStateManager& mgr) const override;
zeus::CVector3f GetAimPosition(const CStateManager& mgr, float val) const override;
virtual const CCollisionPrimitive* GetCollisionPrimitive() const;
virtual zeus::CTransform GetPrimitiveTransform() const;
virtual void CollidedWith(TUniqueId id, const CCollisionInfoList& list, CStateManager& mgr);
virtual float GetStepUpHeight() const;
virtual float GetStepDownHeight() const;
virtual float GetWeight() const;
float GetMass() const { return xe8_mass; }
void SetPrimitiveOffset(const zeus::CVector2f& offset);
const zeus::CVector3f& GetPrimitiveOffset() const { return x1e8_primitiveOffset; }
void MoveCollisionPrimitive(const zeus::CVector3f& offset);
void SetBoundingBox(const zeus::CAABox& box);
zeus::CAABox GetMotionVolume(float dt) const;
zeus::CVector3f CalculateNewVelocityWR_UsingImpulses() const;
zeus::CAABox GetBoundingBox() const;
const zeus::CAABox& GetBaseBoundingBox() const;
void AddMotionState(const CMotionState& mst);
CMotionState GetMotionState() const;
const CMotionState& GetLastNonCollidingState() const { return x1f4_lastNonCollidingState; }
void SetLastNonCollidingState(const CMotionState& mst) { x1f4_lastNonCollidingState = mst; }
void SetMotionState(const CMotionState& mst);
float GetMaximumCollisionVelocity() const { return x238_maximumCollisionVelocity; }
void SetMaximumCollisionVelocity(float velocity) { x238_maximumCollisionVelocity = velocity; }
void SetInertiaTensorScalar(float tensor);
void SetMass(float mass);
void SetAngularVelocityOR(const zeus::CAxisAngle& angVel);
zeus::CAxisAngle GetAngularVelocityOR() const;
const zeus::CAxisAngle& GetAngularVelocityWR() const { return x144_angularVelocity; }
void SetAngularVelocityWR(const zeus::CAxisAngle& angVel);
const zeus::CVector3f& GetForceOR() const { return x15c_force; }
const zeus::CVector3f& GetImpulseOR() const { return x168_impulse; }
const zeus::CVector3f& GetMoveImpulseOR() const { return x18c_moveImpulse; }
void SetVelocityWR(const zeus::CVector3f& vel);
void SetVelocityOR(const zeus::CVector3f& vel);
void SetMomentumWR(const zeus::CVector3f& momentum) { x150_momentum = momentum; }
const zeus::CVector3f& GetConstantForce() const { return xfc_constantForce; }
void SetConstantForce(const zeus::CVector3f& force) { xfc_constantForce = force; }
void SetAngularMomentum(const zeus::CAxisAngle& momentum) { x108_angularMomentum = momentum; }
const zeus::CVector3f& GetMomentum() const { return x150_momentum; }
const zeus::CVector3f& GetVelocity() const { return x138_velocity; }
const zeus::CAxisAngle& GetAngularImpulse() const { return x180_angularImpulse; }
void SetAngularImpulse(const zeus::CAxisAngle& impulse) { x180_angularImpulse = impulse; }
zeus::CVector3f GetTotalForcesWR() const;
void RotateInOneFrameOR(const zeus::CQuaternion& q, float d);
void MoveInOneFrameOR(const zeus::CVector3f& trans, float d);
void RotateToOR(const zeus::CQuaternion& q, float d);
void MoveToOR(const zeus::CVector3f& trans, float d);
void MoveToInOneFrameWR(const zeus::CVector3f& v1, float d);
void MoveToWR(const zeus::CVector3f& trans, float d);
zeus::CAxisAngle GetRotateToORAngularMomentumWR(const zeus::CQuaternion& q, float d) const;
zeus::CVector3f GetMoveToORImpulseWR(const zeus::CVector3f& trans, float d) const;
void ClearImpulses();
void ClearForcesAndTorques();
void Stop();
void ComputeDerivedQuantities();
bool WillMove(const CStateManager& mgr) const;
void SetPhysicsState(const CPhysicsState& state);
CPhysicsState GetPhysicsState() const;
bool IsMovable() const { return xf8_24_movable; }
void SetMovable(bool movable) { xf8_24_movable = movable; }
bool IsAngularEnabled() const { return xf8_25_angularEnabled; }
void SetAngularEnabled(bool enabled) { xf8_25_angularEnabled = enabled; }
float GetCollisionAccuracyModifier() const { return x248_collisionAccuracyModifier; }
void SetCollisionAccuracyModifier(float modifier) { x248_collisionAccuracyModifier = modifier; }
float GetCoefficientOfRestitutionModifier() const { return x244_restitutionCoefModifier; }
void SetCoefficientOfRestitutionModifier(float modifier) { x244_restitutionCoefModifier = modifier; }
bool IsUseStandardCollider() const { return xf9_standardCollider; }
u32 GetNumTicksPartialUpdate() const { return x250_numTicksPartialUpdate; }
void SetNumTicksPartialUpdate(u32 ticks) { x250_numTicksPartialUpdate = ticks; }
u32 GetNumTicksStuck() const { return x24c_numTicksStuck; }
void SetNumTicksStuck(u32 ticks) { x24c_numTicksStuck = ticks; }
const std::optional<zeus::CVector3f>& GetLastFloorPlaneNormal() const {
return x228_lastFloorPlaneNormal;
}
void SetLastFloorPlaneNormal(const std::optional<zeus::CVector3f>& normal) { x228_lastFloorPlaneNormal = normal; }
CMotionState PredictMotion_Internal(float) const;
CMotionState PredictMotion(float dt) const;
CMotionState PredictLinearMotion(float dt) const;
CMotionState PredictAngularMotion(float dt) const;
void ApplyForceOR(const zeus::CVector3f& force, const zeus::CAxisAngle& angle);
void ApplyForceWR(const zeus::CVector3f& force, const zeus::CAxisAngle& angle);
void ApplyImpulseOR(const zeus::CVector3f& impulse, const zeus::CAxisAngle& angle);
void ApplyImpulseWR(const zeus::CVector3f& impulse, const zeus::CAxisAngle& angle);
void ApplyTorqueWR(const zeus::CVector3f& torque);
void UseCollisionImpulses();
static constexpr float GravityConstant() { return 9.81f * 2.5f; } /* 9.81 m/s ^ 2 is normal acceleration under earth gravity, Tallon 4 is 2.5 times that */
};
} // namespace urde
<commit_msg>CPhysicsActor: Amend constructor names for CPhysicsState<commit_after>#pragma once
#include <optional>
#include "Runtime/Collision/CCollidableAABox.hpp"
#include "Runtime/World/CActor.hpp"
#include <zeus/CAxisAngle.hpp>
#include <zeus/CQuaternion.hpp>
#include <zeus/CTransform.hpp>
#include <zeus/CVector3f.hpp>
namespace urde {
class CCollisionInfoList;
struct SMoverData;
struct SMoverData {
zeus::CVector3f x0_velocity;
zeus::CAxisAngle xc_angularVelocity;
zeus::CVector3f x18_momentum;
zeus::CAxisAngle x24_;
float x30_mass;
SMoverData(float mass) : x30_mass(mass) {}
};
struct CMotionState {
zeus::CVector3f x0_translation;
zeus::CNUQuaternion xc_orientation;
zeus::CVector3f x1c_velocity;
zeus::CAxisAngle x28_angularMomentum;
CMotionState(const zeus::CVector3f& origin, const zeus::CNUQuaternion& orientation, const zeus::CVector3f& velocity,
const zeus::CAxisAngle& angle)
: x0_translation(origin), xc_orientation(orientation), x1c_velocity(velocity), x28_angularMomentum(angle) {}
CMotionState(const zeus::CVector3f& origin, const zeus::CNUQuaternion& orientation)
: x0_translation(origin), xc_orientation(orientation) {}
};
class CPhysicsState {
zeus::CVector3f x0_translation;
zeus::CQuaternion xc_orientation;
zeus::CVector3f x1c_constantForce;
zeus::CAxisAngle x28_angularMomentum;
zeus::CVector3f x34_momentum;
zeus::CVector3f x40_force;
zeus::CVector3f x4c_impulse;
zeus::CAxisAngle x58_torque;
zeus::CAxisAngle x64_angularImpulse;
public:
CPhysicsState(const zeus::CVector3f& translation, const zeus::CQuaternion& orient,
const zeus::CVector3f& constantForce, const zeus::CAxisAngle& angularMomentum,
const zeus::CVector3f& momentum, const zeus::CVector3f& force, const zeus::CVector3f& impulse,
const zeus::CAxisAngle& torque, const zeus::CAxisAngle& angularImpulse)
: x0_translation(translation)
, xc_orientation(orient)
, x1c_constantForce(constantForce)
, x28_angularMomentum(angularMomentum)
, x34_momentum(momentum)
, x40_force(force)
, x4c_impulse(impulse)
, x58_torque(torque)
, x64_angularImpulse(angularImpulse) {}
void SetTranslation(const zeus::CVector3f& tr) { x0_translation = tr; }
void SetOrientation(const zeus::CQuaternion& orient) { xc_orientation = orient; }
const zeus::CQuaternion& GetOrientation() const { return xc_orientation; }
const zeus::CVector3f& GetTranslation() const { return x0_translation; }
const zeus::CVector3f& GetConstantForceWR() const { return x1c_constantForce; }
const zeus::CAxisAngle& GetAngularMomentumWR() const { return x28_angularMomentum; }
const zeus::CVector3f& GetMomentumWR() const { return x34_momentum; }
const zeus::CVector3f& GetForceWR() const { return x40_force; }
const zeus::CVector3f& GetImpulseWR() const { return x4c_impulse; }
const zeus::CAxisAngle& GetTorque() const { return x58_torque; }
const zeus::CAxisAngle& GetAngularImpulseWR() const { return x64_angularImpulse; }
};
class CPhysicsActor : public CActor {
friend class CGroundMovement;
protected:
float xe8_mass;
float xec_massRecip;
float xf0_inertiaTensor;
float xf4_inertiaTensorRecip;
union {
struct {
bool xf8_24_movable : 1;
bool xf8_25_angularEnabled : 1;
};
u8 _dummy = 0;
};
bool xf9_standardCollider = false;
zeus::CVector3f xfc_constantForce;
zeus::CAxisAngle x108_angularMomentum;
zeus::CMatrix3f x114_;
zeus::CVector3f x138_velocity;
zeus::CAxisAngle x144_angularVelocity;
zeus::CVector3f x150_momentum;
zeus::CVector3f x15c_force;
zeus::CVector3f x168_impulse;
zeus::CAxisAngle x174_torque;
zeus::CAxisAngle x180_angularImpulse;
zeus::CVector3f x18c_moveImpulse;
zeus::CAxisAngle x198_moveAngularImpulse;
zeus::CAABox x1a4_baseBoundingBox;
CCollidableAABox x1c0_collisionPrimitive;
zeus::CVector3f x1e8_primitiveOffset;
CMotionState x1f4_lastNonCollidingState;
std::optional<zeus::CVector3f> x228_lastFloorPlaneNormal;
float x238_maximumCollisionVelocity = 1000000.0f;
float x23c_stepUpHeight;
float x240_stepDownHeight;
float x244_restitutionCoefModifier = 0.f;
float x248_collisionAccuracyModifier = 1.f;
u32 x24c_numTicksStuck = 0;
u32 x250_numTicksPartialUpdate = 0;
public:
CPhysicsActor(TUniqueId uid, bool active, std::string_view name, const CEntityInfo& info, const zeus::CTransform& xf,
CModelData&& mData, const CMaterialList& matList, const zeus::CAABox& box, const SMoverData& moverData,
const CActorParameters& actorParms, float stepUp, float stepDown);
void Render(const CStateManager& mgr) const override;
zeus::CVector3f GetOrbitPosition(const CStateManager& mgr) const override;
zeus::CVector3f GetAimPosition(const CStateManager& mgr, float val) const override;
virtual const CCollisionPrimitive* GetCollisionPrimitive() const;
virtual zeus::CTransform GetPrimitiveTransform() const;
virtual void CollidedWith(TUniqueId id, const CCollisionInfoList& list, CStateManager& mgr);
virtual float GetStepUpHeight() const;
virtual float GetStepDownHeight() const;
virtual float GetWeight() const;
float GetMass() const { return xe8_mass; }
void SetPrimitiveOffset(const zeus::CVector2f& offset);
const zeus::CVector3f& GetPrimitiveOffset() const { return x1e8_primitiveOffset; }
void MoveCollisionPrimitive(const zeus::CVector3f& offset);
void SetBoundingBox(const zeus::CAABox& box);
zeus::CAABox GetMotionVolume(float dt) const;
zeus::CVector3f CalculateNewVelocityWR_UsingImpulses() const;
zeus::CAABox GetBoundingBox() const;
const zeus::CAABox& GetBaseBoundingBox() const;
void AddMotionState(const CMotionState& mst);
CMotionState GetMotionState() const;
const CMotionState& GetLastNonCollidingState() const { return x1f4_lastNonCollidingState; }
void SetLastNonCollidingState(const CMotionState& mst) { x1f4_lastNonCollidingState = mst; }
void SetMotionState(const CMotionState& mst);
float GetMaximumCollisionVelocity() const { return x238_maximumCollisionVelocity; }
void SetMaximumCollisionVelocity(float velocity) { x238_maximumCollisionVelocity = velocity; }
void SetInertiaTensorScalar(float tensor);
void SetMass(float mass);
void SetAngularVelocityOR(const zeus::CAxisAngle& angVel);
zeus::CAxisAngle GetAngularVelocityOR() const;
const zeus::CAxisAngle& GetAngularVelocityWR() const { return x144_angularVelocity; }
void SetAngularVelocityWR(const zeus::CAxisAngle& angVel);
const zeus::CVector3f& GetForceOR() const { return x15c_force; }
const zeus::CVector3f& GetImpulseOR() const { return x168_impulse; }
const zeus::CVector3f& GetMoveImpulseOR() const { return x18c_moveImpulse; }
void SetVelocityWR(const zeus::CVector3f& vel);
void SetVelocityOR(const zeus::CVector3f& vel);
void SetMomentumWR(const zeus::CVector3f& momentum) { x150_momentum = momentum; }
const zeus::CVector3f& GetConstantForce() const { return xfc_constantForce; }
void SetConstantForce(const zeus::CVector3f& force) { xfc_constantForce = force; }
void SetAngularMomentum(const zeus::CAxisAngle& momentum) { x108_angularMomentum = momentum; }
const zeus::CVector3f& GetMomentum() const { return x150_momentum; }
const zeus::CVector3f& GetVelocity() const { return x138_velocity; }
const zeus::CAxisAngle& GetAngularImpulse() const { return x180_angularImpulse; }
void SetAngularImpulse(const zeus::CAxisAngle& impulse) { x180_angularImpulse = impulse; }
zeus::CVector3f GetTotalForcesWR() const;
void RotateInOneFrameOR(const zeus::CQuaternion& q, float d);
void MoveInOneFrameOR(const zeus::CVector3f& trans, float d);
void RotateToOR(const zeus::CQuaternion& q, float d);
void MoveToOR(const zeus::CVector3f& trans, float d);
void MoveToInOneFrameWR(const zeus::CVector3f& v1, float d);
void MoveToWR(const zeus::CVector3f& trans, float d);
zeus::CAxisAngle GetRotateToORAngularMomentumWR(const zeus::CQuaternion& q, float d) const;
zeus::CVector3f GetMoveToORImpulseWR(const zeus::CVector3f& trans, float d) const;
void ClearImpulses();
void ClearForcesAndTorques();
void Stop();
void ComputeDerivedQuantities();
bool WillMove(const CStateManager& mgr) const;
void SetPhysicsState(const CPhysicsState& state);
CPhysicsState GetPhysicsState() const;
bool IsMovable() const { return xf8_24_movable; }
void SetMovable(bool movable) { xf8_24_movable = movable; }
bool IsAngularEnabled() const { return xf8_25_angularEnabled; }
void SetAngularEnabled(bool enabled) { xf8_25_angularEnabled = enabled; }
float GetCollisionAccuracyModifier() const { return x248_collisionAccuracyModifier; }
void SetCollisionAccuracyModifier(float modifier) { x248_collisionAccuracyModifier = modifier; }
float GetCoefficientOfRestitutionModifier() const { return x244_restitutionCoefModifier; }
void SetCoefficientOfRestitutionModifier(float modifier) { x244_restitutionCoefModifier = modifier; }
bool IsUseStandardCollider() const { return xf9_standardCollider; }
u32 GetNumTicksPartialUpdate() const { return x250_numTicksPartialUpdate; }
void SetNumTicksPartialUpdate(u32 ticks) { x250_numTicksPartialUpdate = ticks; }
u32 GetNumTicksStuck() const { return x24c_numTicksStuck; }
void SetNumTicksStuck(u32 ticks) { x24c_numTicksStuck = ticks; }
const std::optional<zeus::CVector3f>& GetLastFloorPlaneNormal() const {
return x228_lastFloorPlaneNormal;
}
void SetLastFloorPlaneNormal(const std::optional<zeus::CVector3f>& normal) { x228_lastFloorPlaneNormal = normal; }
CMotionState PredictMotion_Internal(float) const;
CMotionState PredictMotion(float dt) const;
CMotionState PredictLinearMotion(float dt) const;
CMotionState PredictAngularMotion(float dt) const;
void ApplyForceOR(const zeus::CVector3f& force, const zeus::CAxisAngle& angle);
void ApplyForceWR(const zeus::CVector3f& force, const zeus::CAxisAngle& angle);
void ApplyImpulseOR(const zeus::CVector3f& impulse, const zeus::CAxisAngle& angle);
void ApplyImpulseWR(const zeus::CVector3f& impulse, const zeus::CAxisAngle& angle);
void ApplyTorqueWR(const zeus::CVector3f& torque);
void UseCollisionImpulses();
static constexpr float GravityConstant() { return 9.81f * 2.5f; } /* 9.81 m/s ^ 2 is normal acceleration under earth gravity, Tallon 4 is 2.5 times that */
};
} // namespace urde
<|endoftext|> |
<commit_before><commit_msg>Add compact option<commit_after><|endoftext|> |
<commit_before>#include <rtt/os/main.h>
#include <rtt/typekit/RealTimeTypekit.hpp>
<% deployer.rtt_transports.each do |transport_name| %>
#include <rtt/transports/<%= transport_name %>/TransportPlugin.hpp>
<% end %>
<% if component.typekit || !component.used_typekits.empty? %>#include <rtt/types/TypekitPlugin.hpp><% end %>
<% if typekit = component.typekit %>
#include "typekit/Plugin.hpp"
<% deployer.transports.each do |transport_name| %>
#include "typekit/transports/<%= transport_name %>/TransportPlugin.hpp"
<% end %>
<% end %>
<% deployer.used_typekits.each do |tk| %>
#include <<%= tk.name %>/typekit/Plugin.hpp>
<% deployer.transports.each do |transport_name| %>
#include <<%= tk.name %>/transports/<%= transport_name %>/TransportPlugin.hpp>
<% end %>
<% end %>
<% task_activities = deployer.task_activities.
sort_by(&:name) %>
<% task_activities.each do |task| %>
#include <<%= task.context.header_file %>>
<% end %>
<% if deployer.corba_enabled? %>
#include <rtt/transports/corba/ApplicationServer.hpp>
#include <rtt/transports/corba/TaskContextServer.hpp>
<% end %>
<% require 'set'
activity_headers = task_activities.
map { |t| t.activity_type.header }.
compact.
to_set %>
<% activity_headers.to_a.sort.each do |header| %>
#include <<%= header %>>
<% end %>
<% if deployer.browse %>
#include <ocl/TaskBrowser.hpp>
<% end %>
#include <rtt/Logger.hpp>
#include <rtt/base/ActivityInterface.hpp>
class Deinitializer
{
friend Deinitializer& operator << (Deinitializer&, RTT::base::ActivityInterface&);
std::vector<RTT::base::ActivityInterface*> m_activities;
public:
~Deinitializer()
{
for (std::vector<RTT::base::ActivityInterface*>::const_iterator it = m_activities.begin();
it != m_activities.end(); ++it)
{
(*it)->stop();
}
}
};
Deinitializer& operator << (Deinitializer& deinit, RTT::base::ActivityInterface& activity)
{
deinit.m_activities.push_back(&activity);
return deinit;
}
using namespace RTT;
int ORO_main(int argc, char* argv[])
{
<% if deployer.loglevel %>
if ( log().getLogLevel() < Logger::<%= deployer.loglevel %> ) {
log().setLogLevel( Logger::<%= deployer.loglevel %> );
}
<% end %>
RTT::types::TypekitRepository::Import( new RTT::types::RealTimeTypekitPlugin );
<% if deployer.transports.include?('corba') %>
RTT::types::TypekitRepository::Import( new RTT::corba::CorbaLibPlugin );
<% end %>
<% if component.typekit %>
RTT::types::TypekitRepository::Import( new orogen_typekits::<%= component.name %>TypekitPlugin );
<% deployer.transports.each do |transport_name| %>
RTT::types::TypekitRepository::Import( new orogen_typekits::<%= component.name %><%= transport_name.capitalize %>TransportPlugin );
<% end %>
<% end %>
<% deployer.used_typekits.each do |tk| %>
RTT::types::TypekitRepository::Import( new orogen_typekits::<%= tk.name %>TypekitPlugin );
<% deployer.transports.each do |transport_name| %>
RTT::types::TypekitRepository::Import( new orogen_typekits::<%= tk.name %><%= transport_name.capitalize %>TransportPlugin );
<% end %>
<% end %>
<% if deployer.corba_enabled? %>
RTT::corba::ApplicationServer::InitOrb(argc, argv);
<% end %>
<% task_activities.each do |task| %>
<%= task.context.class_name %> task_<%= task.name%>("<%= task.name %>");
<% if task.activity_type %>
<%= task.activity_type.class_name %>* activity_<%= task.name%> = new <%= task.activity_type.class_name %>(
<%= task.rtt_scheduler %>,
<%= task.rtt_priority %>,
<% if task.period %><%= task.period %>, <% end %>
task_<%= task.name%>.engine());
task_<%= task.name %>.setActivity(activity_<%= task.name %>);
<% if task.period %>
RTT::os::Thread* thread_<%= task.name %> =
dynamic_cast<RTT::os::Thread*>(activity_<%= task.name %>->thread());
thread_<%= task.name %>->setMaxOverrun(<%= task.max_overruns %>);
<% end %>
<% else %>
RTT::base::ActivityInterface* activity_<%= task.name %> = task_<%= task.name %>.getActivity().get();
<% end # activity_type %>
<% task.properties.sort_by { |prop| prop.name }.each do |prop|
if prop.value %>
task_<%= task.name %>.properties()->getProperty<<%= prop.interface_object.type.cxx_name %>>("<%= prop.name %>")->set(<%= prop.value.inspect %>);
<% end %>
<% end %>
<% if deployer.corba_enabled? %>
RTT::corba::TaskContextServer::Create( &task_<%= task.name%> );
<% end %>
<% end %>
<% if !deployer.loggers.empty?
deployer.loggers.sort_by { |filename, _| filename }.each do |filename, logger|
logger.config.each do |type, reported_activity, args| %>
task_<%= logger.task.name %>.connectPeers(&task_<%= reported_activity.name %>);
task_<%= logger.task.name %>.report<%= type %>(<%= args.map { |v| "\"#{v}\"" }.join(", ") %>);
<% end %>
<% end %>
<% end %>
Deinitializer deinit;
// Start some activities
<% task_activities.each do |task| %>
deinit << *activity_<%= task.name%>;
<% if task.start?
if task.context.needs_configuration? %>
if (!task_<%= task.name %>.configure())
{
log(Error) << "cannot configure <%= task.name %>" << endlog();
return -1;
}
<% end %>
if (!task_<%= task.name %>.start())
{
log(Error) << "cannot start <%= task.name %>" << endlog();
return -1;
}
<% end %>
<% end %>
<% deployer.peers.sort_by { |a, b| [a.name, b.name] }.each do |a, b| %>
task_<%= a.name %>.connectPeers(&task_<%= b.name %>);
<% end %>
<% deployer.connections.
sort_by { |src, dst, policy| [src.name, dst.name] }.
each do |src, dst, policy|
if src.kind_of?(TaskDeployment) %>
task_<%= src.activity.name %>.connectPorts(&task_<%= dst.activity.name %>);
<% else %>
{
<%= policy.to_code("policy") %>
base::OutputPortInterface* src = dynamic_cast<base::OutputPortInterface*>(
task_<%= src.activity.name %>.ports()->getPort("<%= src.name %>"));
base::InputPortInterface* dst = dynamic_cast<base::InputPortInterface*>(
task_<%= dst.activity.name %>.ports()->getPort("<%= dst.name %>"));
src->createConnection(*dst, policy);
}
<% end %>
<% end %>
<% if deployer.corba_enabled? %>
RTT::corba::TaskContextServer::RunOrb();
<% elsif deployer.browse %>
OCL::TaskBrowser browser(& task_<%= deployer.browse.name %>);
browser.loop();
<% end %>
return 0;
}
<commit_msg>until we get a corba service on the task contexts, call shutdownorb on SIGINT<commit_after>#include <rtt/os/main.h>
#include <rtt/typekit/RealTimeTypekit.hpp>
<% deployer.rtt_transports.each do |transport_name| %>
#include <rtt/transports/<%= transport_name %>/TransportPlugin.hpp>
<% end %>
<% if component.typekit || !component.used_typekits.empty? %>#include <rtt/types/TypekitPlugin.hpp><% end %>
<% if typekit = component.typekit %>
#include "typekit/Plugin.hpp"
<% deployer.transports.each do |transport_name| %>
#include "typekit/transports/<%= transport_name %>/TransportPlugin.hpp"
<% end %>
<% end %>
<% deployer.used_typekits.each do |tk| %>
#include <<%= tk.name %>/typekit/Plugin.hpp>
<% deployer.transports.each do |transport_name| %>
#include <<%= tk.name %>/transports/<%= transport_name %>/TransportPlugin.hpp>
<% end %>
<% end %>
<% task_activities = deployer.task_activities.
sort_by(&:name) %>
<% task_activities.each do |task| %>
#include <<%= task.context.header_file %>>
<% end %>
<% if deployer.corba_enabled? %>
#include <rtt/transports/corba/ApplicationServer.hpp>
#include <rtt/transports/corba/TaskContextServer.hpp>
#include <signal.h>
<% end %>
<% require 'set'
activity_headers = task_activities.
map { |t| t.activity_type.header }.
compact.
to_set %>
<% activity_headers.to_a.sort.each do |header| %>
#include <<%= header %>>
<% end %>
<% if deployer.browse %>
#include <ocl/TaskBrowser.hpp>
<% end %>
#include <rtt/Logger.hpp>
#include <rtt/base/ActivityInterface.hpp>
class Deinitializer
{
friend Deinitializer& operator << (Deinitializer&, RTT::base::ActivityInterface&);
std::vector<RTT::base::ActivityInterface*> m_activities;
public:
~Deinitializer()
{
for (std::vector<RTT::base::ActivityInterface*>::const_iterator it = m_activities.begin();
it != m_activities.end(); ++it)
{
(*it)->stop();
}
}
};
Deinitializer& operator << (Deinitializer& deinit, RTT::base::ActivityInterface& activity)
{
deinit.m_activities.push_back(&activity);
return deinit;
}
void sigint_quit_orb(int)
{
RTT::corba::TaskContextServer::ShutdownOrb(false);
}
using namespace RTT;
int ORO_main(int argc, char* argv[])
{
<% if deployer.loglevel %>
if ( log().getLogLevel() < Logger::<%= deployer.loglevel %> ) {
log().setLogLevel( Logger::<%= deployer.loglevel %> );
}
<% end %>
RTT::types::TypekitRepository::Import( new RTT::types::RealTimeTypekitPlugin );
<% if deployer.transports.include?('corba') %>
RTT::types::TypekitRepository::Import( new RTT::corba::CorbaLibPlugin );
<% end %>
<% if component.typekit %>
RTT::types::TypekitRepository::Import( new orogen_typekits::<%= component.name %>TypekitPlugin );
<% deployer.transports.each do |transport_name| %>
RTT::types::TypekitRepository::Import( new orogen_typekits::<%= component.name %><%= transport_name.capitalize %>TransportPlugin );
<% end %>
<% end %>
<% deployer.used_typekits.each do |tk| %>
RTT::types::TypekitRepository::Import( new orogen_typekits::<%= tk.name %>TypekitPlugin );
<% deployer.transports.each do |transport_name| %>
RTT::types::TypekitRepository::Import( new orogen_typekits::<%= tk.name %><%= transport_name.capitalize %>TransportPlugin );
<% end %>
<% end %>
<% if deployer.corba_enabled? %>
RTT::corba::ApplicationServer::InitOrb(argc, argv);
<% end %>
<% task_activities.each do |task| %>
<%= task.context.class_name %> task_<%= task.name%>("<%= task.name %>");
<% if task.activity_type %>
<%= task.activity_type.class_name %>* activity_<%= task.name%> = new <%= task.activity_type.class_name %>(
<%= task.rtt_scheduler %>,
<%= task.rtt_priority %>,
<% if task.period %><%= task.period %>, <% end %>
task_<%= task.name%>.engine());
task_<%= task.name %>.setActivity(activity_<%= task.name %>);
<% if task.period %>
RTT::os::Thread* thread_<%= task.name %> =
dynamic_cast<RTT::os::Thread*>(activity_<%= task.name %>->thread());
thread_<%= task.name %>->setMaxOverrun(<%= task.max_overruns %>);
<% end %>
<% else %>
RTT::base::ActivityInterface* activity_<%= task.name %> = task_<%= task.name %>.getActivity().get();
<% end # activity_type %>
<% task.properties.sort_by { |prop| prop.name }.each do |prop|
if prop.value %>
task_<%= task.name %>.properties()->getProperty<<%= prop.interface_object.type.cxx_name %>>("<%= prop.name %>")->set(<%= prop.value.inspect %>);
<% end %>
<% end %>
<% if deployer.corba_enabled? %>
RTT::corba::TaskContextServer::Create( &task_<%= task.name%> );
<% end %>
<% end %>
<% if !deployer.loggers.empty?
deployer.loggers.sort_by { |filename, _| filename }.each do |filename, logger|
logger.config.each do |type, reported_activity, args| %>
task_<%= logger.task.name %>.connectPeers(&task_<%= reported_activity.name %>);
task_<%= logger.task.name %>.report<%= type %>(<%= args.map { |v| "\"#{v}\"" }.join(", ") %>);
<% end %>
<% end %>
<% end %>
Deinitializer deinit;
// Start some activities
<% task_activities.each do |task| %>
deinit << *activity_<%= task.name%>;
<% if task.start?
if task.context.needs_configuration? %>
if (!task_<%= task.name %>.configure())
{
log(Error) << "cannot configure <%= task.name %>" << endlog();
return -1;
}
<% end %>
if (!task_<%= task.name %>.start())
{
log(Error) << "cannot start <%= task.name %>" << endlog();
return -1;
}
<% end %>
<% end %>
<% deployer.peers.sort_by { |a, b| [a.name, b.name] }.each do |a, b| %>
task_<%= a.name %>.connectPeers(&task_<%= b.name %>);
<% end %>
<% deployer.connections.
sort_by { |src, dst, policy| [src.name, dst.name] }.
each do |src, dst, policy|
if src.kind_of?(TaskDeployment) %>
task_<%= src.activity.name %>.connectPorts(&task_<%= dst.activity.name %>);
<% else %>
{
<%= policy.to_code("policy") %>
base::OutputPortInterface* src = dynamic_cast<base::OutputPortInterface*>(
task_<%= src.activity.name %>.ports()->getPort("<%= src.name %>"));
base::InputPortInterface* dst = dynamic_cast<base::InputPortInterface*>(
task_<%= dst.activity.name %>.ports()->getPort("<%= dst.name %>"));
src->createConnection(*dst, policy);
}
<% end %>
<% end %>
<% if deployer.corba_enabled? %>
struct sigaction sigint_handler;
sigint_handler.sa_handler = &sigint_quit_orb;
sigemptyset(&sigint_handler.sa_mask);
sigint_handler.sa_flags = 0;
sigint_handler.sa_restorer = 0;
if (-1 == sigaction(SIGINT, &sigint_handler, 0))
{
std::cerr << "failed to install SIGINT handler" << std::endl;
return 1;
}
sigset_t unblock_sigint;
sigemptyset(&unblock_sigint);
sigaddset(&unblock_sigint, SIGINT);
if (-1 == sigprocmask(SIG_UNBLOCK, &unblock_sigint, NULL))
{
std::cerr << "failed to install SIGINT handler" << std::endl;
return 1;
}
RTT::corba::TaskContextServer::RunOrb();
<% elsif deployer.browse %>
OCL::TaskBrowser browser(& task_<%= deployer.browse.name %>);
browser.loop();
<% end %>
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>update to new lircd socket location for lircd >= 0.8.6 BUG: 209100<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/pepper/pepper_flash_file_message_filter.h"
#include "base/bind.h"
#include "base/file_util.h"
#include "base/files/file_enumerator.h"
#include "base/threading/sequenced_worker_pool.h"
#include "content/browser/child_process_security_policy_impl.h"
#include "content/browser/renderer_host/pepper/pepper_security_helper.h"
#include "content/public/browser/browser_ppapi_host.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_constants.h"
#include "ipc/ipc_platform_file.h"
#include "ppapi/c/pp_errors.h"
#include "ppapi/host/dispatch_host_message.h"
#include "ppapi/host/host_message_context.h"
#include "ppapi/host/ppapi_host.h"
#include "ppapi/proxy/ppapi_messages.h"
#include "ppapi/shared_impl/file_path.h"
#include "ppapi/shared_impl/file_type_conversion.h"
namespace content {
namespace {
bool CanRead(int process_id, const base::FilePath& path) {
return ChildProcessSecurityPolicyImpl::GetInstance()->
CanReadFile(process_id, path);
}
bool CanCreateReadWrite(int process_id, const base::FilePath& path) {
return ChildProcessSecurityPolicyImpl::GetInstance()->
CanCreateReadWriteFile(process_id, path);
}
} // namespace
PepperFlashFileMessageFilter::PepperFlashFileMessageFilter(
PP_Instance instance,
BrowserPpapiHost* host)
: plugin_process_handle_(host->GetPluginProcessHandle()) {
int unused;
host->GetRenderFrameIDsForInstance(instance, &render_process_id_, &unused);
base::FilePath profile_data_directory = host->GetProfileDataDirectory();
std::string plugin_name = host->GetPluginName();
if (profile_data_directory.empty() || plugin_name.empty()) {
// These are used to construct the path. If they are not set it means we
// will construct a bad path and could provide access to the wrong files.
// In this case, |plugin_data_directory_| will remain unset and
// |ValidateAndConvertPepperFilePath| will fail.
NOTREACHED();
} else {
plugin_data_directory_ = GetDataDirName(profile_data_directory).Append(
base::FilePath::FromUTF8Unsafe(plugin_name));
}
}
PepperFlashFileMessageFilter::~PepperFlashFileMessageFilter() {
}
// static
base::FilePath PepperFlashFileMessageFilter::GetDataDirName(
const base::FilePath& profile_path) {
return profile_path.Append(kPepperDataDirname);
}
scoped_refptr<base::TaskRunner>
PepperFlashFileMessageFilter::OverrideTaskRunnerForMessage(
const IPC::Message& msg) {
// The blocking pool provides a pool of threads to run file
// operations, instead of a single thread which might require
// queuing time. Since these messages are synchronous as sent from
// the plugin, the sending thread cannot send a new message until
// this one returns, so there is no need to sequence tasks here. If
// the plugin has multiple threads, it cannot make assumptions about
// ordering of IPC message sends, so it cannot make assumptions
// about ordering of operations caused by those IPC messages.
return scoped_refptr<base::TaskRunner>(BrowserThread::GetBlockingPool());
}
int32_t PepperFlashFileMessageFilter::OnResourceMessageReceived(
const IPC::Message& msg,
ppapi::host::HostMessageContext* context) {
IPC_BEGIN_MESSAGE_MAP(PepperFlashFileMessageFilter, msg)
PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_FlashFile_OpenFile,
OnOpenFile)
PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_FlashFile_RenameFile,
OnRenameFile)
PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_FlashFile_DeleteFileOrDir,
OnDeleteFileOrDir)
PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_FlashFile_CreateDir,
OnCreateDir)
PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_FlashFile_QueryFile,
OnQueryFile)
PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_FlashFile_GetDirContents,
OnGetDirContents)
PPAPI_DISPATCH_HOST_RESOURCE_CALL_0(
PpapiHostMsg_FlashFile_CreateTemporaryFile,
OnCreateTemporaryFile)
IPC_END_MESSAGE_MAP()
return PP_ERROR_FAILED;
}
int32_t PepperFlashFileMessageFilter::OnOpenFile(
ppapi::host::HostMessageContext* context,
const ppapi::PepperFilePath& path,
int pp_open_flags) {
base::FilePath full_path = ValidateAndConvertPepperFilePath(
path,
base::Bind(&CanOpenWithPepperFlags, pp_open_flags));
if (full_path.empty()) {
return ppapi::FileErrorToPepperError(
base::File::FILE_ERROR_ACCESS_DENIED);
}
int platform_file_flags = 0;
if (!ppapi::PepperFileOpenFlagsToPlatformFileFlags(
pp_open_flags, &platform_file_flags)) {
return base::File::FILE_ERROR_FAILED;
}
// TODO(rvargas): Convert this code to base::File.
base::PlatformFileError error = base::PLATFORM_FILE_ERROR_FAILED;
base::PlatformFile file_handle = base::CreatePlatformFile(
full_path, platform_file_flags, NULL, &error);
if (error != base::PLATFORM_FILE_OK) {
DCHECK_EQ(file_handle, base::kInvalidPlatformFileValue);
return ppapi::FileErrorToPepperError(static_cast<base::File::Error>(error));
}
// Make sure we didn't try to open a directory: directory fd shouldn't be
// passed to untrusted processes because they open security holes.
base::PlatformFileInfo info;
if (!base::GetPlatformFileInfo(file_handle, &info) || info.is_directory) {
// When in doubt, throw it out.
base::ClosePlatformFile(file_handle);
return ppapi::FileErrorToPepperError(
base::File::FILE_ERROR_ACCESS_DENIED);
}
IPC::PlatformFileForTransit file = IPC::GetFileHandleForProcess(file_handle,
plugin_process_handle_, true);
ppapi::host::ReplyMessageContext reply_context =
context->MakeReplyMessageContext();
reply_context.params.AppendHandle(ppapi::proxy::SerializedHandle(
ppapi::proxy::SerializedHandle::FILE, file));
SendReply(reply_context, IPC::Message());
return PP_OK_COMPLETIONPENDING;
}
int32_t PepperFlashFileMessageFilter::OnRenameFile(
ppapi::host::HostMessageContext* context,
const ppapi::PepperFilePath& from_path,
const ppapi::PepperFilePath& to_path) {
base::FilePath from_full_path = ValidateAndConvertPepperFilePath(
from_path, base::Bind(&CanCreateReadWrite));
base::FilePath to_full_path = ValidateAndConvertPepperFilePath(
to_path, base::Bind(&CanCreateReadWrite));
if (from_full_path.empty() || to_full_path.empty()) {
return ppapi::FileErrorToPepperError(
base::File::FILE_ERROR_ACCESS_DENIED);
}
bool result = base::Move(from_full_path, to_full_path);
return ppapi::FileErrorToPepperError(result ?
base::File::FILE_OK : base::File::FILE_ERROR_ACCESS_DENIED);
}
int32_t PepperFlashFileMessageFilter::OnDeleteFileOrDir(
ppapi::host::HostMessageContext* context,
const ppapi::PepperFilePath& path,
bool recursive) {
base::FilePath full_path = ValidateAndConvertPepperFilePath(
path, base::Bind(&CanCreateReadWrite));
if (full_path.empty()) {
return ppapi::FileErrorToPepperError(
base::File::FILE_ERROR_ACCESS_DENIED);
}
bool result = base::DeleteFile(full_path, recursive);
return ppapi::FileErrorToPepperError(result ?
base::File::FILE_OK : base::File::FILE_ERROR_ACCESS_DENIED);
}
int32_t PepperFlashFileMessageFilter::OnCreateDir(
ppapi::host::HostMessageContext* context,
const ppapi::PepperFilePath& path) {
base::FilePath full_path = ValidateAndConvertPepperFilePath(
path, base::Bind(&CanCreateReadWrite));
if (full_path.empty()) {
return ppapi::FileErrorToPepperError(
base::File::FILE_ERROR_ACCESS_DENIED);
}
bool result = base::CreateDirectory(full_path);
return ppapi::FileErrorToPepperError(result ?
base::File::FILE_OK : base::File::FILE_ERROR_ACCESS_DENIED);
}
int32_t PepperFlashFileMessageFilter::OnQueryFile(
ppapi::host::HostMessageContext* context,
const ppapi::PepperFilePath& path) {
base::FilePath full_path = ValidateAndConvertPepperFilePath(
path, base::Bind(&CanRead));
if (full_path.empty()) {
return ppapi::FileErrorToPepperError(
base::File::FILE_ERROR_ACCESS_DENIED);
}
base::File::Info info;
bool result = base::GetFileInfo(full_path, &info);
context->reply_msg = PpapiPluginMsg_FlashFile_QueryFileReply(info);
return ppapi::FileErrorToPepperError(result ?
base::File::FILE_OK : base::File::FILE_ERROR_ACCESS_DENIED);
}
int32_t PepperFlashFileMessageFilter::OnGetDirContents(
ppapi::host::HostMessageContext* context,
const ppapi::PepperFilePath& path) {
base::FilePath full_path = ValidateAndConvertPepperFilePath(
path, base::Bind(&CanRead));
if (full_path.empty()) {
return ppapi::FileErrorToPepperError(
base::File::FILE_ERROR_ACCESS_DENIED);
}
ppapi::DirContents contents;
base::FileEnumerator enumerator(full_path, false,
base::FileEnumerator::FILES |
base::FileEnumerator::DIRECTORIES |
base::FileEnumerator::INCLUDE_DOT_DOT);
while (!enumerator.Next().empty()) {
base::FileEnumerator::FileInfo info = enumerator.GetInfo();
ppapi::DirEntry entry = {
info.GetName(),
info.IsDirectory()
};
contents.push_back(entry);
}
context->reply_msg = PpapiPluginMsg_FlashFile_GetDirContentsReply(contents);
return PP_OK;
}
int32_t PepperFlashFileMessageFilter::OnCreateTemporaryFile(
ppapi::host::HostMessageContext* context) {
ppapi::PepperFilePath dir_path(
ppapi::PepperFilePath::DOMAIN_MODULE_LOCAL, base::FilePath());
base::FilePath validated_dir_path = ValidateAndConvertPepperFilePath(
dir_path, base::Bind(&CanCreateReadWrite));
if (validated_dir_path.empty() ||
(!base::DirectoryExists(validated_dir_path) &&
!base::CreateDirectory(validated_dir_path))) {
return ppapi::FileErrorToPepperError(
base::File::FILE_ERROR_ACCESS_DENIED);
}
base::FilePath file_path;
if (!base::CreateTemporaryFileInDir(validated_dir_path, &file_path)) {
return ppapi::FileErrorToPepperError(
base::File::FILE_ERROR_FAILED);
}
// TODO(rvargas): Convert this code to base::File.
base::PlatformFileError error = base::PLATFORM_FILE_ERROR_FAILED;
base::PlatformFile file_handle = base::CreatePlatformFile(
file_path,
base::PLATFORM_FILE_CREATE_ALWAYS | base::PLATFORM_FILE_READ |
base::PLATFORM_FILE_WRITE | base::PLATFORM_FILE_TEMPORARY |
base::PLATFORM_FILE_DELETE_ON_CLOSE, NULL, &error);
if (error != base::PLATFORM_FILE_OK) {
DCHECK_EQ(file_handle, base::kInvalidPlatformFileValue);
return ppapi::FileErrorToPepperError(static_cast<base::File::Error>(error));
}
IPC::PlatformFileForTransit file = IPC::GetFileHandleForProcess(file_handle,
plugin_process_handle_, true);
ppapi::host::ReplyMessageContext reply_context =
context->MakeReplyMessageContext();
reply_context.params.AppendHandle(ppapi::proxy::SerializedHandle(
ppapi::proxy::SerializedHandle::FILE, file));
SendReply(reply_context, IPC::Message());
return PP_OK_COMPLETIONPENDING;
}
base::FilePath PepperFlashFileMessageFilter::ValidateAndConvertPepperFilePath(
const ppapi::PepperFilePath& pepper_path,
const CheckPermissionsCallback& check_permissions_callback) const {
base::FilePath file_path; // Empty path returned on error.
switch (pepper_path.domain()) {
case ppapi::PepperFilePath::DOMAIN_ABSOLUTE:
if (pepper_path.path().IsAbsolute() &&
check_permissions_callback.Run(render_process_id_,
pepper_path.path()))
file_path = pepper_path.path();
break;
case ppapi::PepperFilePath::DOMAIN_MODULE_LOCAL:
// This filter provides the module name portion of the path to prevent
// plugins from accessing each other's data.
if (!plugin_data_directory_.empty() &&
!pepper_path.path().IsAbsolute() &&
!pepper_path.path().ReferencesParent())
file_path = plugin_data_directory_.Append(pepper_path.path());
break;
default:
NOTREACHED();
break;
}
return file_path;
}
} // namespace content
<commit_msg>Remove CreatePlatformFile from pepper<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/pepper/pepper_flash_file_message_filter.h"
#include "base/bind.h"
#include "base/file_util.h"
#include "base/files/file.h"
#include "base/files/file_enumerator.h"
#include "base/threading/sequenced_worker_pool.h"
#include "content/browser/child_process_security_policy_impl.h"
#include "content/browser/renderer_host/pepper/pepper_security_helper.h"
#include "content/public/browser/browser_ppapi_host.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_constants.h"
#include "ipc/ipc_platform_file.h"
#include "ppapi/c/pp_errors.h"
#include "ppapi/host/dispatch_host_message.h"
#include "ppapi/host/host_message_context.h"
#include "ppapi/host/ppapi_host.h"
#include "ppapi/proxy/ppapi_messages.h"
#include "ppapi/shared_impl/file_path.h"
#include "ppapi/shared_impl/file_type_conversion.h"
namespace content {
namespace {
bool CanRead(int process_id, const base::FilePath& path) {
return ChildProcessSecurityPolicyImpl::GetInstance()->
CanReadFile(process_id, path);
}
bool CanCreateReadWrite(int process_id, const base::FilePath& path) {
return ChildProcessSecurityPolicyImpl::GetInstance()->
CanCreateReadWriteFile(process_id, path);
}
} // namespace
PepperFlashFileMessageFilter::PepperFlashFileMessageFilter(
PP_Instance instance,
BrowserPpapiHost* host)
: plugin_process_handle_(host->GetPluginProcessHandle()) {
int unused;
host->GetRenderFrameIDsForInstance(instance, &render_process_id_, &unused);
base::FilePath profile_data_directory = host->GetProfileDataDirectory();
std::string plugin_name = host->GetPluginName();
if (profile_data_directory.empty() || plugin_name.empty()) {
// These are used to construct the path. If they are not set it means we
// will construct a bad path and could provide access to the wrong files.
// In this case, |plugin_data_directory_| will remain unset and
// |ValidateAndConvertPepperFilePath| will fail.
NOTREACHED();
} else {
plugin_data_directory_ = GetDataDirName(profile_data_directory).Append(
base::FilePath::FromUTF8Unsafe(plugin_name));
}
}
PepperFlashFileMessageFilter::~PepperFlashFileMessageFilter() {
}
// static
base::FilePath PepperFlashFileMessageFilter::GetDataDirName(
const base::FilePath& profile_path) {
return profile_path.Append(kPepperDataDirname);
}
scoped_refptr<base::TaskRunner>
PepperFlashFileMessageFilter::OverrideTaskRunnerForMessage(
const IPC::Message& msg) {
// The blocking pool provides a pool of threads to run file
// operations, instead of a single thread which might require
// queuing time. Since these messages are synchronous as sent from
// the plugin, the sending thread cannot send a new message until
// this one returns, so there is no need to sequence tasks here. If
// the plugin has multiple threads, it cannot make assumptions about
// ordering of IPC message sends, so it cannot make assumptions
// about ordering of operations caused by those IPC messages.
return scoped_refptr<base::TaskRunner>(BrowserThread::GetBlockingPool());
}
int32_t PepperFlashFileMessageFilter::OnResourceMessageReceived(
const IPC::Message& msg,
ppapi::host::HostMessageContext* context) {
IPC_BEGIN_MESSAGE_MAP(PepperFlashFileMessageFilter, msg)
PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_FlashFile_OpenFile,
OnOpenFile)
PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_FlashFile_RenameFile,
OnRenameFile)
PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_FlashFile_DeleteFileOrDir,
OnDeleteFileOrDir)
PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_FlashFile_CreateDir,
OnCreateDir)
PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_FlashFile_QueryFile,
OnQueryFile)
PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_FlashFile_GetDirContents,
OnGetDirContents)
PPAPI_DISPATCH_HOST_RESOURCE_CALL_0(
PpapiHostMsg_FlashFile_CreateTemporaryFile,
OnCreateTemporaryFile)
IPC_END_MESSAGE_MAP()
return PP_ERROR_FAILED;
}
int32_t PepperFlashFileMessageFilter::OnOpenFile(
ppapi::host::HostMessageContext* context,
const ppapi::PepperFilePath& path,
int pp_open_flags) {
base::FilePath full_path = ValidateAndConvertPepperFilePath(
path,
base::Bind(&CanOpenWithPepperFlags, pp_open_flags));
if (full_path.empty()) {
return ppapi::FileErrorToPepperError(
base::File::FILE_ERROR_ACCESS_DENIED);
}
int platform_file_flags = 0;
if (!ppapi::PepperFileOpenFlagsToPlatformFileFlags(
pp_open_flags, &platform_file_flags)) {
return base::File::FILE_ERROR_FAILED;
}
base::File file(full_path, platform_file_flags);
if (!file.IsValid()) {
return ppapi::FileErrorToPepperError(file.error_details());
}
// Make sure we didn't try to open a directory: directory fd shouldn't be
// passed to untrusted processes because they open security holes.
base::File::Info info;
if (!file.GetInfo(&info) || info.is_directory) {
// When in doubt, throw it out.
return ppapi::FileErrorToPepperError(
base::File::FILE_ERROR_ACCESS_DENIED);
}
IPC::PlatformFileForTransit transit_file =
IPC::TakeFileHandleForProcess(file.Pass(), plugin_process_handle_);
ppapi::host::ReplyMessageContext reply_context =
context->MakeReplyMessageContext();
reply_context.params.AppendHandle(ppapi::proxy::SerializedHandle(
ppapi::proxy::SerializedHandle::FILE, transit_file));
SendReply(reply_context, IPC::Message());
return PP_OK_COMPLETIONPENDING;
}
int32_t PepperFlashFileMessageFilter::OnRenameFile(
ppapi::host::HostMessageContext* context,
const ppapi::PepperFilePath& from_path,
const ppapi::PepperFilePath& to_path) {
base::FilePath from_full_path = ValidateAndConvertPepperFilePath(
from_path, base::Bind(&CanCreateReadWrite));
base::FilePath to_full_path = ValidateAndConvertPepperFilePath(
to_path, base::Bind(&CanCreateReadWrite));
if (from_full_path.empty() || to_full_path.empty()) {
return ppapi::FileErrorToPepperError(
base::File::FILE_ERROR_ACCESS_DENIED);
}
bool result = base::Move(from_full_path, to_full_path);
return ppapi::FileErrorToPepperError(result ?
base::File::FILE_OK : base::File::FILE_ERROR_ACCESS_DENIED);
}
int32_t PepperFlashFileMessageFilter::OnDeleteFileOrDir(
ppapi::host::HostMessageContext* context,
const ppapi::PepperFilePath& path,
bool recursive) {
base::FilePath full_path = ValidateAndConvertPepperFilePath(
path, base::Bind(&CanCreateReadWrite));
if (full_path.empty()) {
return ppapi::FileErrorToPepperError(
base::File::FILE_ERROR_ACCESS_DENIED);
}
bool result = base::DeleteFile(full_path, recursive);
return ppapi::FileErrorToPepperError(result ?
base::File::FILE_OK : base::File::FILE_ERROR_ACCESS_DENIED);
}
int32_t PepperFlashFileMessageFilter::OnCreateDir(
ppapi::host::HostMessageContext* context,
const ppapi::PepperFilePath& path) {
base::FilePath full_path = ValidateAndConvertPepperFilePath(
path, base::Bind(&CanCreateReadWrite));
if (full_path.empty()) {
return ppapi::FileErrorToPepperError(
base::File::FILE_ERROR_ACCESS_DENIED);
}
bool result = base::CreateDirectory(full_path);
return ppapi::FileErrorToPepperError(result ?
base::File::FILE_OK : base::File::FILE_ERROR_ACCESS_DENIED);
}
int32_t PepperFlashFileMessageFilter::OnQueryFile(
ppapi::host::HostMessageContext* context,
const ppapi::PepperFilePath& path) {
base::FilePath full_path = ValidateAndConvertPepperFilePath(
path, base::Bind(&CanRead));
if (full_path.empty()) {
return ppapi::FileErrorToPepperError(
base::File::FILE_ERROR_ACCESS_DENIED);
}
base::File::Info info;
bool result = base::GetFileInfo(full_path, &info);
context->reply_msg = PpapiPluginMsg_FlashFile_QueryFileReply(info);
return ppapi::FileErrorToPepperError(result ?
base::File::FILE_OK : base::File::FILE_ERROR_ACCESS_DENIED);
}
int32_t PepperFlashFileMessageFilter::OnGetDirContents(
ppapi::host::HostMessageContext* context,
const ppapi::PepperFilePath& path) {
base::FilePath full_path = ValidateAndConvertPepperFilePath(
path, base::Bind(&CanRead));
if (full_path.empty()) {
return ppapi::FileErrorToPepperError(
base::File::FILE_ERROR_ACCESS_DENIED);
}
ppapi::DirContents contents;
base::FileEnumerator enumerator(full_path, false,
base::FileEnumerator::FILES |
base::FileEnumerator::DIRECTORIES |
base::FileEnumerator::INCLUDE_DOT_DOT);
while (!enumerator.Next().empty()) {
base::FileEnumerator::FileInfo info = enumerator.GetInfo();
ppapi::DirEntry entry = {
info.GetName(),
info.IsDirectory()
};
contents.push_back(entry);
}
context->reply_msg = PpapiPluginMsg_FlashFile_GetDirContentsReply(contents);
return PP_OK;
}
int32_t PepperFlashFileMessageFilter::OnCreateTemporaryFile(
ppapi::host::HostMessageContext* context) {
ppapi::PepperFilePath dir_path(
ppapi::PepperFilePath::DOMAIN_MODULE_LOCAL, base::FilePath());
base::FilePath validated_dir_path = ValidateAndConvertPepperFilePath(
dir_path, base::Bind(&CanCreateReadWrite));
if (validated_dir_path.empty() ||
(!base::DirectoryExists(validated_dir_path) &&
!base::CreateDirectory(validated_dir_path))) {
return ppapi::FileErrorToPepperError(
base::File::FILE_ERROR_ACCESS_DENIED);
}
base::FilePath file_path;
if (!base::CreateTemporaryFileInDir(validated_dir_path, &file_path)) {
return ppapi::FileErrorToPepperError(
base::File::FILE_ERROR_FAILED);
}
base::File file(file_path,
base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_READ |
base::File::FLAG_WRITE | base::File::FLAG_TEMPORARY |
base::File::FLAG_DELETE_ON_CLOSE);
if (!file.IsValid())
return ppapi::FileErrorToPepperError(file.error_details());
IPC::PlatformFileForTransit transit_file =
IPC::TakeFileHandleForProcess(file.Pass(), plugin_process_handle_);
ppapi::host::ReplyMessageContext reply_context =
context->MakeReplyMessageContext();
reply_context.params.AppendHandle(ppapi::proxy::SerializedHandle(
ppapi::proxy::SerializedHandle::FILE, transit_file));
SendReply(reply_context, IPC::Message());
return PP_OK_COMPLETIONPENDING;
}
base::FilePath PepperFlashFileMessageFilter::ValidateAndConvertPepperFilePath(
const ppapi::PepperFilePath& pepper_path,
const CheckPermissionsCallback& check_permissions_callback) const {
base::FilePath file_path; // Empty path returned on error.
switch (pepper_path.domain()) {
case ppapi::PepperFilePath::DOMAIN_ABSOLUTE:
if (pepper_path.path().IsAbsolute() &&
check_permissions_callback.Run(render_process_id_,
pepper_path.path()))
file_path = pepper_path.path();
break;
case ppapi::PepperFilePath::DOMAIN_MODULE_LOCAL:
// This filter provides the module name portion of the path to prevent
// plugins from accessing each other's data.
if (!plugin_data_directory_.empty() &&
!pepper_path.path().IsAbsolute() &&
!pepper_path.path().ReferencesParent())
file_path = plugin_data_directory_.Append(pepper_path.path());
break;
default:
NOTREACHED();
break;
}
return file_path;
}
} // namespace content
<|endoftext|> |
<commit_before>#include "ConsoleReporter.h"
#include <chrono>
#include <cstdio>
#include <iostream>
#include <memory>
#include <mutex>
#include "xUnit++/LineInfo.h"
#include "xUnit++/TestDetails.h"
#include "xUnit++/TestEvent.h"
namespace
{
std::string FileAndLine(const xUnitpp::TestDetails &td, const xUnitpp::LineInfo &lineInfo)
{
auto result = to_string(lineInfo);
if (result.empty())
{
result = to_string(td.LineInfo);
}
return result;
}
class CachedOutput
{
typedef std::map<int, std::shared_ptr<CachedOutput>> OutputCache;
public:
CachedOutput(const std::string &name)
: name(name)
{
}
~CachedOutput()
{
if (!messages.empty())
{
std::cout << "\n[" << name << "]\n";
for (const auto &msg : messages)
{
std::cout << msg << std::endl;
}
}
}
static void Instant(const std::string &output)
{
std::cout << output;
}
static CachedOutput &Cache(const xUnitpp::TestDetails &td)
{
auto &cache = Cache();
auto it = cache.find(td.Id);
if (it == cache.end())
{
cache.insert(std::make_pair(td.Id, std::make_shared<CachedOutput>(td.Name)));
}
return *cache[td.Id];
}
static void Finish(const xUnitpp::TestDetails &td)
{
auto &cache = Cache();
auto it = cache.find(td.Id);
if (it != cache.end())
{
cache.erase(it);
}
}
CachedOutput &operator <<(const std::string &output)
{
messages.push_back(output);
return *this;
}
private:
static OutputCache &Cache()
{
static OutputCache cache;
return cache;
}
std::string name;
std::vector<std::string> messages;
};
}
namespace xUnitpp
{
ConsoleReporter::ConsoleReporter(bool verbose, bool veryVerbose)
: mVerbose(verbose)
, mVeryVerbose(veryVerbose)
{
}
void ConsoleReporter::ReportStart(const TestDetails &testDetails)
{
if (mVeryVerbose)
{
CachedOutput::Instant("Starting test " + testDetails.Name + ".");
}
}
void ConsoleReporter::ReportEvent(const TestDetails &testDetails, const TestEvent &evt)
{
CachedOutput::Cache(testDetails) << (FileAndLine(testDetails, evt.LineInfo()) +
": " + to_string(evt.Level()) + ": " + to_string(evt));
}
void ConsoleReporter::ReportSkip(const TestDetails &testDetails, const std::string &reason)
{
CachedOutput::Instant(FileAndLine(testDetails, LineInfo::empty()) +
": skipping " + testDetails.Name + ": " + reason);
}
void ConsoleReporter::ReportFinish(const TestDetails &testDetails, Time::Duration timeTaken)
{
if (mVerbose)
{
auto ms = Time::ToMilliseconds(timeTaken);
CachedOutput::Cache(testDetails) << (testDetails.Name + ": Completed in " +
(ms.count() == 0 ? (std::to_string(timeTaken.count()) + " nanoseconds.\n") : (std::to_string(ms.count()) + " milliseconds.\n")));
}
CachedOutput::Finish(testDetails);
}
void ConsoleReporter::ReportAllTestsComplete(size_t testCount, size_t skipped, size_t failureCount, Time::Duration totalTime)
{
std::string total = std::to_string(testCount) + " tests, ";
std::string failures = std::to_string(failureCount) + " failed, ";
std::string skips = std::to_string(skipped) + " skipped.";
std::string header;
if (failureCount > 0)
{
header = "\nFAILURE: ";
}
else if (skipped > 0)
{
header = "\nWARNING: ";
}
else
{
header = "\nSuccess: ";
}
CachedOutput::Instant(header + total + failures + skips);
header = "Test time: ";
auto ms = Time::ToMilliseconds(totalTime);
if (ms.count() > 500)
{
CachedOutput::Instant(header + std::to_string(Time::ToSeconds(totalTime).count()) + " seconds.");
}
else
{
CachedOutput::Instant(header + std::to_string(ms.count()) + " milliseconds.");
}
}
}
<commit_msg>accidentally removed newline in output<commit_after>#include "ConsoleReporter.h"
#include <chrono>
#include <cstdio>
#include <iostream>
#include <memory>
#include <mutex>
#include "xUnit++/LineInfo.h"
#include "xUnit++/TestDetails.h"
#include "xUnit++/TestEvent.h"
namespace
{
std::string FileAndLine(const xUnitpp::TestDetails &td, const xUnitpp::LineInfo &lineInfo)
{
auto result = to_string(lineInfo);
if (result.empty())
{
result = to_string(td.LineInfo);
}
return result;
}
class CachedOutput
{
typedef std::map<int, std::shared_ptr<CachedOutput>> OutputCache;
public:
CachedOutput(const std::string &name)
: name(name)
{
}
~CachedOutput()
{
if (!messages.empty())
{
std::cout << "\n[" << name << "]\n";
for (const auto &msg : messages)
{
std::cout << msg << std::endl;
}
}
}
static void Instant(const std::string &output)
{
std::cout << output;
}
static CachedOutput &Cache(const xUnitpp::TestDetails &td)
{
auto &cache = Cache();
auto it = cache.find(td.Id);
if (it == cache.end())
{
cache.insert(std::make_pair(td.Id, std::make_shared<CachedOutput>(td.Name)));
}
return *cache[td.Id];
}
static void Finish(const xUnitpp::TestDetails &td)
{
auto &cache = Cache();
auto it = cache.find(td.Id);
if (it != cache.end())
{
cache.erase(it);
}
}
CachedOutput &operator <<(const std::string &output)
{
messages.push_back(output);
return *this;
}
private:
static OutputCache &Cache()
{
static OutputCache cache;
return cache;
}
std::string name;
std::vector<std::string> messages;
};
}
namespace xUnitpp
{
ConsoleReporter::ConsoleReporter(bool verbose, bool veryVerbose)
: mVerbose(verbose)
, mVeryVerbose(veryVerbose)
{
}
void ConsoleReporter::ReportStart(const TestDetails &testDetails)
{
if (mVeryVerbose)
{
CachedOutput::Instant("Starting test " + testDetails.Name + ".");
}
}
void ConsoleReporter::ReportEvent(const TestDetails &testDetails, const TestEvent &evt)
{
CachedOutput::Cache(testDetails) << (FileAndLine(testDetails, evt.LineInfo()) +
": " + to_string(evt.Level()) + ": " + to_string(evt));
}
void ConsoleReporter::ReportSkip(const TestDetails &testDetails, const std::string &reason)
{
CachedOutput::Instant(FileAndLine(testDetails, LineInfo::empty()) +
": skipping " + testDetails.Name + ": " + reason);
}
void ConsoleReporter::ReportFinish(const TestDetails &testDetails, Time::Duration timeTaken)
{
if (mVerbose)
{
auto ms = Time::ToMilliseconds(timeTaken);
CachedOutput::Cache(testDetails) << (testDetails.Name + ": Completed in " +
(ms.count() == 0 ? (std::to_string(timeTaken.count()) + " nanoseconds.\n") : (std::to_string(ms.count()) + " milliseconds.\n")));
}
CachedOutput::Finish(testDetails);
}
void ConsoleReporter::ReportAllTestsComplete(size_t testCount, size_t skipped, size_t failureCount, Time::Duration totalTime)
{
std::string total = std::to_string(testCount) + " tests, ";
std::string failures = std::to_string(failureCount) + " failed, ";
std::string skips = std::to_string(skipped) + " skipped.";
std::string header;
if (failureCount > 0)
{
header = "\nFAILURE: ";
}
else if (skipped > 0)
{
header = "\nWARNING: ";
}
else
{
header = "\nSuccess: ";
}
CachedOutput::Instant(header + total + failures + skips);
header = "\nTest time: ";
auto ms = Time::ToMilliseconds(totalTime);
if (ms.count() > 500)
{
CachedOutput::Instant(header + std::to_string(Time::ToSeconds(totalTime).count()) + " seconds.");
}
else
{
CachedOutput::Instant(header + std::to_string(ms.count()) + " milliseconds.");
}
}
}
<|endoftext|> |
<commit_before>#include <string>
#include <stdexcept>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <sauce/sauce.h>
using ::testing::Sequence;
using ::testing::Return;
using ::sauce::Binder;
using ::sauce::Named;
namespace sauce {
namespace test {
struct CustomBuilt {};
struct CustomBuiltProvider: Provider<CustomBuilt> {
CustomBuilt * provide() {
return new CustomBuilt();
}
void dispose(CustomBuilt * customBuilt) {
delete customBuilt;
}
};
void ProviderModule(Binder & binder) {
binder.bind<CustomBuiltProvider>().to<CustomBuiltProvider()>();
binder.bind<CustomBuilt>().toProvider<CustomBuiltProvider>();
}
TEST(BindingTest, shouldBindProviders) {
sauce::shared_ptr<Injector> injector(Modules().add(&ProviderModule).createInjector());
sauce::shared_ptr<CustomBuilt> customBuilt = injector->get<CustomBuilt>();
}
struct Unbound {};
TEST(BindingTest, shouldThrowExceptionWhenGettingAnUnboundIface) {
sauce::shared_ptr<Injector> injector(Modules().createInjector());
ASSERT_THROW((injector->get<Unbound>()), ::sauce::UnboundException);
}
TEST(BindingTest, shouldImplicitlyBindTheInjectorItself) {
sauce::shared_ptr<Injector> expected = Modules().createInjector();
sauce::shared_ptr<Injector> actual = expected->get<Injector>();
ASSERT_EQ(expected, actual);
}
struct Dog;
struct Tail {
Tail(sauce::shared_ptr<Dog>) {}
};
struct Dog {
Dog(sauce::shared_ptr<Tail>) {}
};
void CircularModule(Binder & binder) {
binder.bind<Tail>().in<SingletonScope>().to<Tail(Dog)>();
binder.bind<Dog>().in<SingletonScope>().to<Dog(Tail)>();
}
TEST(BindingTest, shouldThrowExceptionWhenResolvingCircularDependency) {
sauce::shared_ptr<Injector> injector(Modules().add(&CircularModule).createInjector());
ASSERT_THROW(injector->get<Tail>(), ::sauce::CircularDependencyException);
}
TEST(BindingTest, shouldThrowExceptionWhenEagerlyProvidingCircularDependency) {
sauce::shared_ptr<Injector> injector(Modules().add(&CircularModule).createInjector());
ASSERT_THROW(injector->eagerlyProvide<SingletonScope>(), ::sauce::CircularDependencyException);
}
struct IncompletelyBound {};
void IncompleteModule(Binder & binder) {
binder.bind<IncompletelyBound>() /* to ...? */;
}
TEST(BindingTest, shouldThrowExceptionOnPartialBinding) {
ASSERT_THROW(
Modules().add(&IncompleteModule).createInjector(),
::sauce::PartialBindingException);
}
struct Animal {
virtual std::string says() = 0;
};
struct Cat: Animal {
std::string says() { return "Meow"; }
};
struct LieutenantShinysides {};
struct Fish: Animal {
std::string says() { return "Blub blub"; }
};
struct Meatloaf {};
struct Cow: Animal {
std::string says() { return "Moo"; }
};
struct Pond {
sauce::shared_ptr<Animal> animal;
Pond(sauce::shared_ptr<Animal> animal):
animal(animal) {}
};
void AnimalModule(Binder & binder) {
binder.bind<Animal>().to<Cat()>();
binder.bind<Animal>().named<LieutenantShinysides>().to<Fish()>();
binder.bind<Animal>().named<Meatloaf>().to<Cow()>();
binder.bind<Pond>().to<Pond(Named<Animal, LieutenantShinysides>)>();
}
TEST(BindingTest, shouldProvidedNamedDependencies) {
sauce::shared_ptr<Injector> injector(Modules().add(&AnimalModule).createInjector());
EXPECT_EQ("Meow", (injector->get<Animal>()->says()));
EXPECT_EQ("Blub blub", (injector->get<Animal, LieutenantShinysides>()->says()));
EXPECT_EQ("Moo", (injector->get<Named<Animal, Meatloaf> >()->says()));
EXPECT_EQ("Blub blub", (injector->get<Pond>()->animal->says()));
}
void IncompleteNamedModule(Binder & binder) {
binder.bind<IncompletelyBound>().named<LieutenantShinysides>() /* to ...? */;
}
TEST(BindingTest, shouldThrowExceptionOnPartialNamedBinding) {
ASSERT_THROW(
Modules().add(&IncompleteNamedModule).createInjector(),
::sauce::PartialBindingException);
}
void IncompleteScopeModule(Binder & binder) {
binder.bind<IncompletelyBound>().in<SingletonScope>();
}
TEST(BindingTest, shouldThrowExceptionOnPartialScopedBinding) {
ASSERT_THROW(
Modules().add(&IncompleteScopeModule).createInjector(),
::sauce::PartialBindingException);
}
}
}
<commit_msg>Tweak<commit_after>#include <string>
#include <stdexcept>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <sauce/sauce.h>
using ::testing::Sequence;
using ::testing::Return;
using ::sauce::Binder;
using ::sauce::Named;
namespace sauce {
namespace test {
struct CustomBuilt {};
struct CustomBuiltProvider: Provider<CustomBuilt> {
CustomBuilt * provide() {
return new CustomBuilt();
}
void dispose(CustomBuilt * customBuilt) {
delete customBuilt;
}
};
void ProviderModule(Binder & binder) {
binder.bind<CustomBuiltProvider>().to<CustomBuiltProvider()>();
binder.bind<CustomBuilt>().toProvider<CustomBuiltProvider>();
}
TEST(BindingTest, shouldBindProviders) {
sauce::shared_ptr<Injector> injector(Modules().add(&ProviderModule).createInjector());
sauce::shared_ptr<CustomBuilt> customBuilt = injector->get<CustomBuilt>();
}
struct Unbound {};
TEST(BindingTest, shouldThrowExceptionWhenGettingAnUnboundIface) {
sauce::shared_ptr<Injector> injector(Modules().createInjector());
ASSERT_THROW(injector->get<Unbound>(), ::sauce::UnboundException);
}
TEST(BindingTest, shouldImplicitlyBindTheInjectorItself) {
sauce::shared_ptr<Injector> expected = Modules().createInjector();
sauce::shared_ptr<Injector> actual = expected->get<Injector>();
ASSERT_EQ(expected, actual);
}
struct Dog;
struct Tail {
Tail(sauce::shared_ptr<Dog>) {}
};
struct Dog {
Dog(sauce::shared_ptr<Tail>) {}
};
void CircularModule(Binder & binder) {
binder.bind<Tail>().in<SingletonScope>().to<Tail(Dog)>();
binder.bind<Dog>().in<SingletonScope>().to<Dog(Tail)>();
}
TEST(BindingTest, shouldThrowExceptionWhenResolvingCircularDependency) {
sauce::shared_ptr<Injector> injector(Modules().add(&CircularModule).createInjector());
ASSERT_THROW(injector->get<Tail>(), ::sauce::CircularDependencyException);
}
TEST(BindingTest, shouldThrowExceptionWhenEagerlyProvidingCircularDependency) {
sauce::shared_ptr<Injector> injector(Modules().add(&CircularModule).createInjector());
ASSERT_THROW(injector->eagerlyProvide<SingletonScope>(), ::sauce::CircularDependencyException);
}
struct IncompletelyBound {};
void IncompleteModule(Binder & binder) {
binder.bind<IncompletelyBound>() /* to ...? */;
}
TEST(BindingTest, shouldThrowExceptionOnPartialBinding) {
ASSERT_THROW(
Modules().add(&IncompleteModule).createInjector(),
::sauce::PartialBindingException);
}
struct Animal {
virtual std::string says() = 0;
};
struct Cat: Animal {
std::string says() { return "Meow"; }
};
struct LieutenantShinysides {};
struct Fish: Animal {
std::string says() { return "Blub blub"; }
};
struct Meatloaf {};
struct Cow: Animal {
std::string says() { return "Moo"; }
};
struct Pond {
sauce::shared_ptr<Animal> animal;
Pond(sauce::shared_ptr<Animal> animal):
animal(animal) {}
};
void AnimalModule(Binder & binder) {
binder.bind<Animal>().to<Cat()>();
binder.bind<Animal>().named<LieutenantShinysides>().to<Fish()>();
binder.bind<Animal>().named<Meatloaf>().to<Cow()>();
binder.bind<Pond>().to<Pond(Named<Animal, LieutenantShinysides>)>();
}
TEST(BindingTest, shouldProvidedNamedDependencies) {
sauce::shared_ptr<Injector> injector(Modules().add(&AnimalModule).createInjector());
EXPECT_EQ("Meow", (injector->get<Animal>()->says()));
EXPECT_EQ("Blub blub", (injector->get<Animal, LieutenantShinysides>()->says()));
EXPECT_EQ("Moo", (injector->get<Named<Animal, Meatloaf> >()->says()));
EXPECT_EQ("Blub blub", (injector->get<Pond>()->animal->says()));
}
void IncompleteNamedModule(Binder & binder) {
binder.bind<IncompletelyBound>().named<LieutenantShinysides>() /* to ...? */;
}
TEST(BindingTest, shouldThrowExceptionOnPartialNamedBinding) {
ASSERT_THROW(
Modules().add(&IncompleteNamedModule).createInjector(),
::sauce::PartialBindingException);
}
void IncompleteScopeModule(Binder & binder) {
binder.bind<IncompletelyBound>().in<SingletonScope>();
}
TEST(BindingTest, shouldThrowExceptionOnPartialScopedBinding) {
ASSERT_THROW(
Modules().add(&IncompleteScopeModule).createInjector(),
::sauce::PartialBindingException);
}
}
}
<|endoftext|> |
<commit_before>/**
** \file scheduler/scheduler.cc
** \brief Implementation of scheduler::Scheduler.
*/
//#define ENABLE_DEBUG_TRACES
#include <cassert>
#include <cstdlib>
#include <libport/compiler.hh>
#include <libport/containers.hh>
#include <libport/contract.hh>
#include <libport/foreach.hh>
#include <object/urbi-exception.hh>
#include <scheduler/scheduler.hh>
#include <scheduler/job.hh>
namespace scheduler
{
// This function is required to start a new job using the libcoroutine.
// Its only purpose is to create the context and start the execution
// of the new job.
static void
run_job(Job* job)
{
job->run();
}
void
Scheduler::add_job(rJob job)
{
assert(job);
assert(!libport::has(jobs_, job));
assert(!libport::has(pending_, job));
// If we are currently in a job, add it to the pending_ queue so that
// the job is started in the course of the current round. To make sure
// that it is not started too late even if the creator is located after
// the job that is causing the creation (think "at job handler" for
// example), insert it right after the current job.
if (current_job_)
{
jobs_type::iterator insert_before = job_p_;
pending_.insert(++insert_before, job);
}
else
{
jobs_.push_back(job);
jobs_to_start_ = true;
}
}
libport::utime_t
Scheduler::work()
{
++cycle_;
ECHO("======================================================== cycle "
<< cycle_);
libport::utime_t deadline = execute_round();
#ifdef ENABLE_DEBUG_TRACES
if (deadline)
ECHO("Scheduler asking to be woken up in "
<< (deadline - get_time_()) / 1000000L << " seconds");
else
ECHO("Scheduler asking to be woken up ASAP");
#endif
return deadline;
}
libport::utime_t
Scheduler::execute_round()
{
// Run all the jobs in the run queue once. If any job declares upon entry or
// return that it is not side-effect free, we remember that for the next
// cycle.
pending_.clear();
std::swap(pending_, jobs_);
// By default, wake us up after one hour and consider that we have no
// new job to start. Also, run waiting jobs only if the previous round
// may have add a side effect and reset this indication for the current
// job.
libport::utime_t start_time = get_time_();
libport::utime_t deadline = start_time + 3600000000LL;
jobs_to_start_ = false;
bool start_waiting = possible_side_effect_;
possible_side_effect_ = false;
bool at_least_one_started = false;
ECHO(pending_.size() << " jobs in the queue for this round");
// Do not use libport::foreach here, as the list of jobs may grow if
// add_job() is called during the iteration.
for (job_p_ = pending_.begin();
job_p_ != pending_.end();
++job_p_)
{
rJob& job = *job_p_;
// If the job has terminated during the previous round, remove the
// references we have on it by just skipping it.
if (job->terminated())
continue;
// Should the job be started?
bool start = false;
// Save the current time since we will use it several times during this job
// analysis.
libport::utime_t current_time = get_time_();
ECHO("Considering " << *job << " in state " << state_name(job->state_get()));
switch (job->state_get())
{
case to_start:
{
// New job. Start its coroutine but do not start the job as it would be queued
// twice otherwise. It will start doing real work at the next cycle, so set
// deadline to 0. Note that we use "continue" here to avoid having the job
// requeued because it hasn't been started by setting "start".
//
// The code below takes care of destroying the rJob reference to the job, so
// that it does not stay in the call stack as a local variable. If it did,
// the job would never be destroyed. However, to prevent the job from being
// prematurely destroyed, we set current_job_ (global to the scheduler) to
// the rJob.
ECHO("Starting job " << *job);
current_job_ = job;
ECHO("Job " << *job << " is starting");
job = 0;
coroutine_start(coro_, current_job_->coro_get(), run_job, current_job_.get());
current_job_ = 0;
deadline = SCHED_IMMEDIATE;
at_least_one_started = true;
continue;
}
case zombie:
assert(false);
break;
case running:
start = true;
break;
case sleeping:
{
libport::utime_t job_deadline = job->deadline_get();
// If the job has been frozen, extend its deadline by the
// corresponding amount of time. The deadline will be adjusted
// later when the job is unfrozen using notice_not_frozen(),
// but in the meantime we do not want to cause an early wakeup.
if (libport::utime_t frozen_since = job->frozen_since_get())
job_deadline += current_time - frozen_since;
if (job_deadline <= current_time)
start = true;
else
deadline = std::min(deadline, job_deadline);
}
break;
case waiting:
// Since jobs keep their orders in the queue, start waiting jobs if
// previous jobs in the run have had a possible side effect or if
// the previous run may have had some. Without it, we may miss some
// changes if the watching job is after the modifying job in the queue
// and the watched condition gets true for only one cycle.
start = start_waiting || possible_side_effect_;
break;
case joining:
break;
}
// Tell the job whether it is frozen or not so that it can remember
// since when it has been in this state.
if (job->frozen())
job->notice_frozen(current_time);
else
job->notice_not_frozen(current_time);
// A job with an exception will start unconditionally.
if (start || job->has_pending_exception())
{
at_least_one_started = true;
ECHO("will resume job " << *job
<< (job->side_effect_free_get() ? " (side-effect free)" : ""));
possible_side_effect_ |= !job->side_effect_free_get();
assert(!current_job_);
coroutine_switch_to(coro_, job->coro_get());
assert(!current_job_);
possible_side_effect_ |= !job->side_effect_free_get();
ECHO("back from job " << *job
<< (job->side_effect_free_get() ? " (side-effect free)" : ""));
switch (job->state_get())
{
case running:
deadline = SCHED_IMMEDIATE;
break;
case sleeping:
deadline = std::min(deadline, job->deadline_get());
break;
default:
break;
}
}
else
jobs_.push_back(job); // Job not started, keep it in queue
}
/// If during this cycle a new job has been created by an existing job,
/// start it. Also start if a possible side effect happened, it may have
/// occurred later then the waiting jobs in the cycle.
if (jobs_to_start_ || possible_side_effect_)
deadline = SCHED_IMMEDIATE;
/// If we are ready to die and there are no jobs left, then die.
if (ready_to_die_ && jobs_.empty())
deadline = SCHED_EXIT;
// Compute statistics
if (at_least_one_started)
stats_.add_sample(get_time_() - start_time);
return deadline;
}
void
Scheduler::resume_scheduler(rJob job)
{
// If the job has not terminated and is side-effect free, then we
// assume it will not take a long time as we are probably evaluating
// a condition. In order to reduce the number of cycles spent to evaluate
// the condition, continue until it asks to be suspended in another
// way or until it is no longer side-effect free.
bool side_effect_free_save = job->side_effect_free_get();
if (job->state_get() == running && side_effect_free_save)
return;
// We may have to suspend the job several time in case it makes no sense
// to start it back. Let's do it in a loop and we'll break when we want
// to resume the job.
while (true)
{
// Add the job at the end of the scheduler queue unless the job has
// already terminated.
if (!job->terminated())
jobs_.push_back(job);
// Switch back to the scheduler. But in the case this job has been
// destroyed, erase the local variable first so that it doesn't keep
// a reference on it which will never be destroyed.
assert(current_job_ == job);
ECHO(*job << " has " << (job->terminated() ? "" : "not ") << "terminated\n\t"
<< "state: " << state_name(job->state_get()) << std::endl);
Coro* current_coro = job->coro_get();
if (job->terminated())
job = 0;
current_job_ = 0;
coroutine_switch_to(current_coro, coro_);
// If we regain control, we are not dead.
assert(job);
// We regained control, we are again in the context of the job.
assert(!current_job_);
current_job_ = job;
ECHO("job " << *job << " resumed");
// Execute a deferred exception if any; this may break out of this loop
job->check_for_pending_exception();
// If we are not frozen, it is time to resume regular execution
if (!job->frozen())
break;
// Ok, we are frozen. Let's requeue ourselves after setting
// the side_effect_free flag, and we will be in waiting mode.
job->side_effect_free_set(true);
job->state_set(waiting);
}
// Check that we are not near exhausting the stack space.
job->check_stack_space();
// Restore the side_effect_free flag
job->side_effect_free_set(side_effect_free_save);
// Resume job execution
}
void
Scheduler::killall_jobs()
{
ECHO("killing all jobs!");
// Mark the scheduler as ready to die when all the jobs are
// really dead.
ready_to_die_ = true;
// Since killing the current job will result in its immediate
// termination, kill all other jobs before.
foreach (rJob job, jobs_get())
if (job != current_job_)
job->terminate_now();
if (current_job_)
current_job_->terminate_now();
}
void
Scheduler::signal_stop(const rTag& tag, boost::any payload)
{
// Tell the jobs that a tag has been stopped, ending with
// the current job to avoid interrupting this method early.
foreach (rJob job, jobs_get())
{
// Job started at this cycle, reset to avoid stack references.
if (!job)
continue;
// Job to be started during this cycle.
if (job->state_get() == to_start)
{
// Check if this job deserves to be removed.
foreach (const rTag& t, job->tags_get())
if (t->derives_from(*tag))
{
pending_.remove(job);
continue;
}
}
// Any other non-current job.
else if (job != current_job_)
job->register_stopped_tag(tag, payload);
}
if (current_job_)
current_job_->register_stopped_tag(tag, payload);
}
jobs_type
Scheduler::jobs_get() const
{
// If this method is called from within a job, return the currently
// executing jobs (pending_), otherwise return the jobs_ content which
// is complete.
return current_job_ ? pending_ : jobs_;
}
const scheduler_stats_type&
Scheduler::stats_get() const
{
return stats_;
}
} // namespace scheduler
<commit_msg>Do not reset current_job_ before switching back to the scheduler.<commit_after>/**
** \file scheduler/scheduler.cc
** \brief Implementation of scheduler::Scheduler.
*/
//#define ENABLE_DEBUG_TRACES
#include <cassert>
#include <cstdlib>
#include <libport/compiler.hh>
#include <libport/containers.hh>
#include <libport/contract.hh>
#include <libport/foreach.hh>
#include <object/urbi-exception.hh>
#include <scheduler/scheduler.hh>
#include <scheduler/job.hh>
namespace scheduler
{
// This function is required to start a new job using the libcoroutine.
// Its only purpose is to create the context and start the execution
// of the new job.
static void
run_job(Job* job)
{
job->run();
}
void
Scheduler::add_job(rJob job)
{
assert(job);
assert(!libport::has(jobs_, job));
assert(!libport::has(pending_, job));
// If we are currently in a job, add it to the pending_ queue so that
// the job is started in the course of the current round. To make sure
// that it is not started too late even if the creator is located after
// the job that is causing the creation (think "at job handler" for
// example), insert it right after the current job.
if (current_job_)
{
jobs_type::iterator insert_before = job_p_;
pending_.insert(++insert_before, job);
}
else
{
jobs_.push_back(job);
jobs_to_start_ = true;
}
}
libport::utime_t
Scheduler::work()
{
++cycle_;
ECHO("======================================================== cycle "
<< cycle_);
libport::utime_t deadline = execute_round();
#ifdef ENABLE_DEBUG_TRACES
if (deadline)
ECHO("Scheduler asking to be woken up in "
<< (deadline - get_time_()) / 1000000L << " seconds");
else
ECHO("Scheduler asking to be woken up ASAP");
#endif
return deadline;
}
libport::utime_t
Scheduler::execute_round()
{
// Run all the jobs in the run queue once. If any job declares upon entry or
// return that it is not side-effect free, we remember that for the next
// cycle.
pending_.clear();
std::swap(pending_, jobs_);
// By default, wake us up after one hour and consider that we have no
// new job to start. Also, run waiting jobs only if the previous round
// may have add a side effect and reset this indication for the current
// job.
libport::utime_t start_time = get_time_();
libport::utime_t deadline = start_time + 3600000000LL;
jobs_to_start_ = false;
bool start_waiting = possible_side_effect_;
possible_side_effect_ = false;
bool at_least_one_started = false;
ECHO(pending_.size() << " jobs in the queue for this round");
// Do not use libport::foreach here, as the list of jobs may grow if
// add_job() is called during the iteration.
for (job_p_ = pending_.begin();
job_p_ != pending_.end();
++job_p_)
{
rJob& job = *job_p_;
// If the job has terminated during the previous round, remove the
// references we have on it by just skipping it.
if (job->terminated())
continue;
// Should the job be started?
bool start = false;
// Save the current time since we will use it several times during this job
// analysis.
libport::utime_t current_time = get_time_();
ECHO("Considering " << *job << " in state " << state_name(job->state_get()));
switch (job->state_get())
{
case to_start:
{
// New job. Start its coroutine but do not start the job as it would be queued
// twice otherwise. It will start doing real work at the next cycle, so set
// deadline to 0. Note that we use "continue" here to avoid having the job
// requeued because it hasn't been started by setting "start".
//
// The code below takes care of destroying the rJob reference to the job, so
// that it does not stay in the call stack as a local variable. If it did,
// the job would never be destroyed. However, to prevent the job from being
// prematurely destroyed, we set current_job_ (global to the scheduler) to
// the rJob.
ECHO("Starting job " << *job);
current_job_ = job;
ECHO("Job " << *job << " is starting");
job = 0;
coroutine_start(coro_, current_job_->coro_get(), run_job, current_job_.get());
current_job_ = 0;
deadline = SCHED_IMMEDIATE;
at_least_one_started = true;
continue;
}
case zombie:
assert(false);
break;
case running:
start = true;
break;
case sleeping:
{
libport::utime_t job_deadline = job->deadline_get();
// If the job has been frozen, extend its deadline by the
// corresponding amount of time. The deadline will be adjusted
// later when the job is unfrozen using notice_not_frozen(),
// but in the meantime we do not want to cause an early wakeup.
if (libport::utime_t frozen_since = job->frozen_since_get())
job_deadline += current_time - frozen_since;
if (job_deadline <= current_time)
start = true;
else
deadline = std::min(deadline, job_deadline);
}
break;
case waiting:
// Since jobs keep their orders in the queue, start waiting jobs if
// previous jobs in the run have had a possible side effect or if
// the previous run may have had some. Without it, we may miss some
// changes if the watching job is after the modifying job in the queue
// and the watched condition gets true for only one cycle.
start = start_waiting || possible_side_effect_;
break;
case joining:
break;
}
// Tell the job whether it is frozen or not so that it can remember
// since when it has been in this state.
if (job->frozen())
job->notice_frozen(current_time);
else
job->notice_not_frozen(current_time);
// A job with an exception will start unconditionally.
if (start || job->has_pending_exception())
{
at_least_one_started = true;
ECHO("will resume job " << *job
<< (job->side_effect_free_get() ? " (side-effect free)" : ""));
possible_side_effect_ |= !job->side_effect_free_get();
assert(!current_job_);
coroutine_switch_to(coro_, job->coro_get());
assert(current_job_);
current_job_ = 0;
possible_side_effect_ |= !job->side_effect_free_get();
ECHO("back from job " << *job
<< (job->side_effect_free_get() ? " (side-effect free)" : ""));
switch (job->state_get())
{
case running:
deadline = SCHED_IMMEDIATE;
break;
case sleeping:
deadline = std::min(deadline, job->deadline_get());
break;
default:
break;
}
}
else
jobs_.push_back(job); // Job not started, keep it in queue
}
/// If during this cycle a new job has been created by an existing job,
/// start it. Also start if a possible side effect happened, it may have
/// occurred later then the waiting jobs in the cycle.
if (jobs_to_start_ || possible_side_effect_)
deadline = SCHED_IMMEDIATE;
/// If we are ready to die and there are no jobs left, then die.
if (ready_to_die_ && jobs_.empty())
deadline = SCHED_EXIT;
// Compute statistics
if (at_least_one_started)
stats_.add_sample(get_time_() - start_time);
return deadline;
}
void
Scheduler::resume_scheduler(rJob job)
{
// If the job has not terminated and is side-effect free, then we
// assume it will not take a long time as we are probably evaluating
// a condition. In order to reduce the number of cycles spent to evaluate
// the condition, continue until it asks to be suspended in another
// way or until it is no longer side-effect free.
bool side_effect_free_save = job->side_effect_free_get();
if (job->state_get() == running && side_effect_free_save)
return;
// We may have to suspend the job several time in case it makes no sense
// to start it back. Let's do it in a loop and we'll break when we want
// to resume the job.
while (true)
{
// Add the job at the end of the scheduler queue unless the job has
// already terminated.
if (!job->terminated())
jobs_.push_back(job);
// Switch back to the scheduler. But in the case this job has been
// destroyed, erase the local variable first so that it doesn't keep
// a reference on it which will never be destroyed.
assert(current_job_ == job);
ECHO(*job << " has " << (job->terminated() ? "" : "not ") << "terminated\n\t"
<< "state: " << state_name(job->state_get()) << std::endl);
Coro* current_coro = job->coro_get();
if (job->terminated())
job = 0;
coroutine_switch_to(current_coro, coro_);
// If we regain control, we are not dead.
assert(job);
// We regained control, we are again in the context of the job.
assert(!current_job_);
current_job_ = job;
ECHO("job " << *job << " resumed");
// Execute a deferred exception if any; this may break out of this loop
job->check_for_pending_exception();
// If we are not frozen, it is time to resume regular execution
if (!job->frozen())
break;
// Ok, we are frozen. Let's requeue ourselves after setting
// the side_effect_free flag, and we will be in waiting mode.
job->side_effect_free_set(true);
job->state_set(waiting);
}
// Check that we are not near exhausting the stack space.
job->check_stack_space();
// Restore the side_effect_free flag
job->side_effect_free_set(side_effect_free_save);
// Resume job execution
}
void
Scheduler::killall_jobs()
{
ECHO("killing all jobs!");
// Mark the scheduler as ready to die when all the jobs are
// really dead.
ready_to_die_ = true;
// Since killing the current job will result in its immediate
// termination, kill all other jobs before.
foreach (rJob job, jobs_get())
if (job != current_job_)
job->terminate_now();
if (current_job_)
current_job_->terminate_now();
}
void
Scheduler::signal_stop(const rTag& tag, boost::any payload)
{
// Tell the jobs that a tag has been stopped, ending with
// the current job to avoid interrupting this method early.
foreach (rJob job, jobs_get())
{
// Job started at this cycle, reset to avoid stack references.
if (!job)
continue;
// Job to be started during this cycle.
if (job->state_get() == to_start)
{
// Check if this job deserves to be removed.
foreach (const rTag& t, job->tags_get())
if (t->derives_from(*tag))
{
pending_.remove(job);
continue;
}
}
// Any other non-current job.
else if (job != current_job_)
job->register_stopped_tag(tag, payload);
}
if (current_job_)
current_job_->register_stopped_tag(tag, payload);
}
jobs_type
Scheduler::jobs_get() const
{
// If this method is called from within a job, return the currently
// executing jobs (pending_), otherwise return the jobs_ content which
// is complete.
return current_job_ ? pending_ : jobs_;
}
const scheduler_stats_type&
Scheduler::stats_get() const
{
return stats_;
}
} // namespace scheduler
<|endoftext|> |
<commit_before>#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <sauce/sauce.h>
using ::testing::Sequence;
using ::testing::Return;
namespace sauce {
namespace test {
class Store {};
class DBStore: public Store {};
class Session {};
class CookieSession: public Session {};
class Request {};
class HttpRequest: public Request {};
class Response {};
class HttpResponse: public Response {};
class Controller {};
class WelcomeController: public Controller {
public:
SAUCE_SHARED_PTR<Store> store;
SAUCE_SHARED_PTR<Session> session;
SAUCE_SHARED_PTR<Request> request;
SAUCE_SHARED_PTR<Response> response;
WelcomeController(SAUCE_SHARED_PTR<Store> store,
SAUCE_SHARED_PTR<Session> session,
SAUCE_SHARED_PTR<Request> request,
SAUCE_SHARED_PTR<Response> response):
store(store),
session(session),
request(request),
response(response) {}
};
struct WebAppModule: ::sauce::AbstractModule {
void configure() {
bind<Store>().to<DBStore()>();
bind<Session>().to<CookieSession()>();
bind<Request>().to<HttpRequest()>();
bind<Response>().to<HttpResponse()>();
bind<Controller>().to<WelcomeController(Store, Session, Request, Response)>();
}
};
struct BindingTest:
public ::testing::Test {
Injector injector;
BindingTest():
injector(Bindings().add(WebAppModule()).createInjector()) {}
virtual void SetUp() {}
virtual void TearDown() {}
};
TEST_F(BindingTest, shouldThrowExceptionWhenGettingAnUnboundIface) {
Injector injector(Bindings().createInjector());
ASSERT_THROW(injector.get<Request>(), ::sauce::UnboundException);
}
struct B;
struct A {
A(SAUCE_SHARED_PTR<B> ) {}
};
struct B {
B(SAUCE_SHARED_PTR<A> ) {}
};
void CircularModule(sauce::Binder & binder) {
binder.bind<A>().to<A(B)>();
binder.bind<B>().to<B(A)>();
}
TEST_F(BindingTest, shouldThrowExceptionWhenResolvingCircularDependency) {
Injector injector(Bindings().add(&CircularModule).createInjector());
ASSERT_THROW(injector.get<A>(), ::sauce::CircularDependencyException);
}
}
}<commit_msg>Let them eat public.<commit_after>#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <sauce/sauce.h>
using ::testing::Sequence;
using ::testing::Return;
namespace sauce {
namespace test {
struct Store {};
struct DBStore: public Store {};
struct Session {};
struct CookieSession: public Session {};
struct Request {};
struct HttpRequest: public Request {};
struct Response {};
struct HttpResponse: public Response {};
struct Controller {};
struct WelcomeController: public Controller {
SAUCE_SHARED_PTR<Store> store;
SAUCE_SHARED_PTR<Session> session;
SAUCE_SHARED_PTR<Request> request;
SAUCE_SHARED_PTR<Response> response;
WelcomeController(SAUCE_SHARED_PTR<Store> store,
SAUCE_SHARED_PTR<Session> session,
SAUCE_SHARED_PTR<Request> request,
SAUCE_SHARED_PTR<Response> response):
store(store),
session(session),
request(request),
response(response) {}
};
struct WebAppModule: ::sauce::AbstractModule {
void configure() {
bind<Store>().to<DBStore()>();
bind<Session>().to<CookieSession()>();
bind<Request>().to<HttpRequest()>();
bind<Response>().to<HttpResponse()>();
bind<Controller>().to<WelcomeController(Store, Session, Request, Response)>();
}
};
struct BindingTest:
public ::testing::Test {
Injector injector;
BindingTest():
injector(Bindings().add(WebAppModule()).createInjector()) {}
virtual void SetUp() {}
virtual void TearDown() {}
};
TEST_F(BindingTest, shouldThrowExceptionWhenGettingAnUnboundIface) {
Injector injector(Bindings().createInjector());
ASSERT_THROW(injector.get<Request>(), ::sauce::UnboundException);
}
struct B;
struct A {
A(SAUCE_SHARED_PTR<B> ) {}
};
struct B {
B(SAUCE_SHARED_PTR<A> ) {}
};
void CircularModule(sauce::Binder & binder) {
binder.bind<A>().to<A(B)>();
binder.bind<B>().to<B(A)>();
}
TEST_F(BindingTest, shouldThrowExceptionWhenResolvingCircularDependency) {
Injector injector(Bindings().add(&CircularModule).createInjector());
ASSERT_THROW(injector.get<A>(), ::sauce::CircularDependencyException);
}
}
}<|endoftext|> |
<commit_before>#include <cstdlib>
#include <cassert>
#include "zs.hh"
#include "test_util.hh"
static bool result = true;
void check(const char* input, const char* expect){
result = read_eval_print_test(input, expect,
[expect](const char* s){
printf("[failed] expected %s, but got %s\n", expect, s);
});
}
int main(){
install_builtin();
check("(list 1)", "(1)");
check("(list 1 2)", "(1 2)");
check("(list 1 2 3)", "(1 2 3)");
check("(list* 1)", "1");
check("(list* 1 2)", "(1 . 2)");
check("(list* 1 2 3)", "(1 2 . 3)");
check("(vector 1)", "#(1)");
check("(vector 1 2)", "#(1 2)");
check("(vector 1 2 3)", "#(1 2 3)");
check("(and)", "#t");
check("(and 1)", "1");
check("(and 1 2)", "2");
check("(and #f 2)", "#f");
check("(and 1 #f 3)", "#f");
check("(and #t #t 3)", "3");
check("(or)", "#f");
check("(or 1)", "1");
check("(or #f 2)", "2");
check("(or #f #f 3)", "3");
check("(or 1 #f 3)", "1");
check("(or #f 2 #f 4)", "2");
//check("(let () 100)", "100");
//check("(let (x) x)", "()");
check("(let ((x 1) (y 2) (z 3)) x)", "1");
check("(let ((x 1) (y 2) (z 3)) y)", "2");
check("(let ((x 1) (y 2) (z 3)) z)", "3");
check("(let ((x 1)) (let ((x 2)) x))", "2");
check("(let ((x 1)) (let ((x 2)) x) x)", "1");
check("(let* ((x 1)) x)", "1");
check("(let* ((x 1) (y x)) y)", "1");
check("(let* ((x 1) (y x) (z y)) z)", "1");
check("(let* ((x 1)) (let ((x 2)) x))", "2");
check("(let* ((x 1)) (let ((x 2)) x) x)", "1");
check("(letrec ((x 1)) x)", "1");
check("(letrec ((x 1) (y 2)) y)", "2");
check("(letrec ((x 1) (y 2) (z 3)) z)", "3");
check("(letrec ((x 1)) (let ((x 2)) x))", "2");
check("(letrec ((x 1)) (let ((x 2)) x) x)", "1");
check("(cond ((eqv? 1 1) 1))", "1");
check("(cond ((eqv? 1 2) xxx) ((eqv? 2 3) yyy) ((eqv? 3 3) 3))", "3");
check("(cond ((eqv? 1 2) xxx) ((eqv? 2 3) yyy) (else 3))", "3");
check("(cond ((eqv? 1 2)) ((eqv? 2 3) fuga) ((+ 5 7)))", "12");
//check("(case 1 ((1 3 5) 'odd) ((2 4 6) 'even))", "odd");
check("(eval 1 ())", "1");
return (result) ? EXIT_SUCCESS : EXIT_FAILURE;
}
<commit_msg>added eval test case<commit_after>#include <cstdlib>
#include <cassert>
#include "zs.hh"
#include "test_util.hh"
static bool result = true;
void check(const char* input, const char* expect){
result = read_eval_print_test(input, expect,
[expect](const char* s){
printf("[failed] expected %s, but got %s\n", expect, s);
});
}
int main(){
install_builtin();
check("(list 1)", "(1)");
check("(list 1 2)", "(1 2)");
check("(list 1 2 3)", "(1 2 3)");
check("(list* 1)", "1");
check("(list* 1 2)", "(1 . 2)");
check("(list* 1 2 3)", "(1 2 . 3)");
check("(vector 1)", "#(1)");
check("(vector 1 2)", "#(1 2)");
check("(vector 1 2 3)", "#(1 2 3)");
check("(and)", "#t");
check("(and 1)", "1");
check("(and 1 2)", "2");
check("(and #f 2)", "#f");
check("(and 1 #f 3)", "#f");
check("(and #t #t 3)", "3");
check("(or)", "#f");
check("(or 1)", "1");
check("(or #f 2)", "2");
check("(or #f #f 3)", "3");
check("(or 1 #f 3)", "1");
check("(or #f 2 #f 4)", "2");
//check("(let () 100)", "100");
//check("(let (x) x)", "()");
check("(let ((x 1) (y 2) (z 3)) x)", "1");
check("(let ((x 1) (y 2) (z 3)) y)", "2");
check("(let ((x 1) (y 2) (z 3)) z)", "3");
check("(let ((x 1)) (let ((x 2)) x))", "2");
check("(let ((x 1)) (let ((x 2)) x) x)", "1");
check("(let* ((x 1)) x)", "1");
check("(let* ((x 1) (y x)) y)", "1");
check("(let* ((x 1) (y x) (z y)) z)", "1");
check("(let* ((x 1)) (let ((x 2)) x))", "2");
check("(let* ((x 1)) (let ((x 2)) x) x)", "1");
check("(letrec ((x 1)) x)", "1");
check("(letrec ((x 1) (y 2)) y)", "2");
check("(letrec ((x 1) (y 2) (z 3)) z)", "3");
check("(letrec ((x 1)) (let ((x 2)) x))", "2");
check("(letrec ((x 1)) (let ((x 2)) x) x)", "1");
check("(cond ((eqv? 1 1) 1))", "1");
check("(cond ((eqv? 1 2) xxx) ((eqv? 2 3) yyy) ((eqv? 3 3) 3))", "3");
check("(cond ((eqv? 1 2) xxx) ((eqv? 2 3) yyy) (else 3))", "3");
check("(cond ((eqv? 1 2)) ((eqv? 2 3) fuga) ((+ 5 7)))", "12");
//check("(case 1 ((1 3 5) 'odd) ((2 4 6) 'even))", "odd");
check("(eval 1 ())", "1");
check("(eval (+ 1 3) ())", "4");
check("(eval '(+ 1 3) ())", "4");
check("(eval '(if (eqv? 1 2) \"same\" \"different\") ())", "\"different\"");
return (result) ? EXIT_SUCCESS : EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>//===-- ValueSymbolTable.cpp - Implement the ValueSymbolTable class -------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group. It is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the ValueSymbolTable class for the VMCore library.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "valuesymtab"
#include "llvm/GlobalValue.h"
#include "llvm/Type.h"
#include "llvm/ValueSymbolTable.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/Debug.h"
#include <algorithm>
using namespace llvm;
// Class destructor
ValueSymbolTable::~ValueSymbolTable() {
#ifndef NDEBUG // Only do this in -g mode...
bool LeftoverValues = true;
for (iterator VI = vmap.begin(), VE = vmap.end(); VI != VE; ++VI)
if (!isa<Constant>(VI->second) ) {
DEBUG(DOUT << "Value still in symbol table! Type = '"
<< VI->second->getType()->getDescription() << "' Name = '"
<< VI->first << "'\n");
LeftoverValues = false;
}
assert(LeftoverValues && "Values remain in symbol table!");
#endif
}
// getUniqueName - Given a base name, return a string that is either equal to
// it (or derived from it) that does not already occur in the symbol table for
// the specified type.
//
std::string ValueSymbolTable::getUniqueName(const std::string &BaseName) const {
std::string TryName = BaseName;
const_iterator End = vmap.end();
// See if the name exists
while (vmap.find(TryName) != End) // Loop until we find a free
TryName = BaseName + utostr(++LastUnique); // name in the symbol table
return TryName;
}
// lookup a value - Returns null on failure...
//
Value *ValueSymbolTable::lookup(const std::string &Name) const {
const_iterator VI = vmap.find(Name);
if (VI != vmap.end()) // We found the symbol
return const_cast<Value*>(VI->second);
return 0;
}
// Strip the symbol table of its names.
//
bool ValueSymbolTable::strip() {
bool RemovedSymbol = false;
for (iterator VI = vmap.begin(), VE = vmap.end(); VI != VE; ) {
Value *V = VI->second;
++VI;
if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasInternalLinkage()) {
// Set name to "", removing from symbol table!
V->setName("");
RemovedSymbol = true;
}
}
return RemovedSymbol;
}
// Insert a value into the symbol table with the specified name...
//
void ValueSymbolTable::insert(Value* V) {
assert(V && "Can't insert null Value into symbol table!");
assert(V->hasName() && "Can't insert nameless Value into symbol table");
// Check to see if there is a naming conflict. If so, rename this value
std::string UniqueName = getUniqueName(V->getName());
DEBUG(DOUT << " Inserting value: " << UniqueName << ": " << *V << "\n");
// Insert the vmap entry
V->Name = UniqueName;
vmap.insert(make_pair(V->Name, V));
}
// Remove a value
bool ValueSymbolTable::remove(Value *V) {
assert(V->hasName() && "Value doesn't have name!");
iterator Entry = vmap.find(V->getName());
if (Entry == vmap.end())
return false;
DEBUG(DOUT << " Removing Value: " << Entry->second->getName() << "\n");
// Remove the value from the plane...
vmap.erase(Entry);
return true;
}
// rename - Given a value with a non-empty name, remove its existing entry
// from the symbol table and insert a new one for Name. This is equivalent to
// doing "remove(V), V->Name = Name, insert(V)",
//
bool ValueSymbolTable::rename(Value *V, const std::string &name) {
assert(V && "Can't rename a null Value");
assert(V->hasName() && "Can't rename a nameless Value");
assert(!V->getName().empty() && "Can't rename an Value with null name");
assert(V->getName() != name && "Can't rename a Value with same name");
assert(!name.empty() && "Can't rename a named Value with a null name");
// Find the name
iterator VI = vmap.find(V->getName());
// If we didn't find it, we're done
if (VI == vmap.end())
return false;
// Remove the old entry.
vmap.erase(VI);
// See if we can insert the new name.
VI = vmap.lower_bound(name);
// Is there a naming conflict?
if (VI != vmap.end() && VI->first == name) {
V->Name = getUniqueName( name);
vmap.insert(make_pair(V->Name, V));
} else {
V->Name = name;
vmap.insert(VI, make_pair(V->Name, V));
}
return true;
}
// DumpVal - a std::for_each function for dumping a value
//
static void DumpVal(const std::pair<const std::string, Value *> &V) {
DOUT << " '" << V.first << "' = ";
V.second->dump();
DOUT << "\n";
}
// dump - print out the symbol table
//
void ValueSymbolTable::dump() const {
DOUT << "ValueSymbolTable:\n";
for_each(vmap.begin(), vmap.end(), DumpVal);
}
<commit_msg>Eliminate a bunch of work from ValueSymbolTable::insert for the common case where a symbol name doesn't conflict. This speeds up bc reading 16% on 176.gcc!<commit_after>//===-- ValueSymbolTable.cpp - Implement the ValueSymbolTable class -------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group. It is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the ValueSymbolTable class for the VMCore library.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "valuesymtab"
#include "llvm/GlobalValue.h"
#include "llvm/Type.h"
#include "llvm/ValueSymbolTable.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/Debug.h"
#include <algorithm>
using namespace llvm;
// Class destructor
ValueSymbolTable::~ValueSymbolTable() {
#ifndef NDEBUG // Only do this in -g mode...
bool LeftoverValues = true;
for (iterator VI = vmap.begin(), VE = vmap.end(); VI != VE; ++VI)
if (!isa<Constant>(VI->second) ) {
DEBUG(DOUT << "Value still in symbol table! Type = '"
<< VI->second->getType()->getDescription() << "' Name = '"
<< VI->first << "'\n");
LeftoverValues = false;
}
assert(LeftoverValues && "Values remain in symbol table!");
#endif
}
// getUniqueName - Given a base name, return a string that is either equal to
// it (or derived from it) that does not already occur in the symbol table for
// the specified type.
//
std::string ValueSymbolTable::getUniqueName(const std::string &BaseName) const {
std::string TryName = BaseName;
const_iterator End = vmap.end();
// See if the name exists
while (vmap.find(TryName) != End) // Loop until we find a free
TryName = BaseName + utostr(++LastUnique); // name in the symbol table
return TryName;
}
// lookup a value - Returns null on failure...
//
Value *ValueSymbolTable::lookup(const std::string &Name) const {
const_iterator VI = vmap.find(Name);
if (VI != vmap.end()) // We found the symbol
return const_cast<Value*>(VI->second);
return 0;
}
// Strip the symbol table of its names.
//
bool ValueSymbolTable::strip() {
bool RemovedSymbol = false;
for (iterator VI = vmap.begin(), VE = vmap.end(); VI != VE; ) {
Value *V = VI->second;
++VI;
if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasInternalLinkage()) {
// Set name to "", removing from symbol table!
V->setName("");
RemovedSymbol = true;
}
}
return RemovedSymbol;
}
// Insert a value into the symbol table with the specified name...
//
void ValueSymbolTable::insert(Value* V) {
assert(V && "Can't insert null Value into symbol table!");
assert(V->hasName() && "Can't insert nameless Value into symbol table");
// Try inserting the name, assuming it won't conflict.
if (vmap.insert(make_pair(V->Name, V)).second) {
DOUT << " Inserted value: " << V->Name << ": " << *V << "\n";
return;
}
// Otherwise, there is a naming conflict. Rename this value.
std::string UniqueName = getUniqueName(V->getName());
DEBUG(DOUT << " Inserting value: " << UniqueName << ": " << *V << "\n");
// Insert the vmap entry
V->Name = UniqueName;
vmap.insert(make_pair(V->Name, V));
}
// Remove a value
bool ValueSymbolTable::remove(Value *V) {
assert(V->hasName() && "Value doesn't have name!");
iterator Entry = vmap.find(V->getName());
if (Entry == vmap.end())
return false;
DEBUG(DOUT << " Removing Value: " << Entry->second->getName() << "\n");
// Remove the value from the plane...
vmap.erase(Entry);
return true;
}
// rename - Given a value with a non-empty name, remove its existing entry
// from the symbol table and insert a new one for Name. This is equivalent to
// doing "remove(V), V->Name = Name, insert(V)",
//
bool ValueSymbolTable::rename(Value *V, const std::string &name) {
assert(V && "Can't rename a null Value");
assert(V->hasName() && "Can't rename a nameless Value");
assert(!V->getName().empty() && "Can't rename an Value with null name");
assert(V->getName() != name && "Can't rename a Value with same name");
assert(!name.empty() && "Can't rename a named Value with a null name");
// Find the name
iterator VI = vmap.find(V->getName());
// If we didn't find it, we're done
if (VI == vmap.end())
return false;
// Remove the old entry.
vmap.erase(VI);
// See if we can insert the new name.
VI = vmap.lower_bound(name);
// Is there a naming conflict?
if (VI != vmap.end() && VI->first == name) {
V->Name = getUniqueName( name);
vmap.insert(make_pair(V->Name, V));
} else {
V->Name = name;
vmap.insert(VI, make_pair(V->Name, V));
}
return true;
}
// DumpVal - a std::for_each function for dumping a value
//
static void DumpVal(const std::pair<const std::string, Value *> &V) {
DOUT << " '" << V.first << "' = ";
V.second->dump();
DOUT << "\n";
}
// dump - print out the symbol table
//
void ValueSymbolTable::dump() const {
DOUT << "ValueSymbolTable:\n";
for_each(vmap.begin(), vmap.end(), DumpVal);
}
<|endoftext|> |
<commit_before>/*
* imageresizer.cpp
*
* Created on: Jul 8, 2016
* Author: Jason
*/
#include "common/base.h"
#include "imageresizer.h"
#include <stdexcept>
ImageResizer::ImageResizer()
:m_handle(NULL), m_result(NULL)
{
}
ImageResizer::~ImageResizer()
{
}
void ImageResizer::Create(int target_width, int target_height)
{
if(eina_lock_new(&m_mutex)==EINA_FALSE)
{
throw std::runtime_error("fail to create eina_lock_new");
}
if(eina_condition_new(&m_cond, &m_mutex)==EINA_FALSE)
{
throw std::runtime_error("fail to create eina_lock_new");
}
int ret = image_util_transform_create(&m_handle);
if(ret != IMAGE_UTIL_ERROR_NONE)
{
throw std::runtime_error(std::string("fail to image_util_transform_create: ")+to_string(ret));
}
ret = image_util_transform_set_resolution(m_handle, target_width, target_height);
}
void ImageResizer::Destroy()
{
image_util_transform_destroy(m_handle);
m_handle = NULL;
eina_condition_free(&m_cond);
eina_lock_free(&m_mutex);
}
bool ImageResizer::Resize(media_packet_h packet, media_packet_h* resized_packet)
{
dlog_print(DLOG_DEBUG, "ImageResizer", "========================original packet===========================");
print_packet_info(packet);
int ret = image_util_transform_run(m_handle, packet, ImageResizer::resize_completed_cb, (void*)this);
dlog_print(DLOG_DEBUG, "ImageResizer", "image_util_transform_run[%d]", ret);
if(ret != IMAGE_UTIL_ERROR_NONE)
{
return false;
}
eina_condition_wait(&m_cond);
*resized_packet = m_result;
dlog_print(DLOG_DEBUG, "ImageResizer", "========================resized packet=================[%p], [%p]", *resized_packet, m_result);
print_packet_info(*resized_packet);
dlog_print(DLOG_DEBUG, "ImageResizer", "image_util_transform_run signaled");
return true;
}
void ImageResizer::resize_completed(media_packet_h *dst, int error_code)
{
m_result = *dst;
dlog_print(DLOG_DEBUG, "ImageResizer", "condition signal dst[%p], error_code[%d]", *dst, error_code);
eina_condition_signal(&m_cond);
}
void ImageResizer::resize_completed_cb(media_packet_h *dst, int error_code, void *user_data)
{
dlog_print(DLOG_DEBUG, "ImageResizer", "resize_completed_cb is called [%p]", *dst );
ImageResizer* resizer = (ImageResizer*)user_data;
resizer->resize_completed(dst, error_code);
}
void ImageResizer::print_packet_info(media_packet_h packet)
{
uint64_t dts = 0;
media_packet_get_dts(packet, &dts);
dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_get_dts [%llu]", dts);
uint64_t duration = 0;
media_packet_get_duration(packet, &duration);
dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_get_duration [%llu]", dts);
media_format_h fmt = NULL;
media_format_mimetype_e mimetype;
int width = 0, height = 0, avg_bps=0, max_bps = 0;
int ret = media_packet_get_format(packet, &fmt);
dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_get_format: [%p] [%d]=====", fmt, ret);
media_format_get_video_info(fmt, &mimetype, &width, &height, &avg_bps, &max_bps);
dlog_print(DLOG_DEBUG, "ImageResizer", "media_format_get_video_info: vidoe mimetype: %x, w:%d, h:%d, avg_bps:%d, max_bps:%d =====", (int)mimetype, width, height, avg_bps, max_bps);
media_format_unref(fmt);
bool codec_config = false;
media_packet_is_codec_config(packet, &codec_config);
dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_codec_config [%d]", (int)codec_config);
bool is_encoded = false;
media_packet_is_encoded(packet, &is_encoded);
dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_encoded [%d]", (int)is_encoded);
bool is_eos = false;
media_packet_is_end_of_stream(packet, &is_eos);
dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_end_of_stream [%d]", (int)is_eos);
bool is_raw = false;
media_packet_is_raw(packet, &is_raw);
dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_raw [%d]", (int)is_raw);
bool is_sync = false;
media_packet_is_sync_frame(packet, &is_sync);
dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_sync_frame [%d]", (int)is_sync);
bool is_video = false;
media_packet_is_video(packet, &is_video);
dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_video [%d]", (int)is_video);
}
<commit_msg>fix the problem that image_transform does not copy the eos flag!!<commit_after>/*
* imageresizer.cpp
*
* Created on: Jul 8, 2016
* Author: Jason
*/
#include "common/base.h"
#include "imageresizer.h"
#include <stdexcept>
ImageResizer::ImageResizer()
:m_handle(NULL), m_result(NULL)
{
}
ImageResizer::~ImageResizer()
{
}
void ImageResizer::Create(int target_width, int target_height)
{
if(eina_lock_new(&m_mutex)==EINA_FALSE)
{
throw std::runtime_error("fail to create eina_lock_new");
}
if(eina_condition_new(&m_cond, &m_mutex)==EINA_FALSE)
{
throw std::runtime_error("fail to create eina_lock_new");
}
int ret = image_util_transform_create(&m_handle);
if(ret != IMAGE_UTIL_ERROR_NONE)
{
throw std::runtime_error(std::string("fail to image_util_transform_create: ")+to_string(ret));
}
ret = image_util_transform_set_resolution(m_handle, target_width, target_height);
}
void ImageResizer::Destroy()
{
image_util_transform_destroy(m_handle);
m_handle = NULL;
eina_condition_free(&m_cond);
eina_lock_free(&m_mutex);
}
bool ImageResizer::Resize(media_packet_h packet, media_packet_h* resized_packet)
{
dlog_print(DLOG_DEBUG, "ImageResizer", "========================original packet===========================");
print_packet_info(packet);
bool is_eos = false;
media_packet_is_end_of_stream(packet, &is_eos);
int ret = image_util_transform_run(m_handle, packet, ImageResizer::resize_completed_cb, (void*)this);
dlog_print(DLOG_DEBUG, "ImageResizer", "image_util_transform_run[%d]", ret);
if(ret != IMAGE_UTIL_ERROR_NONE)
{
return false;
}
eina_condition_wait(&m_cond);
*resized_packet = m_result;
dlog_print(DLOG_DEBUG, "ImageResizer", "========================resized packet=================[%p], [%p]", *resized_packet, m_result);
if(is_eos)
{
media_packet_set_flags(*resized_packet, MEDIA_PACKET_END_OF_STREAM);
}
print_packet_info(*resized_packet);
dlog_print(DLOG_DEBUG, "ImageResizer", "image_util_transform_run signaled");
return true;
}
void ImageResizer::resize_completed(media_packet_h *dst, int error_code)
{
m_result = *dst;
dlog_print(DLOG_DEBUG, "ImageResizer", "condition signal dst[%p], error_code[%d]", *dst, error_code);
eina_condition_signal(&m_cond);
}
void ImageResizer::resize_completed_cb(media_packet_h *dst, int error_code, void *user_data)
{
dlog_print(DLOG_DEBUG, "ImageResizer", "resize_completed_cb is called [%p]", *dst );
ImageResizer* resizer = (ImageResizer*)user_data;
resizer->resize_completed(dst, error_code);
}
void ImageResizer::print_packet_info(media_packet_h packet)
{
uint64_t dts = 0;
media_packet_get_dts(packet, &dts);
dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_get_dts [%llu]", dts);
uint64_t duration = 0;
media_packet_get_duration(packet, &duration);
dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_get_duration [%llu]", dts);
media_format_h fmt = NULL;
media_format_mimetype_e mimetype;
int width = 0, height = 0, avg_bps=0, max_bps = 0;
int ret = media_packet_get_format(packet, &fmt);
dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_get_format: [%p] [%d]=====", fmt, ret);
media_format_get_video_info(fmt, &mimetype, &width, &height, &avg_bps, &max_bps);
dlog_print(DLOG_DEBUG, "ImageResizer", "media_format_get_video_info: vidoe mimetype: %x, w:%d, h:%d, avg_bps:%d, max_bps:%d =====", (int)mimetype, width, height, avg_bps, max_bps);
media_format_unref(fmt);
bool codec_config = false;
media_packet_is_codec_config(packet, &codec_config);
dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_codec_config [%d]", (int)codec_config);
bool is_encoded = false;
media_packet_is_encoded(packet, &is_encoded);
dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_encoded [%d]", (int)is_encoded);
bool is_eos = false;
media_packet_is_end_of_stream(packet, &is_eos);
dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_end_of_stream [%d]", (int)is_eos);
bool is_raw = false;
media_packet_is_raw(packet, &is_raw);
dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_raw [%d]", (int)is_raw);
bool is_sync = false;
media_packet_is_sync_frame(packet, &is_sync);
dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_sync_frame [%d]", (int)is_sync);
bool is_video = false;
media_packet_is_video(packet, &is_video);
dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_video [%d]", (int)is_video);
}
<|endoftext|> |
<commit_before>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2016 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#include "caf/config.hpp"
#define CAF_SUITE expected
#include "caf/test/unit_test.hpp"
#include "caf/sec.hpp"
#include "caf/expected.hpp"
using namespace std;
using namespace caf;
#define CHECK(x) CAF_CHECK(x);
#define CHECK_EQ(x, y) \
CAF_CHECK(x == y); \
CAF_CHECK(y == x);
#define CHECK_NEQ(x, y) \
CAF_CHECK(x != y); \
CAF_CHECK(y != x);
namespace {
using e_int = expected<int>;
using e_str = expected<std::string>;
} // namespace <anonymous>
CAF_TEST(both_engaged_equal) {
e_int x{42};
e_int y{42};
CHECK(x);
CHECK(y);
CHECK_EQ(x, y);
CHECK_EQ(x, 42);
CHECK_EQ(y, 42);
}
CAF_TEST(both_engaged_not_equal) {
e_int x{42};
e_int y{24};
CHECK(x);
CHECK(y);
CHECK_NEQ(x, y);
CHECK_NEQ(x, sec::unexpected_message);
CHECK_NEQ(y, sec::unexpected_message);
CHECK_EQ(x, 42);
CHECK_EQ(y, 24);
}
CAF_TEST(engaged_plus_not_engaged) {
e_int x{42};
e_int y{sec::unexpected_message};
CHECK(x);
CHECK(!y);
CHECK_EQ(x, 42);
CHECK_EQ(y, sec::unexpected_message);
CHECK_NEQ(x, sec::unexpected_message);
CHECK_NEQ(x, y);
CHECK_NEQ(y, 42);
CHECK_NEQ(y, sec::unsupported_sys_key);
}
CAF_TEST(both_not_engaged) {
e_int x{sec::unexpected_message};
e_int y{sec::unexpected_message};
CHECK(!x);
CHECK(!y);
CHECK_EQ(x, y);
CHECK_EQ(x, sec::unexpected_message);
CHECK_EQ(y, sec::unexpected_message);
CHECK_EQ(x.error(), y.error());
CHECK_NEQ(x, sec::unsupported_sys_key);
CHECK_NEQ(y, sec::unsupported_sys_key);
}
CAF_TEST(move_and_copy) {
e_str x{sec::unexpected_message};
e_str y{"hello"};
x = "hello";
CHECK_NEQ(x, sec::unexpected_message);
CHECK_EQ(x, "hello");
CHECK_EQ(x, y);
y = "world";
x = std::move(y);
CHECK_EQ(x, "world");
e_str z{std::move(x)};
CHECK_EQ(z, "world");
e_str z_cpy{z};
CHECK_EQ(z_cpy, "world");
CHECK_EQ(z, z_cpy);
z = e_str{sec::unsupported_sys_key};
CHECK_NEQ(z, z_cpy);
CHECK_EQ(z, sec::unsupported_sys_key);
}
<commit_msg>Add test that constructs expected<T> from none_t<commit_after>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2016 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#include "caf/config.hpp"
#define CAF_SUITE expected
#include "caf/test/unit_test.hpp"
#include "caf/sec.hpp"
#include "caf/expected.hpp"
using namespace std;
using namespace caf;
#define CHECK(x) CAF_CHECK(x);
#define CHECK_EQ(x, y) \
CAF_CHECK(x == y); \
CAF_CHECK(y == x);
#define CHECK_NEQ(x, y) \
CAF_CHECK(x != y); \
CAF_CHECK(y != x);
namespace {
using e_int = expected<int>;
using e_str = expected<std::string>;
} // namespace <anonymous>
CAF_TEST(both_engaged_equal) {
e_int x{42};
e_int y{42};
CHECK(x);
CHECK(y);
CHECK_EQ(x, y);
CHECK_EQ(x, 42);
CHECK_EQ(y, 42);
}
CAF_TEST(both_engaged_not_equal) {
e_int x{42};
e_int y{24};
CHECK(x);
CHECK(y);
CHECK_NEQ(x, y);
CHECK_NEQ(x, sec::unexpected_message);
CHECK_NEQ(y, sec::unexpected_message);
CHECK_EQ(x, 42);
CHECK_EQ(y, 24);
}
CAF_TEST(engaged_plus_not_engaged) {
e_int x{42};
e_int y{sec::unexpected_message};
CHECK(x);
CHECK(!y);
CHECK_EQ(x, 42);
CHECK_EQ(y, sec::unexpected_message);
CHECK_NEQ(x, sec::unexpected_message);
CHECK_NEQ(x, y);
CHECK_NEQ(y, 42);
CHECK_NEQ(y, sec::unsupported_sys_key);
}
CAF_TEST(both_not_engaged) {
e_int x{sec::unexpected_message};
e_int y{sec::unexpected_message};
CHECK(!x);
CHECK(!y);
CHECK_EQ(x, y);
CHECK_EQ(x, sec::unexpected_message);
CHECK_EQ(y, sec::unexpected_message);
CHECK_EQ(x.error(), y.error());
CHECK_NEQ(x, sec::unsupported_sys_key);
CHECK_NEQ(y, sec::unsupported_sys_key);
}
CAF_TEST(move_and_copy) {
e_str x{sec::unexpected_message};
e_str y{"hello"};
x = "hello";
CHECK_NEQ(x, sec::unexpected_message);
CHECK_EQ(x, "hello");
CHECK_EQ(x, y);
y = "world";
x = std::move(y);
CHECK_EQ(x, "world");
e_str z{std::move(x)};
CHECK_EQ(z, "world");
e_str z_cpy{z};
CHECK_EQ(z_cpy, "world");
CHECK_EQ(z, z_cpy);
z = e_str{sec::unsupported_sys_key};
CHECK_NEQ(z, z_cpy);
CHECK_EQ(z, sec::unsupported_sys_key);
}
CAF_TEST(construction_with_none) {
e_int x{none};
CHECK(!x);
CHECK(!x.error());
}
<|endoftext|> |
<commit_before>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Gearmand client and server library.
*
* Copyright (C) 2011-2012 Data Differential, http://datadifferential.com/
* Copyright (C) 2008 Brian Aker, Eric Day
* 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.
*
* * The names of its contributors may not 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
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
* @file
* @brief Server function definitions
*/
#include <config.h>
#include <libgearman-server/common.h>
#include <cstring>
#include <memory>
#include <libgearman-server/list.h>
/*
* Public definitions
*/
static gearman_server_function_st* gearman_server_function_create(gearman_server_st *server)
{
gearman_server_function_st* function= new (std::nothrow) gearman_server_function_st;
if (function == NULL)
{
gearmand_merror("new gearman_server_function_st", gearman_server_function_st, 0);
return NULL;
}
function->worker_count= 0;
function->job_count= 0;
function->job_total= 0;
function->job_running= 0;
memset(function->max_queue_size, GEARMAN_DEFAULT_MAX_QUEUE_SIZE,
sizeof(uint32_t) * GEARMAN_JOB_PRIORITY_MAX);
function->function_name_size= 0;
gearmand_server_list_add(server, function);
function->function_name= NULL;
function->worker_list= NULL;
memset(function->job_list, 0,
sizeof(gearman_server_job_st *) * GEARMAN_JOB_PRIORITY_MAX);
memset(function->job_end, 0,
sizeof(gearman_server_job_st *) * GEARMAN_JOB_PRIORITY_MAX);
return function;
}
#ifndef __INTEL_COMPILER
#pragma GCC diagnostic ignored "-Wold-style-cast"
#endif
gearman_server_function_st *
gearman_server_function_get(gearman_server_st *server,
const char *function_name,
size_t function_name_size)
{
gearman_server_function_st *function;
for (function= server->function_list; function != NULL;
function= function->next)
{
if (function->function_name_size == function_name_size and
memcmp(function->function_name, function_name, function_name_size) == 0)
{
return function;
}
}
function= gearman_server_function_create(server);
if (function == NULL)
{
return NULL;
}
function->function_name= new char[function_name_size +1];
if (function->function_name == NULL)
{
gearmand_merror("new[]", char, function_name_size +1);
gearman_server_function_free(server, function);
return NULL;
}
memcpy(function->function_name, function_name, function_name_size);
function->function_name[function_name_size]= 0;
function->function_name_size= function_name_size;
return function;
}
void gearman_server_function_free(gearman_server_st *server, gearman_server_function_st *function)
{
delete function->function_name;
gearmand_server_list_free(server, function);
delete function;
}
<commit_msg>Bug fix for lp:1065852<commit_after>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Gearmand client and server library.
*
* Copyright (C) 2011-2012 Data Differential, http://datadifferential.com/
* Copyright (C) 2008 Brian Aker, Eric Day
* 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.
*
* * The names of its contributors may not 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
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
* @file
* @brief Server function definitions
*/
#include <config.h>
#include <libgearman-server/common.h>
#include <cstring>
#include <memory>
#include <libgearman-server/list.h>
/*
* Public definitions
*/
static gearman_server_function_st* gearman_server_function_create(gearman_server_st *server)
{
gearman_server_function_st* function= new (std::nothrow) gearman_server_function_st;
if (function == NULL)
{
gearmand_merror("new gearman_server_function_st", gearman_server_function_st, 0);
return NULL;
}
function->worker_count= 0;
function->job_count= 0;
function->job_total= 0;
function->job_running= 0;
memset(function->max_queue_size, GEARMAN_DEFAULT_MAX_QUEUE_SIZE,
sizeof(uint32_t) * GEARMAN_JOB_PRIORITY_MAX);
function->function_name_size= 0;
gearmand_server_list_add(server, function);
function->function_name= NULL;
function->worker_list= NULL;
memset(function->job_list, 0,
sizeof(gearman_server_job_st *) * GEARMAN_JOB_PRIORITY_MAX);
memset(function->job_end, 0,
sizeof(gearman_server_job_st *) * GEARMAN_JOB_PRIORITY_MAX);
return function;
}
#ifndef __INTEL_COMPILER
#pragma GCC diagnostic ignored "-Wold-style-cast"
#endif
gearman_server_function_st *
gearman_server_function_get(gearman_server_st *server,
const char *function_name,
size_t function_name_size)
{
gearman_server_function_st *function;
for (function= server->function_list; function != NULL;
function= function->next)
{
if (function->function_name_size == function_name_size and
memcmp(function->function_name, function_name, function_name_size) == 0)
{
return function;
}
}
function= gearman_server_function_create(server);
if (function == NULL)
{
return NULL;
}
function->function_name= new char[function_name_size +1];
if (function->function_name == NULL)
{
gearmand_merror("new[]", char, function_name_size +1);
gearman_server_function_free(server, function);
return NULL;
}
memcpy(function->function_name, function_name, function_name_size);
function->function_name[function_name_size]= 0;
function->function_name_size= function_name_size;
return function;
}
void gearman_server_function_free(gearman_server_st *server, gearman_server_function_st *function)
{
delete [] function->function_name;
gearmand_server_list_free(server, function);
delete function;
}
<|endoftext|> |
<commit_before>#include "inc/cxx/json.hpp"
#include "test/catch.hpp"
#include <type_traits>
TEST_CASE("can create cxx::json from std::initializer_list<cxx::json>")
{
static_assert(std::is_assignable_v<cxx::json, std::initializer_list<cxx::json>>);
cxx::json json;
REQUIRE(cxx::holds_alternative<cxx::document>(json));
json = {42, true, cxx::null, 3.14};
REQUIRE(cxx::holds_alternative<cxx::array>(json));
REQUIRE(json == cxx::array({42, true, cxx::null, 3.14}));
REQUIRE(std::size(json) == 4);
}
TEST_CASE("can create cxx::json from std::initializer_list<cxx::document::value_type>")
{
using namespace cxx::literals;
static_assert(std::is_assignable_v<cxx::json, std::initializer_list<cxx::document::value_type>>);
cxx::json json = 42;
REQUIRE(cxx::holds_alternative<std::int64_t>(json));
json = {
// clang-format off
{"lorem"_key, 42},
{"ipsum"_key, "dolor"},
{"sit"_key, cxx::null},
{"amet"_key, 3.14},
{"consectetur"_key, true}
// clang-format on
};
REQUIRE(cxx::holds_alternative<cxx::document>(json));
cxx::document const document = {
// clang-format off
{"lorem", 42},
{"ipsum", "dolor"},
{"sit", cxx::null},
{"amet", 3.14},
{"consectetur", true}
// clang-format on
};
REQUIRE(std::size(json) == std::size(document));
REQUIRE(json == document);
}
<commit_msg>assignment<commit_after>#include "inc/cxx/json.hpp"
#include "test/catch.hpp"
#include <type_traits>
TEST_CASE("cxx::json is copy assignable")
{
static_assert(std::is_copy_assignable_v<cxx::json>);
cxx::json const orig = 42;
cxx::json json;
REQUIRE_FALSE(cxx::holds_alternative<std::int64_t>(json));
REQUIRE(json != orig);
json = orig;
REQUIRE(cxx::holds_alternative<std::int64_t>(json));
REQUIRE(json == orig);
}
TEST_CASE("cxx::json is nothrow move assignable")
{
static_assert(std::is_nothrow_move_assignable_v<cxx::json>);
cxx::json orig = 42;
cxx::json json;
REQUIRE_FALSE(cxx::holds_alternative<std::int64_t>(json));
REQUIRE(json != orig);
json = std::move(orig);
REQUIRE(cxx::holds_alternative<std::int64_t>(json));
REQUIRE(json == 42);
}
TEST_CASE("can assign std::initializer_list<cxx::json> to cxx::json")
{
static_assert(std::is_assignable_v<cxx::json, std::initializer_list<cxx::json>>);
cxx::json json;
REQUIRE(cxx::holds_alternative<cxx::document>(json));
json = {42, true, cxx::null, 3.14};
REQUIRE(cxx::holds_alternative<cxx::array>(json));
REQUIRE(json == cxx::array({42, true, cxx::null, 3.14}));
REQUIRE(std::size(json) == 4);
}
TEST_CASE("can assign std::initializer_list<cxx::document::value_type> to cxx::json")
{
using namespace cxx::literals;
static_assert(std::is_assignable_v<cxx::json, std::initializer_list<cxx::document::value_type>>);
cxx::json json = 42;
REQUIRE(cxx::holds_alternative<std::int64_t>(json));
json = {
// clang-format off
{"lorem"_key, 42},
{"ipsum"_key, "dolor"},
{"sit"_key, cxx::null},
{"amet"_key, 3.14},
{"consectetur"_key, true}
// clang-format on
};
REQUIRE(cxx::holds_alternative<cxx::document>(json));
cxx::document const document = {
// clang-format off
{"lorem", 42},
{"ipsum", "dolor"},
{"sit", cxx::null},
{"amet", 3.14},
{"consectetur", true}
// clang-format on
};
REQUIRE(std::size(json) == std::size(document));
REQUIRE(json == document);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <functional>
#include <neu/activate_func/rectifier.hpp>
#include <neu/activate_func/sigmoid.hpp>
#include <neu/layer.hpp>
#include <neu/full_connected_layer.hpp>
#include <neu/activate_layer.hpp>
#include <neu/learning_rate_gen/fixed_learning_rate_gen.hpp>
int main() {
std::cout << "hello world" << std::endl;
/*
auto fc1 = neu::make_full_connected_layer(1,1,1,
neu::to_gpu_vector(neu::cpu_vector{10.f}),
neu::to_gpu_vector(neu::cpu_vector{1.f}),
neu::fixed_learning_rate_gen(0.01));
auto fc1_layer = static_cast<neu::layer>(std::ref(fc1));
*/
auto ac1_layer = static_cast<neu::layer>(neu::make_activate_layer(1, 1, 1,
neu::sigmoid()));
ac1_layer.forward(neu::to_gpu_vector(neu::cpu_vector{10.f}));
//std::cout << fc1_layer.get_next_input()[0] << std::endl;
std::cout << ac1_layer.get_next_input()[0] << std::endl;
}
<commit_msg>rename test/layer/layer.cpp<commit_after><|endoftext|> |
<commit_before>// $Id$
// The libMesh Finite Element Library.
// Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// library configuration
#include "libmesh_config.h"
// C++ includes
#include <algorithm> // for std::min
#include <map> // for std::multimap
#include <sstream> // for std::ostringstream
// Local includes
#include "boundary_info.h"
#include "elem.h"
#include "mesh_base.h"
#include "parallel.h"
#include "partitioner.h"
#include "point_locator_base.h"
#include "threads.h"
namespace libMesh
{
// ------------------------------------------------------------
// MeshBase class member functions
MeshBase::MeshBase (unsigned int d) :
boundary_info (new BoundaryInfo(*this)),
_n_parts (1),
_dim (d),
_is_prepared (false),
_point_locator (NULL),
_partitioner (NULL)
{
libmesh_assert (LIBMESH_DIM <= 3);
libmesh_assert (LIBMESH_DIM >= _dim);
libmesh_assert (libMesh::initialized());
}
MeshBase::MeshBase (const MeshBase& other_mesh) :
boundary_info (new BoundaryInfo(*this)), // no copy constructor defined for BoundaryInfo?
_n_parts (other_mesh._n_parts),
_dim (other_mesh._dim),
_is_prepared (other_mesh._is_prepared),
_point_locator (NULL),
_partitioner (other_mesh._partitioner->clone())
{
}
MeshBase::~MeshBase()
{
this->clear();
libmesh_assert (!libMesh::closed());
}
void MeshBase::prepare_for_use (const bool skip_renumber_nodes_and_elements)
{
// Renumber the nodes and elements so that they in contiguous
// blocks. By default, skip_renumber_nodes_and_elements is false,
// however we may skip this step by passing
// skip_renumber_nodes_and_elements==true to this function.
//
// Instances where you if prepare_for_use() should not renumber the nodes
// and elements include reading in e.g. an xda/r or gmv file. In
// this case, the ordering of the nodes may depend on an accompanying
// solution, and the node ordering cannot be changed.
if(!skip_renumber_nodes_and_elements)
this->renumber_nodes_and_elements();
// Let all the elements find their neighbors
this->find_neighbors();
// Partition the mesh.
this->partition();
// If we're using ParallelMesh, we'll want it parallelized.
this->delete_remote_elements();
if(!skip_renumber_nodes_and_elements)
this->renumber_nodes_and_elements();
// Reset our PointLocator. This needs to happen any time the elements
// in the underlying elements in the mesh have changed, so we do it here.
this->clear_point_locator();
// The mesh is now prepared for use.
_is_prepared = true;
}
void MeshBase::clear ()
{
// Reset the number of partitions
_n_parts = 1;
// Reset the _is_prepared flag
_is_prepared = false;
// Clear boundary information
this->boundary_info->clear();
// Clear our point locator.
this->clear_point_locator();
}
unsigned int MeshBase::n_subdomains() const
{
// This requires an inspection on every processor
parallel_only();
const_element_iterator el = this->active_elements_begin();
const const_element_iterator end = this->active_elements_end();
std::set<unsigned int> subdomain_ids;
for (; el!=end; ++el)
subdomain_ids.insert((*el)->subdomain_id());
// Some subdomains may only live on other processors
Parallel::set_union(subdomain_ids, 0);
unsigned int n_sbd_ids = subdomain_ids.size();
Parallel::broadcast(n_sbd_ids);
return n_sbd_ids;
}
unsigned int MeshBase::n_nodes_on_proc (const unsigned int proc_id) const
{
// We're either counting a processor's nodes or unpartitioned
// nodes
libmesh_assert (proc_id < libMesh::n_processors() ||
proc_id == DofObject::invalid_processor_id);
return static_cast<unsigned int>(std::distance (this->pid_nodes_begin(proc_id),
this->pid_nodes_end (proc_id)));
}
unsigned int MeshBase::n_elem_on_proc (const unsigned int proc_id) const
{
// We're either counting a processor's elements or unpartitioned
// elements
libmesh_assert (proc_id < libMesh::n_processors() ||
proc_id == DofObject::invalid_processor_id);
return static_cast<unsigned int>(std::distance (this->pid_elements_begin(proc_id),
this->pid_elements_end (proc_id)));
}
unsigned int MeshBase::n_active_elem_on_proc (const unsigned int proc_id) const
{
libmesh_assert (proc_id < libMesh::n_processors());
return static_cast<unsigned int>(std::distance (this->active_pid_elements_begin(proc_id),
this->active_pid_elements_end (proc_id)));
}
unsigned int MeshBase::n_sub_elem () const
{
unsigned int ne=0;
const_element_iterator el = this->elements_begin();
const const_element_iterator end = this->elements_end();
for (; el!=end; ++el)
ne += (*el)->n_sub_elem();
return ne;
}
unsigned int MeshBase::n_active_sub_elem () const
{
unsigned int ne=0;
const_element_iterator el = this->active_elements_begin();
const const_element_iterator end = this->active_elements_end();
for (; el!=end; ++el)
ne += (*el)->n_sub_elem();
return ne;
}
std::string MeshBase::get_info() const
{
std::ostringstream out;
out << " Mesh Information:" << '\n'
<< " mesh_dimension()=" << this->mesh_dimension() << '\n'
<< " spatial_dimension()=" << this->spatial_dimension() << '\n'
<< " n_nodes()=" << this->n_nodes() << '\n'
<< " n_local_nodes()=" << this->n_local_nodes() << '\n'
<< " n_elem()=" << this->n_elem() << '\n'
<< " n_local_elem()=" << this->n_local_elem() << '\n'
#ifdef LIBMESH_ENABLE_AMR
<< " n_active_elem()=" << this->n_active_elem() << '\n'
#endif
<< " n_subdomains()=" << this->n_subdomains() << '\n'
<< " n_processors()=" << this->n_processors() << '\n'
<< " processor_id()=" << this->processor_id() << '\n';
return out.str();
}
void MeshBase::print_info(std::ostream& os) const
{
os << this->get_info()
<< std::endl;
}
std::ostream& operator << (std::ostream& os, const MeshBase& m)
{
m.print_info(os);
return os;
}
void MeshBase::partition (const unsigned int n_parts)
{
if (partitioner().get()) // "NULL" means don't partition
partitioner()->partition (*this, n_parts);
}
unsigned int MeshBase::recalculate_n_partitions()
{
const_element_iterator el = this->active_elements_begin();
const const_element_iterator end = this->active_elements_end();
unsigned int max_proc_id=0;
for (; el!=end; ++el)
max_proc_id = std::max(max_proc_id, static_cast<unsigned int>((*el)->processor_id()));
// The number of partitions is one more than the max processor ID.
_n_parts = max_proc_id+1;
return _n_parts;
}
const PointLocatorBase & MeshBase::point_locator () const
{
if (_point_locator.get() == NULL)
{
// PointLocator construction may not be safe within threads
libmesh_assert(!Threads::in_threads);
_point_locator.reset (PointLocatorBase::build(TREE, *this).release());
}
return *_point_locator;
}
void MeshBase::clear_point_locator ()
{
_point_locator.reset(NULL);
}
} // namespace libMesh
<commit_msg>Copy associated BoundaryInfo when copying any Mesh<commit_after>// $Id$
// The libMesh Finite Element Library.
// Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// library configuration
#include "libmesh_config.h"
// C++ includes
#include <algorithm> // for std::min
#include <map> // for std::multimap
#include <sstream> // for std::ostringstream
// Local includes
#include "boundary_info.h"
#include "elem.h"
#include "mesh_base.h"
#include "parallel.h"
#include "partitioner.h"
#include "point_locator_base.h"
#include "threads.h"
namespace libMesh
{
// ------------------------------------------------------------
// MeshBase class member functions
MeshBase::MeshBase (unsigned int d) :
boundary_info (new BoundaryInfo(*this)),
_n_parts (1),
_dim (d),
_is_prepared (false),
_point_locator (NULL),
_partitioner (NULL)
{
libmesh_assert (LIBMESH_DIM <= 3);
libmesh_assert (LIBMESH_DIM >= _dim);
libmesh_assert (libMesh::initialized());
}
MeshBase::MeshBase (const MeshBase& other_mesh) :
boundary_info (new BoundaryInfo(*this)),
_n_parts (other_mesh._n_parts),
_dim (other_mesh._dim),
_is_prepared (other_mesh._is_prepared),
_point_locator (NULL),
_partitioner (other_mesh._partitioner->clone())
{
*boundary_info = *other_mesh.boundary_info;
}
MeshBase::~MeshBase()
{
this->clear();
libmesh_assert (!libMesh::closed());
}
void MeshBase::prepare_for_use (const bool skip_renumber_nodes_and_elements)
{
// Renumber the nodes and elements so that they in contiguous
// blocks. By default, skip_renumber_nodes_and_elements is false,
// however we may skip this step by passing
// skip_renumber_nodes_and_elements==true to this function.
//
// Instances where you if prepare_for_use() should not renumber the nodes
// and elements include reading in e.g. an xda/r or gmv file. In
// this case, the ordering of the nodes may depend on an accompanying
// solution, and the node ordering cannot be changed.
if(!skip_renumber_nodes_and_elements)
this->renumber_nodes_and_elements();
// Let all the elements find their neighbors
this->find_neighbors();
// Partition the mesh.
this->partition();
// If we're using ParallelMesh, we'll want it parallelized.
this->delete_remote_elements();
if(!skip_renumber_nodes_and_elements)
this->renumber_nodes_and_elements();
// Reset our PointLocator. This needs to happen any time the elements
// in the underlying elements in the mesh have changed, so we do it here.
this->clear_point_locator();
// The mesh is now prepared for use.
_is_prepared = true;
}
void MeshBase::clear ()
{
// Reset the number of partitions
_n_parts = 1;
// Reset the _is_prepared flag
_is_prepared = false;
// Clear boundary information
this->boundary_info->clear();
// Clear our point locator.
this->clear_point_locator();
}
unsigned int MeshBase::n_subdomains() const
{
// This requires an inspection on every processor
parallel_only();
const_element_iterator el = this->active_elements_begin();
const const_element_iterator end = this->active_elements_end();
std::set<unsigned int> subdomain_ids;
for (; el!=end; ++el)
subdomain_ids.insert((*el)->subdomain_id());
// Some subdomains may only live on other processors
Parallel::set_union(subdomain_ids, 0);
unsigned int n_sbd_ids = subdomain_ids.size();
Parallel::broadcast(n_sbd_ids);
return n_sbd_ids;
}
unsigned int MeshBase::n_nodes_on_proc (const unsigned int proc_id) const
{
// We're either counting a processor's nodes or unpartitioned
// nodes
libmesh_assert (proc_id < libMesh::n_processors() ||
proc_id == DofObject::invalid_processor_id);
return static_cast<unsigned int>(std::distance (this->pid_nodes_begin(proc_id),
this->pid_nodes_end (proc_id)));
}
unsigned int MeshBase::n_elem_on_proc (const unsigned int proc_id) const
{
// We're either counting a processor's elements or unpartitioned
// elements
libmesh_assert (proc_id < libMesh::n_processors() ||
proc_id == DofObject::invalid_processor_id);
return static_cast<unsigned int>(std::distance (this->pid_elements_begin(proc_id),
this->pid_elements_end (proc_id)));
}
unsigned int MeshBase::n_active_elem_on_proc (const unsigned int proc_id) const
{
libmesh_assert (proc_id < libMesh::n_processors());
return static_cast<unsigned int>(std::distance (this->active_pid_elements_begin(proc_id),
this->active_pid_elements_end (proc_id)));
}
unsigned int MeshBase::n_sub_elem () const
{
unsigned int ne=0;
const_element_iterator el = this->elements_begin();
const const_element_iterator end = this->elements_end();
for (; el!=end; ++el)
ne += (*el)->n_sub_elem();
return ne;
}
unsigned int MeshBase::n_active_sub_elem () const
{
unsigned int ne=0;
const_element_iterator el = this->active_elements_begin();
const const_element_iterator end = this->active_elements_end();
for (; el!=end; ++el)
ne += (*el)->n_sub_elem();
return ne;
}
std::string MeshBase::get_info() const
{
std::ostringstream out;
out << " Mesh Information:" << '\n'
<< " mesh_dimension()=" << this->mesh_dimension() << '\n'
<< " spatial_dimension()=" << this->spatial_dimension() << '\n'
<< " n_nodes()=" << this->n_nodes() << '\n'
<< " n_local_nodes()=" << this->n_local_nodes() << '\n'
<< " n_elem()=" << this->n_elem() << '\n'
<< " n_local_elem()=" << this->n_local_elem() << '\n'
#ifdef LIBMESH_ENABLE_AMR
<< " n_active_elem()=" << this->n_active_elem() << '\n'
#endif
<< " n_subdomains()=" << this->n_subdomains() << '\n'
<< " n_processors()=" << this->n_processors() << '\n'
<< " processor_id()=" << this->processor_id() << '\n';
return out.str();
}
void MeshBase::print_info(std::ostream& os) const
{
os << this->get_info()
<< std::endl;
}
std::ostream& operator << (std::ostream& os, const MeshBase& m)
{
m.print_info(os);
return os;
}
void MeshBase::partition (const unsigned int n_parts)
{
if (partitioner().get()) // "NULL" means don't partition
partitioner()->partition (*this, n_parts);
}
unsigned int MeshBase::recalculate_n_partitions()
{
const_element_iterator el = this->active_elements_begin();
const const_element_iterator end = this->active_elements_end();
unsigned int max_proc_id=0;
for (; el!=end; ++el)
max_proc_id = std::max(max_proc_id, static_cast<unsigned int>((*el)->processor_id()));
// The number of partitions is one more than the max processor ID.
_n_parts = max_proc_id+1;
return _n_parts;
}
const PointLocatorBase & MeshBase::point_locator () const
{
if (_point_locator.get() == NULL)
{
// PointLocator construction may not be safe within threads
libmesh_assert(!Threads::in_threads);
_point_locator.reset (PointLocatorBase::build(TREE, *this).release());
}
return *_point_locator;
}
void MeshBase::clear_point_locator ()
{
_point_locator.reset(NULL);
}
} // namespace libMesh
<|endoftext|> |
<commit_before>#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <array>
#include <vector>
#include <set>
#include <map>
#include <random>
#include <chrono>
#include <functional>
#include <algorithm>
#include <cmath>
#define NF 16
#define SPLIT 20
using Entry = std::array<double, NF>;
using IntPair = std::pair<int, int>;
struct CompareSecond: std::binary_function<IntPair, IntPair, bool>
{
bool operator()(const IntPair& a, const IntPair& b)
{
return a.second < b.second;
}
};
int main(int argc, char** argv)
{
// smoothing factor
const double alpha = 1.0;
// decision rule
const int decision = 1;
if (argc < 2)
return 1;
// preparing data
int total = 0, correct = 0, totalClassified = 0;
std::map<std::string, std::vector<Entry> > data;
std::map<std::string, int> n;
std::map<std::string, double> priors;
std::map<std::string, std::vector<double> > multinomialLikelihoods;
std::map<std::string, int> multinomialSums;
std::map<std::string, Entry > sumX;
std::map<std::string, std::vector<double> > means;
std::map<std::string, std::vector<double> > variances;
auto classify = [&](const std::string& label, const Entry& entry)
{
std::string predlabel;
double maxlikelihood = 0.0;
double denom = 0.0;
std::vector<double> probs;
for (auto it = priors.begin(); it != priors.end(); it++)
{
double numer = priors[it->first];
const auto& firstMultinomialLikelihood = multinomialLikelihoods[it->first];
const auto& firstMean = means[it->first];
const auto& firstVariance = variances[it->first];
for (int j = 0; j < NF; j++)
switch (decision)
{
case 2:
// Multinomial
if (entry[j])
numer *= pow(firstMultinomialLikelihood[j], entry[j]);
break;
case 3:
// Bernoulli
numer *= pow(firstMean[j], entry[j]) * pow(1.0 - firstMean[j], 1.0 - entry[j]);
break;
default:
// Gaussian
numer *= 1 / sqrt(2 * M_PI * firstVariance[j]) * exp((-1 * (entry[j] - firstMean[j]) * (entry[j] -firstMean[j])) / (2 * firstVariance[j]));
break;
}
if (numer > maxlikelihood)
{
maxlikelihood = numer;
predlabel = it->first;
}
denom += numer;
probs.push_back(numer);
}
std::cout << predlabel << "\t" << std::setw(1) << std::setprecision(3) << maxlikelihood/denom << "\t";
if ("" == label)
std::cout << "<no label>" << std::endl;
else if (predlabel == label)
{
std::cout << "correct" << std::endl;
correct++;
}
else
std::cout << "incorrect" << std::endl;
totalClassified++;
};
auto readFromFile = [&](const char* filename, bool isClassification)
{
std::ifstream file(argv[1]);
if (!file.is_open())
return 1;
while (!file.eof())
{
std::string line;
std::getline(file, line);
if ("" == line)
continue;
std::istringstream linein(std::move(line));
std::string label;
std::getline(linein, label, ',');
Entry entry;
auto setField = [&entry, &label, &sumX, &multinomialSums, isClassification](int i, const std::string& field)
{
switch (field[0])
{
case 'y':
entry[i] = 1.0;
break;
case 'n':
entry[i] = 0.0;
break;
case '?':
entry[i] = 0.5;
break;
}
if (!isClassification)
{
sumX[label][i] += entry[i];
multinomialSums[label] += entry[i];
}
};
for (int i = 0; i < NF; i++)
{
std::string field;
std::getline(linein, field, ',');
setField(i, field);
}
std::string field;
std::getline(linein, field);
setField(NF - 1, field);
if (!isClassification)
{
data[label].push_back(std::move(entry));
n[label]++;
total++;
}
else
classify(label, entry);
}
};
readFromFile(argv[1], false);
for (auto it = sumX.begin(); it != sumX.end(); it++)
{
priors[it->first] = (double)n[it->first] / total;
std::cout << "Class " << it->first << ", prior: " << std::setw(1) << std::setprecision(3) << priors[it->first] << std::endl;
std::cout << "feature\tmean\tvar\tstddev\tmnl" << std::endl;
// calculate means
std::vector<double> featureMeans(NF);
for (int i = 0; i < NF; i++)
featureMeans[i] = sumX[it->first][i] / n[it->first];
// calculate variances
std::vector<double> featureVariances(NF);
const auto& firstData = data[it->first];
for (int i = 0; i < firstData.size(); i++)
for (int j = 0; j < NF; j++)
featureVariances[j] += (firstData[i][j] - featureMeans[j]) * (firstData[i][j] - featureMeans[j]);
for (int i = 0; i < NF; i++)
featureVariances[i] /= firstData.size();
const auto& firstSumX = sumX[it->first];
auto firstMultinomialSum = multinomialSums[it->first];
auto& firstMultinomialLikelihood = multinomialLikelihoods[it->first];
// calculate multinomial likelihoods
for (int i = 0; i < NF; i++)
{
double mnl = (firstSumX[i] + alpha) / (firstMultinomialSum + (alpha * featureMeans.size()));
firstMultinomialLikelihood.push_back(mnl);
}
for (unsigned int i = 0; i < NF; i++)
printf("%i\t%2.3f\t%2.3f\t%2.3f\t%2.3f\n",i+1,featureMeans[i],featureVariances[i],sqrt(featureVariances[i]),firstMultinomialLikelihood[i]);
means[it->first] = std::move(featureMeans);
variances[it->first] = std::move(featureVariances);
}
// classify
std::cout << "Classifying:" << std::endl;
std::cout << "class\tprob\tresult" << std::endl;
readFromFile(argv[2], true);
printf("Accuracy: %3.2f %% (%i/%i)\n", 100.0 * correct / totalClassified, correct, totalClassified);
return 0;
}
<commit_msg>fixed some warnings enabled by `-Wall`<commit_after>#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <array>
#include <vector>
#include <set>
#include <map>
#include <random>
#include <chrono>
#include <functional>
#include <algorithm>
#include <cmath>
#define NF 16
#define SPLIT 20
using Entry = std::array<double, NF>;
using IntPair = std::pair<int, int>;
struct CompareSecond: std::binary_function<IntPair, IntPair, bool>
{
bool operator()(const IntPair& a, const IntPair& b)
{
return a.second < b.second;
}
};
int main(int argc, char** argv)
{
// smoothing factor
const double alpha = 1.0;
// decision rule
const int decision = 1;
if (argc < 2)
return 1;
// preparing data
int total = 0, correct = 0, totalClassified = 0;
std::map<std::string, std::vector<Entry> > data;
std::map<std::string, int> n;
std::map<std::string, double> priors;
std::map<std::string, std::vector<double> > multinomialLikelihoods;
std::map<std::string, int> multinomialSums;
std::map<std::string, Entry > sumX;
std::map<std::string, std::vector<double> > means;
std::map<std::string, std::vector<double> > variances;
auto classify = [&](const std::string& label, const Entry& entry)
{
std::string predlabel;
double maxlikelihood = 0.0;
double denom = 0.0;
std::vector<double> probs;
for (auto it = priors.begin(); it != priors.end(); it++)
{
double numer = priors[it->first];
const auto& firstMultinomialLikelihood = multinomialLikelihoods[it->first];
const auto& firstMean = means[it->first];
const auto& firstVariance = variances[it->first];
for (int j = 0; j < NF; j++)
switch (decision)
{
case 2:
// Multinomial
if (entry[j])
numer *= pow(firstMultinomialLikelihood[j], entry[j]);
break;
case 3:
// Bernoulli
numer *= pow(firstMean[j], entry[j]) * pow(1.0 - firstMean[j], 1.0 - entry[j]);
break;
default:
// Gaussian
numer *= 1 / sqrt(2 * M_PI * firstVariance[j]) * exp((-1 * (entry[j] - firstMean[j]) * (entry[j] -firstMean[j])) / (2 * firstVariance[j]));
break;
}
if (numer > maxlikelihood)
{
maxlikelihood = numer;
predlabel = it->first;
}
denom += numer;
probs.push_back(numer);
}
std::cout << predlabel << "\t" << std::setw(1) << std::setprecision(3) << maxlikelihood/denom << "\t";
if ("" == label)
std::cout << "<no label>" << std::endl;
else if (predlabel == label)
{
std::cout << "correct" << std::endl;
correct++;
}
else
std::cout << "incorrect" << std::endl;
totalClassified++;
};
auto readFromFile = [&](const char* filename, bool isClassification)
{
std::ifstream file(argv[1]);
if (!file.is_open())
return 1;
while (!file.eof())
{
std::string line;
std::getline(file, line);
if ("" == line)
continue;
std::istringstream linein(std::move(line));
std::string label;
std::getline(linein, label, ',');
Entry entry;
auto setField = [&entry, &label, &sumX, &multinomialSums, isClassification](int i, const std::string& field)
{
switch (field[0])
{
case 'y':
entry[i] = 1.0;
break;
case 'n':
entry[i] = 0.0;
break;
case '?':
entry[i] = 0.5;
break;
}
if (!isClassification)
{
sumX[label][i] += entry[i];
multinomialSums[label] += entry[i];
}
};
for (int i = 0; i < NF; i++)
{
std::string field;
std::getline(linein, field, ',');
setField(i, field);
}
std::string field;
std::getline(linein, field);
setField(NF - 1, field);
if (!isClassification)
{
data[label].push_back(std::move(entry));
n[label]++;
total++;
}
else
classify(label, entry);
}
return 0;
};
int errcode = readFromFile(argv[1], false);
if (errcode)
return errcode;
for (auto it = sumX.begin(); it != sumX.end(); it++)
{
priors[it->first] = (double)n[it->first] / total;
std::cout << "Class " << it->first << ", prior: " << std::setw(1) << std::setprecision(3) << priors[it->first] << std::endl;
std::cout << "feature\tmean\tvar\tstddev\tmnl" << std::endl;
// calculate means
std::vector<double> featureMeans(NF);
for (int i = 0; i < NF; i++)
featureMeans[i] = sumX[it->first][i] / n[it->first];
// calculate variances
std::vector<double> featureVariances(NF);
const auto& firstData = data[it->first];
for (int i = 0; i < (int)firstData.size(); i++)
for (int j = 0; j < NF; j++)
featureVariances[j] += (firstData[i][j] - featureMeans[j]) * (firstData[i][j] - featureMeans[j]);
for (int i = 0; i < NF; i++)
featureVariances[i] /= firstData.size();
const auto& firstSumX = sumX[it->first];
auto firstMultinomialSum = multinomialSums[it->first];
auto& firstMultinomialLikelihood = multinomialLikelihoods[it->first];
// calculate multinomial likelihoods
for (int i = 0; i < NF; i++)
{
double mnl = (firstSumX[i] + alpha) / (firstMultinomialSum + (alpha * featureMeans.size()));
firstMultinomialLikelihood.push_back(mnl);
}
for (unsigned int i = 0; i < NF; i++)
printf("%i\t%2.3f\t%2.3f\t%2.3f\t%2.3f\n",i+1,featureMeans[i],featureVariances[i],sqrt(featureVariances[i]),firstMultinomialLikelihood[i]);
means[it->first] = std::move(featureMeans);
variances[it->first] = std::move(featureVariances);
}
// classify
std::cout << "Classifying:" << std::endl;
std::cout << "class\tprob\tresult" << std::endl;
errcode = readFromFile(argv[2], true);
if (errcode)
return errcode;
printf("Accuracy: %3.2f %% (%i/%i)\n", 100.0 * correct / totalClassified, correct, totalClassified);
return 0;
}
<|endoftext|> |
<commit_before>/*
Copyright 2015, Jernej Kovacic
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 "IntUtilGeneric.hpp"
/**
* @file
* @author Jernej Kovacic
*
* Implementation of auxiliary functions that handle integer variables.
*/
// no #include "IntUtilGeneric.hpp" !!!
#include <limits>
// A namespace with "private" functions and classes
namespace math { namespace IntUtil { namespace __private
{
/*
* A set of clases that check whether an integer is negative.
*
* An integer value can only be negative if its type is signed. This could be
* quickly checked by comparing (I)(-1) and (I)(0), however, if I is an unsigned type,
* a compiler would raise a warning that "comparison of unsigned expression < 0 is
* always false". One workaround this would be partial specialization. As C++ does
* allow partial specialization of templated functions, thiswork around using an
* additional templated static class has been introduced.
*/
template <typename I, bool isSigned>
struct __CheckSign
{
/*
* A "general" implementation of the class when isSigned equals 'true'
*/
static inline bool isNeg(const I& n)
{
// As I is a signed type, 'n' must be compared to 0:
return ( n < static_cast<I>(0) );
}
};
// Partial specialization of __checkSignImpl for isSigned = false
template <typename I>
struct __CheckSign<I, false>
{
/*
* A specialization for isSigned == false, i.e. I is an unsigned integer type
*/
static inline bool isNeg(const I& n)
{
// Since I is an unsigned type, 'n' can never be negative
(void) n;
return false;
}
};
}}} // namespace math::IntUtil::__private
/*
* Checks the sign of 'n'.
* Both, signed and unsigned, integer types are handled correctly.
*
* @param n - integer value to check
*
* @return 'true' if 'n' is strictly negative, 'false' otherwise
*/
template <typename I>
bool math::IntUtil::isNegative(const I& n)
{
return
math::IntUtil::__private::__CheckSign<I, std::numeric_limits<I>::is_signed>::isNeg(n);
}
/*
* A simple integer implementation of abs
*
* @param n
* @return absolute value of 'n'
*/
template <typename I>
inline I math::IntUtil::absolute(const I& n)
{
return ( false==math::IntUtil::isNegative<I>(n) ? n : -n );
}
<commit_msg>error handling in int abs.<commit_after>/*
Copyright 2015, Jernej Kovacic
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 "IntUtilGeneric.hpp"
/**
* @file
* @author Jernej Kovacic
*
* Implementation of auxiliary functions that handle integer variables.
*/
// no #include "IntUtilGeneric.hpp" !!!
#include <limits>
// A namespace with "private" functions and classes
namespace math { namespace IntUtil { namespace __private
{
/*
* A set of clases that check whether an integer is negative.
*
* An integer value can only be negative if its type is signed. This could be
* quickly checked by comparing (I)(-1) and (I)(0), however, if I is an unsigned type,
* a compiler would raise a warning that "comparison of unsigned expression < 0 is
* always false". One workaround this would be partial specialization. As C++ does
* allow partial specialization of templated functions, thiswork around using an
* additional templated static class has been introduced.
*/
template <typename I, bool isSigned>
struct __CheckSign
{
/*
* A "general" implementation of the class when isSigned equals 'true'
*/
static inline bool isNeg(const I& n)
{
// As I is a signed type, 'n' must be compared to 0:
return ( n < static_cast<I>(0) );
}
};
// Partial specialization of __checkSignImpl for isSigned = false
template <typename I>
struct __CheckSign<I, false>
{
/*
* A specialization for isSigned == false, i.e. I is an unsigned integer type
*/
static inline bool isNeg(const I& n)
{
// Since I is an unsigned type, 'n' can never be negative
(void) n;
return false;
}
};
}}} // namespace math::IntUtil::__private
/*
* Checks the sign of 'n'.
* Both, signed and unsigned, integer types are handled correctly.
*
* @param n - integer value to check
*
* @return 'true' if 'n' is strictly negative, 'false' otherwise
*/
template <typename I>
bool math::IntUtil::isNegative(const I& n)
{
return
math::IntUtil::__private::__CheckSign<I, std::numeric_limits<I>::is_signed>::isNeg(n);
}
/*
* A simple integer implementation of abs
*
* @param n
* @return absolute value of 'n'
*/
template <typename I>
inline I math::IntUtil::absolute(const I& n)
{
const bool neg = math::IntUtil::isNegative<I>(n);
// TODO find better handling of this case!!!
/*
* If 'I' represents a signed type and 'n' equals I_MIN,
* the function should return -I_MIN. However, in such a case,
* I_MAX is typically less than -I_MIN (I_MAX = I_MIN - 1) which
* would result in an integer overflow (and possibly a core dump).
* If this situation occurs, the function will return I_MAX.
* Not really the correct handling but until a better solution is proposed...
*/
if ( true==neg && std::numeric_limits<I>::min()==n )
{
return std::numeric_limits<I>::max();
}
return ( false==neg ? n : -n );
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 1998,2000 by Jorrit Tyberghein
This is the entry point for console executables
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csutil/scf.h"
extern int csMain (int argc, char* argv[]);
extern int ApplicationShow;
HINSTANCE ModuleHandle;
#undef main
// The main entry for console applications
int main (int argc, char* argv[])
{
// hInstance is really the handle of module
ModuleHandle = GetModuleHandle (NULL);
return csMain (argc, argv);
}
// The main entry for GUI applications
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
ModuleHandle = hInstance;
ApplicationShow = nCmdShow;
(void)lpCmdLine;
(void)hPrevInstance;
return
#ifdef COMP_BC
csMain ( _argc, _argv);
#else
csMain (__argc, __argv);
#endif
}
<commit_msg>set ApplicationShow to SW_SHOWNORMAL in main (). For some reason the mingw links main and not WinMain for gui apps. In that case ApplicationShow was initialized to 0 which means HIDE which in turn was the reason the window was invisible when running with opengl/mingw. I remember that it worked before, so probably some linker options slightly changed when linking with mingw - i dont know.<commit_after>/*
Copyright (C) 1998,2000 by Jorrit Tyberghein
This is the entry point for console executables
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csutil/scf.h"
extern int csMain (int argc, char* argv[]);
extern int ApplicationShow;
HINSTANCE ModuleHandle;
#undef main
// The main entry for console applications
int main (int argc, char* argv[])
{
// hInstance is really the handle of module
ModuleHandle = GetModuleHandle (NULL);
ApplicationShow = SW_SHOWNORMAL;
return csMain (argc, argv);
}
// The main entry for GUI applications
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
ModuleHandle = hInstance;
ApplicationShow = nCmdShow;
(void)lpCmdLine;
(void)hPrevInstance;
return
#ifdef COMP_BC
csMain ( _argc, _argv);
#else
csMain (__argc, __argv);
#endif
}
<|endoftext|> |
<commit_before>/* ****************************************************************************
*
* FILE workerStatus.cpp
*
* DESCRIPTION extraction of machine information
*
*/
#include <stdio.h> // FILE, fopen, ...
#include <errno.h> // errno
#include <string.h> // strerror
#include "logMsg.h" // LM_*
#include "networkTraceLevels.h" // LMT_*
#include "samson.pb.h" // WorkerStatus
#include "workerStatus.h" // Own interface
namespace ss {
/* ****************************************************************************
*
* Definitions
*/
#define CPUINFO_PATH "/proc/cpuinfo"
#define STAT_PATH "/proc/stat"
#define NETDEV_PATH "/proc/net/dev"
/* ****************************************************************************
*
* CpuTimes -
*/
typedef struct CpuTimes
{
long user;
long nice;
long system;
long idle;
long iowait;
long irq;
long softIrq;
long steal;
long guest;
} CpuTimes;
/* ****************************************************************************
*
* cLoad - measure the load of core 'coreNo'
*/
static int cLoad(int coreNo)
{
FILE* fP;
char line[160];
static CpuTimes oldticks[MAX_CORES + 1] = { { -1 } };
CpuTimes ticks;
int load;
if (coreNo > MAX_CORES)
LM_X(1, ("request for load on core %d - max core number is %d. Please redefine MAX_CORES and recompile", coreNo, MAX_CORES));
fP = fopen(STAT_PATH, "r");
if (fP == NULL)
LM_RE(-1, ("fopen(%s): %s", STAT_PATH, strerror(errno)));
char coreName[7];
if (coreNo == MAX_CORES) /* Grand total */
sprintf(coreName, "cpu ");
else
sprintf(coreName, "cpu%d ", coreNo);
while (fgets(line, sizeof(line), fP) != NULL)
{
char coreName2[16];
if (strncmp(line, coreName, strlen(coreName)) != 0)
continue;
sscanf(line, "%s %ld %ld %ld %ld %ld %ld %ld %ld",
coreName2,
&ticks.user,
&ticks.nice,
&ticks.system,
&ticks.idle,
&ticks.iowait,
&ticks.irq,
&ticks.softIrq,
&ticks.steal);
/* Do I have an old measurement? - if not, I cannot measure the CPU load ... */
if (oldticks[coreNo].user == -1)
return 0;
CpuTimes* oldP = &oldticks[coreNo];
long long total = ticks.user + ticks.nice + ticks.system + ticks.idle + ticks.iowait + ticks.irq + ticks.softIrq + ticks.steal;
long long oldTotal = oldP->user + oldP->nice + oldP->system + oldP->idle + oldP->iowait + oldP->irq + oldP->softIrq + oldP->steal;
long long totalDiff = total - oldTotal;
if (totalDiff != 0)
{
long long idleDiff = ticks.idle - oldticks[coreNo].idle;
long long idlePercentage = (100 * idleDiff) / totalDiff;
load = 100 - idlePercentage;
}
else
load = 0;
// Remember what was just measured for the next time
oldticks[coreNo] = ticks;
return load;
}
LM_W(("core %d not found ...", coreNo));
return 0;
}
/* ****************************************************************************
*
* cores -
*/
static int cores(void)
{
FILE* fP;
char line[160];
int coreNo = -2;
fP = fopen(CPUINFO_PATH, "r");
if (fP == NULL)
LM_RE(-1, ("fopen(%s): %s", CPUINFO_PATH, strerror(errno)));
while (fgets(line, sizeof(line), fP) != NULL)
{
char* colon;
if (strncmp(line, "processor", 9) != 0)
continue;
colon = strchr(line, ':');
if (colon == NULL)
continue;
++colon;
coreNo = atoi(colon);
}
fclose(fP);
return coreNo + 1;
}
/* ****************************************************************************
*
* coreInfo -
*/
static void coreInfo(int coreNo, CoreInfo* ciP)
{
ciP->load = cLoad(coreNo);
FILE* fP;
char line[160];
int cNo = -1;
fP = fopen(CPUINFO_PATH, "r");
if (fP == NULL)
LM_RVE(("fopen(%s): %s", CPUINFO_PATH, strerror(errno)));
while (fgets(line, sizeof(line), fP) != NULL)
{
char* colon;
if (strncmp(line, "processor", 9) == 0)
{
colon = strchr(line, ':');
if (colon == NULL)
continue;
++colon;
cNo = atoi(colon);
if (cNo > coreNo)
return;
}
else if (cNo == coreNo)
{
if (strncmp(line, "cpu MHz", 7) == 0)
{
colon = strchr(line, ':');
if (colon == NULL)
continue;
++colon;
ciP->mhz = atoi(colon);
}
else if (strncmp(line, "bogomips", 8) == 0)
{
colon = strchr(line, ':');
if (colon == NULL)
continue;
++colon;
ciP->bogomips = atoi(colon);
}
else if (strncmp(line, "cache size", 10) == 0)
{
colon = strchr(line, ':');
if (colon == NULL)
continue;
++colon;
ciP->cacheSize = atoi(colon);
}
}
}
fclose(fP);
}
/* ****************************************************************************
*
* netifs -
*/
static int netifs(void)
{
FILE* fP;
char line[160];
int ifs = 0;
fP = fopen(NETDEV_PATH, "r");
if (fP == NULL)
LM_RE(-1, ("fopen(%s): %s", CPUINFO_PATH, strerror(errno)));
while (fgets(line, sizeof(line), fP) != NULL)
{
char* colon;
colon = strchr(line, ':');
if (colon == NULL)
continue;
++ifs;
}
fclose(fP);
return ifs;
}
/* ****************************************************************************
*
* cpuInfo -
*/
static void cpuInfo(CpuInfo* ciP)
{
int cIx;
ciP->cores = cores();
ciP->load = cLoad(MAX_CORES);
for (cIx = 0; cIx < ciP->cores; cIx++)
{
memset(&ciP->coreInfo[cIx], 0, sizeof(ciP->coreInfo[cIx]));
coreInfo(cIx, &ciP->coreInfo[cIx]);
}
}
/* ****************************************************************************
*
* netifInfo -
*/
static void netifInfo(int ifIndex, NetIf* nifP, time_t now, time_t lastTime)
{
FILE* fP;
char line[160];
int lineNo = 0;
static NetIf netif[MAX_NETIFS] = { { { 0 }, 0 } };
unsigned long intervalInSecs = now - lastTime;
fP = fopen(NETDEV_PATH, "r");
if (fP == NULL)
LM_RVE(("fopen(%s): %s", NETDEV_PATH, strerror(errno)));
while (fgets(line, sizeof(line), fP) != NULL)
{
++lineNo;
if (lineNo - 3 != ifIndex)
{
continue;
}
char* colon;
colon = strchr(line, ':');
if (colon == NULL)
{
LM_W(("no colon in '%s'", line));
continue;
}
*colon = 0;
++colon;
strcpy(nifP->name, line);
sscanf(colon, "%ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld",
&nifP->rcvBytes, &nifP->rcvPackets, &nifP->rcvErrors, &nifP->rcvDrop,
&nifP->rcvFifo, &nifP->rcvFrame, &nifP->rcvCompressed, &nifP->rcvMulticast,
&nifP->sndBytes, &nifP->sndPackets, &nifP->sndErrs, &nifP->sndDrop,
&nifP->sndFifo, &nifP->sndColls, &nifP->sndCarrier, &nifP->sndCompressed);
if (lastTime == 0)
{
nifP->rcvSpeed = 0;
nifP->sndSpeed = 0;
}
else
{
if (netif[ifIndex].rcvBytes != 0)
nifP->rcvSpeed = (nifP->rcvBytes - netif[ifIndex].rcvBytes) / intervalInSecs;
if (netif[ifIndex].sndBytes != 0)
nifP->sndSpeed = (nifP->sndBytes - netif[ifIndex].sndBytes) / intervalInSecs;
}
netif[ifIndex] = *nifP;
fclose(fP);
return;
}
}
/* ****************************************************************************
*
* netInfo -
*/
static void netInfo(NetIfInfo* niP)
{
int nIx;
time_t now = time(NULL);
static time_t then = 0;
niP->ifaces = netifs();
for (nIx = 0; nIx < niP->ifaces; nIx++)
{
memset(&niP->iface[nIx], 0, sizeof(niP->iface[nIx]));
strcpy(niP->iface[nIx].name, "nada");
netifInfo(nIx, &niP->iface[nIx], now, then);
}
then = now;
}
/* ****************************************************************************
*
* workerStatus -
*/
void workerStatus(WorkerStatus* wsP)
{
cpuInfo(&wsP->cpuInfo);
netInfo(&wsP->netInfo);
}
}
<commit_msg>new feature - closing files after using them ...<commit_after>/* ****************************************************************************
*
* FILE workerStatus.cpp
*
* DESCRIPTION extraction of machine information
*
*/
#include <stdio.h> // FILE, fopen, ...
#include <errno.h> // errno
#include <string.h> // strerror
#include "logMsg.h" // LM_*
#include "networkTraceLevels.h" // LMT_*
#include "samson.pb.h" // WorkerStatus
#include "workerStatus.h" // Own interface
namespace ss {
/* ****************************************************************************
*
* Definitions
*/
#define CPUINFO_PATH "/proc/cpuinfo"
#define STAT_PATH "/proc/stat"
#define NETDEV_PATH "/proc/net/dev"
/* ****************************************************************************
*
* CpuTimes -
*/
typedef struct CpuTimes
{
long user;
long nice;
long system;
long idle;
long iowait;
long irq;
long softIrq;
long steal;
long guest;
} CpuTimes;
/* ****************************************************************************
*
* cLoad - measure the load of core 'coreNo'
*/
static int cLoad(int coreNo)
{
FILE* fP;
char line[160];
static CpuTimes oldticks[MAX_CORES + 1] = { { -1 } };
CpuTimes ticks;
int load;
if (coreNo > MAX_CORES)
LM_X(1, ("request for load on core %d - max core number is %d. Please redefine MAX_CORES and recompile", coreNo, MAX_CORES));
fP = fopen(STAT_PATH, "r");
if (fP == NULL)
LM_RE(-1, ("fopen(%s): %s", STAT_PATH, strerror(errno)));
char coreName[7];
if (coreNo == MAX_CORES) /* Grand total */
sprintf(coreName, "cpu ");
else
sprintf(coreName, "cpu%d ", coreNo);
while (fgets(line, sizeof(line), fP) != NULL)
{
char coreName2[16];
if (strncmp(line, coreName, strlen(coreName)) != 0)
continue;
sscanf(line, "%s %ld %ld %ld %ld %ld %ld %ld %ld",
coreName2,
&ticks.user,
&ticks.nice,
&ticks.system,
&ticks.idle,
&ticks.iowait,
&ticks.irq,
&ticks.softIrq,
&ticks.steal);
/* Do I have an old measurement? - if not, I cannot measure the CPU load ... */
if (oldticks[coreNo].user == -1)
{
fclose(fP);
return 0;
}
CpuTimes* oldP = &oldticks[coreNo];
long long total = ticks.user + ticks.nice + ticks.system + ticks.idle + ticks.iowait + ticks.irq + ticks.softIrq + ticks.steal;
long long oldTotal = oldP->user + oldP->nice + oldP->system + oldP->idle + oldP->iowait + oldP->irq + oldP->softIrq + oldP->steal;
long long totalDiff = total - oldTotal;
if (totalDiff != 0)
{
long long idleDiff = ticks.idle - oldticks[coreNo].idle;
long long idlePercentage = (100 * idleDiff) / totalDiff;
load = 100 - idlePercentage;
}
else
load = 0;
// Remember what was just measured for the next time
oldticks[coreNo] = ticks;
fclose(fP);
return load;
}
LM_W(("core %d not found ...", coreNo));
fclose(fP);
return 0;
}
/* ****************************************************************************
*
* cores -
*/
static int cores(void)
{
FILE* fP;
char line[160];
int coreNo = -2;
fP = fopen(CPUINFO_PATH, "r");
if (fP == NULL)
LM_RE(-1, ("fopen(%s): %s", CPUINFO_PATH, strerror(errno)));
while (fgets(line, sizeof(line), fP) != NULL)
{
char* colon;
if (strncmp(line, "processor", 9) != 0)
continue;
colon = strchr(line, ':');
if (colon == NULL)
continue;
++colon;
coreNo = atoi(colon);
}
fclose(fP);
return coreNo + 1;
}
/* ****************************************************************************
*
* coreInfo -
*/
static void coreInfo(int coreNo, CoreInfo* ciP)
{
ciP->load = cLoad(coreNo);
FILE* fP;
char line[160];
int cNo = -1;
fP = fopen(CPUINFO_PATH, "r");
if (fP == NULL)
LM_RVE(("fopen(%s): %s", CPUINFO_PATH, strerror(errno)));
while (fgets(line, sizeof(line), fP) != NULL)
{
char* colon;
if (strncmp(line, "processor", 9) == 0)
{
colon = strchr(line, ':');
if (colon == NULL)
continue;
++colon;
cNo = atoi(colon);
if (cNo > coreNo)
{
fclose(fP);
return;
}
}
else if (cNo == coreNo)
{
if (strncmp(line, "cpu MHz", 7) == 0)
{
colon = strchr(line, ':');
if (colon == NULL)
continue;
++colon;
ciP->mhz = atoi(colon);
}
else if (strncmp(line, "bogomips", 8) == 0)
{
colon = strchr(line, ':');
if (colon == NULL)
continue;
++colon;
ciP->bogomips = atoi(colon);
}
else if (strncmp(line, "cache size", 10) == 0)
{
colon = strchr(line, ':');
if (colon == NULL)
continue;
++colon;
ciP->cacheSize = atoi(colon);
}
}
}
fclose(fP);
}
/* ****************************************************************************
*
* netifs -
*/
static int netifs(void)
{
FILE* fP;
char line[160];
int ifs = 0;
fP = fopen(NETDEV_PATH, "r");
if (fP == NULL)
LM_RE(-1, ("fopen(%s): %s", CPUINFO_PATH, strerror(errno)));
while (fgets(line, sizeof(line), fP) != NULL)
{
char* colon;
colon = strchr(line, ':');
if (colon == NULL)
continue;
++ifs;
}
fclose(fP);
return ifs;
}
/* ****************************************************************************
*
* cpuInfo -
*/
static void cpuInfo(CpuInfo* ciP)
{
int cIx;
ciP->cores = cores();
ciP->load = cLoad(MAX_CORES);
for (cIx = 0; cIx < ciP->cores; cIx++)
{
memset(&ciP->coreInfo[cIx], 0, sizeof(ciP->coreInfo[cIx]));
coreInfo(cIx, &ciP->coreInfo[cIx]);
}
}
/* ****************************************************************************
*
* netifInfo -
*/
static void netifInfo(int ifIndex, NetIf* nifP, time_t now, time_t lastTime)
{
FILE* fP;
char line[160];
int lineNo = 0;
static NetIf netif[MAX_NETIFS] = { { { 0 }, 0 } };
unsigned long intervalInSecs = now - lastTime;
fP = fopen(NETDEV_PATH, "r");
if (fP == NULL)
LM_RVE(("fopen(%s): %s", NETDEV_PATH, strerror(errno)));
while (fgets(line, sizeof(line), fP) != NULL)
{
++lineNo;
if (lineNo - 3 != ifIndex)
{
continue;
}
char* colon;
colon = strchr(line, ':');
if (colon == NULL)
{
LM_W(("no colon in '%s'", line));
continue;
}
*colon = 0;
++colon;
strcpy(nifP->name, line);
sscanf(colon, "%ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld",
&nifP->rcvBytes, &nifP->rcvPackets, &nifP->rcvErrors, &nifP->rcvDrop,
&nifP->rcvFifo, &nifP->rcvFrame, &nifP->rcvCompressed, &nifP->rcvMulticast,
&nifP->sndBytes, &nifP->sndPackets, &nifP->sndErrs, &nifP->sndDrop,
&nifP->sndFifo, &nifP->sndColls, &nifP->sndCarrier, &nifP->sndCompressed);
if (lastTime == 0)
{
nifP->rcvSpeed = 0;
nifP->sndSpeed = 0;
}
else
{
if (netif[ifIndex].rcvBytes != 0)
nifP->rcvSpeed = (nifP->rcvBytes - netif[ifIndex].rcvBytes) / intervalInSecs;
if (netif[ifIndex].sndBytes != 0)
nifP->sndSpeed = (nifP->sndBytes - netif[ifIndex].sndBytes) / intervalInSecs;
}
netif[ifIndex] = *nifP;
fclose(fP);
return;
}
fclose(fP);
}
/* ****************************************************************************
*
* netInfo -
*/
static void netInfo(NetIfInfo* niP)
{
int nIx;
time_t now = time(NULL);
static time_t then = 0;
niP->ifaces = netifs();
for (nIx = 0; nIx < niP->ifaces; nIx++)
{
memset(&niP->iface[nIx], 0, sizeof(niP->iface[nIx]));
strcpy(niP->iface[nIx].name, "nada");
netifInfo(nIx, &niP->iface[nIx], now, then);
}
then = now;
}
/* ****************************************************************************
*
* workerStatus -
*/
void workerStatus(WorkerStatus* wsP)
{
cpuInfo(&wsP->cpuInfo);
netInfo(&wsP->netInfo);
}
}
<|endoftext|> |
<commit_before><commit_msg>Use the proper variable name to enhance the redability (#5602)<commit_after><|endoftext|> |
<commit_before>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#define SUITE scope_linked
#include "vast/scope_linked.hpp"
#include "test.hpp"
#include "fixtures/actor_system.hpp"
using namespace vast;
namespace {
caf::behavior dummy() {
return {
[] {
// nop
}
};
}
} // namespace <anonymous>
FIXTURE_SCOPE(scope_linked_tests, fixtures::deterministic_actor_system)
TEST(exit message on exit) {
caf::actor hdl;
{ // "lifetime scope" for our dummy
scope_linked_actor sla{sys.spawn(dummy)};
hdl = sla.get();
}
expect((caf::exit_msg), from(_).to(hdl));
}
FIXTURE_SCOPE_END()
<commit_msg>Clarify non-obvious test with comments<commit_after>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#define SUITE scope_linked
#include "vast/scope_linked.hpp"
#include "test.hpp"
#include "fixtures/actor_system.hpp"
using namespace vast;
namespace {
caf::behavior dummy() {
return {
[] {
// nop
}
};
}
} // namespace <anonymous>
FIXTURE_SCOPE(scope_linked_tests, fixtures::deterministic_actor_system)
TEST(exit message on exit) {
// Spawn dummy, assign it to a scope_linked handle (sla) and make sure it
// gets killed when sla goes out of scope.
caf::actor hdl;
{ // "lifetime scope" for our dummy
scope_linked_actor sla{sys.spawn(dummy)};
// Store the actor handle in the outer scope, otherwise we can't check for
// a message to the dummy.
hdl = sla.get();
}
// The sla handle must send an exit_msg when going out of scope.
expect((caf::exit_msg), from(_).to(hdl));
}
FIXTURE_SCOPE_END()
<|endoftext|> |
<commit_before>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
// vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
/* Copyright (C) 2010 LinBox
*
* Time-stamp: <16 Dec 10 17:48:13 Jean-Guillaume.Dumas@imag.fr>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/*! @file tests-test-cradomain.C
* @ingroup tests
* @brief tests LinBox::ChineseRemainer
* @test tests LinBox::ChineseRemainer (see \ref CRA)
*/
#include <linbox/algorithms/cra-domain.h>
#include <linbox/field/modular-double.h>
#include "linbox/algorithms/blas-domain.h"
#include "linbox/algorithms/cra-early-multip.h"
#include "linbox/algorithms/cra-full-multip.h"
#include "linbox/algorithms/cra-full-multip-fixed.h"
#include "linbox/randiter/random-prime.h"
struct Interator {
std::vector<Integer> _v;
double maxsize;
Interator(const std::vector<Integer>& v) :
_v(v), maxsize(0.0)
{
for(std::vector<Integer>::const_iterator it=_v.begin();
it != _v.end(); ++it) {
double ds = naturallog(*it);
maxsize = (maxsize<ds?ds:maxsize);
}
}
Interator(int n, int s) :
_v(n), maxsize(0.0)
{
for(std::vector<Integer>::iterator it=_v.begin();
it != _v.end(); ++it) {
Integer::random(*it, s);
double ds = naturallog(*it);
maxsize = (maxsize<ds?ds:maxsize);
}
}
const std::vector<Integer>& getVector() { return _v; }
const double getLogSize() { return maxsize; }
template<typename Field>
std::vector<typename Field::Element>& operator()(std::vector<typename Field::Element>& v,
const Field& F) const
{
v.resize(_v.size());
std::vector<Integer>::const_iterator vit=_v.begin();
typename std::vector<typename Field::Element>::iterator eit=v.begin();
for( ; vit != _v.end(); ++vit, ++eit)
F.init(*eit, *vit);
return v;
}
};
struct InteratorIt;
namespace LinBox
{
template<class Element> struct CRATemporaryVectorTrait<InteratorIt , Element> {
typedef typename std::vector<double>::iterator Type_t;
};
}
struct InteratorIt : public Interator {
mutable std::vector<double> _C;
InteratorIt(const std::vector<Integer>& v) :
Interator(v), _C(v.size())
{}
InteratorIt(int n, int s) :
Interator(n,s), _C(n)
{}
template<typename Iterator, typename Field>
Iterator& operator()(Iterator& res, const Field& F) const
{
std::vector<Integer>::const_iterator vit=this->_v.begin();
std::vector<double>::iterator eit=_C.begin();
for( ; vit != _v.end(); ++vit, ++eit)
F.init(*eit, *vit);
return res=_C.begin();
}
};
template<typename Field> struct InteratorBlas;
namespace LinBox
{
template<class Element,class Field> struct CRATemporaryVectorTrait<InteratorBlas<Field> , Element> {
typedef typename LinBox::BlasMatrix<Element>::pointer Type_t;
};
}
template<typename Field>
struct InteratorBlas : public Interator {
typedef typename Field::Element Element;
typedef LinBox::BlasMatrix<Element> Matrix;
typedef typename Matrix::pointer Pointer;
mutable Matrix _C;
InteratorBlas(const std::vector<Integer>& v) : Interator(v), _C(v.size(),1) {}
InteratorBlas(int n, int s) : Interator(n,s), _C(n,1) {}
Pointer& operator()(Pointer& res, const Field& F) const {
std::vector<Integer>::const_iterator vit=this->_v.begin();
res = _C.getWritePointer();
for( ; vit != _v.end(); ++vit, ++res)
F.init(*res, *vit);
return res=_C.getWritePointer();
}
};
bool TestCra(int N, int S, size_t seed)
{
std::ostream &report = LinBox::commentator.report
(LinBox::Commentator::LEVEL_IMPORTANT, INTERNAL_DESCRIPTION);
report << "TestCra(" << N << ',' << S << ',' << seed << ')' << std::endl;
Integer::seeding(seed);
Interator iteration(N, S);
InteratorIt iterationIt(iteration.getVector());
LinBox::RandomPrimeIterator genprime( 24, seed );
bool pass = true;
report << "ChineseRemainder<EarlyMultipCRA>(4)" << std::endl;
{
LinBox::ChineseRemainder< LinBox::EarlyMultipCRA< LinBox::Modular<double> > > craEM(4UL);
std::vector<Integer> ResEM(N);
craEM( ResEM, iteration, genprime);
bool locpass = std::equal( ResEM.begin(), ResEM.end(), iteration.getVector().begin() );
if (locpass) report << "ChineseRemainder<EarlyMultipCRA>(4)" << ", passed." << std::endl;
else report << "***ERROR***: ChineseRemainder<EarlyMultipCRA>(4)" << "***ERROR***" << std::endl;
pass = pass && locpass;
}
report << "ChineseRemainder<FullMultipCRA>(" << iteration.getLogSize() << ')' << std::endl;
{
LinBox::ChineseRemainder< LinBox::FullMultipCRA< LinBox::Modular<double> > > craFM( iteration.getLogSize() );
std::vector<Integer> ResFM(N);
craFM( ResFM, iteration, genprime);
bool locpass = std::equal( ResFM.begin(), ResFM.end(), iteration.getVector().begin() );
if (locpass) report << "ChineseRemainder<FullMultipCRA>(" << iteration.getLogSize() << ')' << ", passed." << std::endl;
else report << "***ERROR***: ChineseRemainder<FullMultipCRA>(" << iteration.getLogSize() << ')' << "***ERROR***" << std::endl;
pass = pass && locpass;
}
report << "ChineseRemainder<FullMultipFixedCRA,vector>(" << N << ',' << iterationIt.getLogSize() << ')' << std::endl;
{
LinBox::ChineseRemainder< LinBox::FullMultipFixedCRA< LinBox::Modular<double> > > craFMF( std::pair<size_t,double>(N,iterationIt.getLogSize()) );
std::vector<Integer> ResFMF(N);
std::vector<Integer>::iterator ResIT= ResFMF.begin();
craFMF( ResIT, iterationIt, genprime);
bool locpass = std::equal( iterationIt.getVector().begin(), iterationIt.getVector().end(), ResFMF.begin() );
if (locpass) report << "ChineseRemainder<FullMultipFixedCRA,vector>(" << N << ',' << iterationIt.getLogSize() << ')' << ", passed." << std::endl;
else report << "***ERROR***: ChineseRemainder<FullMultipFixedCRA,vector>(" << N << ',' << iterationIt.getLogSize() << ')' << "***ERROR***" << std::endl;
pass = pass && locpass;
}
report << "ChineseRemainder<FullMultipFixedCRA,BlasMatrix>(" << N << ',' << iterationIt.getLogSize() << ')' << std::endl;
{
LinBox::ChineseRemainder< LinBox::FullMultipFixedCRA< LinBox::Modular<double> > > craFMFBM( std::pair<size_t,double>(N,iterationIt.getLogSize()) );
LinBox::BlasMatrix<Integer> ResFMFBM(N,1);
craFMFBM( ResFMFBM.getWritePointer(), iterationIt, genprime);
bool locpass = std::equal( iterationIt.getVector().begin(), iterationIt.getVector().end(), ResFMFBM.getWritePointer() );
if (locpass) report << "ChineseRemainder<FullMultipFixedCRA,BlasMatrix>(" << N << ',' << iterationIt.getLogSize() << ')' << ", passed." << std::endl;
else
report << "***ERROR***: ChineseRemainder<FullMultipFixedCRA,BlasMatrix>(" << N << ',' << iterationIt.getLogSize() << ')' << " ***ERROR***" << std::endl;
pass = pass && locpass;
}
if (pass) report << "TestCra(" << N << ',' << S << ')' << ", passed." << std::endl;
else
report << "***ERROR***: TestCra(" << N << ',' << S << ')' << " ***ERROR***" << std::endl;
return pass;
}
#include "test-common.h"
#include "linbox/util/timer.h"
int main (int argc, char **argv)
{
static size_t n = 1000;
static size_t s = 30;
static size_t seed = LinBox::BaseTimer::seed();
static int iterations = 20;
static Argument args[] = {
{ 'n', "-n N", "Set dimension of test vectors to NxN.", TYPE_INT
, &n },
{ 's', "-s S", "Set size of test integers.", TYPE_INT
, &s },
{ 'z', "-z Z", "Set seed.", TYPE_INT
, &seed },
{ 'i', "-i I", "Perform each test for I iterations.", TYPE_INT, &iterations },
{ '\0' }
};
parseArguments (argc, argv, args);
commentator.start("CRA-Domain test suite", "CRADom");
bool pass = true;
for(int i=0; pass && i<iterations; ++i)
pass &= TestCra(n,s,seed);
commentator.stop(MSG_STATUS (pass), (const char *) 0,"CRA-Domain test suite");
return pass ? 0 : -1;
}
<commit_msg>pass &=<commit_after>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
// vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
/* Copyright (C) 2010 LinBox
*
* Time-stamp: <16 Dec 10 18:13:45 Jean-Guillaume.Dumas@imag.fr>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/*! @file tests-test-cradomain.C
* @ingroup tests
* @brief tests LinBox::ChineseRemainer
* @test tests LinBox::ChineseRemainer (see \ref CRA)
*/
#include <linbox/algorithms/cra-domain.h>
#include <linbox/field/modular-double.h>
#include "linbox/algorithms/blas-domain.h"
#include "linbox/algorithms/cra-early-multip.h"
#include "linbox/algorithms/cra-full-multip.h"
#include "linbox/algorithms/cra-full-multip-fixed.h"
#include "linbox/randiter/random-prime.h"
struct Interator {
std::vector<Integer> _v;
double maxsize;
Interator(const std::vector<Integer>& v) :
_v(v), maxsize(0.0)
{
for(std::vector<Integer>::const_iterator it=_v.begin();
it != _v.end(); ++it) {
double ds = naturallog(*it);
maxsize = (maxsize<ds?ds:maxsize);
}
}
Interator(int n, int s) :
_v(n), maxsize(0.0)
{
for(std::vector<Integer>::iterator it=_v.begin();
it != _v.end(); ++it) {
Integer::random(*it, s);
double ds = naturallog(*it);
maxsize = (maxsize<ds?ds:maxsize);
}
}
const std::vector<Integer>& getVector() { return _v; }
const double getLogSize() { return maxsize; }
template<typename Field>
std::vector<typename Field::Element>& operator()(std::vector<typename Field::Element>& v,
const Field& F) const
{
v.resize(_v.size());
std::vector<Integer>::const_iterator vit=_v.begin();
typename std::vector<typename Field::Element>::iterator eit=v.begin();
for( ; vit != _v.end(); ++vit, ++eit)
F.init(*eit, *vit);
return v;
}
};
struct InteratorIt;
namespace LinBox
{
template<class Element> struct CRATemporaryVectorTrait<InteratorIt , Element> {
typedef typename std::vector<double>::iterator Type_t;
};
}
struct InteratorIt : public Interator {
mutable std::vector<double> _C;
InteratorIt(const std::vector<Integer>& v) :
Interator(v), _C(v.size())
{}
InteratorIt(int n, int s) :
Interator(n,s), _C(n)
{}
template<typename Iterator, typename Field>
Iterator& operator()(Iterator& res, const Field& F) const
{
std::vector<Integer>::const_iterator vit=this->_v.begin();
std::vector<double>::iterator eit=_C.begin();
for( ; vit != _v.end(); ++vit, ++eit)
F.init(*eit, *vit);
return res=_C.begin();
}
};
template<typename Field> struct InteratorBlas;
namespace LinBox
{
template<class Element,class Field> struct CRATemporaryVectorTrait<InteratorBlas<Field> , Element> {
typedef typename LinBox::BlasMatrix<Element>::pointer Type_t;
};
}
template<typename Field>
struct InteratorBlas : public Interator {
typedef typename Field::Element Element;
typedef LinBox::BlasMatrix<Element> Matrix;
typedef typename Matrix::pointer Pointer;
mutable Matrix _C;
InteratorBlas(const std::vector<Integer>& v) : Interator(v), _C(v.size(),1) {}
InteratorBlas(int n, int s) : Interator(n,s), _C(n,1) {}
Pointer& operator()(Pointer& res, const Field& F) const {
std::vector<Integer>::const_iterator vit=this->_v.begin();
res = _C.getWritePointer();
for( ; vit != _v.end(); ++vit, ++res)
F.init(*res, *vit);
return res=_C.getWritePointer();
}
};
bool TestCra(int N, int S, size_t seed)
{
std::ostream &report = LinBox::commentator.report
(LinBox::Commentator::LEVEL_IMPORTANT, INTERNAL_DESCRIPTION);
report << "TestCra(" << N << ',' << S << ',' << seed << ')' << std::endl;
Integer::seeding(seed);
Interator iteration(N, S);
InteratorIt iterationIt(iteration.getVector());
LinBox::RandomPrimeIterator genprime( 24, seed );
bool pass = true;
report << "ChineseRemainder<EarlyMultipCRA>(4)" << std::endl;
{
LinBox::ChineseRemainder< LinBox::EarlyMultipCRA< LinBox::Modular<double> > > craEM(4UL);
std::vector<Integer> ResEM(N);
craEM( ResEM, iteration, genprime);
bool locpass = std::equal( ResEM.begin(), ResEM.end(), iteration.getVector().begin() );
if (locpass) report << "ChineseRemainder<EarlyMultipCRA>(4)" << ", passed." << std::endl;
else report << "***ERROR***: ChineseRemainder<EarlyMultipCRA>(4)" << "***ERROR***" << std::endl;
pass &= locpass;
}
report << "ChineseRemainder<FullMultipCRA>(" << iteration.getLogSize() << ')' << std::endl;
{
LinBox::ChineseRemainder< LinBox::FullMultipCRA< LinBox::Modular<double> > > craFM( iteration.getLogSize() );
std::vector<Integer> ResFM(N);
craFM( ResFM, iteration, genprime);
bool locpass = std::equal( ResFM.begin(), ResFM.end(), iteration.getVector().begin() );
if (locpass) report << "ChineseRemainder<FullMultipCRA>(" << iteration.getLogSize() << ')' << ", passed." << std::endl;
else report << "***ERROR***: ChineseRemainder<FullMultipCRA>(" << iteration.getLogSize() << ')' << "***ERROR***" << std::endl;
pass &= locpass;
}
report << "ChineseRemainder<FullMultipFixedCRA,vector>(" << N << ',' << iterationIt.getLogSize() << ')' << std::endl;
{
LinBox::ChineseRemainder< LinBox::FullMultipFixedCRA< LinBox::Modular<double> > > craFMF( std::pair<size_t,double>(N,iterationIt.getLogSize()) );
std::vector<Integer> ResFMF(N);
std::vector<Integer>::iterator ResIT= ResFMF.begin();
craFMF( ResIT, iterationIt, genprime);
bool locpass = std::equal( iterationIt.getVector().begin(), iterationIt.getVector().end(), ResFMF.begin() );
if (locpass) report << "ChineseRemainder<FullMultipFixedCRA,vector>(" << N << ',' << iterationIt.getLogSize() << ')' << ", passed." << std::endl;
else report << "***ERROR***: ChineseRemainder<FullMultipFixedCRA,vector>(" << N << ',' << iterationIt.getLogSize() << ')' << "***ERROR***" << std::endl;
pass &= locpass;
}
report << "ChineseRemainder<FullMultipFixedCRA,BlasMatrix>(" << N << ',' << iterationIt.getLogSize() << ')' << std::endl;
{
LinBox::ChineseRemainder< LinBox::FullMultipFixedCRA< LinBox::Modular<double> > > craFMFBM( std::pair<size_t,double>(N,iterationIt.getLogSize()) );
LinBox::BlasMatrix<Integer> ResFMFBM(N,1);
craFMFBM( ResFMFBM.getWritePointer(), iterationIt, genprime);
bool locpass = std::equal( iterationIt.getVector().begin(), iterationIt.getVector().end(), ResFMFBM.getWritePointer() );
if (locpass) report << "ChineseRemainder<FullMultipFixedCRA,BlasMatrix>(" << N << ',' << iterationIt.getLogSize() << ')' << ", passed." << std::endl;
else
report << "***ERROR***: ChineseRemainder<FullMultipFixedCRA,BlasMatrix>(" << N << ',' << iterationIt.getLogSize() << ')' << " ***ERROR***" << std::endl;
pass &= locpass;
}
if (pass) report << "TestCra(" << N << ',' << S << ')' << ", passed." << std::endl;
else
report << "***ERROR***: TestCra(" << N << ',' << S << ')' << " ***ERROR***" << std::endl;
return pass;
}
#include "test-common.h"
#include "linbox/util/timer.h"
int main (int argc, char **argv)
{
static size_t n = 1000;
static size_t s = 30;
static size_t seed = LinBox::BaseTimer::seed();
static int iterations = 20;
static Argument args[] = {
{ 'n', "-n N", "Set dimension of test vectors to NxN.", TYPE_INT
, &n },
{ 's', "-s S", "Set size of test integers.", TYPE_INT
, &s },
{ 'z', "-z Z", "Set seed.", TYPE_INT
, &seed },
{ 'i', "-i I", "Perform each test for I iterations.", TYPE_INT, &iterations },
{ '\0' }
};
parseArguments (argc, argv, args);
commentator.start("CRA-Domain test suite", "CRADom");
bool pass = true;
for(int i=0; pass && i<iterations; ++i)
pass &= TestCra(n,s,seed);
commentator.stop(MSG_STATUS (pass), (const char *) 0,"CRA-Domain test suite");
return pass ? 0 : -1;
}
<|endoftext|> |
<commit_before>// https://www.facebook.com/hackercup/problem/1424196571244550/
// Facebook Hacker Cup 2016 Round 1
// Boomerang Tournament
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
int n;
int in[16][16];
int memo[16][1<<16];
void input() {
cin >> n;
for (int r = 0; r < n ; r++) {
for (int c = 0; c < n ; c++) {
cin >> in[r][c];
}
}
}
int next(int v) {
unsigned int t = (v | (v - 1)) + 1;
return (int)(t | ((((t & -t) / (v & -v)) >> 1) - 1));
}
int win(int i, int flag) {
int &result = memo[i][flag];
if ((1<<i) & flag) return result;
int temp = flag;
while (temp) {
int index = __builtin_ctz(temp);
if (memo[index][flag] && in[i][index]) {
result = 1;
break;
}
temp &= temp - 1;
}
return result;
}
void set_each(int a, int b) {
int index = a | b;
for (int i = 0; i < n; i++) {
if (memo[i][index] == 1 || !(index & (1<<i))) continue;
if (win(i, a) && win(i, b)) {
memo[i][index] = 1;
}
}
}
int calc_best() {
memset(memo, 0, sizeof(memo));
const int limit = 1 << n;
for (int r = 0; r < n ; r++) {
memo[r][1<<r] = 1; // itself
}
for (int num = 1; num < n; num <<= 1) { // for (1, 2, 4, 8, 16)
vector<int> v;
int flag = (1 << num) - 1;
while (flag < limit) {
v.push_back(flag);
flag = next(flag);
}
for (int a : v) {
for (int b : v) {
if (a <= b) continue; // only b < a
if (__builtin_popcount(a|b) != (num << 1)) continue;
set_each(a, b);
}
}
}
return 0;
}
int worst(int x) {
for (int i = 0; i < n; i++) {
if (i != x && in[x][i] == 0) return ((n >> 1) + 1);
}
return 1;
}
int best(int me) {
const int rank [] = {1, 2, 3, 5, 9};
const int limit = 1 << n;
int i(0), num(n);
for (; 0 < num; num >>= 1, i++) {
int flag = (1 << num) - 1;
while (flag < limit) {
if (flag & (1<<me) && memo[me][flag]) return rank[i];
flag = next(flag);
}
}
return rank[i];
}
void solve() {
calc_best();
for (int i = 0; i < n; i++) {
printf("%d %d\n", best(i), worst(i));
}
}
int main() {
int t; cin >> t;
for (int i = 1; i <= t; i++) {
input();
printf("Case #%d:\n", i);
solve();
}
return 0;
}
<commit_msg>Update main.cpp<commit_after>// https://www.facebook.com/hackercup/problem/1424196571244550/
// Facebook Hacker Cup 2016 Round 1
// Boomerang Tournament
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
int n;
int in[16][16];
int memo[16][1<<16];
void input() {
cin >> n;
for (int r = 0; r < n ; r++) {
for (int c = 0; c < n ; c++) {
cin >> in[r][c];
}
}
}
int next(int v) {
unsigned int t = (v | (v - 1)) + 1;
return (int)(t | ((((t & -t) / (v & -v)) >> 1) - 1));
}
int win(int i, int flag) {
int &result = memo[i][flag];
if ((1<<i) & flag) return result;
int temp = flag;
while (temp) {
int index = __builtin_ctz(temp);
if (memo[index][flag] && in[i][index]) {
result = 1;
break;
}
temp &= temp - 1;
}
return result;
}
void set_each(int a, int b) {
int index = a | b;
for (int i = 0; i < n; i++) {
if (memo[i][index] == 1 || !(index & (1<<i))) continue;
if (win(i, a) && win(i, b)) {
memo[i][index] = 1;
}
}
}
int calc_best() {
memset(memo, 0, sizeof(memo));
const int limit = 1 << n;
for (int r = 0; r < n ; r++) {
memo[r][1<<r] = 1; // itself
}
for (int num = 1; num < n; num <<= 1) { // for (1, 2, 4, 8, 16)
vector<int> v;
int flag = (1 << num) - 1;
while (flag < limit) {
v.push_back(flag);
flag = next(flag);
}
for (int a : v) {
for (int b : v) {
if (a <= b) continue; // only b < a
if (a & b) continue;
set_each(a, b);
}
}
}
return 0;
}
int worst(int x) {
for (int i = 0; i < n; i++) {
if (i != x && in[x][i] == 0) return ((n >> 1) + 1);
}
return 1;
}
int best(int me) {
const int rank [] = {1, 2, 3, 5, 9};
const int limit = 1 << n;
int i(0), num(n);
for (; 0 < num; num >>= 1, i++) {
int flag = (1 << num) - 1;
while (flag < limit) {
if (flag & (1<<me) && memo[me][flag]) return rank[i];
flag = next(flag);
}
}
return rank[i];
}
void solve() {
calc_best();
for (int i = 0; i < n; i++) {
printf("%d %d\n", best(i), worst(i));
}
}
int main() {
int t; cin >> t;
for (int i = 1; i <= t; i++) {
input();
printf("Case #%d:\n", i);
solve();
}
return 0;
}
<|endoftext|> |
<commit_before>/**
* \file
* Copyright 2014-2015 Benjamin Worpitz
*
* This file is part of alpaka.
*
* alpaka is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* alpaka is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with alpaka.
* If not, see <http://www.gnu.org/licenses/>.
*/
#include <alpaka/alpaka.hpp> // alpaka::exec::create
#include <alpaka/integ/MeasureKernelRunTime.hpp> // measureKernelRunTimeMs
#include <alpaka/integ/accs/EnabledAccs.hpp> // EnabledAccs
#include <iostream> // std::cout
#include <typeinfo> // typeid
#include <vector> // std::vector
//#############################################################################
//! A kernel using atomicOp, syncBlockThreads, getBlockSharedExternMem, getIdx, getWorkDiv and global memory to compute a (useless) result.
//! \tparam TAcc The accelerator environment to be executed on.
//! \tparam TnumUselessWork The number of useless calculations done in each kernel execution.
//#############################################################################
template<
typename TnumUselessWork>
class SharedMemKernel
{
public:
//-----------------------------------------------------------------------------
//! Constructor.
//-----------------------------------------------------------------------------
SharedMemKernel(
std::uint32_t const mult = 2) :
m_mult(mult)
{}
//-----------------------------------------------------------------------------
//! The kernel.
//-----------------------------------------------------------------------------
ALPAKA_NO_HOST_ACC_WARNING
template<
typename TAcc>
ALPAKA_FN_ACC auto operator()(
TAcc const & acc,
std::uint32_t * const puiBlockRetVals,
std::uint32_t const mult2) const
-> void
{
static_assert(
alpaka::dim::Dim<TAcc>::value == 1,
"The SharedMemKernel expects 1-dimensional indices!");
// The number of threads in this block.
std::size_t const blockThreadCount(alpaka::workdiv::getWorkDiv<alpaka::Block, alpaka::Threads>(acc)[0u]);
// Get the extern allocated shared memory.
std::uint32_t * const pBlockShared(acc.template getBlockSharedExternMem<std::uint32_t>());
// Get some shared memory (allocate a second buffer directly afterwards to check for some synchronization bugs).
//std::uint32_t * const pBlockShared1(alpaka::block::shared::allocArr<std::uint32_t, TnumUselessWork::value>());
//std::uint32_t * const pBlockShared2(alpaka::block::shared::allocArr<std::uint32_t, TnumUselessWork::value>());
// Calculate linearized index of the thread in the block.
std::size_t const blockThreadIdx1d(alpaka::idx::getIdx<alpaka::Block, alpaka::Threads>(acc)[0u]);
// Fill the shared block with the thread ids [1+X, 2+X, 3+X, ..., #Threads+X].
std::uint32_t iSum1(static_cast<std::uint32_t>(blockThreadIdx1d+1));
for(std::uint32_t i(0); i<TnumUselessWork::value; ++i)
{
iSum1 += i;
}
pBlockShared[blockThreadIdx1d] = iSum1;
// Synchronize all threads because now we are writing to the memory again but inverse.
alpaka::block::sync::syncBlockThreads(acc);
// Do something useless.
std::uint32_t iSum2(static_cast<std::uint32_t>(blockThreadIdx1d));
for(std::uint32_t i(0); i<TnumUselessWork::value; ++i)
{
iSum2 -= i;
}
// Add the inverse so that every cell is filled with [#Threads, #Threads, ..., #Threads].
pBlockShared[(blockThreadCount-1)-blockThreadIdx1d] += iSum2;
// Synchronize all threads again.
alpaka::block::sync::syncBlockThreads(acc);
// Now add up all the cells atomically and write the result to cell 0 of the shared memory.
if(blockThreadIdx1d > 0)
{
alpaka::atomic::atomicOp<alpaka::atomic::op::Add>(acc, &pBlockShared[0], pBlockShared[blockThreadIdx1d]);
}
alpaka::block::sync::syncBlockThreads(acc);
// Only master writes result to global memory.
if(blockThreadIdx1d==0)
{
// Calculate linearized block id.
std::size_t const blockIdx(alpaka::idx::getIdx<alpaka::Grid, alpaka::Blocks>(acc)[0u]);
puiBlockRetVals[blockIdx] = pBlockShared[0] * m_mult * mult2;
}
}
public:
std::uint32_t const m_mult;
};
namespace alpaka
{
namespace kernel
{
namespace traits
{
//#############################################################################
//! The trait for getting the size of the block shared extern memory for a kernel.
//#############################################################################
template<
typename TnumUselessWork,
typename TAcc>
struct BlockSharedExternMemSizeBytes<
SharedMemKernel<TnumUselessWork>,
TAcc>
{
//-----------------------------------------------------------------------------
//! \return The size of the shared memory allocated for a block.
//-----------------------------------------------------------------------------
template<
typename TVec,
typename... TArgs>
ALPAKA_FN_HOST static auto getBlockSharedExternMemSizeBytes(
TVec const & blockElemExtent,
TArgs && ...)
-> std::uint32_t
{
return blockElemExtent.prod() * sizeof(std::uint32_t);
}
};
}
}
}
//#############################################################################
//! Profiles the example kernel and checks the result.
//#############################################################################
template<
typename TnumUselessWork>
struct SharedMemTester
{
template<
typename TAcc,
typename TSize,
typename TVal>
auto operator()(
TSize const numElements,
TVal const mult2)
-> void
{
std::cout << std::endl;
std::cout << "################################################################################" << std::endl;
// Create the kernel function object.
SharedMemKernel<TnumUselessWork> kernel(42);
// Select a device to execute on.
alpaka::dev::Dev<TAcc> devAcc(
alpaka::dev::DevMan<TAcc>::getDevByIdx(0));
// Get a stream on this device.
alpaka::integ::Stream<alpaka::dev::Dev<TAcc>> stream(devAcc);
// Set the grid blocks extent.
alpaka::workdiv::WorkDivMembers<alpaka::dim::DimInt<1u>, TSize> const workDiv(
alpaka::workdiv::getValidWorkDiv<TAcc>(
devAcc,
numElements,
static_cast<TSize>(1u),
false,
alpaka::workdiv::GridBlockExtentSubDivRestrictions::Unrestricted));
std::cout
<< "SharedMemTester("
<< " accelerator: " << alpaka::acc::getAccName<TAcc>()
<< ", kernel: " << typeid(kernel).name()
<< ", workDiv: " << workDiv
<< ")" << std::endl;
TSize const gridBlocksCount(
alpaka::workdiv::getWorkDiv<alpaka::Grid, alpaka::Blocks>(workDiv)[0u]);
TSize const blockThreadCount(
alpaka::workdiv::getWorkDiv<alpaka::Block, alpaka::Threads>(workDiv)[0u]);
// An array for the return values calculated by the blocks.
std::vector<TVal> blockRetVals(gridBlocksCount, static_cast<TVal>(0));
// Allocate accelerator buffers and copy.
TSize const resultElemCount(gridBlocksCount);
auto blockRetValsAcc(alpaka::mem::buf::alloc<TVal, TSize>(devAcc, resultElemCount));
alpaka::mem::view::copy(stream, blockRetValsAcc, blockRetVals, resultElemCount);
// Create the executor task.
auto const exec(alpaka::exec::create<TAcc>(
workDiv,
kernel,
alpaka::mem::view::getPtrNative(blockRetValsAcc),
mult2));
// Profile the kernel execution.
std::cout << "Execution time: "
<< alpaka::integ::measureKernelRunTimeMs(
stream,
exec)
<< " ms"
<< std::endl;
// Copy back the result.
alpaka::mem::view::copy(stream, blockRetVals, blockRetValsAcc, resultElemCount);
// Wait for the stream to finish the memory operation.
alpaka::wait::wait(stream);
// Assert that the results are correct.
TVal const correctResult(
static_cast<TVal>(blockThreadCount*blockThreadCount)
* kernel.m_mult
* mult2);
bool resultCorrect(true);
for(std::size_t i(0); i<gridBlocksCount; ++i)
{
if(blockRetVals[i] != correctResult)
{
std::cout << "blockRetVals[" << i << "] == " << blockRetVals[i] << " != " << correctResult << std::endl;
resultCorrect = false;
}
}
if(resultCorrect)
{
std::cout << "Execution results correct!" << std::endl;
}
std::cout << "################################################################################" << std::endl;
allResultsCorrect = allResultsCorrect && resultCorrect;
}
public:
bool allResultsCorrect = true;
};
//-----------------------------------------------------------------------------
//! Program entry point.
//-----------------------------------------------------------------------------
auto main()
-> int
{
try
{
std::cout << std::endl;
std::cout << "################################################################################" << std::endl;
std::cout << " alpaka sharedMem test " << std::endl;
std::cout << "################################################################################" << std::endl;
std::cout << std::endl;
// Logs the enabled accelerators.
alpaka::integ::accs::writeEnabledAccs<alpaka::dim::DimInt<1u>, std::uint32_t>(std::cout);
std::cout << std::endl;
using TnumUselessWork = std::integral_constant<std::size_t, 100u>;
std::uint32_t const mult2(5u);
SharedMemTester<TnumUselessWork> sharedMemTester;
// Execute the kernel on all enabled accelerators.
alpaka::core::forEachType<
alpaka::integ::accs::EnabledAccs<alpaka::dim::DimInt<1u>, std::uint32_t>>(
sharedMemTester,
static_cast<std::uint32_t>(512u),
mult2);
return sharedMemTester.allResultsCorrect ? EXIT_SUCCESS : EXIT_FAILURE;
}
catch(std::exception const & e)
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
catch(...)
{
std::cerr << "Unknown Exception" << std::endl;
return EXIT_FAILURE;
}
}
<commit_msg>update example with new shared memory interface<commit_after>/**
* \file
* Copyright 2014-2015 Benjamin Worpitz
*
* This file is part of alpaka.
*
* alpaka is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* alpaka is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with alpaka.
* If not, see <http://www.gnu.org/licenses/>.
*/
#include <alpaka/alpaka.hpp> // alpaka::exec::create
#include <alpaka/integ/MeasureKernelRunTime.hpp> // measureKernelRunTimeMs
#include <alpaka/integ/accs/EnabledAccs.hpp> // EnabledAccs
#include <iostream> // std::cout
#include <typeinfo> // typeid
#include <vector> // std::vector
//#############################################################################
//! A kernel using atomicOp, syncBlockThreads, getBlockSharedExternMem, getIdx, getWorkDiv and global memory to compute a (useless) result.
//! \tparam TAcc The accelerator environment to be executed on.
//! \tparam TnumUselessWork The number of useless calculations done in each kernel execution.
//#############################################################################
template<
typename TnumUselessWork>
class SharedMemKernel
{
public:
//-----------------------------------------------------------------------------
//! Constructor.
//-----------------------------------------------------------------------------
SharedMemKernel(
std::uint32_t const mult = 2) :
m_mult(mult)
{}
//-----------------------------------------------------------------------------
//! The kernel.
//-----------------------------------------------------------------------------
ALPAKA_NO_HOST_ACC_WARNING
template<
typename TAcc>
ALPAKA_FN_ACC auto operator()(
TAcc const & acc,
std::uint32_t * const puiBlockRetVals,
std::uint32_t const mult2) const
-> void
{
static_assert(
alpaka::dim::Dim<TAcc>::value == 1,
"The SharedMemKernel expects 1-dimensional indices!");
// The number of threads in this block.
std::size_t const blockThreadCount(alpaka::workdiv::getWorkDiv<alpaka::Block, alpaka::Threads>(acc)[0u]);
// Get the extern allocated shared memory.
std::uint32_t * const pBlockShared(acc.template getBlockSharedExternMem<std::uint32_t>());
// Get some shared memory (allocate a second buffer directly afterwards to check for some synchronization bugs).
//std::uint32_t * const pBlockShared1(alpaka::block::shared::allocArr<std::uint32_t, TnumUselessWork::value,__COUNTER__>());
//std::uint32_t * const pBlockShared2(alpaka::block::shared::allocArr<std::uint32_t, TnumUselessWork::value,__COUNTER__>());
// Calculate linearized index of the thread in the block.
std::size_t const blockThreadIdx1d(alpaka::idx::getIdx<alpaka::Block, alpaka::Threads>(acc)[0u]);
// Fill the shared block with the thread ids [1+X, 2+X, 3+X, ..., #Threads+X].
std::uint32_t iSum1(static_cast<std::uint32_t>(blockThreadIdx1d+1));
for(std::uint32_t i(0); i<TnumUselessWork::value; ++i)
{
iSum1 += i;
}
pBlockShared[blockThreadIdx1d] = iSum1;
// Synchronize all threads because now we are writing to the memory again but inverse.
alpaka::block::sync::syncBlockThreads(acc);
// Do something useless.
std::uint32_t iSum2(static_cast<std::uint32_t>(blockThreadIdx1d));
for(std::uint32_t i(0); i<TnumUselessWork::value; ++i)
{
iSum2 -= i;
}
// Add the inverse so that every cell is filled with [#Threads, #Threads, ..., #Threads].
pBlockShared[(blockThreadCount-1)-blockThreadIdx1d] += iSum2;
// Synchronize all threads again.
alpaka::block::sync::syncBlockThreads(acc);
// Now add up all the cells atomically and write the result to cell 0 of the shared memory.
if(blockThreadIdx1d > 0)
{
alpaka::atomic::atomicOp<alpaka::atomic::op::Add>(acc, &pBlockShared[0], pBlockShared[blockThreadIdx1d]);
}
alpaka::block::sync::syncBlockThreads(acc);
// Only master writes result to global memory.
if(blockThreadIdx1d==0)
{
// Calculate linearized block id.
std::size_t const blockIdx(alpaka::idx::getIdx<alpaka::Grid, alpaka::Blocks>(acc)[0u]);
puiBlockRetVals[blockIdx] = pBlockShared[0] * m_mult * mult2;
}
}
public:
std::uint32_t const m_mult;
};
namespace alpaka
{
namespace kernel
{
namespace traits
{
//#############################################################################
//! The trait for getting the size of the block shared extern memory for a kernel.
//#############################################################################
template<
typename TnumUselessWork,
typename TAcc>
struct BlockSharedExternMemSizeBytes<
SharedMemKernel<TnumUselessWork>,
TAcc>
{
//-----------------------------------------------------------------------------
//! \return The size of the shared memory allocated for a block.
//-----------------------------------------------------------------------------
template<
typename TVec,
typename... TArgs>
ALPAKA_FN_HOST static auto getBlockSharedExternMemSizeBytes(
TVec const & blockElemExtent,
TArgs && ...)
-> std::uint32_t
{
return blockElemExtent.prod() * sizeof(std::uint32_t);
}
};
}
}
}
//#############################################################################
//! Profiles the example kernel and checks the result.
//#############################################################################
template<
typename TnumUselessWork>
struct SharedMemTester
{
template<
typename TAcc,
typename TSize,
typename TVal>
auto operator()(
TSize const numElements,
TVal const mult2)
-> void
{
std::cout << std::endl;
std::cout << "################################################################################" << std::endl;
// Create the kernel function object.
SharedMemKernel<TnumUselessWork> kernel(42);
// Select a device to execute on.
alpaka::dev::Dev<TAcc> devAcc(
alpaka::dev::DevMan<TAcc>::getDevByIdx(0));
// Get a stream on this device.
alpaka::integ::Stream<alpaka::dev::Dev<TAcc>> stream(devAcc);
// Set the grid blocks extent.
alpaka::workdiv::WorkDivMembers<alpaka::dim::DimInt<1u>, TSize> const workDiv(
alpaka::workdiv::getValidWorkDiv<TAcc>(
devAcc,
numElements,
static_cast<TSize>(1u),
false,
alpaka::workdiv::GridBlockExtentSubDivRestrictions::Unrestricted));
std::cout
<< "SharedMemTester("
<< " accelerator: " << alpaka::acc::getAccName<TAcc>()
<< ", kernel: " << typeid(kernel).name()
<< ", workDiv: " << workDiv
<< ")" << std::endl;
TSize const gridBlocksCount(
alpaka::workdiv::getWorkDiv<alpaka::Grid, alpaka::Blocks>(workDiv)[0u]);
TSize const blockThreadCount(
alpaka::workdiv::getWorkDiv<alpaka::Block, alpaka::Threads>(workDiv)[0u]);
// An array for the return values calculated by the blocks.
std::vector<TVal> blockRetVals(gridBlocksCount, static_cast<TVal>(0));
// Allocate accelerator buffers and copy.
TSize const resultElemCount(gridBlocksCount);
auto blockRetValsAcc(alpaka::mem::buf::alloc<TVal, TSize>(devAcc, resultElemCount));
alpaka::mem::view::copy(stream, blockRetValsAcc, blockRetVals, resultElemCount);
// Create the executor task.
auto const exec(alpaka::exec::create<TAcc>(
workDiv,
kernel,
alpaka::mem::view::getPtrNative(blockRetValsAcc),
mult2));
// Profile the kernel execution.
std::cout << "Execution time: "
<< alpaka::integ::measureKernelRunTimeMs(
stream,
exec)
<< " ms"
<< std::endl;
// Copy back the result.
alpaka::mem::view::copy(stream, blockRetVals, blockRetValsAcc, resultElemCount);
// Wait for the stream to finish the memory operation.
alpaka::wait::wait(stream);
// Assert that the results are correct.
TVal const correctResult(
static_cast<TVal>(blockThreadCount*blockThreadCount)
* kernel.m_mult
* mult2);
bool resultCorrect(true);
for(std::size_t i(0); i<gridBlocksCount; ++i)
{
if(blockRetVals[i] != correctResult)
{
std::cout << "blockRetVals[" << i << "] == " << blockRetVals[i] << " != " << correctResult << std::endl;
resultCorrect = false;
}
}
if(resultCorrect)
{
std::cout << "Execution results correct!" << std::endl;
}
std::cout << "################################################################################" << std::endl;
allResultsCorrect = allResultsCorrect && resultCorrect;
}
public:
bool allResultsCorrect = true;
};
//-----------------------------------------------------------------------------
//! Program entry point.
//-----------------------------------------------------------------------------
auto main()
-> int
{
try
{
std::cout << std::endl;
std::cout << "################################################################################" << std::endl;
std::cout << " alpaka sharedMem test " << std::endl;
std::cout << "################################################################################" << std::endl;
std::cout << std::endl;
// Logs the enabled accelerators.
alpaka::integ::accs::writeEnabledAccs<alpaka::dim::DimInt<1u>, std::uint32_t>(std::cout);
std::cout << std::endl;
using TnumUselessWork = std::integral_constant<std::size_t, 100u>;
std::uint32_t const mult2(5u);
SharedMemTester<TnumUselessWork> sharedMemTester;
// Execute the kernel on all enabled accelerators.
alpaka::core::forEachType<
alpaka::integ::accs::EnabledAccs<alpaka::dim::DimInt<1u>, std::uint32_t>>(
sharedMemTester,
static_cast<std::uint32_t>(512u),
mult2);
return sharedMemTester.allResultsCorrect ? EXIT_SUCCESS : EXIT_FAILURE;
}
catch(std::exception const & e)
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
catch(...)
{
std::cerr << "Unknown Exception" << std::endl;
return EXIT_FAILURE;
}
}
<|endoftext|> |
<commit_before>#include "SoundManager.hpp"
#include "ResourceManager.hpp"
#include <svc/Timer.hpp>
#include <svc/ServiceLocator.hpp>
#include <boost/bind.hpp>
SoundManager::SoundManager()
{
ServiceLocator::timer().callEvery(
sf::seconds(10), boost::bind(&SoundManager::tidy, this));
}
SoundManager::~SoundManager()
{
}
SoundManager::FadedMusic::FadedMusic(
VFileMusic& music, float target, sf::Time fadeDuration):
target(target),
music(&music),
increment(target - music.getVolume() / fadeDuration.asSeconds())
{
music.setVolume(100 - target);
}
SoundManager::FadedMusic& SoundManager::FadedMusic::operator= (FadedMusic&& rhs)
{
target = rhs.target;
increment = rhs.increment;
music = std::move(rhs.music);
return *this;
}
bool SoundManager::FadedMusic::fade()
{
float const newVolume = music->getVolume() + increment;
music->setVolume(newVolume);
if (increment < 0 ? newVolume <= target : newVolume >= target) {
music->setVolume(target);
return true;
}
return false;
}
void SoundManager::playSound(std::string const& name)
{
playSound(resMng<sf::SoundBuffer>().keepLoaded(name));
}
void SoundManager::playSound(ResourceTraits<sf::SoundBuffer>::Ptr const& buf)
{
std::unique_ptr<AutoSound> snd(new AutoSound);
snd->setResource(buf);
snd->play();
playSound(*snd.release());
}
void SoundManager::playSound(AutoSound& sound)
{
m_playingSounds.push_back(&sound);
}
void SoundManager::setBackgroundMusic(std::string const& name, sf::Time fadeDuration)
{
std::unique_ptr<VFileMusic> music(new VFileMusic);
music->stream.open(name);
music->openFromStream(music->stream);
music->play();
setBackgroundMusic(*music.release(), fadeDuration);
}
void SoundManager::setBackgroundMusic(VFileMusic& music, sf::Time fadeDuration)
{
m_previousMusic = FadedMusic(*m_currentMusic.music.release(), 0, fadeDuration);
m_currentMusic = FadedMusic(music, 100, fadeDuration);
}
void SoundManager::tidy()
{
m_playingSounds.erase(
std::remove_if(m_playingSounds.begin(), m_playingSounds.end(),
[](AutoSound& snd) { return snd.getStatus() != sf::Sound::Playing; }),
m_playingSounds.end());
}
void SoundManager::fade()
{
if (!m_previousMusic.music)
return;
m_previousMusic.fade();
if (m_currentMusic.fade())
m_previousMusic.music.reset();
}
<commit_msg>SoundManager: Don't connect to timer (done by main()).<commit_after>#include "SoundManager.hpp"
#include "ResourceManager.hpp"
#include <boost/bind.hpp>
SoundManager::SoundManager()
{
}
SoundManager::~SoundManager()
{
}
SoundManager::FadedMusic::FadedMusic(
VFileMusic& music, float target, sf::Time fadeDuration):
target(target),
music(&music),
increment(target - music.getVolume() / fadeDuration.asSeconds())
{
music.setVolume(100 - target);
}
SoundManager::FadedMusic& SoundManager::FadedMusic::operator= (FadedMusic&& rhs)
{
target = rhs.target;
increment = rhs.increment;
music = std::move(rhs.music);
return *this;
}
bool SoundManager::FadedMusic::fade()
{
float const newVolume = music->getVolume() + increment;
music->setVolume(newVolume);
if (increment < 0 ? newVolume <= target : newVolume >= target) {
music->setVolume(target);
return true;
}
return false;
}
void SoundManager::playSound(std::string const& name)
{
playSound(resMng<sf::SoundBuffer>().keepLoaded(name));
}
void SoundManager::playSound(ResourceTraits<sf::SoundBuffer>::Ptr const& buf)
{
std::unique_ptr<AutoSound> snd(new AutoSound);
snd->setResource(buf);
snd->play();
playSound(*snd.release());
}
void SoundManager::playSound(AutoSound& sound)
{
m_playingSounds.push_back(&sound);
}
void SoundManager::setBackgroundMusic(std::string const& name, sf::Time fadeDuration)
{
std::unique_ptr<VFileMusic> music(new VFileMusic);
music->stream.open(name);
music->openFromStream(music->stream);
music->play();
setBackgroundMusic(*music.release(), fadeDuration);
}
void SoundManager::setBackgroundMusic(VFileMusic& music, sf::Time fadeDuration)
{
m_previousMusic = FadedMusic(*m_currentMusic.music.release(), 0, fadeDuration);
m_currentMusic = FadedMusic(music, 100, fadeDuration);
}
void SoundManager::tidy()
{
m_playingSounds.erase(
std::remove_if(m_playingSounds.begin(), m_playingSounds.end(),
[](AutoSound& snd) { return snd.getStatus() != sf::Sound::Playing; }),
m_playingSounds.end());
}
void SoundManager::fade()
{
if (!m_previousMusic.music)
return;
m_previousMusic.fade();
if (m_currentMusic.fade())
m_previousMusic.music.reset();
}
<|endoftext|> |
<commit_before>#include <stack>
#include <string>
#include <string.h>
using namespace std;
bool IsOp(const char ch)
{
return ch == '+' || ch == '-' || ch == '*' || ch == '/';
}
bool IsEqualOrGreat(char ch1, char ch2)
{
if(ch1 == '+' || ch1 == '-')
{
if(ch2 == '+' || ch2 == '-')
{
return true;
}
return false;
}
return true;
}
int main()
{
const int kInputSize = 1024;
char input[kInputSize];
while(scanf("%s", input) == 1)
{
stack<char> op;
stack<string> prefix;
int input_size = static_cast<int>(strlen(input));
for(int index = input_size - 1; index >= 0; )
{
if(isdigit(input[index]))
{
int begin_index = index - 1;
for(; begin_index >= 0 && isdigit(input[begin_index]); --begin_index);
if(begin_index < 0)
{
prefix.push(string(input, index + 1));
break;
}
else if(begin_index == 0)
{
if(input[0] != '-')
{
prefix.push(string(input + 1, index));
index = 0;
}
else
{
prefix.push(string(input, index + 1));
break;
}
}
else
{
if(IsOp(input[begin_index - 1]) && input[begin_index] == '-')
{
prefix.push(string(input + begin_index, index - begin_index + 1));
index = begin_index - 1;
}
else
{
prefix.push(string(input + begin_index + 1, index - begin_index));
index = begin_index;
}
}
}
else if(IsOp(input[index]))
{
if(op.empty() == true || op.top() == ')' || IsEqualOrGreat(input[index], op.top()))
{
op.push(input[index]);
--index;
}
else
{
prefix.push(string(&op.top(), 1));
op.pop();
continue;
}
}
else
{
if(input[index] == ')')
{
op.push(input[index]);
}
else
{
while(op.top() != ')')
{
prefix.push(string(&op.top(), 1));
op.pop();
}
op.pop();
}
--index;
}
}
while(op.empty() == false)
{
prefix.push(string(&op.top(), 1));
op.pop();
}
while(prefix.empty() == false)
{
printf("%s", prefix.top().data());
prefix.pop();
}
printf("\n");
}
}
<commit_msg>docs: encapsaulate function<commit_after>#include <stack>
#include <string>
#include <string.h>
using namespace std;
bool IsOp(const char ch)
{
return ch == '+' || ch == '-' || ch == '*' || ch == '/';
}
bool IsOp(const string &str)
{
return str == "+" || str == "-" || str == "*" || str == "/";
}
bool IsEqualOrGreat(char ch1, char ch2)
{
if(ch1 == '+' || ch1 == '-')
{
if(ch2 == '+' || ch2 == '-')
{
return true;
}
return false;
}
return true;
}
void CalculatePrefix(stack<string> &prefix)
{
stack<int> cal;
while(prefix.empty() == false)
{
string str = prefix.top();
prefix.pop();
if(IsOp(str) == false)
{
cal.push(atoi(str.data()));
}
else
{
int lhs = cal.top();
cal.pop();
int rhs = cal.top();
cal.pop();
switch(*str.data())
{
case '+':
lhs += rhs;
break;
case '-':
lhs -= rhs;
break;
case '*':
lhs *= rhs;
break;
case '/':
lhs /= rhs;
}
cal.push(lhs);
}
}
printf("\nResult is: %d\n", cal.top());
}
void InfixToPrefix(const char *infix)
{
stack<char> op;
stack<string> prefix;
int input_size = static_cast<int>(strlen(infix));
for(int index = input_size - 1; index >= 0; )
{
if(isdigit(infix[index]))
{
int begin_index = index - 1;
for(; begin_index >= 0 && isdigit(infix[begin_index]); --begin_index);
if(begin_index < 0)
{
prefix.push(string(infix, index + 1));
break;
}
else if(begin_index == 0)
{
if(infix[0] != '-')
{
prefix.push(string(infix + 1, index));
index = 0;
}
else
{
prefix.push(string(infix, index + 1));
break;
}
}
else
{
if(IsOp(infix[begin_index - 1]) && infix[begin_index] == '-')
{
prefix.push(string(infix + begin_index, index - begin_index + 1));
index = begin_index - 1;
}
else
{
prefix.push(string(infix + begin_index + 1, index - begin_index));
index = begin_index;
}
}
}
else if(IsOp(infix[index]))
{
if(op.empty() == true || op.top() == ')' || IsEqualOrGreat(infix[index], op.top()))
{
op.push(infix[index]);
--index;
}
else
{
prefix.push(string(&op.top(), 1));
op.pop();
continue;
}
}
else
{
if(infix[index] == ')')
{
op.push(infix[index]);
}
else
{
while(op.top() != ')')
{
prefix.push(string(&op.top(), 1));
op.pop();
}
op.pop();
}
--index;
}
}
while(op.empty() == false)
{
prefix.push(string(&op.top(), 1));
op.pop();
}
stack<string> temp;
printf("Prefix is: ");
while(prefix.empty() == false)
{
temp.push(prefix.top());
printf("%s,", prefix.top().data());
prefix.pop();
}
CalculatePrefix(temp);
}
int main()
{
const int kInputSize = 1024;
char infix[kInputSize];
while(scanf("%s", infix) == 1)
{
InfixToPrefix(infix);
}
}
/*
-23+((4+56)*78)+-5+6*-78+123
**********************************
Prefix is: +,+,+,+,-23,*,+,4,56,78,-5,*,6,-78,123,
Result is: 4307
*/
<|endoftext|> |
<commit_before>/*
* writer.cpp
*
*/
#include "writer.h"
#include "logger_factory.h"
#include "plugin_factory.h"
#include "timer_factory.h"
#include "util.h"
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <fstream>
#include "cache.h"
#include "csv.h"
#include "grib.h"
#include "neons.h"
#include "querydata.h"
#include "radon.h"
using namespace himan::plugin;
writer::writer() : itsWriteOptions()
{
itsLogger = std::unique_ptr<logger>(logger_factory::Instance()->GetLog("writer"));
}
bool writer::CreateFile(info& theInfo, std::shared_ptr<const plugin_configuration> conf, std::string& theOutputFile)
{
namespace fs = boost::filesystem;
itsWriteOptions.configuration = conf;
if (theOutputFile.empty())
{
theOutputFile = util::MakeFileName(itsWriteOptions.configuration->FileWriteOption(), theInfo);
}
fs::path pathname(theOutputFile);
if (!pathname.parent_path().empty() && !fs::is_directory(pathname.parent_path()))
{
fs::create_directories(pathname.parent_path());
}
switch (itsWriteOptions.configuration->OutputFileType())
{
case kGRIB:
case kGRIB1:
case kGRIB2:
{
auto theGribWriter = GET_PLUGIN(grib);
theOutputFile += ".grib";
if (itsWriteOptions.configuration->OutputFileType() == kGRIB2)
{
theOutputFile += "2";
}
if (itsWriteOptions.configuration->FileCompression() == kGZIP)
{
theOutputFile += ".gz";
}
else if (itsWriteOptions.configuration->FileCompression() == kBZIP2)
{
theOutputFile += ".bz2";
}
theGribWriter->WriteOptions(itsWriteOptions);
return
theGribWriter->ToFile(theInfo, theOutputFile,
(itsWriteOptions.configuration->FileWriteOption() == kSingleFile) ? true : false);
break;
}
case kQueryData:
{
if (theInfo.Grid()->Type() == kReducedGaussian)
{
itsLogger->Error("Reduced gaussian grid cannot be written to querydata");
return false;
}
auto theWriter = GET_PLUGIN(querydata);
theWriter->WriteOptions(itsWriteOptions);
theOutputFile += ".fqd";
return theWriter->ToFile(theInfo, theOutputFile);
break;
}
case kNetCDF:
break;
case kCSV:
{
auto theWriter = GET_PLUGIN(csv);
theWriter->WriteOptions(itsWriteOptions);
theOutputFile += ".csv";
return theWriter->ToFile(theInfo, theOutputFile);
break;
}
// Must have this or compiler complains
default:
throw std::runtime_error(ClassName() + ": Invalid file type: " +
HPFileTypeToString.at(itsWriteOptions.configuration->OutputFileType()));
break;
}
return false;
}
bool writer::ToFile(info& theInfo, std::shared_ptr<const plugin_configuration> conf, const std::string& theOriginalOutputFile)
{
std::unique_ptr<himan::timer> t = std::unique_ptr<himan::timer>(timer_factory::Instance()->GetTimer());
if (conf->StatisticsEnabled())
{
t->Start();
}
bool ret = true;
std::string theOutputFile = theOriginalOutputFile; // This is modified
if (conf->FileWriteOption() != kCacheOnly)
{
// When writing previ to database, no file is needed. In all other cases we have to create
// a file.
if (theInfo.Producer().Class() == kGridClass ||
(theInfo.Producer().Class() == kPreviClass && conf->FileWriteOption() != kDatabase))
{
ret = CreateFile(theInfo, conf, theOutputFile);
}
if (ret && conf->FileWriteOption() == kDatabase)
{
HPDatabaseType dbtype = conf->DatabaseType();
if (dbtype == kNeons || dbtype == kNeonsAndRadon)
{
auto n = GET_PLUGIN(neons);
ret = n->Save(theInfo, theOutputFile);
if (!ret)
{
itsLogger->Warning("Saving file information to neons failed");
}
}
if (dbtype == kRadon || dbtype == kNeonsAndRadon)
{
auto r = GET_PLUGIN(radon);
// Try to save file information to radon
try
{
ret = r->Save(theInfo, theOutputFile);
if (!ret)
{
itsLogger->Error("Writing to radon failed");
}
}
catch (const std::exception& e)
{
itsLogger->Error("Writing to radon failed: " + std::string(e.what()));
}
catch (...)
{
itsLogger->Error("Writing to radon failed: general exception");
}
}
}
}
if (conf->UseCache())
{
std::shared_ptr<cache> c = GET_PLUGIN(cache);
c->Insert(theInfo);
}
if (conf->StatisticsEnabled())
{
t->Stop();
conf->Statistics()->AddToWritingTime(t->GetTime());
}
return ret;
}
write_options writer::WriteOptions() const { return itsWriteOptions; }
void writer::WriteOptions(const write_options& theWriteOptions) { itsWriteOptions = theWriteOptions; }
<commit_msg>Data that is not written to file is pinned to cache.<commit_after>/*
* writer.cpp
*
*/
#include "writer.h"
#include "logger_factory.h"
#include "plugin_factory.h"
#include "timer_factory.h"
#include "util.h"
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <fstream>
#include "cache.h"
#include "csv.h"
#include "grib.h"
#include "neons.h"
#include "querydata.h"
#include "radon.h"
using namespace himan::plugin;
writer::writer() : itsWriteOptions()
{
itsLogger = std::unique_ptr<logger>(logger_factory::Instance()->GetLog("writer"));
}
bool writer::CreateFile(info& theInfo, std::shared_ptr<const plugin_configuration> conf, std::string& theOutputFile)
{
namespace fs = boost::filesystem;
itsWriteOptions.configuration = conf;
if (theOutputFile.empty())
{
theOutputFile = util::MakeFileName(itsWriteOptions.configuration->FileWriteOption(), theInfo);
}
fs::path pathname(theOutputFile);
if (!pathname.parent_path().empty() && !fs::is_directory(pathname.parent_path()))
{
fs::create_directories(pathname.parent_path());
}
switch (itsWriteOptions.configuration->OutputFileType())
{
case kGRIB:
case kGRIB1:
case kGRIB2:
{
auto theGribWriter = GET_PLUGIN(grib);
theOutputFile += ".grib";
if (itsWriteOptions.configuration->OutputFileType() == kGRIB2)
{
theOutputFile += "2";
}
if (itsWriteOptions.configuration->FileCompression() == kGZIP)
{
theOutputFile += ".gz";
}
else if (itsWriteOptions.configuration->FileCompression() == kBZIP2)
{
theOutputFile += ".bz2";
}
theGribWriter->WriteOptions(itsWriteOptions);
return theGribWriter->ToFile(
theInfo, theOutputFile,
(itsWriteOptions.configuration->FileWriteOption() == kSingleFile) ? true : false);
break;
}
case kQueryData:
{
if (theInfo.Grid()->Type() == kReducedGaussian)
{
itsLogger->Error("Reduced gaussian grid cannot be written to querydata");
return false;
}
auto theWriter = GET_PLUGIN(querydata);
theWriter->WriteOptions(itsWriteOptions);
theOutputFile += ".fqd";
return theWriter->ToFile(theInfo, theOutputFile);
break;
}
case kNetCDF:
break;
case kCSV:
{
auto theWriter = GET_PLUGIN(csv);
theWriter->WriteOptions(itsWriteOptions);
theOutputFile += ".csv";
return theWriter->ToFile(theInfo, theOutputFile);
break;
}
// Must have this or compiler complains
default:
throw std::runtime_error(ClassName() + ": Invalid file type: " +
HPFileTypeToString.at(itsWriteOptions.configuration->OutputFileType()));
break;
}
return false;
}
bool writer::ToFile(info& theInfo, std::shared_ptr<const plugin_configuration> conf,
const std::string& theOriginalOutputFile)
{
std::unique_ptr<himan::timer> t = std::unique_ptr<himan::timer>(timer_factory::Instance()->GetTimer());
if (conf->StatisticsEnabled())
{
t->Start();
}
bool ret = true;
std::string theOutputFile = theOriginalOutputFile; // This is modified
if (conf->FileWriteOption() != kCacheOnly)
{
// When writing previ to database, no file is needed. In all other cases we have to create
// a file.
if (theInfo.Producer().Class() == kGridClass ||
(theInfo.Producer().Class() == kPreviClass && conf->FileWriteOption() != kDatabase))
{
ret = CreateFile(theInfo, conf, theOutputFile);
}
if (ret && conf->FileWriteOption() == kDatabase)
{
HPDatabaseType dbtype = conf->DatabaseType();
if (dbtype == kNeons || dbtype == kNeonsAndRadon)
{
auto n = GET_PLUGIN(neons);
ret = n->Save(theInfo, theOutputFile);
if (!ret)
{
itsLogger->Warning("Saving file information to neons failed");
}
}
if (dbtype == kRadon || dbtype == kNeonsAndRadon)
{
auto r = GET_PLUGIN(radon);
// Try to save file information to radon
try
{
ret = r->Save(theInfo, theOutputFile);
if (!ret)
{
itsLogger->Error("Writing to radon failed");
}
}
catch (const std::exception& e)
{
itsLogger->Error("Writing to radon failed: " + std::string(e.what()));
}
catch (...)
{
itsLogger->Error("Writing to radon failed: general exception");
}
}
}
}
if (conf->UseCache())
{
std::shared_ptr<cache> c = GET_PLUGIN(cache);
// Pin those items that are not written to file at all
// so they can't be removed from cache if cache size is limited
c->Insert(theInfo, (conf->FileWriteOption() == kCacheOnly));
}
if (conf->StatisticsEnabled())
{
t->Stop();
conf->Statistics()->AddToWritingTime(t->GetTime());
}
return ret;
}
write_options writer::WriteOptions() const { return itsWriteOptions; }
void writer::WriteOptions(const write_options& theWriteOptions) { itsWriteOptions = theWriteOptions; }
<|endoftext|> |
<commit_before>#include "svgInterpolation.h"
//--------------------------------------------------------------
void svgInterpolation::setup(){
selectedId = -1;
ofDirectory dir;
shapeSize = 500;
ofLogNotice("svgInterpolation") << "load SVG from formes_interpol";
dir.listDir("formes_interpol/");
dir.sort(); // in linux the file system doesn't return file lists ordered in alphabetical order
ofLogNotice("svgInterpolation") << "found " << (int)dir.size() << " images to load.";
for(int i = 0; i < (int)dir.size(); i++){
// if ( i == 0 ) cout << "load : " << dir.getPath(i) << endl;
ofxSVG svg;
svg.load(dir.getPath(i));
ofLogNotice("svgInterpolation") << "loading : " << dir.getPath(i);
ofPolyline myLine;
ofVec2f ptMin = ofVec2f(1000.,1000.), ptMax = ofVec2f(-1000.,-1000.);
ofLogVerbose("svgInterpolation") << "shape " << i << " has " << svg.getNumPath() << " paths";
for (int j = 0; j < svg.getNumPath(); j++){
ofPath p = svg.getPathAt(j);
// svg defaults to non zero winding which doesn't look so good as contours
p.setPolyWindingMode(OF_POLY_WINDING_ODD);
vector<ofPolyline>& lines = const_cast<vector<ofPolyline>&>(p.getOutline());
for(int k=0;k<(int)lines.size();k++){
ofPolyline line=lines[k];
for(int n=0;n<line.size();n++){
ofVec3f pt = line[n];
pt/=40;
pt-=1.;
ptMin.x = std::min(pt.x, ptMin.x);
ptMin.y = std::min(pt.y, ptMin.y);
ptMax.x = std::max(pt.x, ptMax.x);
ptMax.y = std::max(pt.y, ptMax.y);
myLine.addVertex(pt);
}
}
}
// myLine.close();
lines.push_back(myLine.getResampledByCount(shapeSize));
ofLogVerbose("svgInterpolation") << "min : " << ptMin.x << " " << ptMin.y;
ofLogVerbose("svgInterpolation") << "max : " << ptMax.x << " " << ptMax.y;
}
ofLogNotice("svgInterpolation") << "load SVG from formes_statiques" << endl;
dir.listDir("formes_statiques/");
dir.sort(); // in linux the file system doesn't return file lists ordered in alphabetical order
for(int i = 0; i < (int)dir.size(); i++){
ofxSVG svg;
svg.load(dir.getPath(i));
ofLogNotice("svgInterpolation") << "load : " << dir.getPath(i) << "with " << svg.getNumPath() << " paths" << endl;
ofPolyline myLine;
ofVec2f ptMin = ofVec2f(1000.,1000.), ptMax = ofVec2f(-1000.,-1000.);
for (int i = 0; i < svg.getNumPath(); i++){
ofPath p = svg.getPathAt(i);
// svg defaults to non zero winding which doesn't look so good as contours
p.setPolyWindingMode(OF_POLY_WINDING_ODD);
vector<ofPolyline>& lines = const_cast<vector<ofPolyline>&>(p.getOutline());
ofLogNotice("svgInterpolation") << "path " << i << " has " << lines.size() << " points " << endl;
for(int k=0;k<(int)lines.size();k++){
ofPolyline line=lines[k];
for(int n=0;n<line.size();n++){
ofVec3f pt = line[n];
ptMin.x = std::min(pt.x, ptMin.x);
ptMin.y = std::min(pt.y, ptMin.y);
ptMax.x = std::max(pt.x, ptMax.x);
ptMax.y = std::max(pt.y, ptMax.y);
myLine.addVertex(pt);
}
}
ofLogVerbose("svgInterpolation") << "normalize shape" << endl;
ofVec2f offset, amplitude;
float scale;
offset = (ptMin + ptMax) /2.;
amplitude = (ptMax - ptMin)/2;
scale = max(amplitude.x,amplitude.y);
for (auto & pt : myLine){
pt-=offset;
pt/=scale;
ofLogVerbose("svgInterpolation") << pt.x << ";" << pt.y << endl;
}
// myLine.close();
static_lines.push_back(myLine.getResampledByCount(shapeSize));
}
}
}
//--------------------------------------------------------------
bool svgInterpolation::updateBool(){
return multiInterpolation() || draw_static();
}
//--------------------------------------------------------------
void svgInterpolation::draw(){
ofDrawBitmapString(ofToString(ofGetFrameRate()),20,20);
ofPushMatrix();
ofTranslate(ofGetWidth() / 2., ofGetHeight() / 2.);
ofScale(ofGetHeight() / 3., ofGetHeight() / 3., 1.);
ofNoFill();
ofBeginShape();
for (int j = 0; j < interpolatedLine.size(); j++){
ofVertex(interpolatedLine[j]);
}
if ( interpolatedLine.size() ) ofVertex(interpolatedLine[0]);
ofEndShape();
ofPopMatrix();
}
bool svgInterpolation::multiInterpolation(){
if ( !dirtyFlag ) return false;
interpolatedLine.clear();
/*
ofLogNotice("svgInterpolation") << "nombre de formes chargées : " << lines.size() << endl;
ofLogNotice("svgInterpolation") << "taille de coeff : " << coeff.size() << endl;
*/
for (int i = 0; i < shapeSize; i++){
ofVec3f pt;
for (int j = 0; j < min(lines.size(), coeff.size()); j++){
pt += coeff[j] * lines[j][i]; // [0] assumes that there is only one line on each ofPolyLine
}
interpolatedLine.addVertex(pt);
}
ofVec3f ptMin(999999. ,999999.);
ofVec3f ptMax(-999999.,-999999.);
// get the bounding box of the shape
for ( ofVec3f pt : interpolatedLine ){
ptMin.x = min(pt.x,ptMin.x);
ptMin.y = min(pt.y,ptMin.y);
ptMax.x = max(pt.x,ptMax.x);
ptMax.y = max(pt.y,ptMax.y);
}
ofLogVerbose("svgInterpolation") << "ptMin : " << ptMin.x << " \t " << ptMin.y << endl;
ofLogVerbose("svgInterpolation") << "ptMax : " << ptMax.x << " \t " << ptMax.y << endl;
ofVec3f offset, diff;
float scale;
// scale and translate shape to center on (0.0;0.0)))))))
offset = (ptMax + ptMin)/2.;
diff = ptMax - ptMin;
scale = max(diff.x,diff.y) / 2.;
ofLogVerbose("svgInterpolation") << "scale : " << scale << endl;
ofLogVerbose("svgInterpolation") << "offset : " << offset << endl;
ofLogVerbose("svgInterpolation") << "normalized line : " << endl;
int i(0);
for ( ofVec3f& pt : interpolatedLine ){
pt -= offset;
pt /= scale;
ofLogVerbose("svgInterpolation") << i++ << " : " << pt.x << " \t " << pt.y << endl;
}
// interpolatedLine = interpolatedLine.getResampledByCount(shapeSize);
ofLogVerbose("svgInterpolation") << "interpolatedLine.size() : " << interpolatedLine.size() << endl;
dirtyFlag=false;
return true;
}
bool svgInterpolation::draw_static(){
if ( selectedId < 0 ) return false;
if ( selectedId > (static_lines.size() - 1)) return false;
interpolatedLine.clear();
interpolatedLine = static_lines[selectedId];
selectedId = -1;
return true;
}
<commit_msg>change verbosity level<commit_after>#include "svgInterpolation.h"
//--------------------------------------------------------------
void svgInterpolation::setup(){
selectedId = -1;
ofDirectory dir;
shapeSize = 500;
ofLogNotice("svgInterpolation") << "load SVG from formes_interpol";
dir.listDir("formes_interpol/");
dir.sort(); // in linux the file system doesn't return file lists ordered in alphabetical order
ofLogNotice("svgInterpolation") << "found " << (int)dir.size() << " images to load.";
for(int i = 0; i < (int)dir.size(); i++){
// if ( i == 0 ) cout << "load : " << dir.getPath(i) << endl;
ofxSVG svg;
svg.load(dir.getPath(i));
ofLogNotice("svgInterpolation") << "loading : " << dir.getPath(i);
ofPolyline myLine;
ofVec2f ptMin = ofVec2f(1000.,1000.), ptMax = ofVec2f(-1000.,-1000.);
ofLogNotice("svgInterpolation") << "shape " << i << " has " << svg.getNumPath() << " paths";
for (int j = 0; j < svg.getNumPath(); j++){
ofPath p = svg.getPathAt(j);
// svg defaults to non zero winding which doesn't look so good as contours
p.setPolyWindingMode(OF_POLY_WINDING_ODD);
vector<ofPolyline>& lines = const_cast<vector<ofPolyline>&>(p.getOutline());
for(int k=0;k<(int)lines.size();k++){
ofPolyline line=lines[k];
for(int n=0;n<line.size();n++){
ofVec3f pt = line[n];
pt/=40;
pt-=1.;
ptMin.x = std::min(pt.x, ptMin.x);
ptMin.y = std::min(pt.y, ptMin.y);
ptMax.x = std::max(pt.x, ptMax.x);
ptMax.y = std::max(pt.y, ptMax.y);
myLine.addVertex(pt);
}
}
}
// myLine.close();
lines.push_back(myLine.getResampledByCount(shapeSize));
ofLogVerbose("svgInterpolation") << "min : " << ptMin.x << " " << ptMin.y;
ofLogVerbose("svgInterpolation") << "max : " << ptMax.x << " " << ptMax.y;
}
ofLogNotice("svgInterpolation") << "load SVG from formes_statiques" << endl;
dir.listDir("formes_statiques/");
dir.sort(); // in linux the file system doesn't return file lists ordered in alphabetical order
for(int i = 0; i < (int)dir.size(); i++){
ofxSVG svg;
svg.load(dir.getPath(i));
ofLogNotice("svgInterpolation") << "load : " << dir.getPath(i) << "with " << svg.getNumPath() << " paths" << endl;
ofPolyline myLine;
ofVec2f ptMin = ofVec2f(1000.,1000.), ptMax = ofVec2f(-1000.,-1000.);
for (int i = 0; i < svg.getNumPath(); i++){
ofPath p = svg.getPathAt(i);
// svg defaults to non zero winding which doesn't look so good as contours
p.setPolyWindingMode(OF_POLY_WINDING_ODD);
vector<ofPolyline>& lines = const_cast<vector<ofPolyline>&>(p.getOutline());
ofLogNotice("svgInterpolation") << "path " << i << " has " << lines.size() << " points " << endl;
for(int k=0;k<(int)lines.size();k++){
ofPolyline line=lines[k];
for(int n=0;n<line.size();n++){
ofVec3f pt = line[n];
ptMin.x = std::min(pt.x, ptMin.x);
ptMin.y = std::min(pt.y, ptMin.y);
ptMax.x = std::max(pt.x, ptMax.x);
ptMax.y = std::max(pt.y, ptMax.y);
myLine.addVertex(pt);
}
}
ofLogVerbose("svgInterpolation") << "normalize shape" << endl;
ofVec2f offset, amplitude;
float scale;
offset = (ptMin + ptMax) /2.;
amplitude = (ptMax - ptMin)/2;
scale = max(amplitude.x,amplitude.y);
for (auto & pt : myLine){
pt-=offset;
pt/=scale;
ofLogVerbose("svgInterpolation") << pt.x << ";" << pt.y << endl;
}
// myLine.close();
static_lines.push_back(myLine.getResampledByCount(shapeSize));
}
}
}
//--------------------------------------------------------------
bool svgInterpolation::updateBool(){
return multiInterpolation() || draw_static();
}
//--------------------------------------------------------------
void svgInterpolation::draw(){
ofDrawBitmapString(ofToString(ofGetFrameRate()),20,20);
ofPushMatrix();
ofTranslate(ofGetWidth() / 2., ofGetHeight() / 2.);
ofScale(ofGetHeight() / 3., ofGetHeight() / 3., 1.);
ofNoFill();
ofBeginShape();
for (int j = 0; j < interpolatedLine.size(); j++){
ofVertex(interpolatedLine[j]);
}
if ( interpolatedLine.size() ) ofVertex(interpolatedLine[0]);
ofEndShape();
ofPopMatrix();
}
bool svgInterpolation::multiInterpolation(){
if ( !dirtyFlag ) return false;
interpolatedLine.clear();
/*
ofLogNotice("svgInterpolation") << "nombre de formes chargées : " << lines.size() << endl;
ofLogNotice("svgInterpolation") << "taille de coeff : " << coeff.size() << endl;
*/
for (int i = 0; i < shapeSize; i++){
ofVec3f pt;
for (int j = 0; j < min(lines.size(), coeff.size()); j++){
pt += coeff[j] * lines[j][i]; // [0] assumes that there is only one line on each ofPolyLine
}
interpolatedLine.addVertex(pt);
}
ofVec3f ptMin(999999. ,999999.);
ofVec3f ptMax(-999999.,-999999.);
// get the bounding box of the shape
for ( ofVec3f pt : interpolatedLine ){
ptMin.x = min(pt.x,ptMin.x);
ptMin.y = min(pt.y,ptMin.y);
ptMax.x = max(pt.x,ptMax.x);
ptMax.y = max(pt.y,ptMax.y);
}
ofLogVerbose("svgInterpolation") << "ptMin : " << ptMin.x << " \t " << ptMin.y << endl;
ofLogVerbose("svgInterpolation") << "ptMax : " << ptMax.x << " \t " << ptMax.y << endl;
ofVec3f offset, diff;
float scale;
// scale and translate shape to center on (0.0;0.0)))))))
offset = (ptMax + ptMin)/2.;
diff = ptMax - ptMin;
scale = max(diff.x,diff.y) / 2.;
ofLogVerbose("svgInterpolation") << "scale : " << scale << endl;
ofLogVerbose("svgInterpolation") << "offset : " << offset << endl;
ofLogVerbose("svgInterpolation") << "normalized line : " << endl;
int i(0);
for ( ofVec3f& pt : interpolatedLine ){
pt -= offset;
pt /= scale;
ofLogVerbose("svgInterpolation") << i++ << " : " << pt.x << " \t " << pt.y << endl;
}
// interpolatedLine = interpolatedLine.getResampledByCount(shapeSize);
ofLogVerbose("svgInterpolation") << "interpolatedLine.size() : " << interpolatedLine.size() << endl;
dirtyFlag=false;
return true;
}
bool svgInterpolation::draw_static(){
if ( selectedId < 0 ) return false;
if ( selectedId > (static_lines.size() - 1)) return false;
interpolatedLine.clear();
interpolatedLine = static_lines[selectedId];
selectedId = -1;
return true;
}
<|endoftext|> |
<commit_before><commit_msg>error C2061: syntax error : identifier 'uint64_t'<commit_after><|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Version: MPL 1.1 / GPLv3+ / LGPLv3+
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Initial Developer of the Original Code is
* Caolán McNamara <caolanm@redhat.com> (Red Hat, Inc.)
* Portions created by the Initial Developer are Copyright (C) 2011 the
* Initial Developer. All Rights Reserved.
*
* Contributor(s): Caolán McNamara <caolanm@redhat.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 3 or later (the "GPLv3+"), or
* the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
* in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
* instead of those above.
*/
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <comphelper/processfactory.hxx>
#include <cppuhelper/bootstrap.hxx>
#include <osl/file.hxx>
#include <ucbhelper/configurationkeys.hxx>
#include <ucbhelper/contentbroker.hxx>
#include <vcl/builder.hxx>
#include <vcl/dialog.hxx>
#include <vcl/svapp.hxx>
class UIPreviewApp : public Application
{
public:
virtual int Main();
};
using namespace com::sun::star;
int UIPreviewApp::Main()
{
std::vector<rtl::OUString> uifiles;
for (sal_uInt16 i = 0; i < GetCommandLineParamCount(); ++i)
{
rtl::OUString aFileUrl;
osl::File::getFileURLFromSystemPath(GetCommandLineParam(i), aFileUrl);
uifiles.push_back(aFileUrl);
}
if (uifiles.empty())
{
fprintf(stderr, "Usage: ui-previewer file.ui\n");
return EXIT_FAILURE;
}
uno::Reference<uno::XComponentContext> xContext =
cppu::defaultBootstrap_InitialComponentContext();
uno::Reference<lang::XMultiComponentFactory> xFactory =
xContext->getServiceManager();
uno::Reference<lang::XMultiServiceFactory> xSFactory =
uno::Reference<lang::XMultiServiceFactory> (xFactory, uno::UNO_QUERY_THROW);
comphelper::setProcessServiceFactory(xSFactory);
// Create UCB.
uno::Sequence< uno::Any > aArgs(2);
aArgs[ 0 ] <<= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(UCB_CONFIGURATION_KEY1_LOCAL));
aArgs[ 1 ] <<= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(UCB_CONFIGURATION_KEY2_OFFICE));
::ucbhelper::ContentBroker::initialize(xSFactory, aArgs);
try
{
VclBuilder aBuilder(NULL, uifiles[0]);
Window *pWindow = aBuilder.get_widget_root();
Dialog *pDialog = dynamic_cast<Dialog*>(pWindow);
if (pDialog)
{
pDialog->SetText(rtl::OUString("LibreOffice ui-previewer"));
pDialog->SetStyle(pDialog->GetStyle()|WB_CLOSEABLE);
pDialog->Execute();
}
else
{
fprintf(stderr, "to-do: no toplevel dialog, make one\n");
}
}
catch (const uno::Exception &e)
{
fprintf(stderr, "fatal error: %s\n", rtl::OUStringToOString(e.Message, osl_getThreadTextEncoding()).getStr());
}
return false;
::ucbhelper::ContentBroker::deinitialize();
return EXIT_SUCCESS;
}
UIPreviewApp aApp;
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>allow previewing trees without toplevel windows<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Version: MPL 1.1 / GPLv3+ / LGPLv3+
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Initial Developer of the Original Code is
* Caolán McNamara <caolanm@redhat.com> (Red Hat, Inc.)
* Portions created by the Initial Developer are Copyright (C) 2011 the
* Initial Developer. All Rights Reserved.
*
* Contributor(s): Caolán McNamara <caolanm@redhat.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 3 or later (the "GPLv3+"), or
* the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
* in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
* instead of those above.
*/
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <comphelper/processfactory.hxx>
#include <cppuhelper/bootstrap.hxx>
#include <osl/file.hxx>
#include <ucbhelper/configurationkeys.hxx>
#include <ucbhelper/contentbroker.hxx>
#include <vcl/builder.hxx>
#include <vcl/dialog.hxx>
#include <vcl/svapp.hxx>
class UIPreviewApp : public Application
{
public:
virtual int Main();
};
using namespace com::sun::star;
int UIPreviewApp::Main()
{
std::vector<rtl::OUString> uifiles;
for (sal_uInt16 i = 0; i < GetCommandLineParamCount(); ++i)
{
rtl::OUString aFileUrl;
osl::File::getFileURLFromSystemPath(GetCommandLineParam(i), aFileUrl);
uifiles.push_back(aFileUrl);
}
if (uifiles.empty())
{
fprintf(stderr, "Usage: ui-previewer file.ui\n");
return EXIT_FAILURE;
}
uno::Reference<uno::XComponentContext> xContext =
cppu::defaultBootstrap_InitialComponentContext();
uno::Reference<lang::XMultiComponentFactory> xFactory =
xContext->getServiceManager();
uno::Reference<lang::XMultiServiceFactory> xSFactory =
uno::Reference<lang::XMultiServiceFactory> (xFactory, uno::UNO_QUERY_THROW);
comphelper::setProcessServiceFactory(xSFactory);
// Create UCB.
uno::Sequence< uno::Any > aArgs(2);
aArgs[ 0 ] <<= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(UCB_CONFIGURATION_KEY1_LOCAL));
aArgs[ 1 ] <<= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(UCB_CONFIGURATION_KEY2_OFFICE));
::ucbhelper::ContentBroker::initialize(xSFactory, aArgs);
try
{
Dialog *pDialog = new Dialog(NULL, WB_STDDIALOG);
{
VclBuilder aBuilder(pDialog, uifiles[0]);
Dialog *pRealDialog = dynamic_cast<Dialog*>(aBuilder.get_widget_root());
if (!pRealDialog)
pRealDialog = pDialog;
if (pRealDialog)
{
pRealDialog->SetText(rtl::OUString("LibreOffice ui-previewer"));
pRealDialog->SetStyle(pDialog->GetStyle()|WB_CLOSEABLE);
pRealDialog->Execute();
}
}
delete pDialog;
}
catch (const uno::Exception &e)
{
fprintf(stderr, "fatal error: %s\n", rtl::OUStringToOString(e.Message, osl_getThreadTextEncoding()).getStr());
}
return false;
::ucbhelper::ContentBroker::deinitialize();
return EXIT_SUCCESS;
}
UIPreviewApp aApp;
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <cstring>
#include "OpenCLHelper.h"
#include "stringhelper.h"
#include "Timer.h"
using namespace std;
int main( int argc, char *argv[] ) {
int its = atoi(argv[1] );
int workgroupSize = atoi( argv[2] );
cout << "its: " << its << " workgroupsize: " << workgroupSize << endl;
string kernelSource = R"DELIM(
kernel void test(global float *stuff) {
float a = stuff[get_global_id(0)];
float b = stuff[1];
float c = stuff[2];
#pragma unroll 100
for( int i = 0; i < N_ITERATIONS; i++ ) {
a = a * b + c;
}
stuff[get_global_id(0)] = a;
}
)DELIM";
OpenCLHelper *cl = OpenCLHelper::createForFirstGpuOtherwiseCpu();
CLKernel *kernel = cl->buildKernelFromString( kernelSource, "test", "-cl-opt-disable -D N_ITERATIONS=" + toString( its ) );
Timer timer;
float stuff[2048];
for( int i = 0; i < 2048; i++ ) {
stuff[i] = 2.0f;
}
stuff[1] = 2.0f;
stuff[2] = -2.0f;
kernel->inout( 2048, stuff );
kernel->run_1d( workgroupSize, workgroupSize );
cl->finish();
timer.timeCheck("After kernel");
cout << stuff[0] << " " << stuff[1] << endl;
delete kernel;
delete cl;
return 0;
}
<commit_msg>testperf<commit_after>#include <iostream>
#include <string>
#include <cstring>
#include "OpenCLHelper.h"
#include "stringhelper.h"
#include "Timer.h"
using namespace std;
int main( int argc, char *argv[] ) {
int its = atoi(argv[1] );
int workgroupSize = atoi( argv[2] );
cout << "its: " << its << " workgroupsize: " << workgroupSize << endl;
string kernelSource = R"DELIM(
kernel void test(global float *stuff) {
float a = stuff[get_global_id(0)];
float b = stuff[1024];
float c = stuff[1025];
#pragma unroll 100
for( int i = 0; i < N_ITERATIONS; i++ ) {
a = a * b + c;
}
stuff[get_global_id(0)] = a;
}
)DELIM";
OpenCLHelper *cl = OpenCLHelper::createForFirstGpuOtherwiseCpu();
CLKernel *kernel = cl->buildKernelFromString( kernelSource, "test", "-cl-opt-disable -D N_ITERATIONS=" + toString( its ) );
Timer timer;
float stuff[2048];
for( int i = 0; i < 2048; i++ ) {
stuff[i] = 2.0f;
}
stuff[1024] = 2.0f;
stuff[1025] = -2.0f;
kernel->inout( 2048, stuff );
kernel->run_1d( workgroupSize, workgroupSize );
cl->finish();
timer.timeCheck("After kernel");
cout << stuff[0] << " " << stuff[1] << endl;
delete kernel;
delete cl;
return 0;
}
<|endoftext|> |
<commit_before>#include "Conformance.h"
#include "vector/Reference.h"
#include "vector/Intrinsic.h"
#include "vector/Aliased.h"
#include "Platform.h"
#include <cstdio>
#include <cmath>
////////////////////////////////////////////////////////////////////////////////
//! Macro for defining a conformance test.
#define TEST(NAME) \
template<typename M, typename V, typename S> \
struct NAME##T { \
static constexpr const char* name = #NAME; \
bool operator()() const; \
}; \
template<typename M, typename V, typename S> \
inline bool NAME##T<M, V, S>::operator()() const
//------------------------------------------------------------------------------
TEST(testComparison) {
V a(1.0f, 2.0f, 3.0f, 4.0f);
V b(1.0f, 1.0f, 2.0f, 3.0f);
if (a != a) {
return false;
}
if (!(a == a)) {
return false;
}
if (a == b) {
return false;
}
if (!(a != b)) {
return false;
}
return true;
}
//------------------------------------------------------------------------------
TEST(testElements) {
V a(1.0f, 2.0f, 3.0f, 4.0f);
V b(1.0f, 1.0f, 2.0f, 3.0f);
if (a[0] != S(1.0f)) {
return false;
}
if (a[1] != S(2.0f)) {
return false;
}
if (a[2] != S(3.0f)) {
return false;
}
if (a[3] != S(4.0f)) {
return false;
}
b[0] = -1.0f;
if (b != V(-1.0f, 1.0f, 2.0f, 3.0f)) {
return false;
}
b[1] = -2.0f;
if (b != V(-1.0f, -2.0f, 2.0f, 3.0f)) {
return false;
}
b[2] = -3.0f;
if (b != V(-1.0f, -2.0f, -3.0f, 3.0f)) {
return false;
}
b[3] = -4.0f;
if (b != V(-1.0f, -2.0f, -3.0f, -4.0f)) {
return false;
}
return true;
}
//------------------------------------------------------------------------------
TEST(testAlgebraic) {
V a(1.0f, 2.0f, 3.0f, 4.0f);
V b(2.0f, 3.0f, 4.0f, 5.0f);
S c = 0.5f;
S d = 3.0f;
if (a + b != V(3.0f, 5.0f, 7.0f, 9.0f)) {
return false;
}
if (a - b != V(-1.0f, -1.0f, -1.0f, -1.0f)) {
return false;
}
if (a * c != V(0.5f, 1.0f, 1.5f, 2.0f)) {
return false;
}
if (a / c != V(2.0f, 4.0f, 6.0f, 8.0f)) {
return false;
}
if (c * (a + b) != c * a + c * b) {
return false;
}
if ((c + d) * a != c * a + d * a) {
return false;
}
return true;
}
//------------------------------------------------------------------------------
TEST(testLength) {
V a(1.0f, 2.0f, 3.0f, 4.0f);
V b(2.0f, 3.0f, 4.0f, 5.0f);
if (a.LengthSqr() != (1.0f + 4.0f + 9.0f + 16.0f)) {
return false;
}
if (a.Length() != std::sqrt(1.0f + 4.0f + 9.0f + 16.0f)) {
return false;
}
S lerr = a.Length() / a.LengthFast();
// Maximum relative error of rsqrtps is less than 1.5*2^-12
if (1.0f - 3e4f > lerr || lerr > 1.0f + 3e-4f) {
return false;
}
S asqr = a.Normalize().LengthSqr();
if (1.0f - 1e-6f > asqr || asqr > 1.0f + 1e-6f) {
return false;
}
S bsqr = b.NormalizeFast().LengthSqr();
// Maximum relative error of rsqrtps is less than 1.5*2^-12
if (1.0f - 3e-4f > bsqr || bsqr > 1.0f + 3e-4f) {
return false;
}
return true;
}
//------------------------------------------------------------------------------
TEST(testDotProduct) {
V a(1.0f, 2.0f, 3.0f, 4.0f);
V b(2.0f, 3.0f, 4.0f, 5.0f);
if (a * b != (2.0f + 6.0f + 12.0f + 20.0f)) {
return false;
}
return true;
}
//------------------------------------------------------------------------------
TEST(testCrossProduct) {
V a(2.0f, 0.0f, 0.0f, 0.0f);
V b(0.0f, 3.0f, 0.0f, 0.0f);
if (a % b != V(0.0f, 0.0f, 6.0f, 0.0f)) {
return false;
}
if (a % b + b % a != V(0.0f, 0.0f, 0.0f, 0.0f)) {
return false;
}
return true;
}
//------------------------------------------------------------------------------
TEST(testMatrixScalarProduct) {
M A = {
1.f, 2.f, 3.f, 4.f,
2.f, 3.f, 4.f, 3.f,
3.f, 4.f, 3.f, 2.f,
4.f, 3.f, 2.f, 1.f,
};
M B = {
2.f, 4.f, 6.f, 8.f,
4.f, 6.f, 8.f, 6.f,
6.f, 8.f, 6.f, 4.f,
8.f, 6.f, 4.f, 2.f,
};
M C = A * 2.f;
if (C != B) {
return false;
}
M D = B / 2.0f;
if (D != A) {
return false;
}
return true;
}
//------------------------------------------------------------------------------
TEST(testMatrixVectorProduct) {
M I = {
1.f, 0.f, 0.f, 0.f,
0.f, 1.f, 0.f, 0.f,
0.f, 0.f, 1.f, 0.f,
0.f, 0.f, 0.f, 1.f,
};
V x = {
1.f, 2.f, 3.f, 4.f,
};
if (I * x != x) {
return false;
}
M A = {
0.f, 0.f, 0.f, 1.f,
0.f, 0.f, 1.f, 0.f,
1.f, 0.f, 0.f, 0.f,
0.f, 1.f, 0.f, 0.f,
};
V y = {
4.f, 3.f, 1.f, 2.f,
};
if (A * x != y) {
return false;
}
if (A * x + A * y != A * (x + y)) {
return false;
}
S z = 0.5f;
if (A * (x * z) != (A * x) * z) {
return false;
}
return true;
}
//------------------------------------------------------------------------------
TEST(testMatrixMatrixProduct) {
M A = {
1.f, 2.f, 3.f, 4.f,
2.f, 3.f, 4.f, 3.f,
3.f, 4.f, 3.f, 2.f,
4.f, 3.f, 2.f, 1.f,
};
M B = {
0.f, 0.f, 0.f, 1.f,
0.f, 0.f, 1.f, 0.f,
1.f, 0.f, 0.f, 0.f,
0.f, 1.f, 0.f, 0.f,
};
M C = {
3.f, 4.f, 2.f, 1.f,
4.f, 3.f, 3.f, 2.f,
3.f, 2.f, 4.f, 3.f,
2.f, 1.f, 3.f, 4.f,
};
if (A * B != C) {
return false;
}
V x = {
1.f, 2.f, 3.f, 4.f,
};
if ((B * A) * x != B * (A * x)) {
return false;
}
return true;
}
//------------------------------------------------------------------------------
TEST(testMatrixTranspose) {
M A = {
1.f, 2.f, 3.f, 4.f,
2.f, 3.f, 4.f, 5.f,
3.f, 4.f, 5.f, 6.f,
4.f, 5.f, 6.f, 7.f,
};
M At = {
1.f, 2.f, 3.f, 4.f,
2.f, 3.f, 4.f, 5.f,
3.f, 4.f, 5.f, 6.f,
4.f, 5.f, 6.f, 7.f,
};
M B = {
3.f, 4.f, 2.f, 1.f,
4.f, 3.f, 3.f, 2.f,
3.f, 2.f, 4.f, 3.f,
2.f, 1.f, 3.f, 4.f,
};
if (A.Transpose() != At) {
return false;
}
if (A.Transpose().Transpose() != A) {
return false;
}
if (A.Transpose() * B.Transpose() != (B * A).Transpose()) {
return false;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
//! Helper function for executing conformance tests on each implementation.
template<template<typename, typename, typename> class Func>
bool testFunc() {
constexpr char const* result_strings[] = {
"failed", "ok",
};
bool b0 = Func<reference::Matrix, reference::Vector, reference::Scalar>()();
bool b1 = Func<intrinsic::Matrix, intrinsic::Vector, intrinsic::Scalar>()();
bool b2 = Func<aliased::Matrix, aliased::Vector, aliased::Scalar>()();
// Print results
printf_s(" %-24s %-15s %-15s %-15s\n",
Func<reference::Matrix, reference::Vector, reference::Scalar>::name,
result_strings[b0],
result_strings[b1],
result_strings[b2]);
return b0 && b1 && b2;
}
//------------------------------------------------------------------------------
bool testComparison() {
return testFunc<testComparisonT>();
}
bool testElements() {
return testFunc<testElementsT>();
}
bool testAlgebraic() {
return testFunc<testAlgebraicT>();
}
bool testLength() {
return testFunc<testLengthT>();
}
bool testDotProduct() {
return testFunc<testDotProductT>();
}
bool testCrossProduct() {
return testFunc<testCrossProductT>();
}
bool testMatrixProduct() {
bool b1 = testFunc<testMatrixScalarProductT>();
bool b2 = testFunc<testMatrixVectorProductT>();
bool b3 = testFunc<testMatrixMatrixProductT>();
return b1 && b2 && b3;
}
bool testMatrixTranspose() {
return testFunc<testMatrixTransposeT>();
}
<commit_msg>Refactor conformance tests using EXPECT_ macros<commit_after>#include "Conformance.h"
#include "vector/Reference.h"
#include "vector/Intrinsic.h"
#include "vector/Aliased.h"
#include "Platform.h"
#include <cstdio>
#include <cmath>
////////////////////////////////////////////////////////////////////////////////
//! Macro for defining a conformance test.
#define TEST(NAME) \
template<typename M, typename V, typename S> \
struct NAME##T { \
static constexpr const char* name = #NAME; \
void operator()() const; \
}; \
template<typename M, typename V, typename S> \
inline void NAME##T<M, V, S>::operator()() const
//------------------------------------------------------------------------------
struct TestFailure {};
//------------------------------------------------------------------------------
#define EXPECT_TRUE(expr) \
if (!(expr)) { throw TestFailure{}; }
//------------------------------------------------------------------------------
#define EXPECT_FALSE(expr) \
if ((expr)) { throw TestFailure{}; }
//------------------------------------------------------------------------------
#define _EXPECT_OP(lhs, op, rhs) EXPECT_TRUE((lhs) op (rhs))
//------------------------------------------------------------------------------
#define EXPECT_EQ(lhs, rhs) _EXPECT_OP(lhs, ==, rhs)
#define EXPECT_NE(lhs, rhs) _EXPECT_OP(lhs, !=, rhs)
//------------------------------------------------------------------------------
#define EXPECT_EQ_EPS(lhs, rhs, eps) { \
auto del = lhs - rhs; \
EXPECT_TRUE(-eps < del && del < eps); \
}
//------------------------------------------------------------------------------
#define EXPECT_NE_EPS(lhs, rhs, eps) { \
auto del = lhs - rhs; \
EXPECT_TRUE(del < -eps || eps < del); \
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------
TEST(testComparison) {
V a(1.0f, 2.0f, 3.0f, 4.0f);
V b(1.0f, 1.0f, 2.0f, 3.0f);
EXPECT_TRUE(a == a);
EXPECT_FALSE(a != a);
EXPECT_FALSE(a == b);
EXPECT_TRUE(a != b);
}
//------------------------------------------------------------------------------
TEST(testElements) {
V a(1.0f, 2.0f, 3.0f, 4.0f);
V b(1.0f, 1.0f, 2.0f, 3.0f);
EXPECT_EQ(a[0], S(1.0f));
EXPECT_EQ(a[1], S(2.0f));
EXPECT_EQ(a[2], S(3.0f));
EXPECT_EQ(a[3], S(4.0f));
b[0] = -1.0f;
EXPECT_EQ(b, V(-1.0f, 1.0f, 2.0f, 3.0f));
b[1] = -2.0f;
EXPECT_EQ(b, V(-1.0f, -2.0f, 2.0f, 3.0f));
b[2] = -3.0f;
EXPECT_EQ(b, V(-1.0f, -2.0f, -3.0f, 3.0f));
b[3] = -4.0f;
EXPECT_EQ(b, V(-1.0f, -2.0f, -3.0f, -4.0f));
}
//------------------------------------------------------------------------------
TEST(testAlgebraic) {
V a(1.0f, 2.0f, 3.0f, 4.0f);
V b(2.0f, 3.0f, 4.0f, 5.0f);
S c = 0.5f;
S d = 3.0f;
EXPECT_EQ(a + b, V(3.0f, 5.0f, 7.0f, 9.0f));
EXPECT_EQ(a - b, V(-1.0f, -1.0f, -1.0f, -1.0f));
EXPECT_EQ(a * c, V(0.5f, 1.0f, 1.5f, 2.0f));
EXPECT_EQ(a / c, V(2.0f, 4.0f, 6.0f, 8.0f));
EXPECT_EQ(c * (a + b), c * a + c * b);
EXPECT_EQ((c + d) * a, c * a + d * a);
}
//------------------------------------------------------------------------------
TEST(testLength) {
V a(1.0f, 2.0f, 3.0f, 4.0f);
V b(2.0f, 3.0f, 4.0f, 5.0f);
EXPECT_EQ(a.LengthSqr(), 1.0f + 4.0f + 9.0f + 16.0f);
EXPECT_EQ(a.Length(), std::sqrt(1.0f + 4.0f + 9.0f + 16.0f));
S lerr = a.Length() / a.LengthFast();
// Maximum relative error of rsqrtps is less than 1.5*2^-12
EXPECT_EQ_EPS(lerr, 1.0f, 3e-4f);
S asqr = a.Normalize().LengthSqr();
EXPECT_EQ_EPS(asqr, 1.0f, 1e-6f);
S bsqr = b.NormalizeFast().LengthSqr();
// Maximum relative error of rsqrtps is less than 1.5*2^-12
EXPECT_EQ_EPS(bsqr, 1.0f, 3e-4f);
}
//------------------------------------------------------------------------------
TEST(testDotProduct) {
V a(1.0f, 2.0f, 3.0f, 4.0f);
V b(2.0f, 3.0f, 4.0f, 5.0f);
EXPECT_EQ(a * b, 2.0f + 6.0f + 12.0f + 20.0f);
}
//------------------------------------------------------------------------------
TEST(testCrossProduct) {
V a(2.0f, 0.0f, 0.0f, 0.0f);
V b(0.0f, 3.0f, 0.0f, 0.0f);
EXPECT_EQ(a % b, V(0.0f, 0.0f, 6.0f, 0.0f));
EXPECT_EQ(a % b + b % a, V(0.0f, 0.0f, 0.0f, 0.0f));
}
//------------------------------------------------------------------------------
TEST(testMatrixScalarProduct) {
M A = {
1.f, 2.f, 3.f, 4.f,
2.f, 3.f, 4.f, 3.f,
3.f, 4.f, 3.f, 2.f,
4.f, 3.f, 2.f, 1.f,
};
M B = {
2.f, 4.f, 6.f, 8.f,
4.f, 6.f, 8.f, 6.f,
6.f, 8.f, 6.f, 4.f,
8.f, 6.f, 4.f, 2.f,
};
M C = A * 2.f;
EXPECT_EQ(C, B);
M D = B / 2.0f;
EXPECT_EQ(D, A);
}
//------------------------------------------------------------------------------
TEST(testMatrixVectorProduct) {
M I = {
1.f, 0.f, 0.f, 0.f,
0.f, 1.f, 0.f, 0.f,
0.f, 0.f, 1.f, 0.f,
0.f, 0.f, 0.f, 1.f,
};
V x = {
1.f, 2.f, 3.f, 4.f,
};
M A = {
0.f, 0.f, 0.f, 1.f,
0.f, 0.f, 1.f, 0.f,
1.f, 0.f, 0.f, 0.f,
0.f, 1.f, 0.f, 0.f,
};
V y = {
4.f, 3.f, 1.f, 2.f,
};
S z = 0.5f;
EXPECT_EQ(I * x, x);
EXPECT_EQ(A * x, y);
EXPECT_EQ(A * x + A * y, A * (x + y));
EXPECT_EQ(A * (x * z), (A * x) * z);
}
//------------------------------------------------------------------------------
TEST(testMatrixMatrixProduct) {
M A = {
1.f, 2.f, 3.f, 4.f,
2.f, 3.f, 4.f, 3.f,
3.f, 4.f, 3.f, 2.f,
4.f, 3.f, 2.f, 1.f,
};
M B = {
0.f, 0.f, 0.f, 1.f,
0.f, 0.f, 1.f, 0.f,
1.f, 0.f, 0.f, 0.f,
0.f, 1.f, 0.f, 0.f,
};
M C = {
3.f, 4.f, 2.f, 1.f,
4.f, 3.f, 3.f, 2.f,
3.f, 2.f, 4.f, 3.f,
2.f, 1.f, 3.f, 4.f,
};
V x = {
1.f, 2.f, 3.f, 4.f,
};
EXPECT_EQ(A * B, C);
EXPECT_EQ((B * A) * x, B * (A * x));
}
//------------------------------------------------------------------------------
TEST(testMatrixTranspose) {
M A = {
1.f, 2.f, 3.f, 4.f,
2.f, 3.f, 4.f, 5.f,
3.f, 4.f, 5.f, 6.f,
4.f, 5.f, 6.f, 7.f,
};
M At = {
1.f, 2.f, 3.f, 4.f,
2.f, 3.f, 4.f, 5.f,
3.f, 4.f, 5.f, 6.f,
4.f, 5.f, 6.f, 7.f,
};
M B = {
3.f, 4.f, 2.f, 1.f,
4.f, 3.f, 3.f, 2.f,
3.f, 2.f, 4.f, 3.f,
2.f, 1.f, 3.f, 4.f,
};
EXPECT_EQ(A.Transpose(), At);
EXPECT_EQ(A.Transpose().Transpose(), A);
EXPECT_EQ(A.Transpose() * B.Transpose(), (B * A).Transpose());
}
////////////////////////////////////////////////////////////////////////////////
//! Helper function for executing a conformance test for one implementation.
template<typename Func>
bool testFuncImpl() {
try {
Func()();
return true;
}
catch (TestFailure const&)
{
return false;
}
}
////////////////////////////////////////////////////////////////////////////////
//! Helper function for executing conformance tests on each implementation.
template<template<typename, typename, typename> class Func>
bool testFunc() {
constexpr char const* result_strings[] = {
"failed", "ok",
};
bool b0 = testFuncImpl<Func<reference::Matrix, reference::Vector, reference::Scalar>>();
bool b1 = testFuncImpl<Func<intrinsic::Matrix, intrinsic::Vector, intrinsic::Scalar>>();
bool b2 = testFuncImpl<Func<aliased::Matrix, aliased::Vector, aliased::Scalar>>();
// Print results
printf_s(" %-24s %-15s %-15s %-15s\n",
Func<reference::Matrix, reference::Vector, reference::Scalar>::name,
result_strings[b0],
result_strings[b1],
result_strings[b2]);
return b0 && b1 && b2;
}
//------------------------------------------------------------------------------
bool testComparison() {
return testFunc<testComparisonT>();
}
bool testElements() {
return testFunc<testElementsT>();
}
bool testAlgebraic() {
return testFunc<testAlgebraicT>();
}
bool testLength() {
return testFunc<testLengthT>();
}
bool testDotProduct() {
return testFunc<testDotProductT>();
}
bool testCrossProduct() {
return testFunc<testCrossProductT>();
}
bool testMatrixProduct() {
bool b1 = testFunc<testMatrixScalarProductT>();
bool b2 = testFunc<testMatrixVectorProductT>();
bool b3 = testFunc<testMatrixMatrixProductT>();
return b1 && b2 && b3;
}
bool testMatrixTranspose() {
return testFunc<testMatrixTransposeT>();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <chainparams.h>
#include <compressor.h>
#include <core_io.h>
#include <core_memusage.h>
#include <policy/policy.h>
#include <pubkey.h>
#include <script/descriptor.h>
#include <script/script.h>
#include <script/sign.h>
#include <script/signingprovider.h>
#include <script/standard.h>
#include <streams.h>
#include <test/fuzz/fuzz.h>
#include <univalue.h>
#include <util/memory.h>
void initialize()
{
// Fuzzers using pubkey must hold an ECCVerifyHandle.
static const auto verify_handle = MakeUnique<ECCVerifyHandle>();
SelectParams(CBaseChainParams::REGTEST);
}
void test_one_input(const std::vector<uint8_t>& buffer)
{
const CScript script(buffer.begin(), buffer.end());
std::vector<unsigned char> compressed;
if (CompressScript(script, compressed)) {
const unsigned int size = compressed[0];
compressed.erase(compressed.begin());
assert(size >= 0 && size <= 5);
CScript decompressed_script;
const bool ok = DecompressScript(decompressed_script, size, compressed);
assert(ok);
assert(script == decompressed_script);
}
for (unsigned int size = 0; size < 6; ++size) {
std::vector<unsigned char> vch(GetSpecialScriptSize(size), 0x00);
vch.insert(vch.end(), buffer.begin(), buffer.end());
CScript decompressed_script;
(void)DecompressScript(decompressed_script, size, vch);
}
CTxDestination address;
(void)ExtractDestination(script, address);
txnouttype type_ret;
std::vector<CTxDestination> addresses;
int required_ret;
(void)ExtractDestinations(script, type_ret, addresses, required_ret);
(void)GetScriptForWitness(script);
const FlatSigningProvider signing_provider;
(void)InferDescriptor(script, signing_provider);
(void)IsSegWitOutput(signing_provider, script);
(void)IsSolvable(signing_provider, script);
txnouttype which_type;
(void)IsStandard(script, which_type);
(void)RecursiveDynamicUsage(script);
std::vector<std::vector<unsigned char>> solutions;
(void)Solver(script, solutions);
(void)script.HasValidOps();
(void)script.IsPayToScriptHash();
(void)script.IsPayToWitnessScriptHash();
(void)script.IsPushOnly();
(void)script.IsUnspendable();
(void)script.GetSigOpCount(/* fAccurate= */ false);
(void)FormatScript(script);
(void)ScriptToAsmStr(script, false);
(void)ScriptToAsmStr(script, true);
UniValue o1(UniValue::VOBJ);
ScriptPubKeyToUniv(script, o1, true);
UniValue o2(UniValue::VOBJ);
ScriptPubKeyToUniv(script, o2, false);
UniValue o3(UniValue::VOBJ);
ScriptToUniv(script, o3, true);
UniValue o4(UniValue::VOBJ);
ScriptToUniv(script, o4, false);
}
<commit_msg>tests: Remove unit test from fuzzing harness<commit_after>// Copyright (c) 2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <chainparams.h>
#include <compressor.h>
#include <core_io.h>
#include <core_memusage.h>
#include <policy/policy.h>
#include <pubkey.h>
#include <script/descriptor.h>
#include <script/script.h>
#include <script/sign.h>
#include <script/signingprovider.h>
#include <script/standard.h>
#include <streams.h>
#include <test/fuzz/fuzz.h>
#include <univalue.h>
#include <util/memory.h>
void initialize()
{
// Fuzzers using pubkey must hold an ECCVerifyHandle.
static const auto verify_handle = MakeUnique<ECCVerifyHandle>();
SelectParams(CBaseChainParams::REGTEST);
}
void test_one_input(const std::vector<uint8_t>& buffer)
{
const CScript script(buffer.begin(), buffer.end());
std::vector<unsigned char> compressed;
if (CompressScript(script, compressed)) {
const unsigned int size = compressed[0];
compressed.erase(compressed.begin());
assert(size >= 0 && size <= 5);
CScript decompressed_script;
const bool ok = DecompressScript(decompressed_script, size, compressed);
assert(ok);
assert(script == decompressed_script);
}
CTxDestination address;
(void)ExtractDestination(script, address);
txnouttype type_ret;
std::vector<CTxDestination> addresses;
int required_ret;
(void)ExtractDestinations(script, type_ret, addresses, required_ret);
(void)GetScriptForWitness(script);
const FlatSigningProvider signing_provider;
(void)InferDescriptor(script, signing_provider);
(void)IsSegWitOutput(signing_provider, script);
(void)IsSolvable(signing_provider, script);
txnouttype which_type;
(void)IsStandard(script, which_type);
(void)RecursiveDynamicUsage(script);
std::vector<std::vector<unsigned char>> solutions;
(void)Solver(script, solutions);
(void)script.HasValidOps();
(void)script.IsPayToScriptHash();
(void)script.IsPayToWitnessScriptHash();
(void)script.IsPushOnly();
(void)script.IsUnspendable();
(void)script.GetSigOpCount(/* fAccurate= */ false);
(void)FormatScript(script);
(void)ScriptToAsmStr(script, false);
(void)ScriptToAsmStr(script, true);
UniValue o1(UniValue::VOBJ);
ScriptPubKeyToUniv(script, o1, true);
UniValue o2(UniValue::VOBJ);
ScriptPubKeyToUniv(script, o2, false);
UniValue o3(UniValue::VOBJ);
ScriptToUniv(script, o3, true);
UniValue o4(UniValue::VOBJ);
ScriptToUniv(script, o4, false);
}
<|endoftext|> |
<commit_before>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <string>
#include <fstream>
#include <iterator>
#include <vector>
#include <algorithm>
#include <limits>
#include <stdexcept>
#include <cfloat>
#include <arrayfire.h>
#include <af/dim4.hpp>
#include <af/array.h>
typedef unsigned char uchar;
typedef unsigned int uint;
typedef unsigned short ushort;
template<typename inType, typename outType, typename FileElementType>
void readTests(const std::string &FileName, std::vector<af::dim4> &inputDims,
std::vector<std::vector<inType> > &testInputs,
std::vector<std::vector<outType> > &testOutputs)
{
using std::vector;
std::ifstream testFile(FileName.c_str());
if(testFile.good()) {
unsigned inputCount;
testFile >> inputCount;
for(unsigned i=0; i<inputCount; i++) {
af::dim4 temp(1);
testFile >> temp;
inputDims.push_back(temp);
}
unsigned testCount;
testFile >> testCount;
testOutputs.resize(testCount);
vector<unsigned> testSizes(testCount);
for(unsigned i = 0; i < testCount; i++) {
testFile >> testSizes[i];
}
testInputs.resize(inputCount,vector<inType>(0));
for(unsigned k=0; k<inputCount; k++) {
unsigned nElems = inputDims[k].elements();
testInputs[k].resize(nElems);
FileElementType tmp;
for(unsigned i = 0; i < nElems; i++) {
testFile >> tmp;
testInputs[k][i] = tmp;
}
}
testOutputs.resize(testCount, vector<outType>(0));
for(unsigned i = 0; i < testCount; i++) {
testOutputs[i].resize(testSizes[i]);
FileElementType tmp;
for(unsigned j = 0; j < testSizes[i]; j++) {
testFile >> tmp;
testOutputs[i][j] = tmp;
}
}
}
else {
FAIL() << "TEST FILE NOT FOUND";
}
}
template<typename inType, typename outType>
void readTestsFromFile(const std::string &FileName, std::vector<af::dim4> &inputDims,
std::vector<std::vector<inType> > &testInputs,
std::vector<std::vector<outType> > &testOutputs)
{
using std::vector;
std::ifstream testFile(FileName.c_str());
if(testFile.good()) {
unsigned inputCount;
testFile >> inputCount;
for(unsigned i=0; i<inputCount; i++) {
af::dim4 temp(1);
testFile >> temp;
inputDims.push_back(temp);
}
unsigned testCount;
testFile >> testCount;
testOutputs.resize(testCount);
vector<unsigned> testSizes(testCount);
for(unsigned i = 0; i < testCount; i++) {
testFile >> testSizes[i];
}
testInputs.resize(inputCount,vector<inType>(0));
for(unsigned k=0; k<inputCount; k++) {
unsigned nElems = inputDims[k].elements();
testInputs[k].resize(nElems);
inType tmp;
for(unsigned i = 0; i < nElems; i++) {
testFile >> tmp;
testInputs[k][i] = tmp;
}
}
testOutputs.resize(testCount, vector<outType>(0));
for(unsigned i = 0; i < testCount; i++) {
testOutputs[i].resize(testSizes[i]);
outType tmp;
for(unsigned j = 0; j < testSizes[i]; j++) {
testFile >> tmp;
testOutputs[i][j] = tmp;
}
}
}
else {
FAIL() << "TEST FILE NOT FOUND";
}
}
void readImageTests(const std::string &pFileName,
std::vector<af::dim4> &pInputDims,
std::vector<std::string> &pTestInputs,
std::vector<dim_t> &pTestOutSizes,
std::vector<std::string> &pTestOutputs)
{
using std::vector;
std::ifstream testFile(pFileName.c_str());
if(testFile.good()) {
unsigned inputCount;
testFile >> inputCount;
for(unsigned i=0; i<inputCount; i++) {
af::dim4 temp(1);
testFile >> temp;
pInputDims.push_back(temp);
}
unsigned testCount;
testFile >> testCount;
pTestOutputs.resize(testCount);
pTestOutSizes.resize(testCount);
for(unsigned i = 0; i < testCount; i++) {
testFile >> pTestOutSizes[i];
}
pTestInputs.resize(inputCount, "");
for(unsigned k=0; k<inputCount; k++) {
std::string temp = "";
while(std::getline(testFile, temp)) {
if (temp!="")
break;
}
if (temp=="")
throw std::runtime_error("Test file might not be per format, please check.");
pTestInputs[k] = temp;
}
pTestOutputs.resize(testCount, "");
for(unsigned i = 0; i < testCount; i++) {
std::string temp = "";
while(std::getline(testFile, temp)) {
if (temp!="")
break;
}
if (temp=="")
throw std::runtime_error("Test file might not be per format, please check.");
pTestOutputs[i] = temp;
}
}
else {
FAIL() << "TEST FILE NOT FOUND";
}
}
template<typename outType>
void readImageTests(const std::string &pFileName,
std::vector<af::dim4> &pInputDims,
std::vector<std::string> &pTestInputs,
std::vector<std::vector<outType> > &pTestOutputs)
{
using std::vector;
std::ifstream testFile(pFileName.c_str());
if(testFile.good()) {
unsigned inputCount;
testFile >> inputCount;
for(unsigned i=0; i<inputCount; i++) {
af::dim4 temp(1);
testFile >> temp;
pInputDims.push_back(temp);
}
unsigned testCount;
testFile >> testCount;
pTestOutputs.resize(testCount);
vector<unsigned> testSizes(testCount);
for(unsigned i = 0; i < testCount; i++) {
testFile >> testSizes[i];
}
pTestInputs.resize(inputCount, "");
for(unsigned k=0; k<inputCount; k++) {
std::string temp = "";
while(std::getline(testFile, temp)) {
if (temp!="")
break;
}
if (temp=="")
throw std::runtime_error("Test file might not be per format, please check.");
pTestInputs[k] = temp;
}
pTestOutputs.resize(testCount, vector<outType>(0));
for(unsigned i = 0; i < testCount; i++) {
pTestOutputs[i].resize(testSizes[i]);
outType tmp;
for(unsigned j = 0; j < testSizes[i]; j++) {
testFile >> tmp;
pTestOutputs[i][j] = tmp;
}
}
}
else {
FAIL() << "TEST FILE NOT FOUND";
}
}
template<typename descType>
void readImageFeaturesDescriptors(const std::string &pFileName,
std::vector<af::dim4> &pInputDims,
std::vector<std::string> &pTestInputs,
std::vector<std::vector<float> > &pTestFeats,
std::vector<std::vector<descType> > &pTestDescs)
{
using std::vector;
std::ifstream testFile(pFileName.c_str());
if(testFile.good()) {
unsigned inputCount;
testFile >> inputCount;
for(unsigned i=0; i<inputCount; i++) {
af::dim4 temp(1);
testFile >> temp;
pInputDims.push_back(temp);
}
unsigned attrCount, featCount, descLen;
testFile >> featCount;
testFile >> attrCount;
testFile >> descLen;
pTestFeats.resize(attrCount);
pTestInputs.resize(inputCount, "");
for(unsigned k=0; k<inputCount; k++) {
std::string temp = "";
while(std::getline(testFile, temp)) {
if (temp!="")
break;
}
if (temp=="")
throw std::runtime_error("Test file might not be per format, please check.");
pTestInputs[k] = temp;
}
pTestFeats.resize(attrCount, vector<float>(0));
for(unsigned i = 0; i < attrCount; i++) {
pTestFeats[i].resize(featCount);
float tmp;
for(unsigned j = 0; j < featCount; j++) {
testFile >> tmp;
pTestFeats[i][j] = tmp;
}
}
pTestDescs.resize(featCount, vector<descType>(0));
for(unsigned i = 0; i < featCount; i++) {
pTestDescs[i].resize(descLen);
descType tmp;
for(unsigned j = 0; j < descLen; j++) {
testFile >> tmp;
pTestDescs[i][j] = tmp;
}
}
}
else {
FAIL() << "TEST FILE NOT FOUND";
}
}
/**
* Below is not a pair wise comparition method, rather
* it computes the accumulated error of the computed
* output and gold output.
*
* The cut off is decided based on root mean square
* deviation from cpu result
*
* For images, the maximum possible error will happen if all
* the observed values are zeros and all the predicted values
* are 255's. In such case, the value of NRMSD will be 1.0
* Similarly, we can deduce that 0.0 will be the minimum
* value of NRMSD. Hence, the range of RMSD is [0,255] for image inputs.
*/
template<typename T>
bool compareArraysRMSD(dim_t data_size, T *gold, T *data, double tolerance)
{
double accum = 0.0;
double maxion = FLT_MAX;//(double)std::numeric_limits<T>::lowest();
double minion = FLT_MAX;//(double)std::numeric_limits<T>::max();
for(dim_t i=0;i<data_size;i++)
{
double dTemp = (double)data[i];
double gTemp = (double)gold[i];
double diff = gTemp-dTemp;
double err = std::abs(diff) > 1.0e-4 ? diff : 0.0f;
accum += std::pow(err,2.0);
maxion = std::max(maxion, dTemp);
minion = std::min(minion, dTemp);
}
accum /= data_size;
double NRMSD = std::sqrt(accum)/(maxion-minion);
std::cout<<"NRMSD = "<<NRMSD<<std::endl;
if (NRMSD > tolerance)
return false;
return true;
}
template<typename T, typename Other>
struct is_same_type{
static const bool value = false;
};
template<typename T>
struct is_same_type<T, T> {
static const bool value = true;
};
template<bool, typename T, typename O>
struct cond_type;
template<typename T, typename Other>
struct cond_type<true, T, Other> {
typedef T type;
};
template<typename T, typename Other>
struct cond_type<false, T, Other> {
typedef Other type;
};
template<typename T>
double real(T val) { return (double)val; }
template<>
double real<af::cdouble>(af::cdouble val) { return real(val); }
template<>
double real<af::cfloat> (af::cfloat val) { return real(val); }
template<typename T>
double imag(T val) { return (double)val; }
template<>
double imag<af::cdouble>(af::cdouble val) { return imag(val); }
template<>
double imag<af::cfloat> (af::cfloat val) { return imag(val); }
template<typename T>
bool noDoubleTests()
{
bool isTypeDouble = is_same_type<T, double>::value || is_same_type<T, af::cdouble>::value;
int dev = af::getDevice();
bool isDoubleSupported = af::isDoubleAvailable(dev);
return ((isTypeDouble && !isDoubleSupported) ? true : false);
}
// TODO: perform conversion on device for CUDA and OpenCL
template<typename T>
af_err conv_image(af_array *out, af_array in)
{
af_array outArray;
dim_t d0, d1, d2, d3;
af_get_dims(&d0, &d1, &d2, &d3, in);
af::dim4 idims(d0, d1, d2, d3);
dim_t nElems = 0;
af_get_elements(&nElems, in);
float *in_data = new float[nElems];
af_get_data_ptr(in_data, in);
T *out_data = new T[nElems];
for (int i = 0; i < (int)nElems; i++)
out_data[i] = (T)in_data[i];
af_create_array(&outArray, out_data, idims.ndims(), idims.get(), (af_dtype) af::dtype_traits<T>::af_type);
std::swap(*out, outArray);
delete [] in_data;
delete [] out_data;
return AF_SUCCESS;
}
template<typename T>
af::array cpu_randu(const af::dim4 dims)
{
typedef typename af::dtype_traits<T>::base_type BT;
bool isTypeCplx = is_same_type<T, af::cfloat>::value || is_same_type<T, af::cdouble>::value;
bool isTypeFloat = is_same_type<BT, float>::value || is_same_type<BT, double>::value;
dim_t elements = (isTypeCplx ? 2 : 1) * dims.elements();
std::vector<BT> out(elements);
for(int i = 0; i < (int)elements; i++) {
out[i] = isTypeFloat ? (BT)(rand())/RAND_MAX : rand() % 100;
}
return af::array(dims, (T *)&out[0]);
}
<commit_msg>Add function to check Image IO availability<commit_after>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <string>
#include <fstream>
#include <iterator>
#include <vector>
#include <algorithm>
#include <limits>
#include <stdexcept>
#include <cfloat>
#include <arrayfire.h>
#include <af/dim4.hpp>
#include <af/array.h>
typedef unsigned char uchar;
typedef unsigned int uint;
typedef unsigned short ushort;
template<typename inType, typename outType, typename FileElementType>
void readTests(const std::string &FileName, std::vector<af::dim4> &inputDims,
std::vector<std::vector<inType> > &testInputs,
std::vector<std::vector<outType> > &testOutputs)
{
using std::vector;
std::ifstream testFile(FileName.c_str());
if(testFile.good()) {
unsigned inputCount;
testFile >> inputCount;
for(unsigned i=0; i<inputCount; i++) {
af::dim4 temp(1);
testFile >> temp;
inputDims.push_back(temp);
}
unsigned testCount;
testFile >> testCount;
testOutputs.resize(testCount);
vector<unsigned> testSizes(testCount);
for(unsigned i = 0; i < testCount; i++) {
testFile >> testSizes[i];
}
testInputs.resize(inputCount,vector<inType>(0));
for(unsigned k=0; k<inputCount; k++) {
unsigned nElems = inputDims[k].elements();
testInputs[k].resize(nElems);
FileElementType tmp;
for(unsigned i = 0; i < nElems; i++) {
testFile >> tmp;
testInputs[k][i] = tmp;
}
}
testOutputs.resize(testCount, vector<outType>(0));
for(unsigned i = 0; i < testCount; i++) {
testOutputs[i].resize(testSizes[i]);
FileElementType tmp;
for(unsigned j = 0; j < testSizes[i]; j++) {
testFile >> tmp;
testOutputs[i][j] = tmp;
}
}
}
else {
FAIL() << "TEST FILE NOT FOUND";
}
}
template<typename inType, typename outType>
void readTestsFromFile(const std::string &FileName, std::vector<af::dim4> &inputDims,
std::vector<std::vector<inType> > &testInputs,
std::vector<std::vector<outType> > &testOutputs)
{
using std::vector;
std::ifstream testFile(FileName.c_str());
if(testFile.good()) {
unsigned inputCount;
testFile >> inputCount;
for(unsigned i=0; i<inputCount; i++) {
af::dim4 temp(1);
testFile >> temp;
inputDims.push_back(temp);
}
unsigned testCount;
testFile >> testCount;
testOutputs.resize(testCount);
vector<unsigned> testSizes(testCount);
for(unsigned i = 0; i < testCount; i++) {
testFile >> testSizes[i];
}
testInputs.resize(inputCount,vector<inType>(0));
for(unsigned k=0; k<inputCount; k++) {
unsigned nElems = inputDims[k].elements();
testInputs[k].resize(nElems);
inType tmp;
for(unsigned i = 0; i < nElems; i++) {
testFile >> tmp;
testInputs[k][i] = tmp;
}
}
testOutputs.resize(testCount, vector<outType>(0));
for(unsigned i = 0; i < testCount; i++) {
testOutputs[i].resize(testSizes[i]);
outType tmp;
for(unsigned j = 0; j < testSizes[i]; j++) {
testFile >> tmp;
testOutputs[i][j] = tmp;
}
}
}
else {
FAIL() << "TEST FILE NOT FOUND";
}
}
void readImageTests(const std::string &pFileName,
std::vector<af::dim4> &pInputDims,
std::vector<std::string> &pTestInputs,
std::vector<dim_t> &pTestOutSizes,
std::vector<std::string> &pTestOutputs)
{
using std::vector;
std::ifstream testFile(pFileName.c_str());
if(testFile.good()) {
unsigned inputCount;
testFile >> inputCount;
for(unsigned i=0; i<inputCount; i++) {
af::dim4 temp(1);
testFile >> temp;
pInputDims.push_back(temp);
}
unsigned testCount;
testFile >> testCount;
pTestOutputs.resize(testCount);
pTestOutSizes.resize(testCount);
for(unsigned i = 0; i < testCount; i++) {
testFile >> pTestOutSizes[i];
}
pTestInputs.resize(inputCount, "");
for(unsigned k=0; k<inputCount; k++) {
std::string temp = "";
while(std::getline(testFile, temp)) {
if (temp!="")
break;
}
if (temp=="")
throw std::runtime_error("Test file might not be per format, please check.");
pTestInputs[k] = temp;
}
pTestOutputs.resize(testCount, "");
for(unsigned i = 0; i < testCount; i++) {
std::string temp = "";
while(std::getline(testFile, temp)) {
if (temp!="")
break;
}
if (temp=="")
throw std::runtime_error("Test file might not be per format, please check.");
pTestOutputs[i] = temp;
}
}
else {
FAIL() << "TEST FILE NOT FOUND";
}
}
template<typename outType>
void readImageTests(const std::string &pFileName,
std::vector<af::dim4> &pInputDims,
std::vector<std::string> &pTestInputs,
std::vector<std::vector<outType> > &pTestOutputs)
{
using std::vector;
std::ifstream testFile(pFileName.c_str());
if(testFile.good()) {
unsigned inputCount;
testFile >> inputCount;
for(unsigned i=0; i<inputCount; i++) {
af::dim4 temp(1);
testFile >> temp;
pInputDims.push_back(temp);
}
unsigned testCount;
testFile >> testCount;
pTestOutputs.resize(testCount);
vector<unsigned> testSizes(testCount);
for(unsigned i = 0; i < testCount; i++) {
testFile >> testSizes[i];
}
pTestInputs.resize(inputCount, "");
for(unsigned k=0; k<inputCount; k++) {
std::string temp = "";
while(std::getline(testFile, temp)) {
if (temp!="")
break;
}
if (temp=="")
throw std::runtime_error("Test file might not be per format, please check.");
pTestInputs[k] = temp;
}
pTestOutputs.resize(testCount, vector<outType>(0));
for(unsigned i = 0; i < testCount; i++) {
pTestOutputs[i].resize(testSizes[i]);
outType tmp;
for(unsigned j = 0; j < testSizes[i]; j++) {
testFile >> tmp;
pTestOutputs[i][j] = tmp;
}
}
}
else {
FAIL() << "TEST FILE NOT FOUND";
}
}
template<typename descType>
void readImageFeaturesDescriptors(const std::string &pFileName,
std::vector<af::dim4> &pInputDims,
std::vector<std::string> &pTestInputs,
std::vector<std::vector<float> > &pTestFeats,
std::vector<std::vector<descType> > &pTestDescs)
{
using std::vector;
std::ifstream testFile(pFileName.c_str());
if(testFile.good()) {
unsigned inputCount;
testFile >> inputCount;
for(unsigned i=0; i<inputCount; i++) {
af::dim4 temp(1);
testFile >> temp;
pInputDims.push_back(temp);
}
unsigned attrCount, featCount, descLen;
testFile >> featCount;
testFile >> attrCount;
testFile >> descLen;
pTestFeats.resize(attrCount);
pTestInputs.resize(inputCount, "");
for(unsigned k=0; k<inputCount; k++) {
std::string temp = "";
while(std::getline(testFile, temp)) {
if (temp!="")
break;
}
if (temp=="")
throw std::runtime_error("Test file might not be per format, please check.");
pTestInputs[k] = temp;
}
pTestFeats.resize(attrCount, vector<float>(0));
for(unsigned i = 0; i < attrCount; i++) {
pTestFeats[i].resize(featCount);
float tmp;
for(unsigned j = 0; j < featCount; j++) {
testFile >> tmp;
pTestFeats[i][j] = tmp;
}
}
pTestDescs.resize(featCount, vector<descType>(0));
for(unsigned i = 0; i < featCount; i++) {
pTestDescs[i].resize(descLen);
descType tmp;
for(unsigned j = 0; j < descLen; j++) {
testFile >> tmp;
pTestDescs[i][j] = tmp;
}
}
}
else {
FAIL() << "TEST FILE NOT FOUND";
}
}
/**
* Below is not a pair wise comparition method, rather
* it computes the accumulated error of the computed
* output and gold output.
*
* The cut off is decided based on root mean square
* deviation from cpu result
*
* For images, the maximum possible error will happen if all
* the observed values are zeros and all the predicted values
* are 255's. In such case, the value of NRMSD will be 1.0
* Similarly, we can deduce that 0.0 will be the minimum
* value of NRMSD. Hence, the range of RMSD is [0,255] for image inputs.
*/
template<typename T>
bool compareArraysRMSD(dim_t data_size, T *gold, T *data, double tolerance)
{
double accum = 0.0;
double maxion = FLT_MAX;//(double)std::numeric_limits<T>::lowest();
double minion = FLT_MAX;//(double)std::numeric_limits<T>::max();
for(dim_t i=0;i<data_size;i++)
{
double dTemp = (double)data[i];
double gTemp = (double)gold[i];
double diff = gTemp-dTemp;
double err = std::abs(diff) > 1.0e-4 ? diff : 0.0f;
accum += std::pow(err,2.0);
maxion = std::max(maxion, dTemp);
minion = std::min(minion, dTemp);
}
accum /= data_size;
double NRMSD = std::sqrt(accum)/(maxion-minion);
std::cout<<"NRMSD = "<<NRMSD<<std::endl;
if (NRMSD > tolerance)
return false;
return true;
}
template<typename T, typename Other>
struct is_same_type{
static const bool value = false;
};
template<typename T>
struct is_same_type<T, T> {
static const bool value = true;
};
template<bool, typename T, typename O>
struct cond_type;
template<typename T, typename Other>
struct cond_type<true, T, Other> {
typedef T type;
};
template<typename T, typename Other>
struct cond_type<false, T, Other> {
typedef Other type;
};
template<typename T>
double real(T val) { return (double)val; }
template<>
double real<af::cdouble>(af::cdouble val) { return real(val); }
template<>
double real<af::cfloat> (af::cfloat val) { return real(val); }
template<typename T>
double imag(T val) { return (double)val; }
template<>
double imag<af::cdouble>(af::cdouble val) { return imag(val); }
template<>
double imag<af::cfloat> (af::cfloat val) { return imag(val); }
template<typename T>
bool noDoubleTests()
{
bool isTypeDouble = is_same_type<T, double>::value || is_same_type<T, af::cdouble>::value;
int dev = af::getDevice();
bool isDoubleSupported = af::isDoubleAvailable(dev);
return ((isTypeDouble && !isDoubleSupported) ? true : false);
}
bool noImageIOTests()
{
af_array arr = 0;
const af_err err = af_load_image(&arr, TEST_DIR"/imageio/color_small.png", true);
if(arr != 0) af_release_array(arr);
if(err == AF_ERR_NOT_CONFIGURED)
return true; // Yes, disable test
else
return false; // No, let test continue
}
// TODO: perform conversion on device for CUDA and OpenCL
template<typename T>
af_err conv_image(af_array *out, af_array in)
{
af_array outArray;
dim_t d0, d1, d2, d3;
af_get_dims(&d0, &d1, &d2, &d3, in);
af::dim4 idims(d0, d1, d2, d3);
dim_t nElems = 0;
af_get_elements(&nElems, in);
float *in_data = new float[nElems];
af_get_data_ptr(in_data, in);
T *out_data = new T[nElems];
for (int i = 0; i < (int)nElems; i++)
out_data[i] = (T)in_data[i];
af_create_array(&outArray, out_data, idims.ndims(), idims.get(), (af_dtype) af::dtype_traits<T>::af_type);
std::swap(*out, outArray);
delete [] in_data;
delete [] out_data;
return AF_SUCCESS;
}
template<typename T>
af::array cpu_randu(const af::dim4 dims)
{
typedef typename af::dtype_traits<T>::base_type BT;
bool isTypeCplx = is_same_type<T, af::cfloat>::value || is_same_type<T, af::cdouble>::value;
bool isTypeFloat = is_same_type<BT, float>::value || is_same_type<BT, double>::value;
dim_t elements = (isTypeCplx ? 2 : 1) * dims.elements();
std::vector<BT> out(elements);
for(int i = 0; i < (int)elements; i++) {
out[i] = isTypeFloat ? (BT)(rand())/RAND_MAX : rand() % 100;
}
return af::array(dims, (T *)&out[0]);
}
<|endoftext|> |
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) <2015> <Stephan Gatzka>
*
* 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.
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE fetch
#include <boost/test/unit_test.hpp>
#include "json/cJSON.h"
#include "peer.h"
#include "router.h"
#include "state.h"
#include "table.h"
enum event {
UNKNOWN_EVENT,
ADD_EVENT,
CHANGE_EVENT,
REMOVE_EVENT
};
static char send_buffer[100000];
static struct peer *fetch_peer_1;
static bool message_for_wrong_peer;
static enum event fetch_peer_1_event;
static cJSON *parse_send_buffer(void)
{
char *read_ptr = send_buffer;
const char *end_parse;
cJSON *root = cJSON_ParseWithOpts(read_ptr, &end_parse, 0);
return root;
}
static enum event get_event_from_json(cJSON *json)
{
cJSON *params = cJSON_GetObjectItem(json, "params");
if (params == NULL) return UNKNOWN_EVENT;
cJSON *event = cJSON_GetObjectItem(params, "event");
if (event == NULL) return UNKNOWN_EVENT;
if (event->type != cJSON_String) return UNKNOWN_EVENT;
if (strcmp(event->valuestring, "add") == 0) return ADD_EVENT;
if (strcmp(event->valuestring, "change") == 0) return CHANGE_EVENT;
if (strcmp(event->valuestring, "remove") == 0) return REMOVE_EVENT;
return UNKNOWN_EVENT;
}
extern "C" {
int send_message(struct peer *p, const char *rendered, size_t len)
{
memcpy(send_buffer, rendered, len);
if (p == fetch_peer_1) {
cJSON *fetch_event = parse_send_buffer();
fetch_peer_1_event = get_event_from_json(fetch_event);
cJSON_Delete(fetch_event);
} else {
message_for_wrong_peer = true;
}
return 0;
}
int add_io(struct peer *p)
{
(void)p;
return 0;
}
void remove_io(const struct peer *p)
{
(void)p;
return;
}
void remove_all_methods_from_peer(struct peer *p)
{
(void)p;
}
}
struct F {
F()
{
state_hashtable_create();
p = alloc_peer(-1);
fetch_peer_1 = alloc_peer(-1);
message_for_wrong_peer = false;
fetch_peer_1_event = UNKNOWN_EVENT;
}
~F()
{
free_peer(fetch_peer_1);
free_peer(p);
state_hashtable_delete();
}
struct peer *p;
};
static struct state_or_method *get_state(const char *path)
{
return (struct state_or_method *)state_table_get(path);
}
static cJSON *create_fetch_params(const char *path_equals_string, const char *path_startsWith_string, const char *path_endsWith_string, const char *path_contains, int ignore_case)
{
cJSON *root = cJSON_CreateObject();
BOOST_REQUIRE(root != NULL);
cJSON_AddStringToObject(root, "id", "fetch_id_1");
cJSON *path = cJSON_CreateObject();
BOOST_REQUIRE(path != NULL);
cJSON_AddItemToObject(root, "path", path);
if (strlen(path_equals_string)) {
cJSON_AddStringToObject(path, "equals", path_equals_string);
}
if (strlen(path_startsWith_string)) {
cJSON_AddStringToObject(path, "startsWith", path_startsWith_string);
}
if (strlen(path_endsWith_string)) {
cJSON_AddStringToObject(path, "endsWith", path_endsWith_string);
}
if (strlen(path_contains)) {
cJSON_AddStringToObject(path, "contains", path_contains);
}
if (ignore_case) {
cJSON_AddBoolToObject(root, "caseInsensitive", 1);
}
return root;
}
BOOST_FIXTURE_TEST_CASE(fetch_matchers, F)
{
const char *path = "foo/bar";
const char *path_upper = "FOO/BAR";
const char *path_startsWith = "foo";
const char *path_endsWith = "bar";
const char *path_contains = "oo/ba";
int state_value = 12345;
{
cJSON *value = cJSON_CreateNumber(state_value);
cJSON *error = add_state_or_method_to_peer(p, path, value);
BOOST_CHECK(error == NULL);
cJSON_Delete(value);
}
struct state_or_method *s = get_state(path);
BOOST_CHECK(s->value->valueint == state_value);
{
/// is to fail because fetch is case sensitive
struct fetch *f = NULL;
cJSON *params = create_fetch_params(path_upper, "", "", "", 0);
cJSON *error = add_fetch_to_peer(fetch_peer_1, params, &f);
BOOST_REQUIRE(error == NULL);
error = add_fetch_to_states(f);
BOOST_REQUIRE(error == NULL);
BOOST_CHECK(fetch_peer_1_event == UNKNOWN_EVENT);
remove_all_fetchers_from_peer(fetch_peer_1);
cJSON_Delete(params);
}
{
struct fetch *f = NULL;
cJSON *params = create_fetch_params(path, "", "", "", 0);
cJSON *error = add_fetch_to_peer(fetch_peer_1, params, &f);
BOOST_REQUIRE(error == NULL);
error = add_fetch_to_states(f);
BOOST_REQUIRE(error == NULL);
BOOST_CHECK(fetch_peer_1_event == ADD_EVENT);
remove_all_fetchers_from_peer(fetch_peer_1);
cJSON_Delete(params);
}
{
struct fetch *f = NULL;
cJSON *params = create_fetch_params("", path_startsWith, "", "", 0);
cJSON *error = add_fetch_to_peer(fetch_peer_1, params, &f);
BOOST_REQUIRE(error == NULL);
error = add_fetch_to_states(f);
BOOST_REQUIRE(error == NULL);
BOOST_CHECK(fetch_peer_1_event == ADD_EVENT);
remove_all_fetchers_from_peer(fetch_peer_1);
cJSON_Delete(params);
}
{
struct fetch *f = NULL;
cJSON *params = create_fetch_params("", "", path_endsWith, "", 0);
cJSON *error = add_fetch_to_peer(fetch_peer_1, params, &f);
BOOST_REQUIRE(error == NULL);
error = add_fetch_to_states(f);
BOOST_REQUIRE(error == NULL);
BOOST_CHECK(fetch_peer_1_event == ADD_EVENT);
remove_all_fetchers_from_peer(fetch_peer_1);
cJSON_Delete(params);
}
{
struct fetch *f = NULL;
cJSON *params = create_fetch_params("", "", "", path_contains, 0);
cJSON *error = add_fetch_to_peer(fetch_peer_1, params, &f);
BOOST_REQUIRE(error == NULL);
error = add_fetch_to_states(f);
BOOST_REQUIRE(error == NULL);
BOOST_CHECK(fetch_peer_1_event == ADD_EVENT);
remove_all_fetchers_from_peer(fetch_peer_1);
cJSON_Delete(params);
}
}
BOOST_FIXTURE_TEST_CASE(fetch_matchers_ignoring_case, F)
{
const char *path = "foo/bar";
const char *path_upper = "FOO/BAR";
const char *path_startsWith = "FOO";
const char *path_endsWith = "BAR";
const char *path_contains = "OO/BA";
int state_value = 12345;
{
cJSON *value = cJSON_CreateNumber(state_value);
cJSON *error = add_state_or_method_to_peer(p, path, value);
BOOST_CHECK(error == NULL);
cJSON_Delete(value);
}
struct state_or_method *s = get_state(path);
BOOST_CHECK(s->value->valueint == state_value);
{
struct fetch *f = NULL;
cJSON *params = create_fetch_params(path_upper, "", "", "", 1);
cJSON *error = add_fetch_to_peer(fetch_peer_1, params, &f);
BOOST_REQUIRE(error == NULL);
error = add_fetch_to_states(f);
BOOST_REQUIRE(error == NULL);
BOOST_CHECK(fetch_peer_1_event == ADD_EVENT);
remove_all_fetchers_from_peer(fetch_peer_1);
cJSON_Delete(params);
}
{
struct fetch *f = NULL;
cJSON *params = create_fetch_params("", path_startsWith, "", "", 1);
cJSON *error = add_fetch_to_peer(fetch_peer_1, params, &f);
BOOST_REQUIRE(error == NULL);
error = add_fetch_to_states(f);
BOOST_REQUIRE(error == NULL);
BOOST_CHECK(fetch_peer_1_event == ADD_EVENT);
remove_all_fetchers_from_peer(fetch_peer_1);
cJSON_Delete(params);
}
{
struct fetch *f = NULL;
cJSON *params = create_fetch_params("", "", path_endsWith, "", 1);
cJSON *error = add_fetch_to_peer(fetch_peer_1, params, &f);
BOOST_REQUIRE(error == NULL);
error = add_fetch_to_states(f);
BOOST_REQUIRE(error == NULL);
BOOST_CHECK(fetch_peer_1_event == ADD_EVENT);
remove_all_fetchers_from_peer(fetch_peer_1);
cJSON_Delete(params);
}
{
struct fetch *f = NULL;
cJSON *params = create_fetch_params("", "", "", path_contains, 1);
cJSON *error = add_fetch_to_peer(fetch_peer_1, params, &f);
BOOST_REQUIRE(error == NULL);
error = add_fetch_to_states(f);
BOOST_REQUIRE(error == NULL);
BOOST_CHECK(fetch_peer_1_event == ADD_EVENT);
remove_all_fetchers_from_peer(fetch_peer_1);
cJSON_Delete(params);
}
}
BOOST_FIXTURE_TEST_CASE(fetch_and_change_and_remove, F)
{
const char *path = "foo/bar";
int state_value = 12345;
{
/// does not fetch anything because nothing does match
struct fetch *f = NULL;
cJSON *params = create_fetch_params(path, "", "", "", 0);
cJSON *error = add_fetch_to_peer(fetch_peer_1, params, &f);
BOOST_REQUIRE(error == NULL);
error = add_fetch_to_states(f);
BOOST_REQUIRE(error == NULL);
BOOST_CHECK(fetch_peer_1_event == UNKNOWN_EVENT);
remove_all_fetchers_from_peer(fetch_peer_1);
cJSON_Delete(params);
}
{
cJSON *value = cJSON_CreateNumber(state_value);
cJSON *error = add_state_or_method_to_peer(p, path, value);
BOOST_CHECK(error == NULL);
cJSON_Delete(value);
}
struct state_or_method *s = get_state(path);
BOOST_CHECK(s->value->valueint == state_value);
{
struct fetch *f = NULL;
cJSON *params = create_fetch_params(path, "", "", "", 0);
cJSON *error = add_fetch_to_peer(fetch_peer_1, params, &f);
BOOST_REQUIRE(error == NULL);
error = add_fetch_to_states(f);
BOOST_REQUIRE(error == NULL);
BOOST_CHECK(fetch_peer_1_event == ADD_EVENT);
cJSON *new_value = cJSON_CreateNumber(4321);
error = change_state(p, path, new_value);
BOOST_REQUIRE(error == NULL);
cJSON_Delete(new_value);
BOOST_CHECK(fetch_peer_1_event == CHANGE_EVENT);
BOOST_CHECK(!message_for_wrong_peer);
remove_all_fetchers_from_peer(fetch_peer_1);
cJSON_Delete(params);
}
{
/// fetch removal of state
struct fetch *f = NULL;
cJSON *params = create_fetch_params(path, "", "", "", 0);
cJSON *error = add_fetch_to_peer(fetch_peer_1, params, &f);
BOOST_REQUIRE(error == NULL);
error = add_fetch_to_states(f);
BOOST_REQUIRE(error == NULL);
remove_state_or_method_from_peer(p, path);
BOOST_CHECK(fetch_peer_1_event == REMOVE_EVENT);
cJSON_Delete(params);
}
}
<commit_msg>Test unfetch.<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) <2015> <Stephan Gatzka>
*
* 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.
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE fetch
#include <boost/test/unit_test.hpp>
#include "json/cJSON.h"
#include "peer.h"
#include "router.h"
#include "state.h"
#include "table.h"
enum event {
UNKNOWN_EVENT,
ADD_EVENT,
CHANGE_EVENT,
REMOVE_EVENT
};
static char send_buffer[100000];
static struct peer *fetch_peer_1;
static bool message_for_wrong_peer;
static enum event fetch_peer_1_event;
static cJSON *parse_send_buffer(void)
{
char *read_ptr = send_buffer;
const char *end_parse;
cJSON *root = cJSON_ParseWithOpts(read_ptr, &end_parse, 0);
return root;
}
static enum event get_event_from_json(cJSON *json)
{
cJSON *params = cJSON_GetObjectItem(json, "params");
if (params == NULL) return UNKNOWN_EVENT;
cJSON *event = cJSON_GetObjectItem(params, "event");
if (event == NULL) return UNKNOWN_EVENT;
if (event->type != cJSON_String) return UNKNOWN_EVENT;
if (strcmp(event->valuestring, "add") == 0) return ADD_EVENT;
if (strcmp(event->valuestring, "change") == 0) return CHANGE_EVENT;
if (strcmp(event->valuestring, "remove") == 0) return REMOVE_EVENT;
return UNKNOWN_EVENT;
}
extern "C" {
int send_message(struct peer *p, const char *rendered, size_t len)
{
memcpy(send_buffer, rendered, len);
if (p == fetch_peer_1) {
cJSON *fetch_event = parse_send_buffer();
fetch_peer_1_event = get_event_from_json(fetch_event);
cJSON_Delete(fetch_event);
} else {
message_for_wrong_peer = true;
}
return 0;
}
int add_io(struct peer *p)
{
(void)p;
return 0;
}
void remove_io(const struct peer *p)
{
(void)p;
return;
}
void remove_all_methods_from_peer(struct peer *p)
{
(void)p;
}
}
struct F {
F()
{
state_hashtable_create();
p = alloc_peer(-1);
fetch_peer_1 = alloc_peer(-1);
message_for_wrong_peer = false;
fetch_peer_1_event = UNKNOWN_EVENT;
}
~F()
{
free_peer(fetch_peer_1);
free_peer(p);
state_hashtable_delete();
}
struct peer *p;
};
static struct state_or_method *get_state(const char *path)
{
return (struct state_or_method *)state_table_get(path);
}
static cJSON *create_fetch_params(const char *path_equals_string, const char *path_startsWith_string, const char *path_endsWith_string, const char *path_contains, int ignore_case)
{
cJSON *root = cJSON_CreateObject();
BOOST_REQUIRE(root != NULL);
cJSON_AddStringToObject(root, "id", "fetch_id_1");
cJSON *path = cJSON_CreateObject();
BOOST_REQUIRE(path != NULL);
cJSON_AddItemToObject(root, "path", path);
if (strlen(path_equals_string)) {
cJSON_AddStringToObject(path, "equals", path_equals_string);
}
if (strlen(path_startsWith_string)) {
cJSON_AddStringToObject(path, "startsWith", path_startsWith_string);
}
if (strlen(path_endsWith_string)) {
cJSON_AddStringToObject(path, "endsWith", path_endsWith_string);
}
if (strlen(path_contains)) {
cJSON_AddStringToObject(path, "contains", path_contains);
}
if (ignore_case) {
cJSON_AddBoolToObject(root, "caseInsensitive", 1);
}
return root;
}
static cJSON *create_unfetch_params()
{
cJSON *root = cJSON_CreateObject();
BOOST_REQUIRE(root != NULL);
cJSON_AddStringToObject(root, "id", "fetch_id_1");
return root;
}
BOOST_FIXTURE_TEST_CASE(fetch_matchers, F)
{
const char *path = "foo/bar";
const char *path_upper = "FOO/BAR";
const char *path_startsWith = "foo";
const char *path_endsWith = "bar";
const char *path_contains = "oo/ba";
int state_value = 12345;
{
cJSON *value = cJSON_CreateNumber(state_value);
cJSON *error = add_state_or_method_to_peer(p, path, value);
BOOST_CHECK(error == NULL);
cJSON_Delete(value);
}
struct state_or_method *s = get_state(path);
BOOST_CHECK(s->value->valueint == state_value);
{
/// is to fail because fetch is case sensitive
struct fetch *f = NULL;
cJSON *params = create_fetch_params(path_upper, "", "", "", 0);
cJSON *error = add_fetch_to_peer(fetch_peer_1, params, &f);
BOOST_REQUIRE(error == NULL);
error = add_fetch_to_states(f);
BOOST_REQUIRE(error == NULL);
BOOST_CHECK(fetch_peer_1_event == UNKNOWN_EVENT);
remove_all_fetchers_from_peer(fetch_peer_1);
cJSON_Delete(params);
}
{
struct fetch *f = NULL;
cJSON *params = create_fetch_params(path, "", "", "", 0);
cJSON *error = add_fetch_to_peer(fetch_peer_1, params, &f);
BOOST_REQUIRE(error == NULL);
error = add_fetch_to_states(f);
BOOST_REQUIRE(error == NULL);
BOOST_CHECK(fetch_peer_1_event == ADD_EVENT);
remove_all_fetchers_from_peer(fetch_peer_1);
cJSON_Delete(params);
}
{
struct fetch *f = NULL;
cJSON *params = create_fetch_params("", path_startsWith, "", "", 0);
cJSON *error = add_fetch_to_peer(fetch_peer_1, params, &f);
BOOST_REQUIRE(error == NULL);
error = add_fetch_to_states(f);
BOOST_REQUIRE(error == NULL);
BOOST_CHECK(fetch_peer_1_event == ADD_EVENT);
remove_all_fetchers_from_peer(fetch_peer_1);
cJSON_Delete(params);
}
{
struct fetch *f = NULL;
cJSON *params = create_fetch_params("", "", path_endsWith, "", 0);
cJSON *error = add_fetch_to_peer(fetch_peer_1, params, &f);
BOOST_REQUIRE(error == NULL);
error = add_fetch_to_states(f);
BOOST_REQUIRE(error == NULL);
BOOST_CHECK(fetch_peer_1_event == ADD_EVENT);
remove_all_fetchers_from_peer(fetch_peer_1);
cJSON_Delete(params);
}
{
struct fetch *f = NULL;
cJSON *params = create_fetch_params("", "", "", path_contains, 0);
cJSON *error = add_fetch_to_peer(fetch_peer_1, params, &f);
BOOST_REQUIRE(error == NULL);
error = add_fetch_to_states(f);
BOOST_REQUIRE(error == NULL);
BOOST_CHECK(fetch_peer_1_event == ADD_EVENT);
remove_all_fetchers_from_peer(fetch_peer_1);
cJSON_Delete(params);
}
}
BOOST_FIXTURE_TEST_CASE(fetch_matchers_ignoring_case, F)
{
const char *path = "foo/bar";
const char *path_upper = "FOO/BAR";
const char *path_startsWith = "FOO";
const char *path_endsWith = "BAR";
const char *path_contains = "OO/BA";
int state_value = 12345;
{
cJSON *value = cJSON_CreateNumber(state_value);
cJSON *error = add_state_or_method_to_peer(p, path, value);
BOOST_CHECK(error == NULL);
cJSON_Delete(value);
}
struct state_or_method *s = get_state(path);
BOOST_CHECK(s->value->valueint == state_value);
{
struct fetch *f = NULL;
cJSON *params = create_fetch_params(path_upper, "", "", "", 1);
cJSON *error = add_fetch_to_peer(fetch_peer_1, params, &f);
BOOST_REQUIRE(error == NULL);
error = add_fetch_to_states(f);
BOOST_REQUIRE(error == NULL);
BOOST_CHECK(fetch_peer_1_event == ADD_EVENT);
remove_all_fetchers_from_peer(fetch_peer_1);
cJSON_Delete(params);
}
{
struct fetch *f = NULL;
cJSON *params = create_fetch_params("", path_startsWith, "", "", 1);
cJSON *error = add_fetch_to_peer(fetch_peer_1, params, &f);
BOOST_REQUIRE(error == NULL);
error = add_fetch_to_states(f);
BOOST_REQUIRE(error == NULL);
BOOST_CHECK(fetch_peer_1_event == ADD_EVENT);
remove_all_fetchers_from_peer(fetch_peer_1);
cJSON_Delete(params);
}
{
struct fetch *f = NULL;
cJSON *params = create_fetch_params("", "", path_endsWith, "", 1);
cJSON *error = add_fetch_to_peer(fetch_peer_1, params, &f);
BOOST_REQUIRE(error == NULL);
error = add_fetch_to_states(f);
BOOST_REQUIRE(error == NULL);
BOOST_CHECK(fetch_peer_1_event == ADD_EVENT);
remove_all_fetchers_from_peer(fetch_peer_1);
cJSON_Delete(params);
}
{
struct fetch *f = NULL;
cJSON *params = create_fetch_params("", "", "", path_contains, 1);
cJSON *error = add_fetch_to_peer(fetch_peer_1, params, &f);
BOOST_REQUIRE(error == NULL);
error = add_fetch_to_states(f);
BOOST_REQUIRE(error == NULL);
BOOST_CHECK(fetch_peer_1_event == ADD_EVENT);
remove_all_fetchers_from_peer(fetch_peer_1);
cJSON_Delete(params);
}
}
BOOST_FIXTURE_TEST_CASE(fetch_and_change_and_remove, F)
{
const char *path = "foo/bar";
int state_value = 12345;
{
/// does not fetch anything because nothing does match
struct fetch *f = NULL;
cJSON *params = create_fetch_params(path, "", "", "", 0);
cJSON *error = add_fetch_to_peer(fetch_peer_1, params, &f);
BOOST_REQUIRE(error == NULL);
error = add_fetch_to_states(f);
BOOST_REQUIRE(error == NULL);
BOOST_CHECK(fetch_peer_1_event == UNKNOWN_EVENT);
remove_all_fetchers_from_peer(fetch_peer_1);
cJSON_Delete(params);
}
{
cJSON *value = cJSON_CreateNumber(state_value);
cJSON *error = add_state_or_method_to_peer(p, path, value);
BOOST_CHECK(error == NULL);
cJSON_Delete(value);
}
struct state_or_method *s = get_state(path);
BOOST_CHECK(s->value->valueint == state_value);
{
struct fetch *f = NULL;
cJSON *params = create_fetch_params(path, "", "", "", 0);
cJSON *error = add_fetch_to_peer(fetch_peer_1, params, &f);
BOOST_REQUIRE(error == NULL);
error = add_fetch_to_states(f);
BOOST_REQUIRE(error == NULL);
BOOST_CHECK(fetch_peer_1_event == ADD_EVENT);
cJSON *new_value = cJSON_CreateNumber(4321);
error = change_state(p, path, new_value);
BOOST_REQUIRE(error == NULL);
cJSON_Delete(new_value);
BOOST_CHECK(fetch_peer_1_event == CHANGE_EVENT);
BOOST_CHECK(!message_for_wrong_peer);
remove_all_fetchers_from_peer(fetch_peer_1);
cJSON_Delete(params);
}
{
/// fetch removal of state
struct fetch *f = NULL;
cJSON *params = create_fetch_params(path, "", "", "", 0);
cJSON *error = add_fetch_to_peer(fetch_peer_1, params, &f);
BOOST_REQUIRE(error == NULL);
error = add_fetch_to_states(f);
BOOST_REQUIRE(error == NULL);
remove_state_or_method_from_peer(p, path);
BOOST_CHECK(fetch_peer_1_event == REMOVE_EVENT);
cJSON_Delete(params);
}
}
BOOST_FIXTURE_TEST_CASE(fetch_and_unfetch, F)
{
struct fetch *f = NULL;
cJSON *params = create_fetch_params("", "", "", "", 0);
cJSON *error = add_fetch_to_peer(fetch_peer_1, params, &f);
BOOST_REQUIRE(error == NULL);
cJSON_Delete(params);
params = create_unfetch_params();
error = remove_fetch_from_peer(fetch_peer_1, params);
BOOST_REQUIRE(error == NULL);
cJSON_Delete(params);
}
<|endoftext|> |
<commit_before>#include <boost/test/unit_test.hpp>
#include "../src/MLGrid.hpp"
#include "../src/GridStorageAccessInterface.hpp"
#include "../src/GridStorageAccess.hpp"
#include "../src/GridStorageFacade.hpp"
using namespace envire::maps;
class PatchBase
{
public:
PatchBase(double m, double ma) : min(m), max(ma)
{
}
double min;
double max;
double getMiddle() const
{
return min + (max - min) / 2.0;
}
bool operator<(const PatchBase &other) const{
return getMiddle() < other.getMiddle();
}
double getMin() const {
return min;
};
double getMax() const {
return max;
};
virtual void test()
{
std::cout << "Base class " << std::endl;
};
};
class Patch : public PatchBase
{
public:
Patch() : PatchBase(0,0)
{
};
Patch(double m, double ma) : PatchBase(m, ma)
{
};
virtual void test()
{
std::cout << "Derived Class " << std::endl;
};
double someValue;
};
BOOST_AUTO_TEST_CASE(test_levelAccess)
{
Patch p;
PatchBase b = p;
p.test();
b.test();
LevelList<Patch> list;
LevelListAccess<PatchBase> *access = new LevelListAccessImpl<Patch, PatchBase>(&list);
delete access;
}
BOOST_AUTO_TEST_CASE(test_levelAccess2)
{
DerivableLevelList<Patch, PatchBase> list;
std::cout << "SuperClass " << std::endl;
list.begin();
std::cout << "BaseClass " << std::endl;
DerivableLevelList<PatchBase> *listBase = &list;
listBase->begin();
// LevelListAccess<PatchBase> *access = new LevelListAccessImpl<Patch, PatchBase>(&list);
}
BOOST_AUTO_TEST_CASE(test_mapAccess)
{
GridMap<Patch> map;
GridStorageAccessInterface<PatchBase> *test = new GridStorageAccess<Patch, PatchBase>(&map);
GridMap<PatchBase, GridStorageFacade<PatchBase> > test2(map, GridStorageFacade<PatchBase>(test));
}
BOOST_AUTO_TEST_CASE(test_mapAccess2)
{
GridMap<DerivableLevelList<Patch, PatchBase> > map(Vector2ui(5,5), Eigen::Vector2d(0.5,0.5), DerivableLevelList<Patch, PatchBase>());
GridStorageAccessInterface<DerivableLevelList<PatchBase, PatchBase> > *test = new GridStorageAccess<DerivableLevelList<Patch, PatchBase>, DerivableLevelList<PatchBase, PatchBase> >(&map);
GridMap<DerivableLevelList<PatchBase, PatchBase>, GridStorageFacade<DerivableLevelList<PatchBase, PatchBase> > > test2(map, GridStorageFacade<DerivableLevelList<PatchBase, PatchBase> >(test));
Patch p(38, 50);
Patch p2(55, 80);
map.at(2,2).insert(p2);
map.at(2,2).insert(p);
BOOST_CHECK_EQUAL(map.at(2,2).size(), 2);
{
auto it = map.at(2,2).begin();
BOOST_CHECK_EQUAL(it->getMin(), 38);
it++;
BOOST_CHECK_EQUAL(it->getMin(), 55);
}
BOOST_CHECK_EQUAL(test2.at(2,2).size(), 2);
{
auto it = test2.at(2,2).begin();
BOOST_CHECK_EQUAL(it->getMin(), 38);
it++;
BOOST_CHECK_EQUAL(it->getMin(), 55);
}
}
BOOST_AUTO_TEST_CASE(test_base_class)
{
MLGrid<PatchBase> grid(Vector2ui(5,5), Eigen::Vector2d(0.5,0.5));
PatchBase p(38, 50);
PatchBase p2(55, 80);
grid.at(2,2).insert(p2);
grid.at(2,2).insert(p);
BOOST_CHECK_EQUAL(grid.at(2,2).size(), 2);
{
auto it = grid.at(2,2).begin();
BOOST_CHECK_EQUAL(it->getMin(), 38);
it++;
BOOST_CHECK_EQUAL(it->getMin(), 55);
}
// for(const Patch &p : grid.at(2,2))
// std::cout << "Bar is " << p.getMin() << std::endl;
// Eigen::Vector3d pos;
// grid.fromGrid(Index(2,2), pos);
//
// std::cout << "From" << pos.transpose() << std::endl;
{
Eigen::AlignedBox3f box(Eigen::Vector3f(0.5, .5, 49),Eigen::Vector3f(2.0, 2.0, 60));
MLGrid<PatchBase>::MLView view = grid.intersectCuboid(box);
// std::cout << "Subview Size : " << view.getNumCells().transpose() << std::endl;
// for(size_t x = 0; x < view.getNumCells().x(); x++)
// {
// for(size_t y = 0; y < view.getNumCells().y(); y++)
// {
// for(const Patch *p : view.at(x,y))
// std::cout << "X " << x << " Y " << y << " Bar is " << p->getMin() << std::endl;
// }
// }
//
BOOST_CHECK_EQUAL(view.at(1,1).size(), 2);
auto it = view.at(1,1).begin();
BOOST_CHECK_EQUAL((*it)->getMin(), 38);
it++;
BOOST_CHECK_EQUAL((*it)->getMin(), 55);
}
{
Eigen::AlignedBox3f box(Eigen::Vector3f(0.5, .5, 37),Eigen::Vector3f(2.0, 2.0, 38));
MLGrid<PatchBase>::MLView view = grid.intersectCuboid(box);
BOOST_CHECK_EQUAL(view.at(1,1).size(), 1);
auto it = view.at(1,1).begin();
BOOST_CHECK_EQUAL((*it)->getMin(), 38);
}
{
Eigen::AlignedBox3f box(Eigen::Vector3f(0.5, .5, 80),Eigen::Vector3f(2.0, 2.0, 105));
MLGrid<PatchBase>::MLView view = grid.intersectCuboid(box);
BOOST_CHECK_EQUAL(view.at(1,1).size(), 1);
auto it = view.at(1,1).begin();
BOOST_CHECK_EQUAL((*it)->getMin(), 55);
}
}
<commit_msg>add test to mlgrid<commit_after>#include <boost/test/unit_test.hpp>
#include "../src/MLGrid.hpp"
#include "../src/GridStorageAccessInterface.hpp"
#include "../src/GridStorageAccess.hpp"
#include "../src/GridStorageFacade.hpp"
using namespace envire::maps;
class PatchBase
{
public:
PatchBase(double m, double ma) : min(m), max(ma)
{
}
double min;
double max;
double getMiddle() const
{
return min + (max - min) / 2.0;
}
bool operator<(const PatchBase &other) const{
return getMiddle() < other.getMiddle();
}
double getMin() const {
return min;
};
double getMax() const {
return max;
};
virtual void test()
{
std::cout << "Base class " << std::endl;
};
};
class Patch : public PatchBase
{
public:
Patch() : PatchBase(0,0)
{
};
Patch(double m, double ma) : PatchBase(m, ma)
{
};
virtual void test()
{
std::cout << "Derived Class " << std::endl;
};
double someValue;
};
BOOST_AUTO_TEST_CASE(test_levelAccess)
{
Patch p;
PatchBase b = p;
p.test();
b.test();
LevelList<Patch> list;
LevelListAccess<PatchBase> *access = new LevelListAccessImpl<Patch, PatchBase>(&list);
delete access;
}
BOOST_AUTO_TEST_CASE(test_levelAccess2)
{
DerivableLevelList<Patch, PatchBase> list;
std::cout << "SuperClass " << std::endl;
list.begin();
std::cout << "BaseClass " << std::endl;
DerivableLevelList<PatchBase> *listBase = &list;
listBase->begin();
// LevelListAccess<PatchBase> *access = new LevelListAccessImpl<Patch, PatchBase>(&list);
}
BOOST_AUTO_TEST_CASE(test_mapAccess)
{
GridMap<Patch> map;
GridStorageAccessInterface<PatchBase> *test = new GridStorageAccess<Patch, PatchBase>(&map);
GridMap<PatchBase, GridStorageFacade<PatchBase> > test2(map, GridStorageFacade<PatchBase>(test));
}
BOOST_AUTO_TEST_CASE(test_map_access3)
{
GridMap<Patch> map(Vector2ui(2,2), Eigen::Vector2d(1,1), Patch(0,0));
map.at(0,0) = Patch(0, 0);
map.at(0,1) = Patch(0, 1);
map.at(1,0) = Patch(1, 0);
map.at(1,1) = Patch(1, 1);
map.at(0,0).test();
map.at(0,1).test();
for (auto it = map.begin(); it != map.end(); ++it)
{
std::cout << it->getMin() << " " << it->getMax() << std::endl;
}
GridStorageAccessInterface<PatchBase> *test = new GridStorageAccess<Patch, PatchBase>(&map);
GridMap<PatchBase, GridStorageFacade<PatchBase> > test2(map, GridStorageFacade<PatchBase>(test));
test2.at(0,0).test();
test2.at(0,1).test();
for (auto it = test2.begin(); it != test2.end(); ++it)
{
std::cout << it->getMin() << " " << it->getMax() << std::endl;
}
}
#include <ctime>
BOOST_AUTO_TEST_CASE(test_map_access_time)
{
GridMap<Patch> map(Vector2ui(1000,1000), Eigen::Vector2d(1,1), Patch(0,0));
clock_t begin = clock();
for (unsigned int x = 0; x < 1000; ++x)
{
for (unsigned int y = 0; y < 1000; ++y)
{
map.at(x, y).getMin();
}
}
clock_t end = clock();
double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
std::cout << "map: " << elapsed_secs << std::endl;
begin = clock();
for (auto it = map.begin(); it != map.end(); ++it)
{
it->getMin();
}
end = clock();
elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
std::cout << "map: " << elapsed_secs << std::endl;
GridStorageAccessInterface<PatchBase> *test = new GridStorageAccess<Patch, PatchBase>(&map);
GridMap<PatchBase, GridStorageFacade<PatchBase> > test2(map, GridStorageFacade<PatchBase>(test));
begin = clock();
for (unsigned int x = 0; x < 1000; ++x)
{
for (unsigned int y = 0; y < 1000; ++y)
{
test2.at(x, y).getMin();
}
}
end = clock();
elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
std::cout << "test2: " << elapsed_secs << std::endl;
auto it_2 = test2.begin();
begin = clock();
for (auto it = test2.begin(); it != test2.end(); ++it)
{
it->getMin();
}
end = clock();
elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
std::cout << "test2: " << elapsed_secs << std::endl;
}
BOOST_AUTO_TEST_CASE(test_mapAccess2)
{
GridMap<DerivableLevelList<Patch, PatchBase> > map(Vector2ui(5,5), Eigen::Vector2d(0.5,0.5), DerivableLevelList<Patch, PatchBase>());
GridStorageAccessInterface<DerivableLevelList<PatchBase, PatchBase> > *test = new GridStorageAccess<DerivableLevelList<Patch, PatchBase>, DerivableLevelList<PatchBase, PatchBase> >(&map);
GridMap<DerivableLevelList<PatchBase, PatchBase>, GridStorageFacade<DerivableLevelList<PatchBase, PatchBase> > > test2(map, GridStorageFacade<DerivableLevelList<PatchBase, PatchBase> >(test));
Patch p(38, 50);
Patch p2(55, 80);
map.at(2,2).insert(p2);
map.at(2,2).insert(p);
BOOST_CHECK_EQUAL(map.at(2,2).size(), 2);
{
auto it = map.at(2,2).begin();
BOOST_CHECK_EQUAL(it->getMin(), 38);
it++;
BOOST_CHECK_EQUAL(it->getMin(), 55);
}
BOOST_CHECK_EQUAL(test2.at(2,2).size(), 2);
{
auto it = test2.at(2,2).begin();
BOOST_CHECK_EQUAL(it->getMin(), 38);
it++;
BOOST_CHECK_EQUAL(it->getMin(), 55);
}
}
BOOST_AUTO_TEST_CASE(test_base_class)
{
MLGrid<PatchBase> grid(Vector2ui(5,5), Eigen::Vector2d(0.5,0.5));
PatchBase p(38, 50);
PatchBase p2(55, 80);
grid.at(2,2).insert(p2);
grid.at(2,2).insert(p);
BOOST_CHECK_EQUAL(grid.at(2,2).size(), 2);
{
auto it = grid.at(2,2).begin();
BOOST_CHECK_EQUAL(it->getMin(), 38);
it++;
BOOST_CHECK_EQUAL(it->getMin(), 55);
}
// for(const Patch &p : grid.at(2,2))
// std::cout << "Bar is " << p.getMin() << std::endl;
// Eigen::Vector3d pos;
// grid.fromGrid(Index(2,2), pos);
//
// std::cout << "From" << pos.transpose() << std::endl;
{
Eigen::AlignedBox3f box(Eigen::Vector3f(0.5, .5, 49),Eigen::Vector3f(2.0, 2.0, 60));
MLGrid<PatchBase>::MLView view = grid.intersectCuboid(box);
// std::cout << "Subview Size : " << view.getNumCells().transpose() << std::endl;
// for(size_t x = 0; x < view.getNumCells().x(); x++)
// {
// for(size_t y = 0; y < view.getNumCells().y(); y++)
// {
// for(const Patch *p : view.at(x,y))
// std::cout << "X " << x << " Y " << y << " Bar is " << p->getMin() << std::endl;
// }
// }
//
BOOST_CHECK_EQUAL(view.at(1,1).size(), 2);
auto it = view.at(1,1).begin();
BOOST_CHECK_EQUAL((*it)->getMin(), 38);
it++;
BOOST_CHECK_EQUAL((*it)->getMin(), 55);
}
{
Eigen::AlignedBox3f box(Eigen::Vector3f(0.5, .5, 37),Eigen::Vector3f(2.0, 2.0, 38));
MLGrid<PatchBase>::MLView view = grid.intersectCuboid(box);
BOOST_CHECK_EQUAL(view.at(1,1).size(), 1);
auto it = view.at(1,1).begin();
BOOST_CHECK_EQUAL((*it)->getMin(), 38);
}
{
Eigen::AlignedBox3f box(Eigen::Vector3f(0.5, .5, 80),Eigen::Vector3f(2.0, 2.0, 105));
MLGrid<PatchBase>::MLView view = grid.intersectCuboid(box);
BOOST_CHECK_EQUAL(view.at(1,1).size(), 1);
auto it = view.at(1,1).begin();
BOOST_CHECK_EQUAL((*it)->getMin(), 55);
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003 - 2005, Arvid Norberg, Daniel Wallin
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 Rasterbar Software 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 OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <cassert>
#include <iostream>
#include <vector>
#include <utility>
#include <set>
#include "libtorrent/buffer.hpp"
#include "libtorrent/chained_buffer.hpp"
#include "libtorrent/socket.hpp"
#include "test.hpp"
using namespace libtorrent;
/*
template<class T>
T const& min_(T const& x, T const& y)
{
return x < y ? x : y;
}
void test_speed()
{
buffer b;
char data[32];
srand(0);
boost::timer t;
int const iterations = 5000000;
int const step = iterations / 20;
for (int i = 0; i < iterations; ++i)
{
int x = rand();
if (i % step == 0) std::cerr << ".";
std::size_t n = rand() % 32;
n = 32;
if (x % 2)
{
b.insert(data, data + n);
}
else
{
b.erase(min_(b.size(), n));
}
}
float t1 = t.elapsed();
std::cerr << "buffer elapsed: " << t.elapsed() << "\n";
std::vector<char> v;
srand(0);
t.restart();
for (int i = 0; i < iterations; ++i)
{
int x = rand();
if (i % step == 0) std::cerr << ".";
std::size_t n = rand() % 32;
n = 32;
if (x % 2)
{
v.insert(v.end(), data, data + n);
}
else
{
v.erase(v.begin(), v.begin() + min_(v.size(), n));
}
}
float t2 = t.elapsed();
std::cerr << "std::vector elapsed: " << t.elapsed() << "\n";
assert(t1 < t2);
}
*/
// -- test buffer --
void test_buffer()
{
char data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
buffer b;
TEST_CHECK(b.size() == 0);
TEST_CHECK(b.capacity() == 0);
TEST_CHECK(b.empty());
b.resize(10);
TEST_CHECK(b.size() == 10);
TEST_CHECK(b.capacity() == 10);
std::memcpy(b.begin(), data, 10);
b.reserve(50);
TEST_CHECK(std::memcmp(b.begin(), data, 10) == 0);
TEST_CHECK(b.capacity() == 50);
b.erase(b.begin() + 6, b.end());
TEST_CHECK(std::memcmp(b.begin(), data, 6) == 0);
TEST_CHECK(b.capacity() == 50);
TEST_CHECK(b.size() == 6);
b.insert(b.begin(), data + 5, data + 10);
TEST_CHECK(b.capacity() == 50);
TEST_CHECK(b.size() == 11);
TEST_CHECK(std::memcmp(b.begin(), data + 5, 5) == 0);
b.clear();
TEST_CHECK(b.size() == 0);
TEST_CHECK(b.capacity() == 50);
b.insert(b.end(), data, data + 10);
TEST_CHECK(b.size() == 10);
TEST_CHECK(std::memcmp(b.begin(), data, 10) == 0);
b.erase(b.begin(), b.end());
TEST_CHECK(b.capacity() == 50);
TEST_CHECK(b.size() == 0);
buffer().swap(b);
TEST_CHECK(b.capacity() == 0);
}
// -- test chained buffer --
std::set<char*> buffer_list;
void free_buffer(char* m)
{
std::set<char*>::iterator i = buffer_list.find(m);
TEST_CHECK(i != buffer_list.end());
buffer_list.erase(i);
std::free(m);
}
char* allocate_buffer(int size)
{
char* mem = (char*)std::malloc(size);
buffer_list.insert(mem);
return mem;
}
template <class T>
int copy_buffers(T const& b, char* target)
{
int copied = 0;
for (typename T::const_iterator i = b.begin()
, end(b.end()); i != end; ++i)
{
memcpy(target, libtorrent::asio::buffer_cast<char const*>(*i), libtorrent::asio::buffer_size(*i));
target += libtorrent::asio::buffer_size(*i);
copied += libtorrent::asio::buffer_size(*i);
}
return copied;
}
bool compare_chained_buffer(chained_buffer& b, char const* mem, int size)
{
if (size == 0) return true;
std::vector<char> flat(size);
std::list<libtorrent::asio::const_buffer> const& iovec2 = b.build_iovec(size);
int copied = copy_buffers(iovec2, &flat[0]);
TEST_CHECK(copied == size);
return std::memcmp(&flat[0], mem, size) == 0;
}
void test_chained_buffer()
{
char data[] = "foobar";
{
chained_buffer b;
TEST_CHECK(b.empty());
TEST_CHECK(b.capacity() == 0);
TEST_CHECK(b.size() == 0);
TEST_CHECK(b.space_in_last_buffer() == 0);
TEST_CHECK(buffer_list.empty());
char* b1 = allocate_buffer(512);
std::memcpy(b1, data, 6);
b.append_buffer(b1, 512, 6, (void(*)(char*))&free_buffer);
TEST_CHECK(buffer_list.size() == 1);
TEST_CHECK(b.capacity() == 512);
TEST_CHECK(b.size() == 6);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
b.pop_front(3);
TEST_CHECK(b.capacity() == 512);
TEST_CHECK(b.size() == 3);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
bool ret = b.append(data, 6);
TEST_CHECK(ret == true);
TEST_CHECK(b.capacity() == 512);
TEST_CHECK(b.size() == 9);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 12);
ret = b.append(data, 1024);
TEST_CHECK(ret == false);
char* b2 = allocate_buffer(512);
std::memcpy(b2, data, 6);
b.append_buffer(b2, 512, 6, (void(*)(char*))&free_buffer);
TEST_CHECK(buffer_list.size() == 2);
char* b3 = allocate_buffer(512);
std::memcpy(b3, data, 6);
b.append_buffer(b3, 512, 6, (void(*)(char*))&free_buffer);
TEST_CHECK(buffer_list.size() == 3);
TEST_CHECK(b.capacity() == 512 * 3);
TEST_CHECK(b.size() == 21);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
TEST_CHECK(compare_chained_buffer(b, "barfoobar", 9));
for (int i = 1; i < 21; ++i)
TEST_CHECK(compare_chained_buffer(b, "barfoobarfoobarfoobar", i));
b.pop_front(5 + 6);
TEST_CHECK(buffer_list.size() == 2);
TEST_CHECK(b.capacity() == 512 * 2);
TEST_CHECK(b.size() == 10);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
char const* str = "obarfooba";
TEST_CHECK(compare_chained_buffer(b, str, 9));
for (int i = 0; i < 9; ++i)
{
b.pop_front(1);
++str;
TEST_CHECK(compare_chained_buffer(b, str, 8 - i));
TEST_CHECK(b.size() == 9 - i);
}
char* b4 = allocate_buffer(20);
std::memcpy(b4, data, 6);
std::memcpy(b4 + 6, data, 6);
b.append_buffer(b4, 20, 12, (void(*)(char*))&free_buffer);
TEST_CHECK(b.space_in_last_buffer() == 8);
ret = b.append(data, 6);
TEST_CHECK(ret == true);
TEST_CHECK(b.space_in_last_buffer() == 2);
std::cout << b.space_in_last_buffer() << std::endl;
ret = b.append(data, 2);
TEST_CHECK(ret == true);
TEST_CHECK(b.space_in_last_buffer() == 0);
std::cout << b.space_in_last_buffer() << std::endl;
char* b5 = allocate_buffer(20);
std::memcpy(b4, data, 6);
b.append_buffer(b5, 20, 6, (void(*)(char*))&free_buffer);
b.pop_front(22);
TEST_CHECK(b.size() == 5);
}
TEST_CHECK(buffer_list.empty());
}
int test_main()
{
test_buffer();
test_chained_buffer();
return 0;
}
<commit_msg>fix potential buffer overrun in unit test<commit_after>/*
Copyright (c) 2003 - 2005, Arvid Norberg, Daniel Wallin
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 Rasterbar Software 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 OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <cassert>
#include <iostream>
#include <vector>
#include <utility>
#include <set>
#include "libtorrent/buffer.hpp"
#include "libtorrent/chained_buffer.hpp"
#include "libtorrent/socket.hpp"
#include "test.hpp"
using namespace libtorrent;
/*
template<class T>
T const& min_(T const& x, T const& y)
{
return x < y ? x : y;
}
void test_speed()
{
buffer b;
char data[32];
srand(0);
boost::timer t;
int const iterations = 5000000;
int const step = iterations / 20;
for (int i = 0; i < iterations; ++i)
{
int x = rand();
if (i % step == 0) std::cerr << ".";
std::size_t n = rand() % 32;
n = 32;
if (x % 2)
{
b.insert(data, data + n);
}
else
{
b.erase(min_(b.size(), n));
}
}
float t1 = t.elapsed();
std::cerr << "buffer elapsed: " << t.elapsed() << "\n";
std::vector<char> v;
srand(0);
t.restart();
for (int i = 0; i < iterations; ++i)
{
int x = rand();
if (i % step == 0) std::cerr << ".";
std::size_t n = rand() % 32;
n = 32;
if (x % 2)
{
v.insert(v.end(), data, data + n);
}
else
{
v.erase(v.begin(), v.begin() + min_(v.size(), n));
}
}
float t2 = t.elapsed();
std::cerr << "std::vector elapsed: " << t.elapsed() << "\n";
assert(t1 < t2);
}
*/
// -- test buffer --
void test_buffer()
{
char data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
buffer b;
TEST_CHECK(b.size() == 0);
TEST_CHECK(b.capacity() == 0);
TEST_CHECK(b.empty());
b.resize(10);
TEST_CHECK(b.size() == 10);
TEST_CHECK(b.capacity() == 10);
std::memcpy(b.begin(), data, 10);
b.reserve(50);
TEST_CHECK(std::memcmp(b.begin(), data, 10) == 0);
TEST_CHECK(b.capacity() == 50);
b.erase(b.begin() + 6, b.end());
TEST_CHECK(std::memcmp(b.begin(), data, 6) == 0);
TEST_CHECK(b.capacity() == 50);
TEST_CHECK(b.size() == 6);
b.insert(b.begin(), data + 5, data + 10);
TEST_CHECK(b.capacity() == 50);
TEST_CHECK(b.size() == 11);
TEST_CHECK(std::memcmp(b.begin(), data + 5, 5) == 0);
b.clear();
TEST_CHECK(b.size() == 0);
TEST_CHECK(b.capacity() == 50);
b.insert(b.end(), data, data + 10);
TEST_CHECK(b.size() == 10);
TEST_CHECK(std::memcmp(b.begin(), data, 10) == 0);
b.erase(b.begin(), b.end());
TEST_CHECK(b.capacity() == 50);
TEST_CHECK(b.size() == 0);
buffer().swap(b);
TEST_CHECK(b.capacity() == 0);
}
// -- test chained buffer --
std::set<char*> buffer_list;
void free_buffer(char* m)
{
std::set<char*>::iterator i = buffer_list.find(m);
TEST_CHECK(i != buffer_list.end());
buffer_list.erase(i);
std::free(m);
}
char* allocate_buffer(int size)
{
char* mem = (char*)std::malloc(size);
buffer_list.insert(mem);
return mem;
}
template <class T>
int copy_buffers(T const& b, char* target)
{
int copied = 0;
for (typename T::const_iterator i = b.begin()
, end(b.end()); i != end; ++i)
{
memcpy(target, libtorrent::asio::buffer_cast<char const*>(*i), libtorrent::asio::buffer_size(*i));
target += libtorrent::asio::buffer_size(*i);
copied += libtorrent::asio::buffer_size(*i);
}
return copied;
}
bool compare_chained_buffer(chained_buffer& b, char const* mem, int size)
{
if (size == 0) return true;
std::vector<char> flat(size);
std::list<libtorrent::asio::const_buffer> const& iovec2 = b.build_iovec(size);
int copied = copy_buffers(iovec2, &flat[0]);
TEST_CHECK(copied == size);
return std::memcmp(&flat[0], mem, size) == 0;
}
void test_chained_buffer()
{
char data[] = "foobar";
{
chained_buffer b;
TEST_CHECK(b.empty());
TEST_CHECK(b.capacity() == 0);
TEST_CHECK(b.size() == 0);
TEST_CHECK(b.space_in_last_buffer() == 0);
TEST_CHECK(buffer_list.empty());
char* b1 = allocate_buffer(512);
std::memcpy(b1, data, 6);
b.append_buffer(b1, 512, 6, (void(*)(char*))&free_buffer);
TEST_CHECK(buffer_list.size() == 1);
TEST_CHECK(b.capacity() == 512);
TEST_CHECK(b.size() == 6);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
b.pop_front(3);
TEST_CHECK(b.capacity() == 512);
TEST_CHECK(b.size() == 3);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
bool ret = b.append(data, 6);
TEST_CHECK(ret == true);
TEST_CHECK(b.capacity() == 512);
TEST_CHECK(b.size() == 9);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 12);
char data2[1024];
ret = b.append(data2, 1024);
TEST_CHECK(ret == false);
char* b2 = allocate_buffer(512);
std::memcpy(b2, data, 6);
b.append_buffer(b2, 512, 6, (void(*)(char*))&free_buffer);
TEST_CHECK(buffer_list.size() == 2);
char* b3 = allocate_buffer(512);
std::memcpy(b3, data, 6);
b.append_buffer(b3, 512, 6, (void(*)(char*))&free_buffer);
TEST_CHECK(buffer_list.size() == 3);
TEST_CHECK(b.capacity() == 512 * 3);
TEST_CHECK(b.size() == 21);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
TEST_CHECK(compare_chained_buffer(b, "barfoobar", 9));
for (int i = 1; i < 21; ++i)
TEST_CHECK(compare_chained_buffer(b, "barfoobarfoobarfoobar", i));
b.pop_front(5 + 6);
TEST_CHECK(buffer_list.size() == 2);
TEST_CHECK(b.capacity() == 512 * 2);
TEST_CHECK(b.size() == 10);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
char const* str = "obarfooba";
TEST_CHECK(compare_chained_buffer(b, str, 9));
for (int i = 0; i < 9; ++i)
{
b.pop_front(1);
++str;
TEST_CHECK(compare_chained_buffer(b, str, 8 - i));
TEST_CHECK(b.size() == 9 - i);
}
char* b4 = allocate_buffer(20);
std::memcpy(b4, data, 6);
std::memcpy(b4 + 6, data, 6);
b.append_buffer(b4, 20, 12, (void(*)(char*))&free_buffer);
TEST_CHECK(b.space_in_last_buffer() == 8);
ret = b.append(data, 6);
TEST_CHECK(ret == true);
TEST_CHECK(b.space_in_last_buffer() == 2);
std::cout << b.space_in_last_buffer() << std::endl;
ret = b.append(data, 2);
TEST_CHECK(ret == true);
TEST_CHECK(b.space_in_last_buffer() == 0);
std::cout << b.space_in_last_buffer() << std::endl;
char* b5 = allocate_buffer(20);
std::memcpy(b4, data, 6);
b.append_buffer(b5, 20, 6, (void(*)(char*))&free_buffer);
b.pop_front(22);
TEST_CHECK(b.size() == 5);
}
TEST_CHECK(buffer_list.empty());
}
int test_main()
{
test_buffer();
test_chained_buffer();
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c)2008-2012, Preferred Infrastructure Inc.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of Preferred Infrastructure nor the names of other
// 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
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "parser.h"
#include <iostream>
#include <new>
#include <stack>
#include <cmath>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include "../../lang/exception.h"
namespace pfi {
namespace text {
namespace json {
class json_builder : public json_parser::callback {
public:
const json& get() const {
if (stk.size() != 1)
throw pfi::lang::parse_error();
return stk[0];
}
void null() {
stk.push_back(new json_null());
}
void boolean(bool val) {
stk.push_back(new json_bool(val));
}
void integer(int64_t val) {
stk.push_back(new json_integer(val));
}
void number(double val) {
stk.push_back(new json_float(val));
}
void string(const char* val, size_t len) {
stk.push_back(new json_string(std::string(val, val+len)));
}
void start_object() {
ixs.push(stk.size());
}
void object_key(const char* val, size_t len) {
key.push_back(std::string(val, val+len));
}
void end_object() {
json obj(new json_object());
int ix = ixs.top();
int jx = stk.size();
int sz = jx - ix;
for (int i = 0; i < sz; i++)
obj.add(key[key.size() - sz + i], stk[ix + i]);
stk.push_back(obj);
stk.erase(stk.end() - sz - 1, stk.end() - 1);
key.erase(key.end() - sz, key.end());
ixs.pop();
}
void start_array() {
ixs.push(stk.size());
}
void end_array() {
json obj(new json_array());
int ix = ixs.top();
int jx = stk.size();
int sz = jx - ix;
for (int i = 0; i < sz; i++)
obj.add(stk[ix + i]);
stk.push_back(obj);
stk.erase(stk.end() - sz - 1, stk.end() - 1);
ixs.pop();
}
std::vector<json> stk;
std::vector<std::string> key;
std::stack<int> ixs;
};
json_parser::json_parser(std::istream& is)
: is(is), it(is), end(), lineno(1), charno(1), cbuf(-1)
{
buf_len = 256;
if ((buf = static_cast<char*>(malloc(buf_len))) == 0)
throw std::bad_alloc();
}
json_parser::~json_parser()
{
free(buf);
}
json json_parser::parse()
{
json_builder jb;
parse_stream(jb);
return jb.get();
}
void json_parser::parse_stream(callback& cb)
{
ss();
if (it == end)
throw lang::end_of_data("json_parser reached end of data");
return parse_impl(cb);
}
void json_parser::parse_impl(callback& cb)
{
ss();
switch(peek()) {
case '{':
parse_object(cb);
return;
case '[':
parse_array(cb);
return;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case '-':
parse_number(cb);
return;
case '\"':
parse_string(cb);
return;
case 'f':
parse_false(cb);
return;
case 'n':
parse_null(cb);
return;
case 't':
parse_true(cb);
return;
default: {
char err_msg[64];
snprintf(err_msg, sizeof(err_msg),
"invalid char: \'%s\' (U+%04X)",
pfi::data::string::uchar_to_string(peek()).c_str(), peek());
error(err_msg);
}
}
return; // dmy for supressing warning
}
void json_parser::parse_object(callback& cb)
{
cb.start_object();
smatch('{');
for (int i = 0; ; i++) {
if (speek() == '}')
break;
if (i > 0)
smatch(',');
ss();
int len = 0;
parse_string_prim(buf, buf_len, len);
cb.object_key(buf, len);
smatch(':');
parse_impl(cb);
}
smatch('}');
cb.end_object();
}
void json_parser::parse_array(callback& cb)
{
cb.start_array();
smatch('[');
for (int i = 0; ; i++) {
if (speek() == ']')
break;
if (i > 0)
smatch(',');
parse_impl(cb);
}
smatch(']');
cb.end_array();
}
void json_parser::parse_number(callback& cb)
{
int sign = 1;
if (peek() == '-') {
incr();
sign=-1;
}
int64_t num = 0;
while(safe_isdigit(peek())) {
num = num*10 + peek() - '0';
incr();
}
bool is_frac = false;
double frac = num;
if (peek() == '.') {
is_frac = true;
incr();
double keta = 0.1;
if (!safe_isdigit(peek()))
error("after decimal-point, digit required.");
while (safe_isdigit(peek())) {
frac += (peek()-'0') * keta;
incr();
keta *= 0.1;
}
}
if (peek() == 'e' || peek() == 'E') {
is_frac = true;
incr();
int exp_sign = 1;
if (peek() == '+') {
incr();
}
else if (peek() == '-') {
exp_sign = -1;
incr();
}
int exp = 0;
if (!safe_isdigit(peek()))
error("after exp, digit required.");
while (safe_isdigit(peek())) {
exp = exp*10 + peek() - '0';
incr();
}
frac *= std::pow(10.0, (double)exp_sign*exp);
}
if (is_frac)
cb.number(sign*frac);
else
cb.integer(sign*num);
}
void json_parser::parse_string(callback& cb)
{
int len = 0;
parse_string_prim(buf, buf_len, len);
cb.string(buf, len);
}
void json_parser::parse_string_prim(char*& buf, int& buf_len, int& str_len)
{
char* p = buf;
match('\"');
for (;;) {
if (p+8 >= buf+buf_len) {
size_t adv = p - buf;
if (char* newbuf = static_cast<char*>(realloc(buf, 2*buf_len)))
buf = newbuf;
else
throw std::bad_alloc();
buf_len *= 2;
p = buf + adv;
}
if (peek() == '\"')
break;
if (peek() == '\\') {
incr();
int c = incr();
switch (c) {
case '\"': *p++ = '\"'; break;
case '\\': *p++ = '\\'; break;
case '/': *p++ = '/'; break;
case 'b': *p++ = '\b'; break;
case 'f': *p++ = '\f'; break;
case 'n': *p++ = '\n'; break;
case 'r': *p++ = '\r'; break;
case 't': *p++ = '\t'; break;
case 'u': {
int a = parse_hex();
int b = parse_hex();
int c = parse_hex();
int d = parse_hex();
pfi::data::string::uchar_to_chars((a<<12)|(b<<8)|(c<<4)|d, p);
break;
}
default: {
char err_msg[64];
snprintf(err_msg, sizeof(err_msg),
"unexpected unescaped char: \'%s\' (U+%04X)",
pfi::data::string::uchar_to_string(c).c_str(), c);
error(err_msg);
}
}
}
else {
int c = incr();
if ((c>=0x20 && c<=0x21) ||
(c>=0x23 && c<=0x5B) ||
(c>=0x5D && c<=0x10FFFF))
pfi::data::string::uchar_to_chars(c, p);
else {
char err_msg[64];
snprintf(err_msg, sizeof(err_msg),
"unexpected unescaped char: \'%s\' (U+%04X)",
pfi::data::string::uchar_to_string(c).c_str(), c);
error(err_msg);
}
}
}
match('\"');
str_len = p - buf;
}
void json_parser::parse_false(callback& cb)
{
match('f');
match('a');
match('l');
match('s');
match('e');
cb.boolean(false);
}
void json_parser::parse_null(callback& cb)
{
match('n');
match('u');
match('l');
match('l');
cb.null();
}
void json_parser::parse_true(callback& cb)
{
match('t');
match('r');
match('u');
match('e');
cb.boolean(true);
}
void json_parser::error(const std::string& msg)
{
std::string filename="<istream>";
throw pfi::lang::parse_error(filename, lineno, charno, msg);
}
} // json
} // text
} // pfi
<commit_msg>Removed a C style cast.<commit_after>// Copyright (c)2008-2012, Preferred Infrastructure Inc.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of Preferred Infrastructure nor the names of other
// 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
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "parser.h"
#include <iostream>
#include <new>
#include <stack>
#include <cmath>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include "../../lang/exception.h"
namespace pfi {
namespace text {
namespace json {
class json_builder : public json_parser::callback {
public:
const json& get() const {
if (stk.size() != 1)
throw pfi::lang::parse_error();
return stk[0];
}
void null() {
stk.push_back(new json_null());
}
void boolean(bool val) {
stk.push_back(new json_bool(val));
}
void integer(int64_t val) {
stk.push_back(new json_integer(val));
}
void number(double val) {
stk.push_back(new json_float(val));
}
void string(const char* val, size_t len) {
stk.push_back(new json_string(std::string(val, val+len)));
}
void start_object() {
ixs.push(stk.size());
}
void object_key(const char* val, size_t len) {
key.push_back(std::string(val, val+len));
}
void end_object() {
json obj(new json_object());
int ix = ixs.top();
int jx = stk.size();
int sz = jx - ix;
for (int i = 0; i < sz; i++)
obj.add(key[key.size() - sz + i], stk[ix + i]);
stk.push_back(obj);
stk.erase(stk.end() - sz - 1, stk.end() - 1);
key.erase(key.end() - sz, key.end());
ixs.pop();
}
void start_array() {
ixs.push(stk.size());
}
void end_array() {
json obj(new json_array());
int ix = ixs.top();
int jx = stk.size();
int sz = jx - ix;
for (int i = 0; i < sz; i++)
obj.add(stk[ix + i]);
stk.push_back(obj);
stk.erase(stk.end() - sz - 1, stk.end() - 1);
ixs.pop();
}
std::vector<json> stk;
std::vector<std::string> key;
std::stack<int> ixs;
};
json_parser::json_parser(std::istream& is)
: is(is), it(is), end(), lineno(1), charno(1), cbuf(-1)
{
buf_len = 256;
if ((buf = static_cast<char*>(malloc(buf_len))) == 0)
throw std::bad_alloc();
}
json_parser::~json_parser()
{
free(buf);
}
json json_parser::parse()
{
json_builder jb;
parse_stream(jb);
return jb.get();
}
void json_parser::parse_stream(callback& cb)
{
ss();
if (it == end)
throw lang::end_of_data("json_parser reached end of data");
return parse_impl(cb);
}
void json_parser::parse_impl(callback& cb)
{
ss();
switch(peek()) {
case '{':
parse_object(cb);
return;
case '[':
parse_array(cb);
return;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case '-':
parse_number(cb);
return;
case '\"':
parse_string(cb);
return;
case 'f':
parse_false(cb);
return;
case 'n':
parse_null(cb);
return;
case 't':
parse_true(cb);
return;
default: {
char err_msg[64];
snprintf(err_msg, sizeof(err_msg),
"invalid char: \'%s\' (U+%04X)",
pfi::data::string::uchar_to_string(peek()).c_str(), peek());
error(err_msg);
}
}
return; // dmy for supressing warning
}
void json_parser::parse_object(callback& cb)
{
cb.start_object();
smatch('{');
for (int i = 0; ; i++) {
if (speek() == '}')
break;
if (i > 0)
smatch(',');
ss();
int len = 0;
parse_string_prim(buf, buf_len, len);
cb.object_key(buf, len);
smatch(':');
parse_impl(cb);
}
smatch('}');
cb.end_object();
}
void json_parser::parse_array(callback& cb)
{
cb.start_array();
smatch('[');
for (int i = 0; ; i++) {
if (speek() == ']')
break;
if (i > 0)
smatch(',');
parse_impl(cb);
}
smatch(']');
cb.end_array();
}
void json_parser::parse_number(callback& cb)
{
int sign = 1;
if (peek() == '-') {
incr();
sign=-1;
}
int64_t num = 0;
while(safe_isdigit(peek())) {
num = num*10 + peek() - '0';
incr();
}
bool is_frac = false;
double frac = num;
if (peek() == '.') {
is_frac = true;
incr();
double keta = 0.1;
if (!safe_isdigit(peek()))
error("after decimal-point, digit required.");
while (safe_isdigit(peek())) {
frac += (peek()-'0') * keta;
incr();
keta *= 0.1;
}
}
if (peek() == 'e' || peek() == 'E') {
is_frac = true;
incr();
int exp_sign = 1;
if (peek() == '+') {
incr();
}
else if (peek() == '-') {
exp_sign = -1;
incr();
}
int exp = 0;
if (!safe_isdigit(peek()))
error("after exp, digit required.");
while (safe_isdigit(peek())) {
exp = exp*10 + peek() - '0';
incr();
}
frac *= std::pow(10.0, exp_sign*exp);
}
if (is_frac)
cb.number(sign*frac);
else
cb.integer(sign*num);
}
void json_parser::parse_string(callback& cb)
{
int len = 0;
parse_string_prim(buf, buf_len, len);
cb.string(buf, len);
}
void json_parser::parse_string_prim(char*& buf, int& buf_len, int& str_len)
{
char* p = buf;
match('\"');
for (;;) {
if (p+8 >= buf+buf_len) {
size_t adv = p - buf;
if (char* newbuf = static_cast<char*>(realloc(buf, 2*buf_len)))
buf = newbuf;
else
throw std::bad_alloc();
buf_len *= 2;
p = buf + adv;
}
if (peek() == '\"')
break;
if (peek() == '\\') {
incr();
int c = incr();
switch (c) {
case '\"': *p++ = '\"'; break;
case '\\': *p++ = '\\'; break;
case '/': *p++ = '/'; break;
case 'b': *p++ = '\b'; break;
case 'f': *p++ = '\f'; break;
case 'n': *p++ = '\n'; break;
case 'r': *p++ = '\r'; break;
case 't': *p++ = '\t'; break;
case 'u': {
int a = parse_hex();
int b = parse_hex();
int c = parse_hex();
int d = parse_hex();
pfi::data::string::uchar_to_chars((a<<12)|(b<<8)|(c<<4)|d, p);
break;
}
default: {
char err_msg[64];
snprintf(err_msg, sizeof(err_msg),
"unexpected unescaped char: \'%s\' (U+%04X)",
pfi::data::string::uchar_to_string(c).c_str(), c);
error(err_msg);
}
}
}
else {
int c = incr();
if ((c>=0x20 && c<=0x21) ||
(c>=0x23 && c<=0x5B) ||
(c>=0x5D && c<=0x10FFFF))
pfi::data::string::uchar_to_chars(c, p);
else {
char err_msg[64];
snprintf(err_msg, sizeof(err_msg),
"unexpected unescaped char: \'%s\' (U+%04X)",
pfi::data::string::uchar_to_string(c).c_str(), c);
error(err_msg);
}
}
}
match('\"');
str_len = p - buf;
}
void json_parser::parse_false(callback& cb)
{
match('f');
match('a');
match('l');
match('s');
match('e');
cb.boolean(false);
}
void json_parser::parse_null(callback& cb)
{
match('n');
match('u');
match('l');
match('l');
cb.null();
}
void json_parser::parse_true(callback& cb)
{
match('t');
match('r');
match('u');
match('e');
cb.boolean(true);
}
void json_parser::error(const std::string& msg)
{
std::string filename="<istream>";
throw pfi::lang::parse_error(filename, lineno, charno, msg);
}
} // json
} // text
} // pfi
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003 - 2005, Arvid Norberg, Daniel Wallin
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 Rasterbar Software 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 OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <cassert>
#include <boost/timer.hpp>
#include <iostream>
#include <vector>
#include <utility>
#include <set>
#include "libtorrent/buffer.hpp"
#include "libtorrent/chained_buffer.hpp"
#include "libtorrent/socket.hpp"
#include "test.hpp"
using libtorrent::buffer;
using libtorrent::chained_buffer;
/*
template<class T>
T const& min_(T const& x, T const& y)
{
return x < y ? x : y;
}
void test_speed()
{
buffer b;
char data[32];
srand(0);
boost::timer t;
int const iterations = 5000000;
int const step = iterations / 20;
for (int i = 0; i < iterations; ++i)
{
int x = rand();
if (i % step == 0) std::cerr << ".";
std::size_t n = rand() % 32;
n = 32;
if (x % 2)
{
b.insert(data, data + n);
}
else
{
b.erase(min_(b.size(), n));
}
}
float t1 = t.elapsed();
std::cerr << "buffer elapsed: " << t.elapsed() << "\n";
std::vector<char> v;
srand(0);
t.restart();
for (int i = 0; i < iterations; ++i)
{
int x = rand();
if (i % step == 0) std::cerr << ".";
std::size_t n = rand() % 32;
n = 32;
if (x % 2)
{
v.insert(v.end(), data, data + n);
}
else
{
v.erase(v.begin(), v.begin() + min_(v.size(), n));
}
}
float t2 = t.elapsed();
std::cerr << "std::vector elapsed: " << t.elapsed() << "\n";
assert(t1 < t2);
}
*/
// -- test buffer --
void test_buffer()
{
char data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
buffer b;
TEST_CHECK(b.size() == 0);
TEST_CHECK(b.capacity() == 0);
TEST_CHECK(b.empty());
b.resize(10);
TEST_CHECK(b.size() == 10);
TEST_CHECK(b.capacity() == 10);
std::memcpy(b.begin(), data, 10);
b.reserve(50);
TEST_CHECK(std::memcmp(b.begin(), data, 10) == 0);
TEST_CHECK(b.capacity() == 50);
b.erase(b.begin() + 6, b.end());
TEST_CHECK(std::memcmp(b.begin(), data, 6) == 0);
TEST_CHECK(b.capacity() == 50);
TEST_CHECK(b.size() == 6);
b.insert(b.begin(), data + 5, data + 10);
TEST_CHECK(b.capacity() == 50);
TEST_CHECK(b.size() == 11);
TEST_CHECK(std::memcmp(b.begin(), data + 5, 5) == 0);
b.clear();
TEST_CHECK(b.size() == 0);
TEST_CHECK(b.capacity() == 50);
b.insert(b.end(), data, data + 10);
TEST_CHECK(b.size() == 10);
TEST_CHECK(std::memcmp(b.begin(), data, 10) == 0);
b.erase(b.begin(), b.end());
TEST_CHECK(b.capacity() == 50);
TEST_CHECK(b.size() == 0);
buffer().swap(b);
TEST_CHECK(b.capacity() == 0);
}
// -- test chained buffer --
std::set<char*> buffer_list;
void free_buffer(char* m)
{
std::set<char*>::iterator i = buffer_list.find(m);
TEST_CHECK(i != buffer_list.end());
buffer_list.erase(i);
std::free(m);
}
char* allocate_buffer(int size)
{
char* mem = (char*)std::malloc(size);
buffer_list.insert(mem);
return mem;
}
template <class T>
int copy_buffers(T const& b, char* target)
{
int copied = 0;
for (typename T::const_iterator i = b.begin()
, end(b.end()); i != end; ++i)
{
memcpy(target, asio::buffer_cast<char const*>(*i), asio::buffer_size(*i));
target += asio::buffer_size(*i);
copied += asio::buffer_size(*i);
}
return copied;
}
bool compare_chained_buffer(chained_buffer& b, char const* mem, int size)
{
if (size == 0) return true;
std::vector<char> flat(size);
std::list<asio::const_buffer> const& iovec2 = b.build_iovec(size);
int copied = copy_buffers(iovec2, &flat[0]);
TEST_CHECK(copied == size);
return std::memcmp(&flat[0], mem, size) == 0;
}
void test_chained_buffer()
{
char data[] = "foobar";
{
chained_buffer b;
TEST_CHECK(b.empty());
TEST_CHECK(b.capacity() == 0);
TEST_CHECK(b.size() == 0);
TEST_CHECK(b.space_in_last_buffer() == 0);
TEST_CHECK(buffer_list.empty());
char* b1 = allocate_buffer(512);
std::memcpy(b1, data, 6);
b.append_buffer(b1, 512, 6, (void(*)(char*))&free_buffer);
TEST_CHECK(buffer_list.size() == 1);
TEST_CHECK(b.capacity() == 512);
TEST_CHECK(b.size() == 6);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
b.pop_front(3);
TEST_CHECK(b.capacity() == 512);
TEST_CHECK(b.size() == 3);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
bool ret = b.append(data, 6);
TEST_CHECK(ret == true);
TEST_CHECK(b.capacity() == 512);
TEST_CHECK(b.size() == 9);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 12);
ret = b.append(data, 1024);
TEST_CHECK(ret == false);
char* b2 = allocate_buffer(512);
std::memcpy(b2, data, 6);
b.append_buffer(b2, 512, 6, (void(*)(char*))&free_buffer);
TEST_CHECK(buffer_list.size() == 2);
char* b3 = allocate_buffer(512);
std::memcpy(b3, data, 6);
b.append_buffer(b3, 512, 6, (void(*)(char*))&free_buffer);
TEST_CHECK(buffer_list.size() == 3);
TEST_CHECK(b.capacity() == 512 * 3);
TEST_CHECK(b.size() == 21);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
TEST_CHECK(compare_chained_buffer(b, "barfoobar", 9));
for (int i = 1; i < 21; ++i)
TEST_CHECK(compare_chained_buffer(b, "barfoobarfoobarfoobar", i));
b.pop_front(5 + 6);
TEST_CHECK(buffer_list.size() == 2);
TEST_CHECK(b.capacity() == 512 * 2);
TEST_CHECK(b.size() == 10);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
char const* str = "obarfooba";
TEST_CHECK(compare_chained_buffer(b, str, 9));
for (int i = 0; i < 9; ++i)
{
b.pop_front(1);
++str;
TEST_CHECK(compare_chained_buffer(b, str, 8 - i));
TEST_CHECK(b.size() == 9 - i);
}
char* b4 = allocate_buffer(20);
std::memcpy(b4, data, 6);
std::memcpy(b4 + 6, data, 6);
b.append_buffer(b4, 20, 12, (void(*)(char*))&free_buffer);
TEST_CHECK(b.space_in_last_buffer() == 8);
ret = b.append(data, 6);
TEST_CHECK(ret == true);
TEST_CHECK(b.space_in_last_buffer() == 2);
std::cout << b.space_in_last_buffer() << std::endl;
ret = b.append(data, 2);
TEST_CHECK(ret == true);
TEST_CHECK(b.space_in_last_buffer() == 0);
std::cout << b.space_in_last_buffer() << std::endl;
char* b5 = allocate_buffer(20);
std::memcpy(b4, data, 6);
b.append_buffer(b5, 20, 6, (void(*)(char*))&free_buffer);
b.pop_front(22);
TEST_CHECK(b.size() == 5);
}
TEST_CHECK(buffer_list.empty());
}
int test_main()
{
test_buffer();
test_chained_buffer();
return 0;
}
<commit_msg>boost 1.35 fix in test_buffer<commit_after>/*
Copyright (c) 2003 - 2005, Arvid Norberg, Daniel Wallin
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 Rasterbar Software 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 OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <cassert>
#include <boost/timer.hpp>
#include <iostream>
#include <vector>
#include <utility>
#include <set>
#include "libtorrent/buffer.hpp"
#include "libtorrent/chained_buffer.hpp"
#include "libtorrent/socket.hpp"
#include "test.hpp"
using namespace libtorrent;
/*
template<class T>
T const& min_(T const& x, T const& y)
{
return x < y ? x : y;
}
void test_speed()
{
buffer b;
char data[32];
srand(0);
boost::timer t;
int const iterations = 5000000;
int const step = iterations / 20;
for (int i = 0; i < iterations; ++i)
{
int x = rand();
if (i % step == 0) std::cerr << ".";
std::size_t n = rand() % 32;
n = 32;
if (x % 2)
{
b.insert(data, data + n);
}
else
{
b.erase(min_(b.size(), n));
}
}
float t1 = t.elapsed();
std::cerr << "buffer elapsed: " << t.elapsed() << "\n";
std::vector<char> v;
srand(0);
t.restart();
for (int i = 0; i < iterations; ++i)
{
int x = rand();
if (i % step == 0) std::cerr << ".";
std::size_t n = rand() % 32;
n = 32;
if (x % 2)
{
v.insert(v.end(), data, data + n);
}
else
{
v.erase(v.begin(), v.begin() + min_(v.size(), n));
}
}
float t2 = t.elapsed();
std::cerr << "std::vector elapsed: " << t.elapsed() << "\n";
assert(t1 < t2);
}
*/
// -- test buffer --
void test_buffer()
{
char data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
buffer b;
TEST_CHECK(b.size() == 0);
TEST_CHECK(b.capacity() == 0);
TEST_CHECK(b.empty());
b.resize(10);
TEST_CHECK(b.size() == 10);
TEST_CHECK(b.capacity() == 10);
std::memcpy(b.begin(), data, 10);
b.reserve(50);
TEST_CHECK(std::memcmp(b.begin(), data, 10) == 0);
TEST_CHECK(b.capacity() == 50);
b.erase(b.begin() + 6, b.end());
TEST_CHECK(std::memcmp(b.begin(), data, 6) == 0);
TEST_CHECK(b.capacity() == 50);
TEST_CHECK(b.size() == 6);
b.insert(b.begin(), data + 5, data + 10);
TEST_CHECK(b.capacity() == 50);
TEST_CHECK(b.size() == 11);
TEST_CHECK(std::memcmp(b.begin(), data + 5, 5) == 0);
b.clear();
TEST_CHECK(b.size() == 0);
TEST_CHECK(b.capacity() == 50);
b.insert(b.end(), data, data + 10);
TEST_CHECK(b.size() == 10);
TEST_CHECK(std::memcmp(b.begin(), data, 10) == 0);
b.erase(b.begin(), b.end());
TEST_CHECK(b.capacity() == 50);
TEST_CHECK(b.size() == 0);
buffer().swap(b);
TEST_CHECK(b.capacity() == 0);
}
// -- test chained buffer --
std::set<char*> buffer_list;
void free_buffer(char* m)
{
std::set<char*>::iterator i = buffer_list.find(m);
TEST_CHECK(i != buffer_list.end());
buffer_list.erase(i);
std::free(m);
}
char* allocate_buffer(int size)
{
char* mem = (char*)std::malloc(size);
buffer_list.insert(mem);
return mem;
}
template <class T>
int copy_buffers(T const& b, char* target)
{
int copied = 0;
for (typename T::const_iterator i = b.begin()
, end(b.end()); i != end; ++i)
{
memcpy(target, asio::buffer_cast<char const*>(*i), asio::buffer_size(*i));
target += asio::buffer_size(*i);
copied += asio::buffer_size(*i);
}
return copied;
}
bool compare_chained_buffer(chained_buffer& b, char const* mem, int size)
{
if (size == 0) return true;
std::vector<char> flat(size);
std::list<asio::const_buffer> const& iovec2 = b.build_iovec(size);
int copied = copy_buffers(iovec2, &flat[0]);
TEST_CHECK(copied == size);
return std::memcmp(&flat[0], mem, size) == 0;
}
void test_chained_buffer()
{
char data[] = "foobar";
{
chained_buffer b;
TEST_CHECK(b.empty());
TEST_CHECK(b.capacity() == 0);
TEST_CHECK(b.size() == 0);
TEST_CHECK(b.space_in_last_buffer() == 0);
TEST_CHECK(buffer_list.empty());
char* b1 = allocate_buffer(512);
std::memcpy(b1, data, 6);
b.append_buffer(b1, 512, 6, (void(*)(char*))&free_buffer);
TEST_CHECK(buffer_list.size() == 1);
TEST_CHECK(b.capacity() == 512);
TEST_CHECK(b.size() == 6);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
b.pop_front(3);
TEST_CHECK(b.capacity() == 512);
TEST_CHECK(b.size() == 3);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
bool ret = b.append(data, 6);
TEST_CHECK(ret == true);
TEST_CHECK(b.capacity() == 512);
TEST_CHECK(b.size() == 9);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 12);
ret = b.append(data, 1024);
TEST_CHECK(ret == false);
char* b2 = allocate_buffer(512);
std::memcpy(b2, data, 6);
b.append_buffer(b2, 512, 6, (void(*)(char*))&free_buffer);
TEST_CHECK(buffer_list.size() == 2);
char* b3 = allocate_buffer(512);
std::memcpy(b3, data, 6);
b.append_buffer(b3, 512, 6, (void(*)(char*))&free_buffer);
TEST_CHECK(buffer_list.size() == 3);
TEST_CHECK(b.capacity() == 512 * 3);
TEST_CHECK(b.size() == 21);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
TEST_CHECK(compare_chained_buffer(b, "barfoobar", 9));
for (int i = 1; i < 21; ++i)
TEST_CHECK(compare_chained_buffer(b, "barfoobarfoobarfoobar", i));
b.pop_front(5 + 6);
TEST_CHECK(buffer_list.size() == 2);
TEST_CHECK(b.capacity() == 512 * 2);
TEST_CHECK(b.size() == 10);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
char const* str = "obarfooba";
TEST_CHECK(compare_chained_buffer(b, str, 9));
for (int i = 0; i < 9; ++i)
{
b.pop_front(1);
++str;
TEST_CHECK(compare_chained_buffer(b, str, 8 - i));
TEST_CHECK(b.size() == 9 - i);
}
char* b4 = allocate_buffer(20);
std::memcpy(b4, data, 6);
std::memcpy(b4 + 6, data, 6);
b.append_buffer(b4, 20, 12, (void(*)(char*))&free_buffer);
TEST_CHECK(b.space_in_last_buffer() == 8);
ret = b.append(data, 6);
TEST_CHECK(ret == true);
TEST_CHECK(b.space_in_last_buffer() == 2);
std::cout << b.space_in_last_buffer() << std::endl;
ret = b.append(data, 2);
TEST_CHECK(ret == true);
TEST_CHECK(b.space_in_last_buffer() == 0);
std::cout << b.space_in_last_buffer() << std::endl;
char* b5 = allocate_buffer(20);
std::memcpy(b4, data, 6);
b.append_buffer(b5, 20, 6, (void(*)(char*))&free_buffer);
b.pop_front(22);
TEST_CHECK(b.size() == 5);
}
TEST_CHECK(buffer_list.empty());
}
int test_main()
{
test_buffer();
test_chained_buffer();
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>astyle - switch cases should not be indented<commit_after><|endoftext|> |
<commit_before>/**
* Copyright (c) 2007-2012, Timothy Stack
*
* 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 Timothy Stack 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 REGENTS 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 REGENTS 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.
*/
#ifndef _top_status_source_hh
#define _top_status_source_hh
#include <string>
#include "logfile_sub_source.hh"
#include "statusview_curses.hh"
class top_status_source
: public status_data_source {
public:
typedef listview_curses::action::mem_functor_t<
top_status_source> lv_functor_t;
typedef enum {
TSF_TIME,
TSF_PARTITION_NAME,
TSF_VIEW_NAME,
TSF_STITCH_VIEW_FORMAT,
TSF_FORMAT,
TSF_STITCH_FORMAT_FILENAME,
TSF_FILENAME,
TSF__MAX
} field_t;
top_status_source()
: filename_wire(*this, &top_status_source::update_filename)
{
this->tss_fields[TSF_TIME].set_width(24);
this->tss_fields[TSF_PARTITION_NAME].set_width(30);
this->tss_fields[TSF_VIEW_NAME].set_width(6);
this->tss_fields[TSF_VIEW_NAME].right_justify(true);
this->tss_fields[TSF_STITCH_VIEW_FORMAT].set_width(2);
this->tss_fields[TSF_STITCH_VIEW_FORMAT].set_stitch_value(
view_colors::ansi_color_pair_index(COLOR_CYAN, COLOR_BLUE));
this->tss_fields[TSF_STITCH_VIEW_FORMAT].right_justify(true);
this->tss_fields[TSF_FORMAT].set_width(13);
this->tss_fields[TSF_FORMAT].right_justify(true);
this->tss_fields[TSF_STITCH_FORMAT_FILENAME].set_width(2);
this->tss_fields[TSF_STITCH_FORMAT_FILENAME].set_stitch_value(
view_colors::ansi_color_pair_index(COLOR_WHITE, COLOR_CYAN));
this->tss_fields[TSF_STITCH_FORMAT_FILENAME].right_justify(true);
this->tss_fields[TSF_FILENAME].set_min_width(35); /* XXX */
this->tss_fields[TSF_FILENAME].set_share(1);
this->tss_fields[TSF_FILENAME].right_justify(true);
};
lv_functor_t filename_wire;
size_t statusview_fields(void) { return TSF__MAX; };
status_field &statusview_value_for_field(int field)
{
return this->tss_fields[field];
};
void update_time(void)
{
status_field &sf = this->tss_fields[TSF_TIME];
time_t current_time = time(NULL);
char buffer[32];
strftime(buffer, sizeof(buffer),
"%a %b %d %H:%M:%S %Z",
localtime(¤t_time));
sf.set_value(buffer);
};
void update_filename(listview_curses *lc)
{
status_field & sf_partition = this->tss_fields[TSF_PARTITION_NAME];
status_field & sf_format = this->tss_fields[TSF_FORMAT];
status_field & sf_filename = this->tss_fields[TSF_FILENAME];
struct line_range lr(0);
if (lc->get_inner_height() > 0) {
string_attrs_t::const_iterator line_attr;
attr_line_t al;
lc->get_data_source()->
listview_value_for_row(*lc, lc->get_top(), al);
string_attrs_t &sa = al.get_attrs();
line_attr = find_string_attr(sa, &logline::L_FILE);
if (line_attr != sa.end()) {
logfile *lf = (logfile *)line_attr->sa_value.sav_ptr;
if (lf->get_format()) {
sf_format.set_value("% 13s",
lf->get_format()->get_name().c_str());
}
else if (!lf->get_filename().empty()) {
sf_format.set_value("% 13s", "plain text");
}
else{
sf_format.clear();
}
sf_filename.set_value(lf->get_filename());
}
else {
sf_format.clear();
sf_filename.clear();
}
line_attr = find_string_attr(sa, &logline::L_PARTITION);
if (line_attr != sa.end()) {
bookmark_metadata *bm = (bookmark_metadata *)line_attr->sa_value.sav_ptr;
sf_partition.set_value(bm->bm_name.c_str());
}
else {
sf_partition.clear();
}
}
else {
sf_format.clear();
if (lc->get_data_source() != NULL) {
sf_filename.set_value(lc->get_data_source()->listview_source_name(*lc));
}
}
sf_format.get_value().get_attrs().push_back(
string_attr(lr, &view_curses::VC_STYLE,
A_REVERSE | view_colors::ansi_color_pair(COLOR_CYAN, COLOR_BLACK)));
};
private:
status_field tss_fields[TSF__MAX];
};
#endif
<commit_msg>[top_status_view] Increase the format name column width<commit_after>/**
* Copyright (c) 2007-2012, Timothy Stack
*
* 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 Timothy Stack 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 REGENTS 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 REGENTS 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.
*/
#ifndef _top_status_source_hh
#define _top_status_source_hh
#include <string>
#include "logfile_sub_source.hh"
#include "statusview_curses.hh"
class top_status_source
: public status_data_source {
public:
typedef listview_curses::action::mem_functor_t<
top_status_source> lv_functor_t;
typedef enum {
TSF_TIME,
TSF_PARTITION_NAME,
TSF_VIEW_NAME,
TSF_STITCH_VIEW_FORMAT,
TSF_FORMAT,
TSF_STITCH_FORMAT_FILENAME,
TSF_FILENAME,
TSF__MAX
} field_t;
top_status_source()
: filename_wire(*this, &top_status_source::update_filename)
{
this->tss_fields[TSF_TIME].set_width(24);
this->tss_fields[TSF_PARTITION_NAME].set_width(30);
this->tss_fields[TSF_VIEW_NAME].set_width(6);
this->tss_fields[TSF_VIEW_NAME].right_justify(true);
this->tss_fields[TSF_STITCH_VIEW_FORMAT].set_width(2);
this->tss_fields[TSF_STITCH_VIEW_FORMAT].set_stitch_value(
view_colors::ansi_color_pair_index(COLOR_CYAN, COLOR_BLUE));
this->tss_fields[TSF_STITCH_VIEW_FORMAT].right_justify(true);
this->tss_fields[TSF_FORMAT].set_width(20);
this->tss_fields[TSF_FORMAT].right_justify(true);
this->tss_fields[TSF_STITCH_FORMAT_FILENAME].set_width(2);
this->tss_fields[TSF_STITCH_FORMAT_FILENAME].set_stitch_value(
view_colors::ansi_color_pair_index(COLOR_WHITE, COLOR_CYAN));
this->tss_fields[TSF_STITCH_FORMAT_FILENAME].right_justify(true);
this->tss_fields[TSF_FILENAME].set_min_width(35); /* XXX */
this->tss_fields[TSF_FILENAME].set_share(1);
this->tss_fields[TSF_FILENAME].right_justify(true);
};
lv_functor_t filename_wire;
size_t statusview_fields(void) { return TSF__MAX; };
status_field &statusview_value_for_field(int field)
{
return this->tss_fields[field];
};
void update_time(void)
{
status_field &sf = this->tss_fields[TSF_TIME];
time_t current_time = time(NULL);
char buffer[32];
strftime(buffer, sizeof(buffer),
"%a %b %d %H:%M:%S %Z",
localtime(¤t_time));
sf.set_value(buffer);
};
void update_filename(listview_curses *lc)
{
status_field & sf_partition = this->tss_fields[TSF_PARTITION_NAME];
status_field & sf_format = this->tss_fields[TSF_FORMAT];
status_field & sf_filename = this->tss_fields[TSF_FILENAME];
struct line_range lr(0);
if (lc->get_inner_height() > 0) {
string_attrs_t::const_iterator line_attr;
attr_line_t al;
lc->get_data_source()->
listview_value_for_row(*lc, lc->get_top(), al);
string_attrs_t &sa = al.get_attrs();
line_attr = find_string_attr(sa, &logline::L_FILE);
if (line_attr != sa.end()) {
logfile *lf = (logfile *)line_attr->sa_value.sav_ptr;
if (lf->get_format()) {
sf_format.set_value("% 13s",
lf->get_format()->get_name().c_str());
}
else if (!lf->get_filename().empty()) {
sf_format.set_value("% 13s", "plain text");
}
else{
sf_format.clear();
}
sf_filename.set_value(lf->get_filename());
}
else {
sf_format.clear();
sf_filename.clear();
}
line_attr = find_string_attr(sa, &logline::L_PARTITION);
if (line_attr != sa.end()) {
bookmark_metadata *bm = (bookmark_metadata *)line_attr->sa_value.sav_ptr;
sf_partition.set_value(bm->bm_name.c_str());
}
else {
sf_partition.clear();
}
}
else {
sf_format.clear();
if (lc->get_data_source() != NULL) {
sf_filename.set_value(lc->get_data_source()->listview_source_name(*lc));
}
}
sf_format.get_value().get_attrs().push_back(
string_attr(lr, &view_curses::VC_STYLE,
A_REVERSE | view_colors::ansi_color_pair(COLOR_CYAN, COLOR_BLACK)));
};
private:
status_field tss_fields[TSF__MAX];
};
#endif
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.