<commit_before>/*
 * Copyright (C) 2013 Google 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:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h"
#include "platform/graphics/DiscardablePixelRef.h"

#include "public/platform/Platform.h"
#include "wtf/StdLibExtras.h"

namespace WebCore {

namespace {

// URI label for a discardable SkPixelRef.
const char labelDiscardable[] = "discardable";

} // namespace

bool DiscardablePixelRefAllocator::allocPixelRef(SkBitmap* dst, SkColorTable* ctable)
{
    // It should not be possible to have a non-null color table in Blink.
    ASSERT(!ctable);

    Sk64 size = dst->getSize64();
    if (size.isNeg() || !size.is32())
        return false;

    SkImageInfo info;
    if (!dst->asImageInfo(&info))
        return false;

    SkAutoTUnref<DiscardablePixelRef> pixelRef(new DiscardablePixelRef(info, adoptPtr(new SkMutex())));
    if (pixelRef->allocAndLockDiscardableMemory(size.get32())) {
        pixelRef->setURI(labelDiscardable);
        dst->setPixelRef(pixelRef.get());
        // This method is only called when a DiscardablePixelRef is created to back a SkBitmap.
        // It is necessary to lock this SkBitmap to have a valid pointer to pixels. Otherwise,
        // this SkBitmap could be assigned to another SkBitmap and locking/unlocking the other
        // SkBitmap will make this one losing its pixels.
        dst->lockPixels();
        return true;
    }

    // Fallback to heap allocator if discardable memory is not available.
    return dst->allocPixels();
}

DiscardablePixelRef::DiscardablePixelRef(const SkImageInfo& info, PassOwnPtr<SkMutex> mutex)
    : SkPixelRef(info, mutex.get())
    , m_lockedMemory(0)
    , m_mutex(mutex)
{
}

DiscardablePixelRef::~DiscardablePixelRef()
{
}

bool DiscardablePixelRef::allocAndLockDiscardableMemory(size_t bytes)
{
    m_discardable = adoptPtr(blink::Platform::current()->allocateAndLockDiscardableMemory(bytes));
    if (m_discardable) {
        m_lockedMemory = m_discardable->data();
        return true;
    }
    return false;
}

void* DiscardablePixelRef::onLockPixels(SkColorTable** ctable)
{
    if (!m_lockedMemory && m_discardable->lock())
        m_lockedMemory = m_discardable->data();

    *ctable = 0;
    return m_lockedMemory;
}

void DiscardablePixelRef::onUnlockPixels()
{
    if (m_lockedMemory)
        m_discardable->unlock();
    m_lockedMemory = 0;
}

bool DiscardablePixelRef::isDiscardable(SkPixelRef* pixelRef)
{
    // FIXME: DEFINE_STATIC_LOCAL is not thread safe.
    // ImageDecodingStore provides the synchronization for this.
    DEFINE_STATIC_LOCAL(const SkString, discardable, (labelDiscardable));
    return pixelRef && pixelRef->getURI() && discardable.equals(pixelRef->getURI());
}

} // namespace WebCore
<commit_msg>use native int64_t api on SkBitmap<commit_after>/*
 * Copyright (C) 2013 Google 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:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h"
#include "platform/graphics/DiscardablePixelRef.h"

#include "public/platform/Platform.h"
#include "wtf/StdLibExtras.h"

namespace WebCore {

namespace {

// URI label for a discardable SkPixelRef.
const char labelDiscardable[] = "discardable";

} // namespace

bool DiscardablePixelRefAllocator::allocPixelRef(SkBitmap* dst, SkColorTable* ctable)
{
    // It should not be possible to have a non-null color table in Blink.
    ASSERT(!ctable);

    int64_t size = dst->computeSize64();
    if (size < 0 || !sk_64_isS32(size))
        return false;

    SkImageInfo info;
    if (!dst->asImageInfo(&info))
        return false;

    SkAutoTUnref<DiscardablePixelRef> pixelRef(new DiscardablePixelRef(info, adoptPtr(new SkMutex())));
    if (pixelRef->allocAndLockDiscardableMemory(sk_64_asS32(size))) {
        pixelRef->setURI(labelDiscardable);
        dst->setPixelRef(pixelRef.get());
        // This method is only called when a DiscardablePixelRef is created to back a SkBitmap.
        // It is necessary to lock this SkBitmap to have a valid pointer to pixels. Otherwise,
        // this SkBitmap could be assigned to another SkBitmap and locking/unlocking the other
        // SkBitmap will make this one losing its pixels.
        dst->lockPixels();
        return true;
    }

    // Fallback to heap allocator if discardable memory is not available.
    return dst->allocPixels();
}

DiscardablePixelRef::DiscardablePixelRef(const SkImageInfo& info, PassOwnPtr<SkMutex> mutex)
    : SkPixelRef(info, mutex.get())
    , m_lockedMemory(0)
    , m_mutex(mutex)
{
}

DiscardablePixelRef::~DiscardablePixelRef()
{
}

bool DiscardablePixelRef::allocAndLockDiscardableMemory(size_t bytes)
{
    m_discardable = adoptPtr(blink::Platform::current()->allocateAndLockDiscardableMemory(bytes));
    if (m_discardable) {
        m_lockedMemory = m_discardable->data();
        return true;
    }
    return false;
}

void* DiscardablePixelRef::onLockPixels(SkColorTable** ctable)
{
    if (!m_lockedMemory && m_discardable->lock())
        m_lockedMemory = m_discardable->data();

    *ctable = 0;
    return m_lockedMemory;
}

void DiscardablePixelRef::onUnlockPixels()
{
    if (m_lockedMemory)
        m_discardable->unlock();
    m_lockedMemory = 0;
}

bool DiscardablePixelRef::isDiscardable(SkPixelRef* pixelRef)
{
    // FIXME: DEFINE_STATIC_LOCAL is not thread safe.
    // ImageDecodingStore provides the synchronization for this.
    DEFINE_STATIC_LOCAL(const SkString, discardable, (labelDiscardable));
    return pixelRef && pixelRef->getURI() && discardable.equals(pixelRef->getURI());
}

} // namespace WebCore
<|endoftext|>


<commit_before>#include "openmc/tallies/filter_mesh.h"

#include <fmt/core.h>
#include <gsl/gsl>

#include "openmc/capi.h"
#include "openmc/constants.h"
#include "openmc/error.h"
#include "openmc/mesh.h"
#include "openmc/xml_interface.h"

namespace openmc {

void
MeshFilter::from_xml(pugi::xml_node node)
{
  auto bins_ = get_node_array<int32_t>(node, "bins");
  if (bins_.size() != 1) {
    fatal_error("Only one mesh can be specified per " + type()
                + " mesh filter.");
  }

  auto id = bins_[0];
  auto search = model::mesh_map.find(id);
  if (search != model::mesh_map.end()) {
    set_mesh(search->second);
  } else{
    fatal_error(fmt::format(
      "Could not find mesh {} specified on tally filter.", id));
  }
}

void
MeshFilter::get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match)
const
{

  Position last_r = p.r_last_;
  Position r = p.r();
  Position u = p.u();

  // apply translation if present
  if (translated_) {
    last_r -= translation_;
    r -= translation_;
  }

  if (estimator != TallyEstimator::TRACKLENGTH) {
    auto bin = model::meshes[mesh_]->get_bin(r);
    if (bin >= 0) {
      match.bins_.push_back(bin);
      match.weights_.push_back(1.0);
    }
  } else {
    model::meshes[mesh_]->bins_crossed(last_r, r, u, match.bins_, match.weights_);
  }
}

void
MeshFilter::to_statepoint(hid_t filter_group) const
{
  Filter::to_statepoint(filter_group);
  write_dataset(filter_group, "bins", model::meshes[mesh_]->id_);
}

std::string
MeshFilter::text_label(int bin) const
{
  auto& mesh = *model::meshes.at(mesh_);
  return mesh.bin_label(bin);
}

void
MeshFilter::set_mesh(int32_t mesh)
{
  mesh_ = mesh;
  n_bins_ = model::meshes[mesh_]->n_bins();
}

void MeshFilter::set_translation(const Position& translation)
{
  translated_ = true;
  translation_ = translation;
}

void MeshFilter::set_translation(const double translation[3])
{
  translated_ = true;
  translation_ = translation;
}

//==============================================================================
// C-API functions
//==============================================================================

extern "C" int
openmc_mesh_filter_get_mesh(int32_t index, int32_t* index_mesh)
{
  if (!index_mesh) {
    set_errmsg("Mesh index argument is a null pointer.");
    return OPENMC_E_INVALID_ARGUMENT;
  }

  // Make sure this is a valid index to an allocated filter.
  if (int err = verify_filter(index)) return err;

  // Get a pointer to the filter and downcast.
  const auto& filt_base = model::tally_filters[index].get();
  auto* filt = dynamic_cast<MeshFilter*>(filt_base);

  // Check the filter type.
  if (!filt) {
    set_errmsg("Tried to get mesh on a non-mesh filter.");
    return OPENMC_E_INVALID_TYPE;
  }

  // Output the mesh.
  *index_mesh = filt->mesh();
  return 0;
}

extern "C" int
openmc_mesh_filter_set_mesh(int32_t index, int32_t index_mesh)
{
  // Make sure this is a valid index to an allocated filter.
  if (int err = verify_filter(index)) return err;

  // Get a pointer to the filter and downcast.
  const auto& filt_base = model::tally_filters[index].get();
  auto* filt = dynamic_cast<MeshFilter*>(filt_base);

  // Check the filter type.
  if (!filt) {
    set_errmsg("Tried to set mesh on a non-mesh filter.");
    return OPENMC_E_INVALID_TYPE;
  }

  // Check the mesh index.
  if (index_mesh < 0 || index_mesh >= model::meshes.size()) {
    set_errmsg("Index in 'meshes' array is out of bounds.");
    return OPENMC_E_OUT_OF_BOUNDS;
  }

  // Update the filter.
  filt->set_mesh(index_mesh);
  return 0;
}

extern "C" int
openmc_mesh_filter_set_translation(int32_t index, double translation[3])
{
  // Make sure this is a valid index to an allocated filter
  if (int err = verify_filter(index)) return err;

  // Get a pointer to the filter and downcast.
  const auto& filt_base = model::tally_filters[index].get();
  auto* filt = dynamic_cast<MeshFilter*>(filt_base);

  // Check the filter type
  if (!filt) {
    set_errmsg("Tried to set mesh on a non-mesh filter.");
    return OPENMC_E_INVALID_TYPE;
  }

  // Set the translation
  filt->set_translation(translation);

  return 0;
}

} // namespace openmc
<commit_msg>Updating label, creation, and statepoint methods for the mesh filter.<commit_after>#include "openmc/tallies/filter_mesh.h"

#include <fmt/core.h>
#include <gsl/gsl>

#include "openmc/capi.h"
#include "openmc/constants.h"
#include "openmc/error.h"
#include "openmc/mesh.h"
#include "openmc/xml_interface.h"

namespace openmc {

void
MeshFilter::from_xml(pugi::xml_node node)
{
  auto bins_ = get_node_array<int32_t>(node, "bins");
  if (bins_.size() != 1) {
    fatal_error("Only one mesh can be specified per " + type()
                + " mesh filter.");
  }

  auto id = bins_[0];
  auto search = model::mesh_map.find(id);
  if (search != model::mesh_map.end()) {
    set_mesh(search->second);
  } else{
    fatal_error(fmt::format(
      "Could not find mesh {} specified on tally filter.", id));
  }

  if (check_for_node(node, "translation")) {
    set_translation(get_node_array<double>(node, "translation"));
  }

}

void
MeshFilter::get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match)
const
{

  Position last_r = p.r_last_;
  Position r = p.r();
  Position u = p.u();

  // apply translation if present
  if (translated_) {
    last_r -= translation_;
    r -= translation_;
  }

  if (estimator != TallyEstimator::TRACKLENGTH) {
    auto bin = model::meshes[mesh_]->get_bin(r);
    if (bin >= 0) {
      match.bins_.push_back(bin);
      match.weights_.push_back(1.0);
    }
  } else {
    model::meshes[mesh_]->bins_crossed(last_r, r, u, match.bins_, match.weights_);
  }
}

void
MeshFilter::to_statepoint(hid_t filter_group) const
{
  Filter::to_statepoint(filter_group);
  write_dataset(filter_group, "bins", model::meshes[mesh_]->id_);
  if (translated_) {
    write_dataset(filter_group, "translation", translation_);
  }
}

std::string
MeshFilter::text_label(int bin) const
{
  auto& mesh = *model::meshes.at(mesh_);
  std::string label = mesh.bin_label(bin);
  if (translated_) {
    label += fmt::format("\nTranslation: {}, {}, {}\n",
                         translation_.x, translation_.y, translation_.z);
  }
  return label;
}

void
MeshFilter::set_mesh(int32_t mesh)
{
  mesh_ = mesh;
  n_bins_ = model::meshes[mesh_]->n_bins();
}

void MeshFilter::set_translation(const Position& translation)
{
  translated_ = true;
  translation_ = translation;
}

void MeshFilter::set_translation(const double translation[3])
{
  translated_ = true;
  translation_ = translation;
}

//==============================================================================
// C-API functions
//==============================================================================

extern "C" int
openmc_mesh_filter_get_mesh(int32_t index, int32_t* index_mesh)
{
  if (!index_mesh) {
    set_errmsg("Mesh index argument is a null pointer.");
    return OPENMC_E_INVALID_ARGUMENT;
  }

  // Make sure this is a valid index to an allocated filter.
  if (int err = verify_filter(index)) return err;

  // Get a pointer to the filter and downcast.
  const auto& filt_base = model::tally_filters[index].get();
  auto* filt = dynamic_cast<MeshFilter*>(filt_base);

  // Check the filter type.
  if (!filt) {
    set_errmsg("Tried to get mesh on a non-mesh filter.");
    return OPENMC_E_INVALID_TYPE;
  }

  // Output the mesh.
  *index_mesh = filt->mesh();
  return 0;
}

extern "C" int
openmc_mesh_filter_set_mesh(int32_t index, int32_t index_mesh)
{
  // Make sure this is a valid index to an allocated filter.
  if (int err = verify_filter(index)) return err;

  // Get a pointer to the filter and downcast.
  const auto& filt_base = model::tally_filters[index].get();
  auto* filt = dynamic_cast<MeshFilter*>(filt_base);

  // Check the filter type.
  if (!filt) {
    set_errmsg("Tried to set mesh on a non-mesh filter.");
    return OPENMC_E_INVALID_TYPE;
  }

  // Check the mesh index.
  if (index_mesh < 0 || index_mesh >= model::meshes.size()) {
    set_errmsg("Index in 'meshes' array is out of bounds.");
    return OPENMC_E_OUT_OF_BOUNDS;
  }

  // Update the filter.
  filt->set_mesh(index_mesh);
  return 0;
}

extern "C" int
openmc_mesh_filter_set_translation(int32_t index, double translation[3])
{
  // Make sure this is a valid index to an allocated filter
  if (int err = verify_filter(index)) return err;

  // Get a pointer to the filter and downcast.
  const auto& filt_base = model::tally_filters[index].get();
  auto* filt = dynamic_cast<MeshFilter*>(filt_base);

  // Check the filter type
  if (!filt) {
    set_errmsg("Tried to set mesh on a non-mesh filter.");
    return OPENMC_E_INVALID_TYPE;
  }

  // Set the translation
  filt->set_translation(translation);

  return 0;
}

} // namespace openmc
<|endoftext|>


<commit_before>#include "amatrix.h"
#include "checks.h"

template <std::size_t TSize1, std::size_t TSize2>
std::size_t TestSubMatrixAcess() {
    AMatrix::Matrix<double, TSize1, TSize2> a_matrix;
    for (std::size_t i = 0; i < a_matrix.size1(); i++)
        for (std::size_t j = 0; j < a_matrix.size2(); j++)
            a_matrix(i, j) = 2.33 * i - 4.52 * j;

    std::size_t sub_size1 = (TSize1 > 1) ? TSize1 - 1 : 1;
    std::size_t sub_size2 = (TSize2 > 1) ? TSize2 - 1 : 1;

    std::size_t sub_index1 = (TSize1 > 1) ? 1 : 0;
    std::size_t sub_index2 = (TSize2 > 1) ? 1 : 0;

    AMatrix::SubMatrix<AMatrix::Matrix<double, TSize1, TSize2>> sub_matrix(
        a_matrix, sub_index1, sub_index2, sub_size1, sub_size2);

    AMATRIX_CHECK_EQUAL(sub_matrix.size1(), sub_size1);
    AMATRIX_CHECK_EQUAL(sub_matrix.size2(), sub_size2);

    for (std::size_t i = 0; i < sub_matrix.size1(); i++)
        for (std::size_t j = 0; j < sub_matrix.size2(); j++) {
            AMATRIX_CHECK_EQUAL(
                sub_matrix(i, j), a_matrix(i + sub_index1, j + sub_index2));
        }

    return 0;  // not failed
}

int main() {
    std::size_t number_of_failed_tests = 0;

    number_of_failed_tests += TestSubMatrixAcess<1, 1>();

    number_of_failed_tests += TestSubMatrixAcess<1, 2>();
    number_of_failed_tests += TestSubMatrixAcess<2, 1>();
    number_of_failed_tests += TestSubMatrixAcess<2, 2>();

    number_of_failed_tests += TestSubMatrixAcess<3, 1>();
    number_of_failed_tests += TestSubMatrixAcess<3, 2>();
    number_of_failed_tests += TestSubMatrixAcess<3, 3>();
    number_of_failed_tests += TestSubMatrixAcess<1, 3>();
    number_of_failed_tests += TestSubMatrixAcess<2, 3>();
    number_of_failed_tests += TestSubMatrixAcess<3, 3>();

    std::cout << number_of_failed_tests << "tests failed" << std::endl;

    return number_of_failed_tests;
}
<commit_msg>Adding sub matrix assign test<commit_after>#include "amatrix.h"
#include "checks.h"

template <std::size_t TSize1, std::size_t TSize2>
std::size_t TestSubMatrixAcess() {
    AMatrix::Matrix<double, TSize1, TSize2> a_matrix;
    for (std::size_t i = 0; i < a_matrix.size1(); i++)
        for (std::size_t j = 0; j < a_matrix.size2(); j++)
            a_matrix(i, j) = 2.33 * i - 4.52 * j;

    std::size_t sub_size1 = (TSize1 > 1) ? TSize1 - 1 : 1;
    std::size_t sub_size2 = (TSize2 > 1) ? TSize2 - 1 : 1;

    std::size_t sub_index1 = (TSize1 > 1) ? 1 : 0;
    std::size_t sub_index2 = (TSize2 > 1) ? 1 : 0;

    AMatrix::SubMatrix<AMatrix::Matrix<double, TSize1, TSize2>> sub_matrix(
        a_matrix, sub_index1, sub_index2, sub_size1, sub_size2);

    AMATRIX_CHECK_EQUAL(sub_matrix.size1(), sub_size1);
    AMATRIX_CHECK_EQUAL(sub_matrix.size2(), sub_size2);

    for (std::size_t i = 0; i < sub_matrix.size1(); i++)
        for (std::size_t j = 0; j < sub_matrix.size2(); j++) {
            AMATRIX_CHECK_EQUAL(
                sub_matrix(i, j), a_matrix(i + sub_index1, j + sub_index2));
        }

    return 0;  // not failed
}

template <std::size_t TSize1, std::size_t TSize2>
std::size_t TestSubMatrixAssign() {
    AMatrix::Matrix<double, TSize1, TSize2> a_matrix(
        AMatrix::ZeroMatrix<double>(TSize1, TSize2));

    std::size_t sub_size1 = (TSize1 > 1) ? TSize1 - 1 : 1;
    std::size_t sub_size2 = (TSize2 > 1) ? TSize2 - 1 : 1;

    std::size_t sub_index1 = (TSize1 > 1) ? 1 : 0;
    std::size_t sub_index2 = (TSize2 > 1) ? 1 : 0;

    AMatrix::SubMatrix<AMatrix::Matrix<double, TSize1, TSize2>> sub_matrix(
        a_matrix, sub_index1, sub_index2, sub_size1, sub_size2);

    AMATRIX_CHECK_EQUAL(sub_matrix.size1(), sub_size1);
    AMATRIX_CHECK_EQUAL(sub_matrix.size2(), sub_size2);

    for (std::size_t i = 0; i < sub_matrix.size1(); i++)
        for (std::size_t j = 0; j < sub_matrix.size2(); j++) {
            sub_matrix(i, j) = 2.33 * i - 4.52 * j;
        }

    for (std::size_t i = sub_index1; i < a_matrix.size1(); i++)
        for (std::size_t j = sub_index2; j < a_matrix.size2(); j++) {
            AMATRIX_CHECK_EQUAL(a_matrix(i, j),
                2.33 * (i - sub_index1) - 4.52 * (j - sub_index2));
        }

    return 0;  // not failed
}

int main() {
    std::size_t number_of_failed_tests = 0;

    number_of_failed_tests += TestSubMatrixAcess<1, 1>();

    number_of_failed_tests += TestSubMatrixAcess<1, 2>();
    number_of_failed_tests += TestSubMatrixAcess<2, 1>();
    number_of_failed_tests += TestSubMatrixAcess<2, 2>();

    number_of_failed_tests += TestSubMatrixAcess<3, 1>();
    number_of_failed_tests += TestSubMatrixAcess<3, 2>();
    number_of_failed_tests += TestSubMatrixAcess<3, 3>();
    number_of_failed_tests += TestSubMatrixAcess<1, 3>();
    number_of_failed_tests += TestSubMatrixAcess<2, 3>();
    number_of_failed_tests += TestSubMatrixAcess<3, 3>();

    number_of_failed_tests += TestSubMatrixAssign<1, 1>();

    number_of_failed_tests += TestSubMatrixAssign<1, 2>();
    number_of_failed_tests += TestSubMatrixAssign<2, 1>();
    number_of_failed_tests += TestSubMatrixAssign<2, 2>();

    number_of_failed_tests += TestSubMatrixAssign<3, 1>();
    number_of_failed_tests += TestSubMatrixAssign<3, 2>();
    number_of_failed_tests += TestSubMatrixAssign<3, 3>();
    number_of_failed_tests += TestSubMatrixAssign<1, 3>();
    number_of_failed_tests += TestSubMatrixAssign<2, 3>();
    number_of_failed_tests += TestSubMatrixAssign<3, 3>();

    std::cout << number_of_failed_tests << "tests failed" << std::endl;

    return number_of_failed_tests;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2017 deepstreamHub GmbH
 *
 * 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 <ostream>

#include <client.hpp>
#include <message.hpp>
#include <use.hpp>

#include <cassert>

namespace deepstream {
namespace client
{

std::ostream& operator<<(std::ostream& os, State state)
{
	os << static_cast<int>(state);
	return os;
}

State transition(State state, const Message& message, Sender sender)
{
	assert( state != State::ERROR );
	assert( state != State::DISCONNECTED );

	const Topic topic = message.topic();
	const Action action = message.action();
	const bool is_ack = message.is_ack();

	const auto expected_num_args = Message::num_arguments( message.header() );
	const std::size_t& num_args = message.num_arguments();

	use(expected_num_args);
	assert( num_args >= expected_num_args.first );
	assert( num_args <= expected_num_args.second );

	// ping/pong
	if( topic == Topic::CONNECTION &&
		action == Action::PING &&
		sender == Sender::SERVER )
	{
		assert( !is_ack );

		return state;
	}

	if( topic == Topic::CONNECTION &&
		action == Action::PONG &&
		sender == Sender::CLIENT )
	{
		assert( !is_ack );

		return state;
	}

	// actual state transitions
	if( state == State::AWAIT_CONNECTION &&
		topic == Topic::CONNECTION &&
		action == Action::CHALLENGE &&
		sender == Sender::SERVER )
	{
		assert( !is_ack );

		return State::CHALLENGING;
	}

	if( state == State::CHALLENGING &&
		topic == Topic::CONNECTION &&
		action == Action::CHALLENGE_RESPONSE &&
		sender == Sender::CLIENT )
	{
		assert( !is_ack );

		return State::CHALLENGING_WAIT;
	}

	if( state == State::CHALLENGING_WAIT &&
		topic == Topic::CONNECTION &&
		action == Action::CHALLENGE_RESPONSE &&
		sender == Sender::SERVER )
	{
		assert( is_ack );

		return State::AWAIT_AUTHENTICATION;
	}

	if( state == State::CHALLENGING_WAIT &&
		topic == Topic::CONNECTION &&
		action == Action::REDIRECT &&
		sender == Sender::SERVER )
	{
		assert( !is_ack );

		return State::AWAIT_CONNECTION;
	}

	if( state == State::CHALLENGING_WAIT &&
		topic == Topic::CONNECTION &&
		action == Action::REJECT &&
		sender == Sender::SERVER )
	{
		assert( !is_ack );

		return State::DISCONNECTED;
	}

	if( state == State::AWAIT_AUTHENTICATION &&
		topic == Topic::AUTH &&
		action == Action::REQUEST &&
		sender == Sender::CLIENT )
	{
		assert( !is_ack );

		return State::AUTHENTICATING;
	}

	if( state == State::AUTHENTICATING &&
		topic == Topic::AUTH &&
		action == Action::REQUEST &&
		sender == Sender::SERVER )
	{
		assert( is_ack );

		return State::CONNECTED;
	}

	if( state == State::AUTHENTICATING &&
		topic == Topic::AUTH &&
		action == Action::ERROR_TOO_MANY_AUTH_ATTEMPTS &&
		sender == Sender::SERVER )
	{
		assert( !is_ack );

		return State::DISCONNECTED;
	}

	if( state == State::AUTHENTICATING &&
		topic == Topic::AUTH &&
		action == Action::ERROR_INVALID_AUTH_DATA &&
		sender == Sender::SERVER )
	{
		assert( !is_ack );

		return State::AWAIT_AUTHENTICATION;
	}

	if( state == State::AUTHENTICATING &&
		topic == Topic::AUTH &&
		action == Action::ERROR_INVALID_AUTH_MSG &&
		sender == Sender::SERVER )
	{
		assert( !is_ack );

		return State::DISCONNECTED;
	}

	if( state == State::CONNECTED &&
		topic == Topic::EVENT )
	{
		if( action == Action::LISTEN ||
			action == Action::SUBSCRIBE ||
			action == Action::UNLISTEN ||
			action == Action::UNSUBSCRIBE )
		{
			if( (sender == Sender::CLIENT && !is_ack) ||
				(sender == Sender::SERVER && is_ack) )
				return state;
		}
		else if( action == Action::EVENT )
			return state;
	}

	return State::ERROR;
}

}
}
<commit_msg>Src: fix client state transition checks<commit_after>/*
 * Copyright 2017 deepstreamHub GmbH
 *
 * 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 <ostream>

#include <client.hpp>
#include <message.hpp>
#include <use.hpp>

#include <cassert>

namespace deepstream {
namespace client
{

std::ostream& operator<<(std::ostream& os, State state)
{
	os << static_cast<int>(state);
	return os;
}

State transition(State state, const Message& message, Sender sender)
{
	assert( state != State::ERROR );
	assert( state != State::DISCONNECTED );

	const Topic topic = message.topic();
	const Action action = message.action();
	const bool is_ack = message.is_ack();

	const auto expected_num_args = Message::num_arguments( message.header() );
	const std::size_t& num_args = message.num_arguments();

	use(expected_num_args);
	assert( num_args >= expected_num_args.first );
	assert( num_args <= expected_num_args.second );

	// ping/pong
	if( topic == Topic::CONNECTION &&
		action == Action::PING &&
		sender == Sender::SERVER )
	{
		assert( !is_ack );

		return state;
	}

	if( topic == Topic::CONNECTION &&
		action == Action::PONG &&
		sender == Sender::CLIENT )
	{
		assert( !is_ack );

		return state;
	}

	// actual state transitions
	if( state == State::AWAIT_CONNECTION &&
		topic == Topic::CONNECTION &&
		action == Action::CHALLENGE &&
		sender == Sender::SERVER )
	{
		assert( !is_ack );

		return State::CHALLENGING;
	}

	if( state == State::CHALLENGING &&
		topic == Topic::CONNECTION &&
		action == Action::CHALLENGE_RESPONSE &&
		!is_ack &&
		sender == Sender::CLIENT )
	{
		return State::CHALLENGING_WAIT;
	}

	if( state == State::CHALLENGING_WAIT &&
		topic == Topic::CONNECTION &&
		action == Action::CHALLENGE_RESPONSE &&
		is_ack &&
		sender == Sender::SERVER )
	{
		return State::AWAIT_AUTHENTICATION;
	}

	if( state == State::CHALLENGING_WAIT &&
		topic == Topic::CONNECTION &&
		action == Action::REDIRECT &&
		sender == Sender::SERVER )
	{
		assert( !is_ack );

		return State::AWAIT_CONNECTION;
	}

	if( state == State::CHALLENGING_WAIT &&
		topic == Topic::CONNECTION &&
		action == Action::REJECT &&
		sender == Sender::SERVER )
	{
		assert( !is_ack );

		return State::DISCONNECTED;
	}

	if( state == State::AWAIT_AUTHENTICATION &&
		topic == Topic::AUTH &&
		action == Action::REQUEST &&
		!is_ack &&
		sender == Sender::CLIENT )
	{
		return State::AUTHENTICATING;
	}

	if( state == State::AUTHENTICATING &&
		topic == Topic::AUTH &&
		action == Action::REQUEST &&
		is_ack &&
		sender == Sender::SERVER )
	{
		return State::CONNECTED;
	}

	if( state == State::AUTHENTICATING &&
		topic == Topic::AUTH &&
		action == Action::ERROR_TOO_MANY_AUTH_ATTEMPTS &&
		sender == Sender::SERVER )
	{
		assert( !is_ack );

		return State::DISCONNECTED;
	}

	if( state == State::AUTHENTICATING &&
		topic == Topic::AUTH &&
		action == Action::ERROR_INVALID_AUTH_DATA &&
		sender == Sender::SERVER )
	{
		assert( !is_ack );

		return State::AWAIT_AUTHENTICATION;
	}

	if( state == State::AUTHENTICATING &&
		topic == Topic::AUTH &&
		action == Action::ERROR_INVALID_AUTH_MSG &&
		sender == Sender::SERVER )
	{
		assert( !is_ack );

		return State::DISCONNECTED;
	}

	if( state == State::CONNECTED &&
		topic == Topic::EVENT )
	{
		if( action == Action::LISTEN ||
			action == Action::SUBSCRIBE ||
			action == Action::UNLISTEN ||
			action == Action::UNSUBSCRIBE )
		{
			if( (sender == Sender::CLIENT && !is_ack) ||
				(sender == Sender::SERVER && is_ack) )
				return state;
		}
		else if( action == Action::EVENT )
			return state;
	}

	return State::ERROR;
}

}
}
<|endoftext|>


<commit_before>// The Modified BSD License
//
// Copyright (c) 2015, Mikhail Balakhno
// 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 fontio 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 <fstream>

#include <gtest/gtest.h>

#include <fontio/logic/cff/CffReader.hpp>
#include <fontio/logic/type2/Type2GlyphMetricsCalculator.hpp>

namespace fontio { namespace logic { namespace type2
{
    using namespace fontio::logic::cff;
    using namespace fontio::model;
    using namespace fontio::model::cff;
    using namespace fontio::model::type2;

    class Type2GlyphMetricsCalculatorTests : public testing::Test
    {
    protected:

        CffReader reader;

        Type2GlyphMetricsCalculator calculator;

    protected:

        std::unique_ptr<Cff> ReadCffFile(const std::string& filename)
        {
            std::ifstream stream(filename, std::ios_base::binary);

            return this->reader.ReadCff(stream);
        }
    };

    TEST_F(Type2GlyphMetricsCalculatorTests, CanCalculateMetrics)
    {
        auto cff = this->ReadCffFile("test_data/cff/bare.cff");

        const auto& charstrings = static_cast<const CffType2Charstrings&>(cff->GetTopDicts()[0].GetCharstrings()).GetCharstrings();

        auto metrics = this->calculator.CalculateMetrics(
            charstrings[10],
            Type2SubroutineAccessor(),
            Type2SubroutineAccessor(),
            472,
            220);

        ASSERT_EQ(328, metrics.GetAdvanceWidth());
        ASSERT_EQ(12, metrics.GetBoundBox().GetX0());
        ASSERT_EQ(-120, metrics.GetBoundBox().GetY0());
        ASSERT_EQ(273, metrics.GetBoundBox().GetX1());
        ASSERT_EQ(739, metrics.GetBoundBox().GetY1());
        ASSERT_EQ(12, metrics.GetLeftSideBearings());
    }

} } }
<commit_msg>Added test for width calculation, which yet fails.<commit_after>// The Modified BSD License
//
// Copyright (c) 2015, Mikhail Balakhno
// 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 fontio 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 <fstream>

#include <gtest/gtest.h>

#include <fontio/logic/cff/CffReader.hpp>
#include <fontio/logic/type2/Type2GlyphMetricsCalculator.hpp>

namespace fontio { namespace logic { namespace type2
{
    using namespace fontio::logic::cff;
    using namespace fontio::model;
    using namespace fontio::model::cff;
    using namespace fontio::model::type2;

    class Type2GlyphMetricsCalculatorTests : public testing::Test
    {
    protected:

        CffReader reader;

        Type2GlyphMetricsCalculator calculator;

    protected:

        std::unique_ptr<Cff> ReadCffFile(const std::string& filename)
        {
            std::ifstream stream(filename, std::ios_base::binary);

            return this->reader.ReadCff(stream);
        }
    };

    TEST_F(Type2GlyphMetricsCalculatorTests, CanCalculateMetrics)
    {
        auto cff = this->ReadCffFile("test_data/cff/bare.cff");

        const auto& charstrings = static_cast<const CffType2Charstrings&>(cff->GetTopDicts()[0].GetCharstrings()).GetCharstrings();

        auto metrics = this->calculator.CalculateMetrics(
            charstrings[10],
            Type2SubroutineAccessor(),
            Type2SubroutineAccessor(),
            472,
            220);

        ASSERT_EQ(328, metrics.GetAdvanceWidth());
        ASSERT_EQ(12, metrics.GetBoundBox().GetX0());
        ASSERT_EQ(-120, metrics.GetBoundBox().GetY0());
        ASSERT_EQ(273, metrics.GetBoundBox().GetX1());
        ASSERT_EQ(739, metrics.GetBoundBox().GetY1());
        ASSERT_EQ(12, metrics.GetLeftSideBearings());
    }

    TEST_F(Type2GlyphMetricsCalculatorTests, CanCalculateSpaceWidth)
    {
        auto cff = this->ReadCffFile("test_data/cff/test_font_width.cff");

        const auto& topDict = cff->GetTopDicts()[0];
        const auto& charstrings = static_cast<const CffType2Charstrings&>(topDict.GetCharstrings()).GetCharstrings();

        auto metrics = this->calculator.CalculateMetrics(
            charstrings[0],
            Type2SubroutineAccessor(),
            Type2SubroutineAccessor(),
            topDict.GetNominalWidthX(),
            topDict.GetDefaultWidthX());

        ASSERT_EQ(227, metrics.GetAdvanceWidth());
    }

} } }
<|endoftext|>


<commit_before>// Copyright (c) 2021 ASMlover. All rights reserved.
//
//  ______             __                  ___
// /\__  _\           /\ \                /\_ \
// \/_/\ \/    __     \_\ \  _____     ___\//\ \      __
//    \ \ \  /'__`\   /'_` \/\ '__`\  / __`\\ \ \   /'__`\
//     \ \ \/\ \L\.\_/\ \L\ \ \ \L\ \/\ \L\ \\_\ \_/\  __/
//      \ \_\ \__/.\_\ \___,_\ \ ,__/\ \____//\____\ \____\
//       \/_/\/__/\/_/\/__,_ /\ \ \/  \/___/ \/____/\/____/
//                             \ \_\
//                              \/_/
//
// 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 ofconditions 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 materialsprovided with the
//    distribution.
//
// 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 <fstream>
#include <iostream>

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

  return 0;
}
<commit_msg>:construction: chore(tadpole): updated the main entry<commit_after>// Copyright (c) 2021 ASMlover. All rights reserved.
//
//  ______             __                  ___
// /\__  _\           /\ \                /\_ \
// \/_/\ \/    __     \_\ \  _____     ___\//\ \      __
//    \ \ \  /'__`\   /'_` \/\ '__`\  / __`\\ \ \   /'__`\
//     \ \ \/\ \L\.\_/\ \L\ \ \ \L\ \/\ \L\ \\_\ \_/\  __/
//      \ \_\ \__/.\_\ \___,_\ \ ,__/\ \____//\____\ \____\
//       \/_/\/__/\/_/\/__,_ /\ \ \/  \/___/ \/____/\/____/
//                             \ \_\
//                              \/_/
//
// 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 ofconditions 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 materialsprovided with the
//    distribution.
//
// 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 <fstream>
#include <iostream>
#include "Common/Common.hh"

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

  return 0;
}
<|endoftext|>


<commit_before>// Filename: hdf2vertex.C
// Created on 31 May 2007 by Boyce Griffith
//
// Copyright (c) 2002-2013, Boyce Griffith
// 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 New York University 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.

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

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

#include <H5LT.h>

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

using namespace std;

/////////////////////////////// STATIC ///////////////////////////////////////

inline string
discard_comments(
    const string& input_string)
{
    // Create a copy of the input string, but without any text following a '!',
    // '#', or '%' character.
    string output_string = input_string;
    istringstream string_stream;

    // Discard any text following a '!' character.
    string_stream.str(output_string);
    getline(string_stream, output_string, '!');
    string_stream.clear();

    // Discard any text following a '#' character.
    string_stream.str(output_string);
    getline(string_stream, output_string, '#');
    string_stream.clear();

    // Discard any text following a '%' character.
    string_stream.str(output_string);
    getline(string_stream, output_string, '%');
    string_stream.clear();
    return output_string;
}// discard_comments

int
main(
    int argc,
    char* argv[])
{
    if (argc != 3)
    {
        cout << argv[0] << ": a tool to convert IBAMR vertex files from HDF5 to ASCII" << "\n"
             << "USAGE: " << argv[0] << " <input filename> <output filename>" << endl;
        return -1;
    }

    const string input_filename = argv[1];
    const string output_filename = argv[2];

    cout << "input file name: " << input_filename << "\n"
         << "output file name: " << output_filename << "\n";

    // Ensure that the input file exists, and that the output file does not.
    ifstream input_fstream, output_fstream;
    input_fstream.open(input_filename.c_str(), ios::in);
    output_fstream.open(output_filename.c_str(), ios::in);

    if (!input_fstream.is_open())
    {
        cout << "error: Unable to open input file " << input_filename << endl;
        return -1;
    }

    if (output_fstream.is_open())
    {
        cout << "error: Output file " << output_filename << " already exists" << endl;
        return -1;
    }

    input_fstream.close();
    output_fstream.close();

    // Process the HDF5 file.
    hid_t file_id;
    int rank;
    hsize_t dims[2];
    H5T_class_t class_id;
    size_t type_size;
    herr_t status;

    file_id = H5Fopen(input_filename.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);
    if (file_id < 0)
    {
        cout << "error: Unable to open input file " << input_filename << endl;
        return -1;
    }

    if (!H5LTfind_dataset(file_id, "vertex"))
    {
        cout << "error: Cannot find vertex dataset in input file " << input_filename << endl;
        return -1;
    }

    status = H5LTget_dataset_ndims(file_id, "vertex", &rank);
    if (rank != 2)
    {
        cout << "error: Invalid dataset rank in input file " << input_filename << endl;
        return -1;
    }

    status = H5LTget_dataset_info(file_id, "vertex", &dims[0], &class_id, &type_size);
    if (dims[0] != NDIM || dims[1] <= 0)
    {
        cout << "error: Invalid dataset dimension in input file " << input_filename << endl;
        return -1;
    }

    static const int num_vertex = dims[1];
    vector<double> vertex_posn(NDIM*num_vertex);
    status = H5LTread_dataset_static_cast<double>(file_id, "vertex", &vertex_posn[0]);

    status = H5Fclose(file_id);

    // Output the vertex file.
    ofstream file_stream;
    file_stream.open(output_filename.c_str(), ios::out);
    if (!file_stream.is_open())
    {
        cout << "error: Unable to open output file " << output_filename << endl;
        return -1;
    }

    // The first entry in the file is the number of vertices.
    ostringstream stream;
    stream << num_vertex;
    string first_line(stream.str());
    first_line.resize((NDIM == 2 ? 46 : 69),' ');
    file_stream << first_line << "# number of vertices\n";

    // Each successive line provides the initial position of each vertex in the
    // input file.
    for (int k = 0; k < num_vertex; ++k)
    {
        for (unsigned int d = 0; d < NDIM; ++d)
        {
            file_stream.setf(ios_base::scientific);
            file_stream.precision(16);
            file_stream << vertex_posn[k*NDIM+d];
            if (d < NDIM-1) file_stream << " ";
        }
#if (NDIM == 2)
        if (k == 0) file_stream << " # x-coord, y-coord";
#endif
#if (NDIM == 3)
        if (k == 0) file_stream << " # x-coord, y-coord, z-coord";
#endif
        file_stream << "\n";
    }

    // Close the output file.
    file_stream.close();
    return 0;
}// main

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

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

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

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

//////////////////////////////////////////////////////////////////////////////
<commit_msg>fixing HDF5 headers in branches/ibamr-dev<commit_after>// Filename: hdf2vertex.C
// Created on 31 May 2007 by Boyce Griffith
//
// Copyright (c) 2002-2013, Boyce Griffith
// 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 New York University 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.

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

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

#include <hdf5.h>
#include <hdf5_lt.h>

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

using namespace std;

/////////////////////////////// STATIC ///////////////////////////////////////

inline string
discard_comments(
    const string& input_string)
{
    // Create a copy of the input string, but without any text following a '!',
    // '#', or '%' character.
    string output_string = input_string;
    istringstream string_stream;

    // Discard any text following a '!' character.
    string_stream.str(output_string);
    getline(string_stream, output_string, '!');
    string_stream.clear();

    // Discard any text following a '#' character.
    string_stream.str(output_string);
    getline(string_stream, output_string, '#');
    string_stream.clear();

    // Discard any text following a '%' character.
    string_stream.str(output_string);
    getline(string_stream, output_string, '%');
    string_stream.clear();
    return output_string;
}// discard_comments

int
main(
    int argc,
    char* argv[])
{
    if (argc != 3)
    {
        cout << argv[0] << ": a tool to convert IBAMR vertex files from HDF5 to ASCII" << "\n"
             << "USAGE: " << argv[0] << " <input filename> <output filename>" << endl;
        return -1;
    }

    const string input_filename = argv[1];
    const string output_filename = argv[2];

    cout << "input file name: " << input_filename << "\n"
         << "output file name: " << output_filename << "\n";

    // Ensure that the input file exists, and that the output file does not.
    ifstream input_fstream, output_fstream;
    input_fstream.open(input_filename.c_str(), ios::in);
    output_fstream.open(output_filename.c_str(), ios::in);

    if (!input_fstream.is_open())
    {
        cout << "error: Unable to open input file " << input_filename << endl;
        return -1;
    }

    if (output_fstream.is_open())
    {
        cout << "error: Output file " << output_filename << " already exists" << endl;
        return -1;
    }

    input_fstream.close();
    output_fstream.close();

    // Process the HDF5 file.
    hid_t file_id;
    int rank;
    hsize_t dims[2];
    H5T_class_t class_id;
    size_t type_size;
    herr_t status;

    file_id = H5Fopen(input_filename.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);
    if (file_id < 0)
    {
        cout << "error: Unable to open input file " << input_filename << endl;
        return -1;
    }

    if (!H5LTfind_dataset(file_id, "vertex"))
    {
        cout << "error: Cannot find vertex dataset in input file " << input_filename << endl;
        return -1;
    }

    status = H5LTget_dataset_ndims(file_id, "vertex", &rank);
    if (rank != 2)
    {
        cout << "error: Invalid dataset rank in input file " << input_filename << endl;
        return -1;
    }

    status = H5LTget_dataset_info(file_id, "vertex", &dims[0], &class_id, &type_size);
    if (dims[0] != NDIM || dims[1] <= 0)
    {
        cout << "error: Invalid dataset dimension in input file " << input_filename << endl;
        return -1;
    }

    static const int num_vertex = dims[1];
    vector<double> vertex_posn(NDIM*num_vertex);
    status = H5LTread_dataset_static_cast<double>(file_id, "vertex", &vertex_posn[0]);

    status = H5Fclose(file_id);

    // Output the vertex file.
    ofstream file_stream;
    file_stream.open(output_filename.c_str(), ios::out);
    if (!file_stream.is_open())
    {
        cout << "error: Unable to open output file " << output_filename << endl;
        return -1;
    }

    // The first entry in the file is the number of vertices.
    ostringstream stream;
    stream << num_vertex;
    string first_line(stream.str());
    first_line.resize((NDIM == 2 ? 46 : 69),' ');
    file_stream << first_line << "# number of vertices\n";

    // Each successive line provides the initial position of each vertex in the
    // input file.
    for (int k = 0; k < num_vertex; ++k)
    {
        for (unsigned int d = 0; d < NDIM; ++d)
        {
            file_stream.setf(ios_base::scientific);
            file_stream.precision(16);
            file_stream << vertex_posn[k*NDIM+d];
            if (d < NDIM-1) file_stream << " ";
        }
#if (NDIM == 2)
        if (k == 0) file_stream << " # x-coord, y-coord";
#endif
#if (NDIM == 3)
        if (k == 0) file_stream << " # x-coord, y-coord, z-coord";
#endif
        file_stream << "\n";
    }

    // Close the output file.
    file_stream.close();
    return 0;
}// main

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

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

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

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

//////////////////////////////////////////////////////////////////////////////
<|endoftext|>


<commit_before>#include "acmacs-base/argv.hh"
#include "acmacs-base/string.hh"
#include "acmacs-base/string-split.hh"
#include "acmacs-base/range.hh"
#include "acmacs-base/stream.hh"
#include "acmacs-chart-2/factory-import.hh"
#include "acmacs-chart-2/chart.hh"
#include "seqdb-3/seqdb.hh"
#include "hidb-5/hidb.hh"
#include "hidb-5/report.hh"

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

struct AntigenData
{
    size_t no;
    const hidb::HiDb* hidb = nullptr;
    std::shared_ptr<acmacs::chart::Antigen> antigen_chart;
    std::shared_ptr<hidb::Antigen> antigen_hidb;
    acmacs::seqdb::ref antigen_seqdb;
};

template <> struct fmt::formatter<AntigenData> : fmt::formatter<acmacs::fmt_default_formatter> {
    template <typename FormatCtx> auto format(const AntigenData& ag, FormatCtx& ctx)
    {
        format_to(ctx.out(), "{} {}", ag.no, *ag.antigen_chart);
        if (ag.antigen_hidb)
            hidb::report_tables(std::cout, *ag.hidb, ag.antigen_hidb->tables(), hidb::report_tables::recent, "\n    ");
        if (ag.antigen_seqdb) {
            if (const auto& clades = ag.antigen_seqdb.seq().clades; !clades.empty())
                format_to(ctx.out(), "\n    clades: {}", clades);
        }
        return ctx.out();
    }
};

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

using namespace acmacs::argv;
struct Options : public argv
{
    Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }

    // option<str> db_dir{*this, "db-dir"};
    option<str> seqdb{*this, "seqdb"};

    option<bool>      sort_by_tables{*this, "sort-by-tables"};
    option<str>       clade{*this, "clade"};
    option<str>       aa{*this, "aa", desc{"report AA at given positions (comma separated)"}};
    option<bool>      verbose{*this, 'v', "verbose"};

    argument<str> chart_file{*this, arg_name{"chart"}, mandatory};
};

int main(int argc, char* const argv[])
{
    int exit_code = 0;
    try {
        Options opt(argc, argv);
        acmacs::seqdb::setup(opt.seqdb);
        const std::vector<size_t> report_aa_at_pos = opt.aa ? acmacs::string::split_into_size_t(*opt.aa, ",") : std::vector<size_t>{};

        auto chart = acmacs::chart::import_from_file(opt.chart_file);
        const auto virus_type = chart->info()->virus_type(acmacs::chart::Info::Compute::Yes);
        const auto& seqdb = acmacs::seqdb::get();
        const auto& hidb = hidb::get(virus_type); // , do_report_time(verbose));
        auto antigens_chart = chart->antigens();
        const auto hidb_antigens = hidb.antigens()->find(*antigens_chart);
        const auto seqdb_antigens = seqdb.match(*antigens_chart, virus_type);
        std::vector<AntigenData> antigens(antigens_chart->size());
        std::transform(acmacs::index_iterator(0UL), acmacs::index_iterator(antigens_chart->size()), antigens.begin(), [&](size_t index) -> AntigenData {
            return {index, &hidb, antigens_chart->at(index), hidb_antigens[index], seqdb_antigens[index]};
        });
        if (opt.clade)
            antigens.erase(std::remove_if(antigens.begin(), antigens.end(), [clade = *opt.clade](const auto& ag) -> bool { return !ag.antigen_seqdb || !ag.antigen_seqdb.seq().has_clade(clade); }),
                           antigens.end());
        std::cerr << "INFO: " << antigens.size() << " antigens upon filtering\n";
        if (opt.sort_by_tables) {
            auto hidb_tables = hidb.tables();
            std::sort(antigens.begin(), antigens.end(), [&](const auto& e1, const auto& e2) -> bool {
                if (!e1.antigen_hidb)
                    return false;
                if (!e2.antigen_hidb)
                    return true;
                if (const auto nt1 = e1.antigen_hidb->number_of_tables(), nt2 = e2.antigen_hidb->number_of_tables(); nt1 == nt2) {
                    auto mrt1 = hidb_tables->most_recent(e1.antigen_hidb->tables()), mrt2 = hidb_tables->most_recent(e2.antigen_hidb->tables());
                    return mrt1->date() > mrt2->date();
                }
                else
                    return nt1 > nt2;
            });
        }
        for (const auto& ad : antigens) {
            fmt::print("{}\n", ad);
            if (!report_aa_at_pos.empty()) {
                const auto aa = ad.antigen_seqdb.seq().amino_acids.aligned();
                fmt::print("   ");
                for (auto pos : report_aa_at_pos) {
                    fmt::print(" {}", pos);
                    if (aa.size() >= pos)
                        fmt::print("{}", aa[pos - 1]);
                    else
                        fmt::print("?");
                }
                fmt::print("\n");
            }
        }
    }
    catch (std::exception& err) {
        fmt::print(stderr, "ERROR: {}\n", err);
        exit_code = 2;
    }
    return exit_code;
}

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>handing seqdb ref with a reference<commit_after>#include "acmacs-base/argv.hh"
#include "acmacs-base/string.hh"
#include "acmacs-base/string-split.hh"
#include "acmacs-base/range.hh"
#include "acmacs-base/stream.hh"
#include "acmacs-chart-2/factory-import.hh"
#include "acmacs-chart-2/chart.hh"
#include "seqdb-3/seqdb.hh"
#include "hidb-5/hidb.hh"
#include "hidb-5/report.hh"

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

struct AntigenData
{
    size_t no;
    const hidb::HiDb* hidb = nullptr;
    std::shared_ptr<acmacs::chart::Antigen> antigen_chart;
    std::shared_ptr<hidb::Antigen> antigen_hidb;
    acmacs::seqdb::ref antigen_seqdb;
};

template <> struct fmt::formatter<AntigenData> : fmt::formatter<acmacs::fmt_default_formatter> {
    template <typename FormatCtx> auto format(const AntigenData& ag, FormatCtx& ctx)
    {
        format_to(ctx.out(), "{} {}", ag.no, *ag.antigen_chart);
        if (ag.antigen_hidb)
            hidb::report_tables(std::cout, *ag.hidb, ag.antigen_hidb->tables(), hidb::report_tables::recent, "\n    ");
        if (ag.antigen_seqdb) {
            if (const auto& clades = ag.antigen_seqdb.seq().clades; !clades.empty())
                format_to(ctx.out(), "\n    clades: {}", clades);
        }
        return ctx.out();
    }
};

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

using namespace acmacs::argv;
struct Options : public argv
{
    Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }

    // option<str> db_dir{*this, "db-dir"};
    option<str> seqdb{*this, "seqdb"};

    option<bool>      sort_by_tables{*this, "sort-by-tables"};
    option<str>       clade{*this, "clade"};
    option<str>       aa{*this, "aa", desc{"report AA at given positions (comma separated)"}};
    option<bool>      verbose{*this, 'v', "verbose"};

    argument<str> chart_file{*this, arg_name{"chart"}, mandatory};
};

int main(int argc, char* const argv[])
{
    int exit_code = 0;
    try {
        Options opt(argc, argv);
        acmacs::seqdb::setup(opt.seqdb);
        const std::vector<size_t> report_aa_at_pos = opt.aa ? acmacs::string::split_into_size_t(*opt.aa, ",") : std::vector<size_t>{};

        auto chart = acmacs::chart::import_from_file(opt.chart_file);
        const auto virus_type = chart->info()->virus_type(acmacs::chart::Info::Compute::Yes);
        const auto& seqdb = acmacs::seqdb::get();
        const auto& hidb = hidb::get(virus_type); // , do_report_time(verbose));
        auto antigens_chart = chart->antigens();
        const auto hidb_antigens = hidb.antigens()->find(*antigens_chart);
        const auto seqdb_antigens = seqdb.match(*antigens_chart, virus_type);
        std::vector<AntigenData> antigens(antigens_chart->size());
        std::transform(acmacs::index_iterator(0UL), acmacs::index_iterator(antigens_chart->size()), antigens.begin(), [&](size_t index) -> AntigenData {
            return {index, &hidb, antigens_chart->at(index), hidb_antigens[index], seqdb_antigens[index]};
        });
        if (opt.clade)
            antigens.erase(std::remove_if(antigens.begin(), antigens.end(), [&seqdb, clade = *opt.clade](const auto& ag) -> bool { return !ag.antigen_seqdb || !ag.antigen_seqdb.has_clade(seqdb, clade); }),
                           antigens.end());
        std::cerr << "INFO: " << antigens.size() << " antigens upon filtering\n";
        if (opt.sort_by_tables) {
            auto hidb_tables = hidb.tables();
            std::sort(antigens.begin(), antigens.end(), [&](const auto& e1, const auto& e2) -> bool {
                if (!e1.antigen_hidb)
                    return false;
                if (!e2.antigen_hidb)
                    return true;
                if (const auto nt1 = e1.antigen_hidb->number_of_tables(), nt2 = e2.antigen_hidb->number_of_tables(); nt1 == nt2) {
                    auto mrt1 = hidb_tables->most_recent(e1.antigen_hidb->tables()), mrt2 = hidb_tables->most_recent(e2.antigen_hidb->tables());
                    return mrt1->date() > mrt2->date();
                }
                else
                    return nt1 > nt2;
            });
        }
        for (const auto& ad : antigens) {
            fmt::print("{}\n", ad);
            if (!report_aa_at_pos.empty()) {
                const auto aa = ad.antigen_seqdb.seq().amino_acids.aligned();
                fmt::print("   ");
                for (auto pos : report_aa_at_pos) {
                    fmt::print(" {}", pos);
                    if (aa.size() >= pos)
                        fmt::print("{}", aa[pos - 1]);
                    else
                        fmt::print("?");
                }
                fmt::print("\n");
            }
        }
    }
    catch (std::exception& err) {
        fmt::print(stderr, "ERROR: {}\n", err);
        exit_code = 2;
    }
    return exit_code;
}

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>


<commit_before>#include "external_task.h"
#include "../sandbox/isolate_sandbox.h"
#include "../helpers/string_utils.h"
#include <fstream>
#include <algorithm>
#define BOOST_FILESYSTEM_NO_DEPRECATED
#define BOOST_NO_CXX11_SCOPED_ENUMS
#include <boost/filesystem.hpp>

namespace fs = boost::filesystem;

external_task::external_task(const create_params &data)
	: task_base(data.id, data.task_meta), worker_config_(data.worker_conf), sandbox_(nullptr),
	  sandbox_config_(data.task_meta->sandbox), limits_(data.limits), logger_(data.logger), temp_dir_(data.temp_dir),
	  source_dir_(data.source_path), working_dir_(data.working_path)
{
	if (worker_config_ == nullptr) {
		throw task_exception("No worker configuration provided.");
	}

	if (limits_ == nullptr) {
		throw task_exception("No limits provided.");
	}

	if (sandbox_config_ == nullptr) {
		throw task_exception("No sandbox configuration provided.");
	}

	sandbox_check();
}

external_task::~external_task()
{
}

void external_task::sandbox_check()
{
	bool found = false;

#ifndef _WIN32
	if (task_meta_->sandbox->name == "isolate") {
		found = true;
	}
#endif

	if (found == false) {
		throw task_exception("Unknown sandbox type: " + task_meta_->sandbox->name);
	}
}

void external_task::sandbox_init()
{
#ifndef _WIN32
	if (task_meta_->sandbox->name == "isolate") {
		sandbox_ = std::make_shared<isolate_sandbox>(
			sandbox_config_, *limits_, worker_config_->get_worker_id(), temp_dir_, logger_);
	}
#endif
}

void external_task::sandbox_fini()
{
	sandbox_ = nullptr;
}

std::shared_ptr<task_results> external_task::run()
{
	sandbox_init();

	// TODO: only temporary solution, should be removed
	if (sandbox_ == nullptr) {
		return nullptr;
	}

	// initialize output from stdout and stderr
	results_output_init();

	// check if binary is executable and set it otherwise
	make_binary_executable(task_meta_->binary);

	std::shared_ptr<task_results> res(new task_results());
	res->sandbox_status =
		std::unique_ptr<sandbox_results>(new sandbox_results(sandbox_->run(task_meta_->binary, task_meta_->cmd_args)));

	// get output from stdout and stderr
	res->sandbox_status->output = get_results_output();

	sandbox_fini();

	// Check if sandbox ran successfully, else report error
	if (res->sandbox_status->status != isolate_status::OK) {
		res->status = task_status::FAILED;
		res->error_message = "Sandboxed program failed: " + res->sandbox_status->message;
	}

	return res;
}

std::shared_ptr<sandbox_limits> external_task::get_limits()
{
	return limits_;
}

void external_task::results_output_init()
{
	if (sandbox_config_->output) {
		std::string random = helpers::random_alphanum_string(10);
		if (sandbox_config_->std_output == "") {
			remove_stdout_ = true;
			std::string stdout_file = task_meta_->task_id + "." + random + ".output.stdout";
			sandbox_config_->std_output = (working_dir_ / fs::path(stdout_file)).string();
		}

		if (sandbox_config_->std_error == "") {
			remove_stderr_ = true;
			std::string stderr_file = task_meta_->task_id + "." + random + ".output.stderr";
			sandbox_config_->std_error = (working_dir_ / fs::path(stderr_file)).string();
		}
	}
}

fs::path external_task::find_path_outside_sandbox(std::string file)
{
	fs::path file_path = fs::path(file);
	fs::path sandbox_dir = file_path.parent_path();
	for (auto &dir : limits_->bound_dirs) {
		fs::path sandbox_dir_bound = fs::path(std::get<1>(dir));
		if (sandbox_dir_bound == sandbox_dir) {
			return fs::path(std::get<0>(dir)) / file_path.filename();
		}
	}
	return fs::path();
}

std::string external_task::get_results_output()
{
	std::string result;

	if (sandbox_config_->output) {
		size_t count = worker_config_->get_max_output_length();
		std::string result_stdout(count, 0);
		std::string result_stderr(count, 0);

		// files were outputted inside sandbox, so we have to find path outside sandbox
		fs::path stdout_file_path = find_path_outside_sandbox(sandbox_config_->std_output);
		fs::path stderr_file_path = find_path_outside_sandbox(sandbox_config_->std_error);

		// open and read files
		std::ifstream std_out(stdout_file_path.string());
		std::ifstream std_err(stderr_file_path.string());
		std_out.read(&result_stdout[0], count);
		std_err.read(&result_stderr[0], count);

		// if there was something in one of the files, write it to the result
		if (std_out.gcount() != 0 || std_err.gcount() != 0) {
			result = result_stdout.substr(0, std_out.gcount()) + result_stderr.substr(0, std_err.gcount());
		}

		// delete produced files
		try {
			if (remove_stdout_) {
				fs::remove(stdout_file_path);
			}
			if (remove_stderr_) {
				fs::remove(stderr_file_path);
			}
		} catch (fs::filesystem_error &e) {
			logger_->warn("Temporary sandbox output files not cleaned properly: {}", e.what());
		}
	}

	return result;
}

void external_task::make_binary_executable(std::string binary)
{
	try {
		fs::permissions(
			fs::path(binary), fs::perms::add_perms | fs::perms::owner_exe | fs::perms::group_exe | fs::others_exe);
	} catch (fs::filesystem_error &e) {
		auto message = std::string("Failed to set executable bits for executed binary. Error: ") + e.what();
		logger_->warn(message);
		throw sandbox_exception(message);
	}
}
<commit_msg>Path to binary is inside sandbox, reflect this in permission setting<commit_after>#include "external_task.h"
#include "../sandbox/isolate_sandbox.h"
#include "../helpers/string_utils.h"
#include <fstream>
#include <algorithm>
#define BOOST_FILESYSTEM_NO_DEPRECATED
#define BOOST_NO_CXX11_SCOPED_ENUMS
#include <boost/filesystem.hpp>

namespace fs = boost::filesystem;

external_task::external_task(const create_params &data)
	: task_base(data.id, data.task_meta), worker_config_(data.worker_conf), sandbox_(nullptr),
	  sandbox_config_(data.task_meta->sandbox), limits_(data.limits), logger_(data.logger), temp_dir_(data.temp_dir),
	  source_dir_(data.source_path), working_dir_(data.working_path)
{
	if (worker_config_ == nullptr) {
		throw task_exception("No worker configuration provided.");
	}

	if (limits_ == nullptr) {
		throw task_exception("No limits provided.");
	}

	if (sandbox_config_ == nullptr) {
		throw task_exception("No sandbox configuration provided.");
	}

	sandbox_check();
}

external_task::~external_task()
{
}

void external_task::sandbox_check()
{
	bool found = false;

#ifndef _WIN32
	if (task_meta_->sandbox->name == "isolate") {
		found = true;
	}
#endif

	if (found == false) {
		throw task_exception("Unknown sandbox type: " + task_meta_->sandbox->name);
	}
}

void external_task::sandbox_init()
{
#ifndef _WIN32
	if (task_meta_->sandbox->name == "isolate") {
		sandbox_ = std::make_shared<isolate_sandbox>(
			sandbox_config_, *limits_, worker_config_->get_worker_id(), temp_dir_, logger_);
	}
#endif
}

void external_task::sandbox_fini()
{
	sandbox_ = nullptr;
}

std::shared_ptr<task_results> external_task::run()
{
	sandbox_init();

	// TODO: only temporary solution, should be removed
	if (sandbox_ == nullptr) {
		return nullptr;
	}

	// initialize output from stdout and stderr
	results_output_init();

	// check if binary is executable and set it otherwise
	make_binary_executable(task_meta_->binary);

	std::shared_ptr<task_results> res(new task_results());
	res->sandbox_status =
		std::unique_ptr<sandbox_results>(new sandbox_results(sandbox_->run(task_meta_->binary, task_meta_->cmd_args)));

	// get output from stdout and stderr
	res->sandbox_status->output = get_results_output();

	sandbox_fini();

	// Check if sandbox ran successfully, else report error
	if (res->sandbox_status->status != isolate_status::OK) {
		res->status = task_status::FAILED;
		res->error_message = "Sandboxed program failed: " + res->sandbox_status->message;
	}

	return res;
}

std::shared_ptr<sandbox_limits> external_task::get_limits()
{
	return limits_;
}

void external_task::results_output_init()
{
	if (sandbox_config_->output) {
		std::string random = helpers::random_alphanum_string(10);
		if (sandbox_config_->std_output == "") {
			remove_stdout_ = true;
			std::string stdout_file = task_meta_->task_id + "." + random + ".output.stdout";
			sandbox_config_->std_output = (working_dir_ / fs::path(stdout_file)).string();
		}

		if (sandbox_config_->std_error == "") {
			remove_stderr_ = true;
			std::string stderr_file = task_meta_->task_id + "." + random + ".output.stderr";
			sandbox_config_->std_error = (working_dir_ / fs::path(stderr_file)).string();
		}
	}
}

fs::path external_task::find_path_outside_sandbox(std::string file)
{
	fs::path file_path = fs::path(file);
	if (!file_path.has_root_directory()) {
		// relative path to chdir
		return fs::path(sandbox_config_->chdir) / file_path;
	}

	// absolute path in sandbox provided
	fs::path sandbox_dir = file_path.parent_path();
	for (auto &dir : limits_->bound_dirs) {
		fs::path sandbox_dir_bound = fs::path(std::get<1>(dir));
		if (sandbox_dir_bound == sandbox_dir) {
			return fs::path(std::get<0>(dir)) / file_path.filename();
		}
	}
	return fs::path();
}

std::string external_task::get_results_output()
{
	std::string result;

	if (sandbox_config_->output) {
		size_t count = worker_config_->get_max_output_length();
		std::string result_stdout(count, 0);
		std::string result_stderr(count, 0);

		// files were outputted inside sandbox, so we have to find path outside sandbox
		fs::path stdout_file_path = find_path_outside_sandbox(sandbox_config_->std_output);
		fs::path stderr_file_path = find_path_outside_sandbox(sandbox_config_->std_error);

		// open and read files
		std::ifstream std_out(stdout_file_path.string());
		std::ifstream std_err(stderr_file_path.string());
		std_out.read(&result_stdout[0], count);
		std_err.read(&result_stderr[0], count);

		// if there was something in one of the files, write it to the result
		if (std_out.gcount() != 0 || std_err.gcount() != 0) {
			result = result_stdout.substr(0, std_out.gcount()) + result_stderr.substr(0, std_err.gcount());
		}

		// delete produced files
		try {
			if (remove_stdout_) {
				fs::remove(stdout_file_path);
			}
			if (remove_stderr_) {
				fs::remove(stderr_file_path);
			}
		} catch (fs::filesystem_error &e) {
			logger_->warn("Temporary sandbox output files not cleaned properly: {}", e.what());
		}
	}

	return result;
}

void external_task::make_binary_executable(std::string binary)
{
	try {
		fs::path binary_path = find_path_outside_sandbox(binary);
		fs::permissions(
			binary_path, fs::perms::add_perms | fs::perms::owner_exe | fs::perms::group_exe | fs::others_exe);
	} catch (fs::filesystem_error &e) {
		auto message = std::string("Failed to set executable bits for executed binary. Error: ") + e.what();
		logger_->warn(message);
		throw sandbox_exception(message);
	}
}
<|endoftext|>


<commit_before>#include "cnn/expr.h"

#include <initializer_list>

#include "cnn/nodes.h"
#include "cnn/conv.h"

namespace cnn { namespace expr {

Expression input(ComputationGraph& g, real s) { return Expression(&g, g.add_input(s)); }
Expression input(ComputationGraph& g, const real *ps) { return Expression(&g, g.add_input(ps)); }
Expression input(ComputationGraph& g, const Dim& d, const std::vector<cnn::real>& pdata) { return Expression(&g, g.add_input(d, pdata)); }
Expression input(ComputationGraph& g, const Dim& d, const std::vector<cnn::real>* pdata) { return Expression(&g, g.add_input(d, pdata)); }
Expression reference(ComputationGraph& g, const Dim& d, const cnn::real* pdata) { return Expression(&g, g.add_reference(d, pdata)); }
Expression const_parameter(ComputationGraph& g, Parameters* p) { return Expression(&g, g.add_const_parameters(p)); }
Expression parameter(ComputationGraph& g, Parameters* p) { return Expression(&g, g.add_parameters(p)); }
Expression lookup(ComputationGraph& g, LookupParameters* p, unsigned index) { return Expression(&g, g.add_lookup(p, index)); }
Expression lookup(ComputationGraph& g, LookupParameters* p, const unsigned* pindex) { return Expression(&g, g.add_lookup(p, pindex)); }
Expression lookup(ComputationGraph& g, LookupParameters* p, const std::vector<unsigned>& indices) { return Expression(&g, g.add_lookup(p, indices)); }
Expression lookup(ComputationGraph& g, LookupParameters* p, const std::vector<unsigned>* pindices) { return Expression(&g, g.add_lookup(p, pindices)); }
Expression const_lookup(ComputationGraph& g, LookupParameters* p, unsigned index) { return Expression(&g, g.add_const_lookup(p, index)); }
Expression const_lookup(ComputationGraph& g, LookupParameters* p, const unsigned* pindex) { return Expression(&g, g.add_const_lookup(p, pindex)); }
Expression const_lookup(ComputationGraph& g, LookupParameters* p, const std::vector<unsigned>& indices) { return Expression(&g, g.add_const_lookup(p, indices)); }
Expression const_lookup(ComputationGraph& g, LookupParameters* p, const std::vector<unsigned>* pindices) { return Expression(&g, g.add_const_lookup(p, pindices)); }
Expression zeroes(ComputationGraph& g, const Dim& d) { return Expression(&g, g.add_function<Zeroes>(d)); }

Expression operator-(const Expression& x) { return Expression(x.pg, x.pg->add_function<Negate>({x.i})); }
Expression operator+(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<Sum>({x.i, y.i})); }
Expression operator+(real x, const Expression& y) { return Expression(y.pg, y.pg->add_function<ConstantPlusX>({y.i}, x)); }
Expression operator+(const Expression& x, real y) { return y+x; }
Expression operator-(const Expression& x, const Expression& y) { return x+(-y); }
Expression operator-(real x, const Expression& y) { return Expression(y.pg, y.pg->add_function<ConstantMinusX>({y.i}, x)); }
Expression operator-(const Expression& x, real y) { return -(y-x); }
Expression operator*(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<MatrixMultiply>({x.i, y.i})); }
Expression operator*(const Expression& x, cnn::real y) { return Expression(x.pg, x.pg->add_function<ConstScalarMultiply>({x.i}, y)); }
Expression cdiv(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<CwiseQuotient>({x.i, y.i})); }
Expression colwise_add(const Expression& x, const Expression& bias) { return Expression(x.pg, x.pg->add_function<AddVectorToAllColumns>({x.i, bias.i})); }
Expression contract3d_1d(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<InnerProduct3D_1D>({x.i, y.i})); }
Expression contract3d_1d(const Expression& x, const Expression& y, const Expression& b) { return Expression(x.pg, x.pg->add_function<InnerProduct3D_1D>({x.i, y.i, b.i})); }

Expression sqrt(const Expression& x) { return Expression(x.pg, x.pg->add_function<Sqrt>({x.i})); }
//Expression erf(const Expression& x) { return Expression(x.pg, x.pg->add_function<Erf>({x.i})); }
Expression tanh(const Expression& x) { return Expression(x.pg, x.pg->add_function<Tanh>({x.i})); }
//Expression lgamma(const Expression& x) { return Expression(x.pg, x.pg->add_function<LogGamma>({x.i})); }
Expression log(const Expression& x) { return Expression(x.pg, x.pg->add_function<Log>({x.i})); }
Expression exp(const Expression& x) { return Expression(x.pg, x.pg->add_function<Exp>({x.i})); }
Expression square(const Expression& x) { return Expression(x.pg, x.pg->add_function<Square>({x.i})); }
Expression cube(const Expression& x) { return Expression(x.pg, x.pg->add_function<Cube>({x.i})); }
Expression logistic(const Expression& x) { return Expression(x.pg, x.pg->add_function<LogisticSigmoid>({x.i})); }
Expression rectify(const Expression& x) { return Expression(x.pg, x.pg->add_function<Rectify>({x.i})); }
Expression hinge(const Expression& x, unsigned index, cnn::real m) { return Expression(x.pg, x.pg->add_function<Hinge>({x.i}, index, m)); }
Expression hinge(const Expression& x, const unsigned* pindex, cnn::real m) { return Expression(x.pg, x.pg->add_function<Hinge>({x.i}, pindex, m)); }
Expression log_softmax(const Expression& x) { return Expression(x.pg, x.pg->add_function<LogSoftmax>({x.i})); }
Expression log_softmax(const Expression& x, const std::vector<unsigned>& d) { return Expression(x.pg, x.pg->add_function<RestrictedLogSoftmax>({x.i}, d)); }
Expression softmax(const Expression& x) { return Expression(x.pg, x.pg->add_function<Softmax>({x.i})); }
Expression softsign(const Expression& x) { return Expression(x.pg, x.pg->add_function<SoftSign>({x.i})); }
Expression pow(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<Pow>({x.i, y.i})); }
Expression min(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<Min>({x.i, y.i})); }
Expression max(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<Max>({x.i, y.i})); }
Expression noise(const Expression& x, real stddev) { return Expression(x.pg, x.pg->add_function<GaussianNoise>({x.i}, stddev)); }
Expression dropout(const Expression& x, real p) { return Expression(x.pg, x.pg->add_function<Dropout>({x.i}, p)); }
Expression block_dropout(const Expression& x, real p) { return Expression(x.pg, x.pg->add_function<BlockDropout>({x.i}, p)); }

Expression reshape(const Expression& x, const Dim& d) { return Expression(x.pg, x.pg->add_function<Reshape>({x.i}, d)); }
Expression transpose(const Expression& x) { return Expression(x.pg, x.pg->add_function<Transpose>({x.i})); }

Expression trace_of_product(const Expression& x, const Expression& y) {return Expression(x.pg, x.pg->add_function<TraceOfProduct>({x.i, y.i}));}
Expression cwise_multiply(const Expression& x, const Expression& y) {return Expression(x.pg, x.pg->add_function<CwiseMultiply>({x.i, y.i}));}

Expression dot_product(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<DotProduct>({x.i, y.i})); }
Expression squared_distance(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<SquaredEuclideanDistance>({x.i, y.i})); }
Expression huber_distance(const Expression& x, const Expression& y, real c) { return Expression(x.pg, x.pg->add_function<HuberDistance>({x.i, y.i}, c)); }
Expression l1_distance(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<L1Distance>({x.i, y.i})); }
Expression binary_log_loss(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<BinaryLogLoss>({x.i,y.i})); }
Expression pairwise_rank_loss(const Expression& x, const Expression& y, real m) { return Expression(x.pg, x.pg->add_function<PairwiseRankLoss>({x.i, y.i}, m)); }
Expression poisson_loss(const Expression& x, unsigned y) { return Expression(x.pg, x.pg->add_function<PoissonRegressionLoss>({x.i}, y)); }
Expression poisson_loss(const Expression& x, const unsigned* py) { return Expression(x.pg, x.pg->add_function<PoissonRegressionLoss>({x.i}, py)); }

Expression conv1d_narrow(const Expression& x, const Expression& f) { return Expression(x.pg, x.pg->add_function<Conv1DNarrow>({x.i, f.i})); }
Expression conv1d_wide(const Expression& x, const Expression& f) { return Expression(x.pg, x.pg->add_function<Conv1DWide>({x.i, f.i})); }
Expression kmax_pooling(const Expression& x, unsigned k) { return Expression(x.pg, x.pg->add_function<KMaxPooling>({x.i}, k)); }
Expression fold_rows(const Expression& x, unsigned nrows) { return Expression(x.pg, x.pg->add_function<FoldRows>({x.i}, nrows)); }

Expression pick(const Expression& x, unsigned v) { return Expression(x.pg, x.pg->add_function<PickElement>({x.i}, v)); }
Expression pick(const Expression& x, unsigned* pv) { return Expression(x.pg, x.pg->add_function<PickElement>({x.i}, pv)); }
Expression pickrange(const Expression& x, unsigned v, unsigned u) { return Expression(x.pg, x.pg->add_function<PickRange>({ x.i }, v, u)); }
Expression columnslices(const Expression& x, unsigned row, unsigned start_column, unsigned exclusive_end_column) { return Expression(x.pg, x.pg->add_function<ColumnSlices>({ x.i }, row, start_column, exclusive_end_column)); }

//Expression pickneglogsoftmax(const Expression& x, unsigned v) { return Expression(x.pg, x.pg->add_function<PickNegLogSoftmax>({x.i}, v)); }
//Expression pickneglogsoftmax(const Expression& x, const std::vector<unsigned> & v) { return Expression(x.pg, x.pg->add_function<PickNegLogSoftmax>({x.i}, v)); }

Expression sum_cols(const Expression& x) { return Expression(x.pg, x.pg->add_function<SumColumns>({x.i})); }

Expression sum_batches(const Expression& x) { return Expression(x.pg, x.pg->add_function<SumBatches>({x.i})); }

Expression kmh_ngram(const Expression& x, unsigned n) { return Expression(x.pg, x.pg->add_function<KMHNGram>({x.i}, n)); }

} }
<commit_msg>implemented exponential linear units<commit_after>#include "cnn/expr.h"

#include <initializer_list>

#include "cnn/nodes.h"
#include "cnn/conv.h"

namespace cnn { namespace expr {

Expression input(ComputationGraph& g, real s) { return Expression(&g, g.add_input(s)); }
Expression input(ComputationGraph& g, const real *ps) { return Expression(&g, g.add_input(ps)); }
Expression input(ComputationGraph& g, const Dim& d, const std::vector<cnn::real>& pdata) { return Expression(&g, g.add_input(d, pdata)); }
Expression input(ComputationGraph& g, const Dim& d, const std::vector<cnn::real>* pdata) { return Expression(&g, g.add_input(d, pdata)); }
Expression reference(ComputationGraph& g, const Dim& d, const cnn::real* pdata) { return Expression(&g, g.add_reference(d, pdata)); }
Expression const_parameter(ComputationGraph& g, Parameters* p) { return Expression(&g, g.add_const_parameters(p)); }
Expression parameter(ComputationGraph& g, Parameters* p) { return Expression(&g, g.add_parameters(p)); }
Expression lookup(ComputationGraph& g, LookupParameters* p, unsigned index) { return Expression(&g, g.add_lookup(p, index)); }
Expression lookup(ComputationGraph& g, LookupParameters* p, const unsigned* pindex) { return Expression(&g, g.add_lookup(p, pindex)); }
Expression lookup(ComputationGraph& g, LookupParameters* p, const std::vector<unsigned>& indices) { return Expression(&g, g.add_lookup(p, indices)); }
Expression lookup(ComputationGraph& g, LookupParameters* p, const std::vector<unsigned>* pindices) { return Expression(&g, g.add_lookup(p, pindices)); }
Expression const_lookup(ComputationGraph& g, LookupParameters* p, unsigned index) { return Expression(&g, g.add_const_lookup(p, index)); }
Expression const_lookup(ComputationGraph& g, LookupParameters* p, const unsigned* pindex) { return Expression(&g, g.add_const_lookup(p, pindex)); }
Expression const_lookup(ComputationGraph& g, LookupParameters* p, const std::vector<unsigned>& indices) { return Expression(&g, g.add_const_lookup(p, indices)); }
Expression const_lookup(ComputationGraph& g, LookupParameters* p, const std::vector<unsigned>* pindices) { return Expression(&g, g.add_const_lookup(p, pindices)); }
Expression zeroes(ComputationGraph& g, const Dim& d) { return Expression(&g, g.add_function<Zeroes>(d)); }

Expression operator-(const Expression& x) { return Expression(x.pg, x.pg->add_function<Negate>({x.i})); }
Expression operator+(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<Sum>({x.i, y.i})); }
Expression operator+(real x, const Expression& y) { return Expression(y.pg, y.pg->add_function<ConstantPlusX>({y.i}, x)); }
Expression operator+(const Expression& x, real y) { return y+x; }
Expression operator-(const Expression& x, const Expression& y) { return x+(-y); }
Expression operator-(real x, const Expression& y) { return Expression(y.pg, y.pg->add_function<ConstantMinusX>({y.i}, x)); }
Expression operator-(const Expression& x, real y) { return -(y-x); }
Expression operator*(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<MatrixMultiply>({x.i, y.i})); }
Expression operator*(const Expression& x, cnn::real y) { return Expression(x.pg, x.pg->add_function<ConstScalarMultiply>({x.i}, y)); }
Expression cdiv(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<CwiseQuotient>({x.i, y.i})); }
Expression colwise_add(const Expression& x, const Expression& bias) { return Expression(x.pg, x.pg->add_function<AddVectorToAllColumns>({x.i, bias.i})); }
Expression contract3d_1d(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<InnerProduct3D_1D>({x.i, y.i})); }
Expression contract3d_1d(const Expression& x, const Expression& y, const Expression& b) { return Expression(x.pg, x.pg->add_function<InnerProduct3D_1D>({x.i, y.i, b.i})); }

Expression sqrt(const Expression& x) { return Expression(x.pg, x.pg->add_function<Sqrt>({x.i})); }
//Expression erf(const Expression& x) { return Expression(x.pg, x.pg->add_function<Erf>({x.i})); }
Expression tanh(const Expression& x) { return Expression(x.pg, x.pg->add_function<Tanh>({x.i})); }
//Expression lgamma(const Expression& x) { return Expression(x.pg, x.pg->add_function<LogGamma>({x.i})); }
Expression log(const Expression& x) { return Expression(x.pg, x.pg->add_function<Log>({x.i})); }
Expression exp(const Expression& x) { return Expression(x.pg, x.pg->add_function<Exp>({x.i})); }
Expression square(const Expression& x) { return Expression(x.pg, x.pg->add_function<Square>({x.i})); }
Expression cube(const Expression& x) { return Expression(x.pg, x.pg->add_function<Cube>({x.i})); }
Expression logistic(const Expression& x) { return Expression(x.pg, x.pg->add_function<LogisticSigmoid>({x.i})); }
Expression rectify(const Expression& x) { return Expression(x.pg, x.pg->add_function<Rectify>({ x.i })); }
Expression exponential_linear_units(const Expression& x, cnn::real scale) { return Expression(x.pg, x.pg->add_function<ExponentialLinearUnits>({ x.i }, scale)); }
Expression hinge(const Expression& x, unsigned index, cnn::real m) { return Expression(x.pg, x.pg->add_function<Hinge>({ x.i }, index, m)); }
Expression hinge(const Expression& x, const unsigned* pindex, cnn::real m) { return Expression(x.pg, x.pg->add_function<Hinge>({x.i}, pindex, m)); }
Expression log_softmax(const Expression& x) { return Expression(x.pg, x.pg->add_function<LogSoftmax>({x.i})); }
Expression log_softmax(const Expression& x, const std::vector<unsigned>& d) { return Expression(x.pg, x.pg->add_function<RestrictedLogSoftmax>({x.i}, d)); }
Expression softmax(const Expression& x) { return Expression(x.pg, x.pg->add_function<Softmax>({x.i})); }
Expression softsign(const Expression& x) { return Expression(x.pg, x.pg->add_function<SoftSign>({x.i})); }
Expression pow(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<Pow>({x.i, y.i})); }
Expression min(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<Min>({x.i, y.i})); }
Expression max(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<Max>({x.i, y.i})); }
Expression noise(const Expression& x, real stddev) { return Expression(x.pg, x.pg->add_function<GaussianNoise>({x.i}, stddev)); }
Expression dropout(const Expression& x, real p) { return Expression(x.pg, x.pg->add_function<Dropout>({x.i}, p)); }
Expression block_dropout(const Expression& x, real p) { return Expression(x.pg, x.pg->add_function<BlockDropout>({x.i}, p)); }

Expression reshape(const Expression& x, const Dim& d) { return Expression(x.pg, x.pg->add_function<Reshape>({x.i}, d)); }
Expression transpose(const Expression& x) { return Expression(x.pg, x.pg->add_function<Transpose>({x.i})); }

Expression trace_of_product(const Expression& x, const Expression& y) {return Expression(x.pg, x.pg->add_function<TraceOfProduct>({x.i, y.i}));}
Expression cwise_multiply(const Expression& x, const Expression& y) {return Expression(x.pg, x.pg->add_function<CwiseMultiply>({x.i, y.i}));}

Expression dot_product(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<DotProduct>({x.i, y.i})); }
Expression squared_distance(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<SquaredEuclideanDistance>({x.i, y.i})); }
Expression huber_distance(const Expression& x, const Expression& y, real c) { return Expression(x.pg, x.pg->add_function<HuberDistance>({x.i, y.i}, c)); }
Expression l1_distance(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<L1Distance>({x.i, y.i})); }
Expression binary_log_loss(const Expression& x, const Expression& y) { return Expression(x.pg, x.pg->add_function<BinaryLogLoss>({x.i,y.i})); }
Expression pairwise_rank_loss(const Expression& x, const Expression& y, real m) { return Expression(x.pg, x.pg->add_function<PairwiseRankLoss>({x.i, y.i}, m)); }
Expression poisson_loss(const Expression& x, unsigned y) { return Expression(x.pg, x.pg->add_function<PoissonRegressionLoss>({x.i}, y)); }
Expression poisson_loss(const Expression& x, const unsigned* py) { return Expression(x.pg, x.pg->add_function<PoissonRegressionLoss>({x.i}, py)); }

Expression conv1d_narrow(const Expression& x, const Expression& f) { return Expression(x.pg, x.pg->add_function<Conv1DNarrow>({x.i, f.i})); }
Expression conv1d_wide(const Expression& x, const Expression& f) { return Expression(x.pg, x.pg->add_function<Conv1DWide>({x.i, f.i})); }
Expression kmax_pooling(const Expression& x, unsigned k) { return Expression(x.pg, x.pg->add_function<KMaxPooling>({x.i}, k)); }
Expression fold_rows(const Expression& x, unsigned nrows) { return Expression(x.pg, x.pg->add_function<FoldRows>({x.i}, nrows)); }

Expression pick(const Expression& x, unsigned v) { return Expression(x.pg, x.pg->add_function<PickElement>({x.i}, v)); }
Expression pick(const Expression& x, unsigned* pv) { return Expression(x.pg, x.pg->add_function<PickElement>({x.i}, pv)); }
Expression pickrange(const Expression& x, unsigned v, unsigned u) { return Expression(x.pg, x.pg->add_function<PickRange>({ x.i }, v, u)); }
Expression columnslices(const Expression& x, unsigned row, unsigned start_column, unsigned exclusive_end_column) { return Expression(x.pg, x.pg->add_function<ColumnSlices>({ x.i }, row, start_column, exclusive_end_column)); }

//Expression pickneglogsoftmax(const Expression& x, unsigned v) { return Expression(x.pg, x.pg->add_function<PickNegLogSoftmax>({x.i}, v)); }
//Expression pickneglogsoftmax(const Expression& x, const std::vector<unsigned> & v) { return Expression(x.pg, x.pg->add_function<PickNegLogSoftmax>({x.i}, v)); }

Expression sum_cols(const Expression& x) { return Expression(x.pg, x.pg->add_function<SumColumns>({x.i})); }

Expression sum_batches(const Expression& x) { return Expression(x.pg, x.pg->add_function<SumBatches>({x.i})); }

Expression kmh_ngram(const Expression& x, unsigned n) { return Expression(x.pg, x.pg->add_function<KMHNGram>({x.i}, n)); }

} }
<|endoftext|>