<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */

/*
 * $Id$
 */

#include <xercesc/framework/LocalFileFormatTarget.hpp>
#include <xercesc/framework/MemoryManager.hpp>
#include <xercesc/util/IOException.hpp>
#include <xercesc/util/OutOfMemoryException.hpp>
#include <assert.h>
#include <string.h>

XERCES_CPP_NAMESPACE_BEGIN

const XMLSize_t MAX_BUFFER_SIZE = 65536;

LocalFileFormatTarget::LocalFileFormatTarget( const XMLCh* const   fileName
                                            , MemoryManager* const manager)
: fSource(0)
, fDataBuf(0)
, fIndex(0)
, fCapacity(1024)
, fMemoryManager(manager)
{
    fSource = XMLPlatformUtils::openFileToWrite(fileName, manager);

    if (fSource == (FileHandle) XERCES_Invalid_File_Handle)
        ThrowXMLwithMemMgr1(IOException, XMLExcepts::File_CouldNotOpenFile, fileName, fMemoryManager);

    fDataBuf = (XMLByte*) fMemoryManager->allocate (
      fCapacity * sizeof(XMLByte));
}

LocalFileFormatTarget::LocalFileFormatTarget( const char* const    fileName
                                            , MemoryManager* const manager)
: fSource(0)
, fDataBuf(0)
, fIndex(0)
, fCapacity(1024)
, fMemoryManager(manager)
{
    fSource = XMLPlatformUtils::openFileToWrite(fileName, manager);

    if (fSource == (FileHandle) XERCES_Invalid_File_Handle)
        ThrowXMLwithMemMgr1(IOException, XMLExcepts::File_CouldNotOpenFile, fileName, fMemoryManager);

    fDataBuf = (XMLByte*) fMemoryManager->allocate (
      fCapacity * sizeof(XMLByte));
}

LocalFileFormatTarget::~LocalFileFormatTarget()
{
    try
    {
        // flush remaining buffer before destroy
        XMLPlatformUtils::writeBufferToFile(fSource, fIndex, fDataBuf, fMemoryManager);

        if (fSource)
          XMLPlatformUtils::closeFile(fSource, fMemoryManager);
    }
    catch (...)
    {
      // There is nothing we can do about it here.
    }

    fMemoryManager->deallocate(fDataBuf);//delete [] fDataBuf;
}

void LocalFileFormatTarget::flush()
{
  XMLPlatformUtils::writeBufferToFile(fSource, fIndex, fDataBuf, fMemoryManager);
  fIndex = 0;
}

void LocalFileFormatTarget::writeChars(const XMLByte* const toWrite
                                     , const XMLSize_t count
                                     , XMLFormatter * const)
{
    if (count)
    {
      if (count < MAX_BUFFER_SIZE)
      {
        // If we don't have enough space, see if we can grow the buffer.
        //
        if (fIndex + count > fCapacity && fCapacity < MAX_BUFFER_SIZE)
          insureCapacity (count);

        // If still not enough space, flush the buffer.
        //
        if (fIndex + count > fCapacity)
        {
          XMLPlatformUtils::writeBufferToFile(fSource, fIndex, fDataBuf, fMemoryManager);
          fIndex = 0;
        }

        memcpy(&fDataBuf[fIndex], toWrite, count * sizeof(XMLByte));
        fIndex += count;
      }
      else
        XMLPlatformUtils::writeBufferToFile(fSource, count, toWrite, fMemoryManager);
    }

    return;
}

void LocalFileFormatTarget::insureCapacity(const XMLSize_t extraNeeded)
{
    XMLSize_t newCap = fCapacity * 2;

    while (fIndex + extraNeeded > newCap)
      newCap *= 2;

    XMLByte* newBuf  = (XMLByte*) fMemoryManager->allocate (
      newCap * sizeof(XMLByte));

    // Copy over the old stuff
    memcpy(newBuf, fDataBuf, fIndex * sizeof(XMLByte));

    // Clean up old buffer and store new stuff
    fMemoryManager->deallocate(fDataBuf);
    fDataBuf = newBuf;
    fCapacity = newCap;
}

XERCES_CPP_NAMESPACE_END
<commit_msg>Fix a bug in the new LocalFileFormatTarget buffering implementation.<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */

/*
 * $Id$
 */

#include <xercesc/framework/LocalFileFormatTarget.hpp>
#include <xercesc/framework/MemoryManager.hpp>
#include <xercesc/util/IOException.hpp>
#include <xercesc/util/OutOfMemoryException.hpp>
#include <assert.h>
#include <string.h>

XERCES_CPP_NAMESPACE_BEGIN

const XMLSize_t MAX_BUFFER_SIZE = 65536;

LocalFileFormatTarget::LocalFileFormatTarget( const XMLCh* const   fileName
                                            , MemoryManager* const manager)
: fSource(0)
, fDataBuf(0)
, fIndex(0)
, fCapacity(1024)
, fMemoryManager(manager)
{
    fSource = XMLPlatformUtils::openFileToWrite(fileName, manager);

    if (fSource == (FileHandle) XERCES_Invalid_File_Handle)
        ThrowXMLwithMemMgr1(IOException, XMLExcepts::File_CouldNotOpenFile, fileName, fMemoryManager);

    fDataBuf = (XMLByte*) fMemoryManager->allocate (
      fCapacity * sizeof(XMLByte));
}

LocalFileFormatTarget::LocalFileFormatTarget( const char* const    fileName
                                            , MemoryManager* const manager)
: fSource(0)
, fDataBuf(0)
, fIndex(0)
, fCapacity(1024)
, fMemoryManager(manager)
{
    fSource = XMLPlatformUtils::openFileToWrite(fileName, manager);

    if (fSource == (FileHandle) XERCES_Invalid_File_Handle)
        ThrowXMLwithMemMgr1(IOException, XMLExcepts::File_CouldNotOpenFile, fileName, fMemoryManager);

    fDataBuf = (XMLByte*) fMemoryManager->allocate (
      fCapacity * sizeof(XMLByte));
}

LocalFileFormatTarget::~LocalFileFormatTarget()
{
    try
    {
        // flush remaining buffer before destroy
        XMLPlatformUtils::writeBufferToFile(fSource, fIndex, fDataBuf, fMemoryManager);

        if (fSource)
          XMLPlatformUtils::closeFile(fSource, fMemoryManager);
    }
    catch (...)
    {
      // There is nothing we can do about it here.
    }

    fMemoryManager->deallocate(fDataBuf);//delete [] fDataBuf;
}

void LocalFileFormatTarget::flush()
{
  XMLPlatformUtils::writeBufferToFile(fSource, fIndex, fDataBuf, fMemoryManager);
  fIndex = 0;
}

void LocalFileFormatTarget::writeChars(const XMLByte* const toWrite
                                     , const XMLSize_t count
                                     , XMLFormatter * const)
{
    if (count)
    {
      if (count < MAX_BUFFER_SIZE)
      {
        // If we don't have enough space, see if we can grow the buffer.
        //
        if (fIndex + count > fCapacity && fCapacity < MAX_BUFFER_SIZE)
          insureCapacity (count);

        // If still not enough space, flush the buffer.
        //
        if (fIndex + count > fCapacity)
        {
          XMLPlatformUtils::writeBufferToFile(fSource, fIndex, fDataBuf, fMemoryManager);
          fIndex = 0;
        }

        memcpy(&fDataBuf[fIndex], toWrite, count * sizeof(XMLByte));
        fIndex += count;
      }
      else
      {
        if (fIndex)
        {
          XMLPlatformUtils::writeBufferToFile(fSource, fIndex, fDataBuf, fMemoryManager);
          fIndex = 0;
        }

        XMLPlatformUtils::writeBufferToFile(fSource, count, toWrite, fMemoryManager);
      }
    }

    return;
}

void LocalFileFormatTarget::insureCapacity(const XMLSize_t extraNeeded)
{
    XMLSize_t newCap = fCapacity * 2;

    while (fIndex + extraNeeded > newCap)
      newCap *= 2;

    XMLByte* newBuf  = (XMLByte*) fMemoryManager->allocate (
      newCap * sizeof(XMLByte));

    // Copy over the old stuff
    memcpy(newBuf, fDataBuf, fIndex * sizeof(XMLByte));

    // Clean up old buffer and store new stuff
    fMemoryManager->deallocate(fDataBuf);
    fDataBuf = newBuf;
    fCapacity = newCap;
}

XERCES_CPP_NAMESPACE_END
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <test/models/model_test_fixture.hpp>

class Models_BugsExamples_Vol2_Estdof :
  public Model_Test_Fixture<Models_BugsExamples_Vol2_Estdof> {
protected:
  virtual void SetUp() {}
public:
  static std::vector<std::string> get_model_path() {
    std::vector<std::string> model_path;
    model_path.push_back("models");
    model_path.push_back("bugs_examples");
    model_path.push_back("vol2");
    model_path.push_back("t_df");
    model_path.push_back("estdof");
    return model_path;
  }

  static bool has_data() {
    return true;
  }

  static bool has_init() {
    return false;
  }

  static int num_iterations() {
    return iterations;
  }

  static std::vector<int> skip_chains_test() {
    std::vector<int> params_to_skip;
    return params_to_skip;
  }

  static void populate_chains() {
    default_populate_chains();
  }

  static std::vector<std::pair<int, double> >
  get_expected_values() {
    std::vector<std::pair<int, double> > expected_values;
    return expected_values;
  }

};

INSTANTIATE_TYPED_TEST_CASE_P(Models_BugsExamples_Vol2_Estdof,
            Model_Test_Fixture,
            Models_BugsExamples_Vol2_Estdof);
<commit_msg>model tests: testing value of models/bugs_examples/vol2/t_df/estdof<commit_after>#include <gtest/gtest.h>
#include <test/models/model_test_fixture.hpp>

class Models_BugsExamples_Vol2_Estdof :
  public Model_Test_Fixture<Models_BugsExamples_Vol2_Estdof> {
protected:
  virtual void SetUp() {}
public:
  static std::vector<std::string> get_model_path() {
    std::vector<std::string> model_path;
    model_path.push_back("models");
    model_path.push_back("bugs_examples");
    model_path.push_back("vol2");
    model_path.push_back("t_df");
    model_path.push_back("estdof");
    return model_path;
  }

  static bool has_data() {
    return true;
  }

  static bool has_init() {
    return false;
  }

  static int num_iterations() {
    return iterations;
  }

  static std::vector<int> skip_chains_test() {
    std::vector<int> params_to_skip;
    return params_to_skip;
  }

  static void populate_chains() {
    default_populate_chains();
  }

  static std::vector<std::pair<int, double> >
  get_expected_values() {
    using std::make_pair;
    std::vector<std::pair<int, double> > expected_values;

    expected_values.push_back(make_pair(chains->index("d"), 4.204));
    return expected_values;
  }

};

INSTANTIATE_TYPED_TEST_CASE_P(Models_BugsExamples_Vol2_Estdof,
            Model_Test_Fixture,
            Models_BugsExamples_Vol2_Estdof);
<|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_PROB_NEG_BINOMIAL_2_LOG_LPMF_HPP
#define STAN_MATH_PRIM_PROB_NEG_BINOMIAL_2_LOG_LPMF_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/binomial_coefficient_log.hpp>
#include <stan/math/prim/fun/digamma.hpp>
#include <stan/math/prim/fun/inv.hpp>
#include <stan/math/prim/fun/log.hpp>
#include <stan/math/prim/fun/log1p_exp.hpp>
#include <stan/math/prim/fun/log_sum_exp.hpp>
#include <stan/math/prim/fun/max_size.hpp>
#include <stan/math/prim/fun/size.hpp>
#include <stan/math/prim/fun/size_zero.hpp>
#include <stan/math/prim/fun/value_of.hpp>
#include <cmath>

namespace stan {
namespace math {

// NegBinomial(n|eta, phi)  [phi > 0;  n >= 0]
template <bool propto, typename T_n, typename T_log_location,
          typename T_precision>
return_type_t<T_log_location, T_precision> neg_binomial_2_log_lpmf(
    const T_n& n, const T_log_location& eta, const T_precision& phi) {
  using T_partials_return = partials_return_t<T_n, T_log_location, T_precision>;
  using std::exp;
  using std::log;
  static const char* function = "neg_binomial_2_log_lpmf";
  check_nonnegative(function, "Failures variable", n);
  check_finite(function, "Log location parameter", eta);
  check_positive_finite(function, "Precision parameter", phi);
  check_consistent_sizes(function, "Failures variable", n,
                         "Log location parameter", eta, "Precision parameter",
                         phi);

  if (size_zero(n, eta, phi)) {
    return 0.0;
  }
  if (!include_summand<propto, T_log_location, T_precision>::value) {
    return 0.0;
  }

  T_partials_return logp(0.0);
  operands_and_partials<T_log_location, T_precision> ops_partials(eta, phi);

  scalar_seq_view<T_n> n_vec(n);
  scalar_seq_view<T_log_location> eta_vec(eta);
  scalar_seq_view<T_precision> phi_vec(phi);
  size_t size_eta = stan::math::size(eta);
  size_t size_phi = stan::math::size(phi);
  size_t size_eta_phi = max_size(eta, phi);
  size_t size_n_phi = max_size(n, phi);
  size_t size_all = max_size(n, eta, phi);

  VectorBuilder<true, T_partials_return, T_log_location> eta_val(size_eta);
  for (size_t i = 0; i < size_eta; ++i) {
    eta_val[i] = value_of(eta_vec[i]);
  }

  VectorBuilder<true, T_partials_return, T_precision> phi_val(size_phi);
  VectorBuilder<true, T_partials_return, T_precision> log_phi(size_phi);
  for (size_t i = 0; i < size_phi; ++i) {
    phi_val[i] = value_of(phi_vec[i]);
    log_phi[i] = log(phi_val[i]);
  }

  VectorBuilder<!is_constant_all<T_log_location, T_precision>::value,
                T_partials_return, T_log_location>
      exp_eta(size_eta);
  if (!is_constant_all<T_log_location, T_precision>::value) {
    for (size_t i = 0; i < size_eta; ++i) {
      exp_eta[i] = exp(eta_val[i]);
    }
  }

  VectorBuilder<!is_constant_all<T_log_location, T_precision>::value,
                T_partials_return, T_log_location, T_precision>
      exp_eta_over_exp_eta_phi(size_eta_phi);
  if (!is_constant_all<T_log_location, T_precision>::value) {
    for (size_t i = 0; i < size_eta_phi; ++i) {
        exp_eta_over_exp_eta_phi[i] = inv(phi_val[i] / exp_eta[i] + 1);
    }
  }

  VectorBuilder<true, T_partials_return, T_log_location, T_precision>
      log1p_exp_eta_m_logphi(size_eta_phi);
  for (size_t i = 0; i < size_eta_phi; ++i) {
    log1p_exp_eta_m_logphi[i] = log1p_exp(eta_val[i] - log_phi[i]);
  }

  VectorBuilder<true, T_partials_return, T_n, T_precision> n_plus_phi(
      size_n_phi);
  for (size_t i = 0; i < size_n_phi; ++i) {
    n_plus_phi[i] = n_vec[i] + phi_val[i];
  }

  for (size_t i = 0; i < size_all; i++) {
    if (include_summand<propto, T_precision>::value) {
      logp += binomial_coefficient_log(n_plus_phi[i] - 1, n_vec[i]);
    }
    if (include_summand<propto, T_log_location>::value) {
      logp += n_vec[i] * eta_val[i];
    }
    logp += -phi_val[i] * log1p_exp_eta_m_logphi[i]
            - n_vec[i] * (log_phi[i] + log1p_exp_eta_m_logphi[i]);

    if (!is_constant_all<T_log_location>::value) {
      ops_partials.edge1_.partials_[i]
          += n_vec[i] - n_plus_phi[i] * exp_eta_over_exp_eta_phi[i];
    }
    if (!is_constant_all<T_precision>::value) {
      ops_partials.edge2_.partials_[i]
          += exp_eta_over_exp_eta_phi[i] - n_vec[i] / (exp_eta[i] + phi_val[i])
             - log1p_exp_eta_m_logphi[i]
             - (digamma(phi_val[i]) - digamma(n_plus_phi[i]));
    }
  }
  return ops_partials.build(logp);
}

template <typename T_n, typename T_log_location, typename T_precision>
inline return_type_t<T_log_location, T_precision> neg_binomial_2_log_lpmf(
    const T_n& n, const T_log_location& eta, const T_precision& phi) {
  return neg_binomial_2_log_lpmf<false>(n, eta, phi);
}

}  // namespace math
}  // namespace stan
#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2 (tags/RELEASE_600/final)<commit_after>#ifndef STAN_MATH_PRIM_PROB_NEG_BINOMIAL_2_LOG_LPMF_HPP
#define STAN_MATH_PRIM_PROB_NEG_BINOMIAL_2_LOG_LPMF_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/binomial_coefficient_log.hpp>
#include <stan/math/prim/fun/digamma.hpp>
#include <stan/math/prim/fun/inv.hpp>
#include <stan/math/prim/fun/log.hpp>
#include <stan/math/prim/fun/log1p_exp.hpp>
#include <stan/math/prim/fun/log_sum_exp.hpp>
#include <stan/math/prim/fun/max_size.hpp>
#include <stan/math/prim/fun/size.hpp>
#include <stan/math/prim/fun/size_zero.hpp>
#include <stan/math/prim/fun/value_of.hpp>
#include <cmath>

namespace stan {
namespace math {

// NegBinomial(n|eta, phi)  [phi > 0;  n >= 0]
template <bool propto, typename T_n, typename T_log_location,
          typename T_precision>
return_type_t<T_log_location, T_precision> neg_binomial_2_log_lpmf(
    const T_n& n, const T_log_location& eta, const T_precision& phi) {
  using T_partials_return = partials_return_t<T_n, T_log_location, T_precision>;
  using std::exp;
  using std::log;
  static const char* function = "neg_binomial_2_log_lpmf";
  check_nonnegative(function, "Failures variable", n);
  check_finite(function, "Log location parameter", eta);
  check_positive_finite(function, "Precision parameter", phi);
  check_consistent_sizes(function, "Failures variable", n,
                         "Log location parameter", eta, "Precision parameter",
                         phi);

  if (size_zero(n, eta, phi)) {
    return 0.0;
  }
  if (!include_summand<propto, T_log_location, T_precision>::value) {
    return 0.0;
  }

  T_partials_return logp(0.0);
  operands_and_partials<T_log_location, T_precision> ops_partials(eta, phi);

  scalar_seq_view<T_n> n_vec(n);
  scalar_seq_view<T_log_location> eta_vec(eta);
  scalar_seq_view<T_precision> phi_vec(phi);
  size_t size_eta = stan::math::size(eta);
  size_t size_phi = stan::math::size(phi);
  size_t size_eta_phi = max_size(eta, phi);
  size_t size_n_phi = max_size(n, phi);
  size_t size_all = max_size(n, eta, phi);

  VectorBuilder<true, T_partials_return, T_log_location> eta_val(size_eta);
  for (size_t i = 0; i < size_eta; ++i) {
    eta_val[i] = value_of(eta_vec[i]);
  }

  VectorBuilder<true, T_partials_return, T_precision> phi_val(size_phi);
  VectorBuilder<true, T_partials_return, T_precision> log_phi(size_phi);
  for (size_t i = 0; i < size_phi; ++i) {
    phi_val[i] = value_of(phi_vec[i]);
    log_phi[i] = log(phi_val[i]);
  }

  VectorBuilder<!is_constant_all<T_log_location, T_precision>::value,
                T_partials_return, T_log_location>
      exp_eta(size_eta);
  if (!is_constant_all<T_log_location, T_precision>::value) {
    for (size_t i = 0; i < size_eta; ++i) {
      exp_eta[i] = exp(eta_val[i]);
    }
  }

  VectorBuilder<!is_constant_all<T_log_location, T_precision>::value,
                T_partials_return, T_log_location, T_precision>
      exp_eta_over_exp_eta_phi(size_eta_phi);
  if (!is_constant_all<T_log_location, T_precision>::value) {
    for (size_t i = 0; i < size_eta_phi; ++i) {
      exp_eta_over_exp_eta_phi[i] = inv(phi_val[i] / exp_eta[i] + 1);
    }
  }

  VectorBuilder<true, T_partials_return, T_log_location, T_precision>
      log1p_exp_eta_m_logphi(size_eta_phi);
  for (size_t i = 0; i < size_eta_phi; ++i) {
    log1p_exp_eta_m_logphi[i] = log1p_exp(eta_val[i] - log_phi[i]);
  }

  VectorBuilder<true, T_partials_return, T_n, T_precision> n_plus_phi(
      size_n_phi);
  for (size_t i = 0; i < size_n_phi; ++i) {
    n_plus_phi[i] = n_vec[i] + phi_val[i];
  }

  for (size_t i = 0; i < size_all; i++) {
    if (include_summand<propto, T_precision>::value) {
      logp += binomial_coefficient_log(n_plus_phi[i] - 1, n_vec[i]);
    }
    if (include_summand<propto, T_log_location>::value) {
      logp += n_vec[i] * eta_val[i];
    }
    logp += -phi_val[i] * log1p_exp_eta_m_logphi[i]
            - n_vec[i] * (log_phi[i] + log1p_exp_eta_m_logphi[i]);

    if (!is_constant_all<T_log_location>::value) {
      ops_partials.edge1_.partials_[i]
          += n_vec[i] - n_plus_phi[i] * exp_eta_over_exp_eta_phi[i];
    }
    if (!is_constant_all<T_precision>::value) {
      ops_partials.edge2_.partials_[i]
          += exp_eta_over_exp_eta_phi[i] - n_vec[i] / (exp_eta[i] + phi_val[i])
             - log1p_exp_eta_m_logphi[i]
             - (digamma(phi_val[i]) - digamma(n_plus_phi[i]));
    }
  }
  return ops_partials.build(logp);
}

template <typename T_n, typename T_log_location, typename T_precision>
inline return_type_t<T_log_location, T_precision> neg_binomial_2_log_lpmf(
    const T_n& n, const T_log_location& eta, const T_precision& phi) {
  return neg_binomial_2_log_lpmf<false>(n, eta, phi);
}

}  // namespace math
}  // namespace stan
#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: EnhancedCustomShapeFontWork.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: kz $ $Date: 2005-11-02 09:57:17 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _ENHANCEDCUSTOMSHAPEFONTWORK_HXX
#define _ENHANCEDCUSTOMSHAPEFONTWORK_HXX

#ifndef _COM_SUN_STAR_I18N_XBREAKITERATOR_HPP_
#include <com/sun/star/i18n/XBreakIterator.hpp>
#endif

class SdrObject;
class EnhancedCustomShapeFontWork
{
        static ::com::sun::star::uno::Reference < ::com::sun::star::i18n::XBreakIterator > mxBreakIterator;

    public :

        static com::sun::star::uno::Reference < ::com::sun::star::i18n::XBreakIterator > GetBreakIterator();
        static SdrObject* CreateFontWork( const SdrObject* pShape2d, const SdrObject* pCustomShape );
};

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.4.1160); FILE MERGED 2008/04/01 12:48:02 thb 1.4.1160.2: #i85898# Stripping all external header guards 2008/03/31 14:19:17 rt 1.4.1160.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: EnhancedCustomShapeFontWork.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _ENHANCEDCUSTOMSHAPEFONTWORK_HXX
#define _ENHANCEDCUSTOMSHAPEFONTWORK_HXX

#include <com/sun/star/i18n/XBreakIterator.hpp>

class SdrObject;
class EnhancedCustomShapeFontWork
{
        static ::com::sun::star::uno::Reference < ::com::sun::star::i18n::XBreakIterator > mxBreakIterator;

    public :

        static com::sun::star::uno::Reference < ::com::sun::star::i18n::XBreakIterator > GetBreakIterator();
        static SdrObject* CreateFontWork( const SdrObject* pShape2d, const SdrObject* pCustomShape );
};

#endif

<|endoftext|>


<commit_before>/* Copyright 2022 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/compiler/xla/service/gpu/hlo_fusion_stats.h"

#include <string>

#include "absl/strings/match.h"
#include "tensorflow/compiler/xla/service/dfs_hlo_visitor_with_default.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
#include "tensorflow/compiler/xla/status.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/statusor.h"

namespace xla {
namespace gpu {

namespace {

class OpcodeCollector : public ConstDfsHloVisitorWithDefault {
 public:
  std::set<std::string> GetUniqueOpcodes() { return opcodes_; }

 protected:
  Status DefaultAction(const xla::HloInstruction* instr) final {
    switch (instr->opcode()) {
      case HloOpcode::kConstant:
        break;
      case HloOpcode::kParameter:
        break;
      case HloOpcode::kAdd:
      case HloOpcode::kSubtract:
      case HloOpcode::kMultiply:
      case HloOpcode::kDivide:
      case HloOpcode::kAbs:
      case HloOpcode::kNegate:
      case HloOpcode::kSign:
      case HloOpcode::kCeil:
      case HloOpcode::kFloor:
      case HloOpcode::kAtan2:
      case HloOpcode::kSin:
      case HloOpcode::kCos:
      case HloOpcode::kTanh:
      case HloOpcode::kExp:
      case HloOpcode::kLog:
      case HloOpcode::kSqrt:
      case HloOpcode::kRsqrt:
        opcodes_.insert("cwise");
        break;
      default:
        opcodes_.insert(HloOpcodeString(instr->opcode()));
    }
    return Status::OK();
  }

 private:
  std::set<std::string> opcodes_;
};

std::set<std::string> GetUniqueOpcodes(HloComputation* computation) {
  OpcodeCollector collector;
  if (computation->Accept(&collector) != Status::OK()) {
    return {};
  }
  return collector.GetUniqueOpcodes();
}

}  // namespace

std::string HloOpcodeHistogram::ToString() {
  std::string result;
  for (const auto& entry : *this) {
    absl::StrAppend(&result, "{", absl::StrJoin(entry.first, ", "),
                    "}: ", entry.second, "\n");
  }
  return result;
}

Status HloFusionStatsVisitor::RunOnModule(HloModule* module) {
  TF_RETURN_IF_ERROR(module->entry_computation()->Accept(this));
  return Status::OK();
}

std::string HloFusionStatsVisitor::ToString() {
  return absl::StrCat("HLO Fusion Stats:\n",
                      "Number of fusion ops: ", num_fusions_, "\n",
                      "Number of kLoop fusions: ", num_loop_fusions_, "\n",
                      loop_fusion_opcode_histogram_.ToString(), "\n",
                      "Number of kInput fusions: ", num_input_fusions_, "\n",
                      input_fusion_opcode_histogram_.ToString());
}

Status HloFusionStatsVisitor::DefaultAction(const xla::HloInstruction* instr) {
  return Status::OK();
}

Status HloFusionStatsVisitor::HandleFusion(const HloInstruction* fusion) {
  num_fusions_++;
  std::set<std::string> opcodes =
      GetUniqueOpcodes(fusion->fused_instructions_computation());
  if (fusion->fusion_kind() == HloInstruction::FusionKind::kLoop) {
    num_loop_fusions_++;
    loop_fusion_opcode_histogram_[opcodes]++;
  } else if (fusion->fusion_kind() == HloInstruction::FusionKind::kInput) {
    num_input_fusions_++;
    input_fusion_opcode_histogram_[opcodes]++;
  }
  return Status::OK();
}

}  // namespace gpu
}  // namespace xla
<commit_msg>[XLA:GPU] Classify some more mhlo ops as cwise.<commit_after>/* Copyright 2022 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/compiler/xla/service/gpu/hlo_fusion_stats.h"

#include <string>

#include "absl/strings/match.h"
#include "tensorflow/compiler/xla/service/dfs_hlo_visitor_with_default.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
#include "tensorflow/compiler/xla/status.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/statusor.h"

namespace xla {
namespace gpu {

namespace {

class OpcodeCollector : public ConstDfsHloVisitorWithDefault {
 public:
  std::set<std::string> GetUniqueOpcodes() { return opcodes_; }

 protected:
  Status DefaultAction(const xla::HloInstruction* instr) final {
    switch (instr->opcode()) {
      case HloOpcode::kConstant:
        break;
      case HloOpcode::kParameter:
        break;
      // Unary
      case HloOpcode::kAbs:
      case HloOpcode::kCbrt:
      case HloOpcode::kCeil:
      case HloOpcode::kCos:
      case HloOpcode::kExp:
      case HloOpcode::kExpm1:
      case HloOpcode::kFloor:
      case HloOpcode::kLog:
      case HloOpcode::kLog1p:
      case HloOpcode::kLogistic:
      case HloOpcode::kNegate:
      case HloOpcode::kRoundNearestAfz:
      case HloOpcode::kRoundNearestEven:
      case HloOpcode::kRsqrt:
      case HloOpcode::kSign:
      case HloOpcode::kSin:
      case HloOpcode::kSqrt:
      case HloOpcode::kTanh:
      // Binary
      case HloOpcode::kAdd:
      case HloOpcode::kAtan2:
      case HloOpcode::kDivide:
      case HloOpcode::kMultiply:
      case HloOpcode::kSubtract:
        opcodes_.insert("cwise");
        break;
      default:
        opcodes_.insert(HloOpcodeString(instr->opcode()));
    }
    return Status::OK();
  }

 private:
  std::set<std::string> opcodes_;
};

std::set<std::string> GetUniqueOpcodes(HloComputation* computation) {
  OpcodeCollector collector;
  if (computation->Accept(&collector) != Status::OK()) {
    return {};
  }
  return collector.GetUniqueOpcodes();
}

}  // namespace

std::string HloOpcodeHistogram::ToString() {
  std::string result;
  for (const auto& entry : *this) {
    absl::StrAppend(&result, "{", absl::StrJoin(entry.first, ", "),
                    "}: ", entry.second, "\n");
  }
  return result;
}

Status HloFusionStatsVisitor::RunOnModule(HloModule* module) {
  TF_RETURN_IF_ERROR(module->entry_computation()->Accept(this));
  return Status::OK();
}

std::string HloFusionStatsVisitor::ToString() {
  return absl::StrCat("HLO Fusion Stats:\n",
                      "Number of fusion ops: ", num_fusions_, "\n",
                      "Number of kLoop fusions: ", num_loop_fusions_, "\n",
                      loop_fusion_opcode_histogram_.ToString(), "\n",
                      "Number of kInput fusions: ", num_input_fusions_, "\n",
                      input_fusion_opcode_histogram_.ToString());
}

Status HloFusionStatsVisitor::DefaultAction(const xla::HloInstruction* instr) {
  return Status::OK();
}

Status HloFusionStatsVisitor::HandleFusion(const HloInstruction* fusion) {
  num_fusions_++;
  std::set<std::string> opcodes =
      GetUniqueOpcodes(fusion->fused_instructions_computation());
  if (fusion->fusion_kind() == HloInstruction::FusionKind::kLoop) {
    num_loop_fusions_++;
    loop_fusion_opcode_histogram_[opcodes]++;
  } else if (fusion->fusion_kind() == HloInstruction::FusionKind::kInput) {
    num_input_fusions_++;
    input_fusion_opcode_histogram_[opcodes]++;
  }
  return Status::OK();
}

}  // namespace gpu
}  // namespace xla
<|endoftext|>


<commit_before>#include <stdio.h>
#include <time.h>
#include <cmath>
#include "simulator.h"
#include "core_manager.h"
#include "config.h"
#include "core.h"
#include "network.h"
#include "utils.h"
#include "semaphore.h"
#include "carbon_user.h"
#include "synthetic_network.h"

// #define DEBUG 1

// Network Traffic Pattern Type
NetworkTrafficType _traffic_pattern_type = UNIFORM_RANDOM;
// Number of packets injected per core per cycle
double _offered_load = 0.1;
// Size of each Packet in Bytes
SInt32 _packet_size = 8;
// Total number of packets injected into the network per core
UInt64 _total_packets = 10000;
// Number of cores in the network
SInt32 _num_cores;

// Type of each packet (so as to send on USER_2 network)
PacketType _packet_type = USER_2;
// FIXME: Hard-coded for now (in bits), Change Later
SInt32 _flit_width = 64;

CoreSpVars* _core_sp_vars;
UInt64 _quantum = 1000;
Semaphore _semaphore;

UInt32 EVENT_NET_SEND = 100;
UInt32 EVENT_PUSH_FIRST_EVENTS = 102;

#include "traffic_generators.h"

int main(int argc, char* argv[])
{
   printf("\n[SYNTHETIC NETWORK BENCHMARK]: Starting Test\n\n");

   debug_printf("CarbonStartSim() start\n");
   CarbonStartSim(argc, argv);
   debug_printf("CarbonStartSim() end\n");

   Simulator::enablePerformanceModelsInCurrentProcess();
   debug_printf("Enabled Performance Models\n");

   // Read Command Line Arguments
   for (SInt32 i = 1; i < argc-1; i += 2)
   {
      if (string(argv[i]) == "-p")
         _traffic_pattern_type = parseTrafficPattern(string(argv[i+1]));
      else if (string(argv[i]) == "-l")
         _offered_load = (double) atof(argv[i+1]);
      else if (string(argv[i]) == "-s")
         _packet_size = (SInt32) atoi(argv[i+1]);
      else if (string(argv[i]) == "-N")
         _total_packets = (UInt64) atoi(argv[i+1]);
      else if (string(argv[i]) == "-c") // Simulator arguments
         break;
      else if (string(argv[i]) == "-h")
      {
         printHelpMessage();
         exit(0);
      }
      else
      {
         fprintf(stderr, "** ERROR **\n");
         printHelpMessage();
         exit(-1);
      }
   }

   debug_printf("Finished parsing command line arguments\n");

   _num_cores = (SInt32) Config::getSingleton()->getApplicationCores();
   debug_printf("Num Application Cores(%i)\n", _num_cores);

   // Initialize Core Specific Variables
   initializeCoreSpVars();

   // Register (NetSend, NetRecv, PushFirstEvents) Events
   Event::registerHandler(EVENT_NET_SEND, processNetSendEvent);
   registerRecvdPacketHandler();
   Event::registerHandler(EVENT_PUSH_FIRST_EVENTS, pushFirstEvents);

   // Push First Event
   UnstructuredBuffer event_args;
   Event* push_first_events = new Event((Event::Type) EVENT_PUSH_FIRST_EVENTS, 0 /* time */, event_args);
   Event::processInOrder(push_first_events, 0 /* core_id */, EventQueue::ORDERED);

   // Wait till all packets are sent and received
   waitForCompletion();

   // Unregister events
   Event::unregisterHandler(EVENT_PUSH_FIRST_EVENTS);
   unregisterRecvdPacketHandler();
   Event::unregisterHandler(EVENT_NET_SEND);

   // Delete Core Specific Variables
   deinitializeCoreSpVars();

   Simulator::disablePerformanceModelsInCurrentProcess();

   printf("\n[SYNTHETIC NETWORK BENCHMARK]: Finished Test successfully\n\n");

   CarbonStopSim();

   return 0;
}

void registerRecvdPacketHandler()
{
   for (SInt32 i = 0; i < _num_cores; i++)
   {
      Core* core = Sim()->getCoreManager()->getCoreFromID(i);
      core->getNetwork()->registerCallback(_packet_type, processRecvdPacket, core);
   }
}

void unregisterRecvdPacketHandler()
{
   for (SInt32 i = 0; i < _num_cores; i++)
   {
      Core* core = Sim()->getCoreManager()->getCoreFromID(i);
      core->getNetwork()->unregisterCallback(_packet_type);
   }
}

void waitForCompletion()
{
   for (SInt32 i = 0; i < (2 * _num_cores); i++)
      _semaphore.wait();
}

void printHelpMessage()
{
   fprintf(stderr, "[Usage]: ./synthetic_network_traffic_generator -p <arg1> -l <arg2> -s <arg3> -N <arg4>\n");
   fprintf(stderr, "where <arg1> = Network Traffic Pattern Type (uniform_random, bit_complement, shuffle, transpose, tornado, nearest_neighbor) (default uniform_random)\n");
   fprintf(stderr, " and  <arg2> = Number of Packets injected into the Network per Core per Cycle (default 0.1)\n");
   fprintf(stderr, " and  <arg3> = Size of each Packet in Bytes (default 8)\n");
   fprintf(stderr, " and  <arg4> = Total Number of Packets injected into the Network per Core (default 10000)\n");
}

void initializeCoreSpVars()
{
   _core_sp_vars = new CoreSpVars[_num_cores];
   for (SInt32 i = 0; i < _num_cores; i++)
   {
      vector<int> send_vec;
      vector<int> receive_vec;

      // Generate the Network Traffic
      switch (_traffic_pattern_type)
      {
         case UNIFORM_RANDOM:
            uniformRandomTrafficGenerator(i, send_vec, receive_vec);
            break;
         case BIT_COMPLEMENT:
            bitComplementTrafficGenerator(i, send_vec, receive_vec);
            break;
         case SHUFFLE:
            shuffleTrafficGenerator(i, send_vec, receive_vec);
            break;
         case TRANSPOSE:
            transposeTrafficGenerator(i, send_vec, receive_vec);
            break;
         case TORNADO:
            tornadoTrafficGenerator(i, send_vec, receive_vec);
            break;
         case NEAREST_NEIGHBOR:
            nearestNeighborTrafficGenerator(i, send_vec, receive_vec);
            break;
         default:
            assert(false);
            break;
      }

      RandNum* rand_num = new RandNum(0,1 /* range */, i /* seed */);

      // Populate the core specific structure
      _core_sp_vars[i].init(rand_num, send_vec, receive_vec);
   }
}

void deinitializeCoreSpVars()
{
   delete [] _core_sp_vars;
}

void processNetSendEvent(Event* event)
{
   assert(event->getType() == (Event::Type) EVENT_NET_SEND);

   Core* core;
   UnstructuredBuffer& event_args = event->getArgs();
   event_args >> core;

   RandNum* rand_num = _core_sp_vars[core->getId()]._rand_num;
   UInt64& total_packets_sent = _core_sp_vars[core->getId()]._total_packets_sent;
   vector<int>& send_vec = _core_sp_vars[core->getId()]._send_vec;
   UInt64& last_packet_time = _core_sp_vars[core->getId()]._last_packet_time;

   for (UInt64 time = event->getTime(); time < (event->getTime() + _quantum); time++)
   {
      if ((total_packets_sent < _total_packets) && (canSendPacket(_offered_load, rand_num)))
      {
         if ((core->getId() == 0) && ((total_packets_sent % 100) == 0))
         {
            printf("Core(0) sending packet(%llu), Time(%llu)\n", \
                  (long long unsigned int) total_packets_sent, (long long unsigned int) event->getTime());
         }

         // Send a packet to its destination core
         Byte data[_packet_size];
         SInt32 receiver = send_vec[total_packets_sent % send_vec.size()];

         last_packet_time = getMax<UInt64>(last_packet_time, time);
         NetPacket net_packet(last_packet_time, _packet_type, core->getId(), receiver, _packet_size, data);
         core->getNetwork()->netSend(net_packet);

         last_packet_time += computeNumFlits(core->getNetwork()->getModeledLength(net_packet));
         total_packets_sent ++;
      }
   }

   if (total_packets_sent < _total_packets)
   {
      pushEvent(event->getTime() + _quantum, core);
   }
   else // (total_packets_sent == _total_packets)
   {
      _semaphore.signal();
   }
}

void processRecvdPacket(void* obj, NetPacket net_packet)
{
   Core* recv_core = (Core*) obj;
   core_id_t receiver = recv_core->getId();
   assert((receiver >= 0) && (receiver < _num_cores));

   UInt64& total_packets_received = _core_sp_vars[receiver]._total_packets_received;

   if ((recv_core->getId() == 0) && ((total_packets_received % 100) == 0))
   {
      printf("Core(0) receiving packet(%llu), Time(%llu)\n", \
            (long long unsigned int) total_packets_received, (long long unsigned int) net_packet.time);
   }

   total_packets_received ++;

   if (total_packets_received == _total_packets)
   {
      _semaphore.signal();
   }
}

void pushFirstEvents(Event* event)
{
   debug_printf("pushFirstEvents\n");
   for (SInt32 i = 0; i < _num_cores; i++)
   {
      Core* ith_core = Sim()->getCoreManager()->getCoreFromID(i);
      // Push the first events
      pushEvent(0 /* time */, ith_core);
   }
}

void pushEvent(UInt64 time, Core* core)
{
   UnstructuredBuffer event_args;
   event_args << core;
   Event* event = new Event((Event::Type) EVENT_NET_SEND, time, event_args);
   Event::processInOrder(event, core->getId(), EventQueue::ORDERED);
}

bool canSendPacket(double offered_load, RandNum* rand_num)
{
   return (rand_num->next() < offered_load);
}

SInt32 computeNumFlits(SInt32 length)
{
   SInt32 num_flits = (SInt32) ceil((float) (length * 8) / _flit_width);
   return num_flits;
}

void debug_printf(const char* fmt, ...)
{
#ifdef DEBUG
   va_list ap;
   va_start(ap, fmt);

   vfprintf(stderr, fmt, ap);
   va_end(ap);
#endif
}
<commit_msg>[synthetic_network] Changed synthetic_network bench test<commit_after>#include <stdio.h>
#include <time.h>
#include <cmath>
#include "simulator.h"
#include "core_manager.h"
#include "config.h"
#include "core.h"
#include "network.h"
#include "utils.h"
#include "semaphore.h"
#include "carbon_user.h"
#include "synthetic_network.h"

// #define DEBUG 1

// Network Traffic Pattern Type
NetworkTrafficType _traffic_pattern_type = UNIFORM_RANDOM;
// Number of packets injected per core per cycle
double _offered_load = 0.1;
// Size of each Packet in Bytes
SInt32 _packet_size = 8;
// Total number of packets injected into the network per core
UInt64 _total_packets = 10000;
// Number of cores in the network
SInt32 _num_cores;

// Type of each packet (so as to send on USER_2 network)
PacketType _packet_type = USER_2;
// FIXME: Hard-coded for now (in bits), Change Later
SInt32 _flit_width = 64;

CoreSpVars* _core_sp_vars;
UInt64 _quantum = 1000;
Semaphore _semaphore;

UInt32 EVENT_NET_SEND = 100;
UInt32 EVENT_PUSH_FIRST_EVENTS = 102;

#include "traffic_generators.h"

int main(int argc, char* argv[])
{
   printf("\n[SYNTHETIC NETWORK BENCHMARK]: Starting Test\n\n");

   CarbonStartSim(argc, argv);
   debug_printf("Executed CarbonStartSim()\n");

   Simulator::__enablePerformanceModels();
   debug_printf("Enabled Performance Models\n");

   // Read Command Line Arguments
   for (SInt32 i = 1; i < argc-1; i += 2)
   {
      if (string(argv[i]) == "-p")
         _traffic_pattern_type = parseTrafficPattern(string(argv[i+1]));
      else if (string(argv[i]) == "-l")
         _offered_load = (double) atof(argv[i+1]);
      else if (string(argv[i]) == "-s")
         _packet_size = (SInt32) atoi(argv[i+1]);
      else if (string(argv[i]) == "-N")
         _total_packets = (UInt64) atoi(argv[i+1]);
      else if (string(argv[i]) == "-c") // Simulator arguments
         break;
      else if (string(argv[i]) == "-h")
      {
         printHelpMessage();
         exit(0);
      }
      else
      {
         fprintf(stderr, "** ERROR **\n");
         printHelpMessage();
         exit(-1);
      }
   }

   debug_printf("Finished parsing command line arguments\n");

   _num_cores = (SInt32) Config::getSingleton()->getTotalCores();
   debug_printf("Num Application Cores(%i)\n", _num_cores);

   // Initialize Core Specific Variables
   initializeCoreSpVars();

   // Register (NetSend, NetRecv, PushFirstEvents) Events
   Event::registerHandler(EVENT_NET_SEND, processNetSendEvent);
   registerRecvdPacketHandler();
   Event::registerHandler(EVENT_PUSH_FIRST_EVENTS, pushFirstEvents);

   // Push First Event
   Event* push_first_events = new Event((Event::Type) EVENT_PUSH_FIRST_EVENTS, 0 /* time */);
   Event::processInOrder(push_first_events, 0 /* core_id */, EventQueue::ORDERED);

   // Wait till all packets are sent and received
   waitForCompletion();

   // Unregister events
   Event::unregisterHandler(EVENT_PUSH_FIRST_EVENTS);
   unregisterRecvdPacketHandler();
   Event::unregisterHandler(EVENT_NET_SEND);

   // Delete Core Specific Variables
   deinitializeCoreSpVars();

   Simulator::__disablePerformanceModels();

   printf("\n[SYNTHETIC NETWORK BENCHMARK]: Finished Test successfully\n\n");

   CarbonStopSim();

   return 0;
}

void registerRecvdPacketHandler()
{
   for (SInt32 i = 0; i < _num_cores; i++)
   {
      Core* core = Sim()->getCoreManager()->getCoreFromID(i);
      core->getNetwork()->registerCallback(_packet_type, processRecvdPacket, core);
   }
}

void unregisterRecvdPacketHandler()
{
   for (SInt32 i = 0; i < _num_cores; i++)
   {
      Core* core = Sim()->getCoreManager()->getCoreFromID(i);
      core->getNetwork()->unregisterCallback(_packet_type);
   }
}

void waitForCompletion()
{
   for (SInt32 i = 0; i < (2 * _num_cores); i++)
      _semaphore.wait();
}

void printHelpMessage()
{
   fprintf(stderr, "[Usage]: ./synthetic_network_traffic_generator -p <arg1> -l <arg2> -s <arg3> -N <arg4>\n");
   fprintf(stderr, "where <arg1> = Network Traffic Pattern Type (uniform_random, bit_complement, shuffle, transpose, tornado, nearest_neighbor) (default uniform_random)\n");
   fprintf(stderr, " and  <arg2> = Number of Packets injected into the Network per Core per Cycle (default 0.1)\n");
   fprintf(stderr, " and  <arg3> = Size of each Packet in Bytes (default 8)\n");
   fprintf(stderr, " and  <arg4> = Total Number of Packets injected into the Network per Core (default 10000)\n");
}

void initializeCoreSpVars()
{
   _core_sp_vars = new CoreSpVars[_num_cores];
   for (SInt32 i = 0; i < _num_cores; i++)
   {
      vector<int> send_vec;
      vector<int> receive_vec;

      // Generate the Network Traffic
      switch (_traffic_pattern_type)
      {
         case UNIFORM_RANDOM:
            uniformRandomTrafficGenerator(i, send_vec, receive_vec);
            break;
         case BIT_COMPLEMENT:
            bitComplementTrafficGenerator(i, send_vec, receive_vec);
            break;
         case SHUFFLE:
            shuffleTrafficGenerator(i, send_vec, receive_vec);
            break;
         case TRANSPOSE:
            transposeTrafficGenerator(i, send_vec, receive_vec);
            break;
         case TORNADO:
            tornadoTrafficGenerator(i, send_vec, receive_vec);
            break;
         case NEAREST_NEIGHBOR:
            nearestNeighborTrafficGenerator(i, send_vec, receive_vec);
            break;
         default:
            assert(false);
            break;
      }

      RandNum* rand_num = new RandNum(0,1 /* range */, i /* seed */);

      // Populate the core specific structure
      _core_sp_vars[i].init(rand_num, send_vec, receive_vec);
   }
}

void deinitializeCoreSpVars()
{
   delete [] _core_sp_vars;
}

void processNetSendEvent(Event* event)
{
   assert(event->getType() == (Event::Type) EVENT_NET_SEND);

   Core* core;
   UnstructuredBuffer* event_args = event->getArgs();
   (*event_args) >> core;

   RandNum* rand_num = _core_sp_vars[core->getId()]._rand_num;
   UInt64& total_packets_sent = _core_sp_vars[core->getId()]._total_packets_sent;
   vector<int>& send_vec = _core_sp_vars[core->getId()]._send_vec;
   UInt64& last_packet_time = _core_sp_vars[core->getId()]._last_packet_time;

   for (UInt64 time = event->getTime(); time < (event->getTime() + _quantum); time++)
   {
      if ((total_packets_sent < _total_packets) && (canSendPacket(_offered_load, rand_num)))
      {
         if ((core->getId() == 0) && ((total_packets_sent % 100) == 0))
         {
            debug_printf("Core(0) sending packet(%llu), Time(%llu)\n", \
                         (long long unsigned int) total_packets_sent, (long long unsigned int) event->getTime());
         }

         // Send a packet to its destination core
         Byte data[_packet_size];
         SInt32 receiver = send_vec[total_packets_sent % send_vec.size()];

         last_packet_time = getMax<UInt64>(last_packet_time, time);
         NetPacket net_packet(last_packet_time, _packet_type, core->getId(), receiver, _packet_size, data);
         core->getNetwork()->netSend(net_packet);

         last_packet_time += computeNumFlits(core->getNetwork()->getModeledLength(net_packet));
         total_packets_sent ++;
      }
   }

   if (total_packets_sent < _total_packets)
   {
      pushEvent(event->getTime() + _quantum, core);
   }
   else // (total_packets_sent == _total_packets)
   {
      _semaphore.signal();
   }
}

void processRecvdPacket(void* obj, NetPacket net_packet)
{
   Core* recv_core = (Core*) obj;
   core_id_t receiver = recv_core->getId();
   assert((receiver >= 0) && (receiver < _num_cores));

   UInt64& total_packets_received = _core_sp_vars[receiver]._total_packets_received;

   if ((recv_core->getId() == 0) && ((total_packets_received % 100) == 0))
   {
      debug_printf("Core(0) receiving packet(%llu), Time(%llu)\n", \
                   (long long unsigned int) total_packets_received, (long long unsigned int) net_packet.time);
   }

   total_packets_received ++;

   if (total_packets_received == _total_packets)
   {
      _semaphore.signal();
   }
}

void pushFirstEvents(Event* event)
{
   debug_printf("pushFirstEvents\n");
   for (SInt32 i = 0; i < _num_cores; i++)
   {
      Core* ith_core = Sim()->getCoreManager()->getCoreFromID(i);
      // Push the first events
      pushEvent(0 /* time */, ith_core);
   }
}

void pushEvent(UInt64 time, Core* core)
{
   UnstructuredBuffer* event_args = new UnstructuredBuffer();
   (*event_args) << core;
   Event* event = new Event((Event::Type) EVENT_NET_SEND, time, event_args);
   Event::processInOrder(event, core->getId(), EventQueue::ORDERED);
}

bool canSendPacket(double offered_load, RandNum* rand_num)
{
   return (rand_num->next() < offered_load);
}

SInt32 computeNumFlits(SInt32 length)
{
   SInt32 num_flits = (SInt32) ceil((float) (length * 8) / _flit_width);
   return num_flits;
}

void debug_printf(const char* fmt, ...)
{
#ifdef DEBUG
   va_list ap;
   va_start(ap, fmt);

   vfprintf(stderr, fmt, ap);
   va_end(ap);
#endif
}
<|endoftext|>


<commit_before>// vimshell.cpp : Defines the entry point for the application.
//

#include "vimshell.h"
#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>
#include <shellapi.h>

bool cvtLPW2stdstring(std::string& s, const LPWSTR pw,
                      UINT codepage = CP_ACP)
{
    bool res = false;
    char* p = 0;
    int bsz;

    bsz = WideCharToMultiByte(codepage,
        0,
        pw,-1,
        0,0,
        0,0);
    if (bsz > 0) {
        p = new char[bsz];
        int rc = WideCharToMultiByte(codepage,
            0,
            pw,-1,
            p,bsz,
            0,0);
        if (rc != 0) {
            p[bsz-1] = 0;
            s = p;
            res = true;
        }
    }
    delete [] p;
    return res;
}

std::string FindAndReplace(std::string tInput, std::string tFind, std::string tReplace )
{
	size_t uPos = 0;
	size_t uFindLen = tFind.length();
	size_t uReplaceLen = tReplace.length();

	if( uFindLen == 0 )
	{
		return tInput;
	}

	while((uPos = tInput.find( tFind, uPos )) != std::string::npos)
	{
		tInput.replace( uPos, uFindLen, tReplace );
		uPos += uReplaceLen;
	}

	return tInput;
}

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
	int count;
	//MessageBox(0, lpCmdLine, 0, 0);
	LPWSTR* strings = CommandLineToArgvW(GetCommandLineW(), &count);
	std::string currentDir;

	cvtLPW2stdstring(currentDir, strings[0]);

	// Cut off the filename
	while((currentDir.length() > 0) &&
		(currentDir[currentDir.length()-1] != '/') &&
		(currentDir[currentDir.length()-1] != '\\'))
	{
		currentDir = currentDir.substr(0, currentDir.length()-1);
	}
	if(currentDir.length() > 0 && currentDir[0] == '"')
		currentDir = currentDir.substr(1);

	std::string filename = currentDir + std::string("shell.txt");

	std::ifstream fileIn(filename.c_str());
	if(!fileIn)
	{
		MessageBox(0, "Please create a file called shell.txt in the same folder you put this new vimrun.exe", 0,0);
		return 1;
	}

	std::string argumentshellcommand;
	std::string silentshellcommand;
	std::string interactiveshellcommand;

	std::getline(fileIn, argumentshellcommand);
	std::getline(fileIn, silentshellcommand);
	std::getline(fileIn, interactiveshellcommand);

	std::string args = lpCmdLine;

	while(args.length() > 0 && args[0] == ' ')
		args = args.substr(1);

	bool execSilently = false;

	if(args.length() > 3 &&
			args[0] == '-' &&
			args[1] == 's' &&
			args[2] == ' ')
	{
		args = args.substr(3);
		execSilently = true;
	}

	size_t spacepos = args.find_first_of(" ");
	args = args.substr(spacepos+1);
	spacepos = args.find_first_of(" ");
	args = args.substr(spacepos+1);

	std::string cmd;

	if(spacepos == std::string::npos)
		args = "";

	std::string argcmd = execSilently ? silentshellcommand : argumentshellcommand;

	if(args.length() == 0)
	{
		cmd = interactiveshellcommand;
	}
	else
	{
		int start = argcmd.find('#F');
		int end = argcmd.find('#', start+1);

		//MessageBox(0, argcmd.c_str(), 0,0);
		if(start == std::string::npos || end == std::string::npos)
			MessageBox(0, "Check your shell.txt", 0,0);

		std::string appendage = argcmd.substr(start+1, end-start-1);

		std::string filename = "C:/vimshelltmp.txt";

		cmd = argcmd.replace(start-1, end-start+2, filename);
		std::ofstream f(filename.c_str());
		f << args.c_str() << appendage;
		f.close();
	}

	//MessageBox(0,cmd.c_str(), 0,0);
	std::ofstream f("C:/output.txt");
	f << cmd.c_str();
	f.close();

	STARTUPINFO si = { sizeof(STARTUPINFO) };
	si.dwFlags = STARTF_USESHOWWINDOW;
	if(execSilently)
		si.wShowWindow = SW_HIDE;
	else
		si.wShowWindow = SW_SHOW;
	PROCESS_INFORMATION pi;
	char arr[1024];
	strcpy_s(arr, 1024, cmd.c_str());
	CreateProcess(NULL, arr, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
	WaitForSingleObject(pi.hProcess, INFINITE);
	DWORD exit_code;
	GetExitCodeProcess(pi.hProcess, &exit_code);

	return exit_code;
}
<commit_msg>Create a proper temporary file for temporary usage (and delete it afterwards)<commit_after>// vimshell.cpp : Defines the entry point for the application.
//

#include "vimshell.h"
#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>
#include <shellapi.h>

bool cvtLPW2stdstring(std::string& s, const LPWSTR pw,
                      UINT codepage = CP_ACP)
{
    bool res = false;
    char* p = 0;
    int bsz;

    bsz = WideCharToMultiByte(codepage,
        0,
        pw,-1,
        0,0,
        0,0);
    if (bsz > 0) {
        p = new char[bsz];
        int rc = WideCharToMultiByte(codepage,
            0,
            pw,-1,
            p,bsz,
            0,0);
        if (rc != 0) {
            p[bsz-1] = 0;
            s = p;
            res = true;
        }
    }
    delete [] p;
    return res;
}

std::string FindAndReplace(std::string tInput, std::string tFind, std::string tReplace )
{
	size_t uPos = 0;
	size_t uFindLen = tFind.length();
	size_t uReplaceLen = tReplace.length();

	if( uFindLen == 0 )
	{
		return tInput;
	}

	while((uPos = tInput.find( tFind, uPos )) != std::string::npos)
	{
		tInput.replace( uPos, uFindLen, tReplace );
		uPos += uReplaceLen;
	}

	return tInput;
}

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
	int count;
	//MessageBox(0, lpCmdLine, 0, 0);
	LPWSTR* strings = CommandLineToArgvW(GetCommandLineW(), &count);
	std::string currentDir;
	std::string tmpFile;

	cvtLPW2stdstring(currentDir, strings[0]);

	// Cut off the filename
	while((currentDir.length() > 0) &&
		(currentDir[currentDir.length()-1] != '/') &&
		(currentDir[currentDir.length()-1] != '\\'))
	{
		currentDir = currentDir.substr(0, currentDir.length()-1);
	}
	if(currentDir.length() > 0 && currentDir[0] == '"')
		currentDir = currentDir.substr(1);

	std::string filename = currentDir + std::string("shell.txt");

	std::ifstream fileIn(filename.c_str());
	if(!fileIn)
	{
		MessageBox(0, "Please create a file called shell.txt in the same folder you put this new vimrun.exe", 0,0);
		return 1;
	}

	std::string argumentshellcommand;
	std::string silentshellcommand;
	std::string interactiveshellcommand;

	std::getline(fileIn, argumentshellcommand);
	std::getline(fileIn, silentshellcommand);
	std::getline(fileIn, interactiveshellcommand);

	std::string args = lpCmdLine;

	while(args.length() > 0 && args[0] == ' ')
		args = args.substr(1);

	bool execSilently = false;

	if(args.length() > 3 &&
			args[0] == '-' &&
			args[1] == 's' &&
			args[2] == ' ')
	{
		args = args.substr(3);
		execSilently = true;
	}

	size_t spacepos = args.find_first_of(" ");
	args = args.substr(spacepos+1);
	spacepos = args.find_first_of(" ");
	args = args.substr(spacepos+1);

	std::string cmd;

	if(spacepos == std::string::npos)
		args = "";

	std::string argcmd = execSilently ? silentshellcommand : argumentshellcommand;

	if(args.length() == 0)
	{
		cmd = interactiveshellcommand;
	}
	else
	{
		int start = argcmd.find('#F');
		int end = argcmd.find('#', start+1);

		//MessageBox(0, argcmd.c_str(), 0,0);
		if(start == std::string::npos || end == std::string::npos)
			MessageBox(0, "Check your shell.txt", 0,0);

		std::string appendage = argcmd.substr(start+1, end-start-1);
		// Get a path to a temporary file
		char pathBuf[MAX_PATH];
		char fileBuf[MAX_PATH];
		GetTempPath(128, pathBuf);
		GetTempFileName(pathBuf, "vsh", 0, fileBuf);

		tmpFile = fileBuf;
		cmd = argcmd.replace(start-1, end-start+2, fileBuf);
		std::ofstream f(fileBuf);
		f << args.c_str() << appendage;
		f.close();
	}

	//MessageBox(0,cmd.c_str(), 0,0);
	//std::ofstream f("C:/output.txt");
	//f << cmd.c_str();
	//f.close();

	STARTUPINFO si = { sizeof(STARTUPINFO) };
	si.dwFlags = STARTF_USESHOWWINDOW;
	if(execSilently)
		si.wShowWindow = SW_HIDE;
	else
		si.wShowWindow = SW_SHOW;
	PROCESS_INFORMATION pi;
	char arr[1024];
	strcpy_s(arr, 1024, cmd.c_str());
	CreateProcess(NULL, arr, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
	WaitForSingleObject(pi.hProcess, INFINITE);
	DWORD exit_code;
	GetExitCodeProcess(pi.hProcess, &exit_code);

	// If we created a temporary file, we need to delete it.
	if(tmpFile.length() > 0)
		DeleteFile(tmpFile.c_str());

	return exit_code;
}
<|endoftext|>


<commit_before>// The MIT License (MIT)

// Copyright (c) 2012-2013 Danny Y., Rapptz

// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#ifndef GEARS_PROGRAM_OPTIONS_CLASS_HPP
#define GEARS_PROGRAM_OPTIONS_CLASS_HPP

#include <map>
#include "details.hpp"
#include "arg.hpp"

namespace gears {
class program_options {
private:
    std::map<std::string, arg> args;
    std::string program_name;
    std::string program_usage;

    int parse_value(arg& argu, char* argv[], int counter) {
        // next arg isn't a flag or option
        // intersperse values with a space separator
        if(argv[counter] != nullptr && argv[counter][0] != '-') {
            // overwrite value
            argu.value = argv[counter];
            ++counter;
        }

        while(argv[counter] != nullptr && argv[counter][0] != '-') {
            // append the value to the space separated list
            argu.value.push_back(' ');
            argu.value.append(argv[counter++]);
        }

        return counter - 1;
    }

    void parse_short_option(const std::string& option, int& i, char* argv[]) {
        for(auto&& arg : args) {

            auto pos = option.find(arg.second.short_name);

            // Single flag or option with value
            if(option.size() == 2) {
                if(pos != std::string::npos) {
                    if(arg.second.is_value()) {
                        i = parse_value(arg.second, argv, i + 1);
                        break;
                    }

                    // regular flag

                    arg.second.active = true;
                }
            }

            // Grouped character or grouped option
            else if(option.size() > 2) {

                // Grouped option
                if(arg.second.is_value() && option[1] == arg.second.short_name) {
                    arg.second.value.append(std::begin(option) + 2, std::end(option));
                    arg.second.active = true;
                    break;
                }

                // regular flag with grouped characters
                arg.second.active = pos != std::string::npos;
            }
            else {
                // Seems to be neither
                break;
            }
        }
    }
public:
    program_options() = default;

    program_options(std::initializer_list<arg> l) {
        for(auto&& i : l) {
            args.insert(std::make_pair("--" + i.name, i));
        }
    }

    arg& add(const std::string& name) {
        auto p = args.emplace(std::piecewise_construct,
                              std::forward_as_tuple("--" + name),
                              std::forward_as_tuple(name));
        return (p.first)->second;
    }

    void parse(int argc, char* argv[]) noexcept {
        program_name = argv[0];
        std::string current;
        for(int i = 1; i < argc; ++i) {
            current = argv[i];

            // Stop parsing if it's --
            if(current == "--")
                break;

            // current arg has equal sign
            auto pos = current.find('=');
            if(pos != std::string::npos) {
                auto it = args.find(current.substr(0, pos));

                // make sure the argument is valid
                if(it != args.end()) {
                    // Override value
                    it->second.value = current.substr(pos + 1);
                }

                continue;
            }

            auto it = args.find(current);

            if(it != args.end()) {

                // value options
                if(it->second.is_value()) {
                    i = parse_value(it->second, argv, i + 1);
                }

                // regular flag

                it->second.active = true;
                continue;
            }

            // short options found
            if(current.front() == '-') {
                parse_short_option(current, i, argv);
            }
        }
    }

    bool is_active(const std::string& name) const noexcept {
        auto it = args.find("--" + name);
        if(it != args.end()) {
            return it->second.active;
        }
        return false;
    }

    void usage(std::string str) noexcept {
        program_usage = std::move(str);
    }

    std::string usage() const noexcept {
        return "usage: " + program_name + ' ' + program_usage;
    }

    template<typename T = std::string>
    T get(const std::string& str) const {
        auto it = args.find("--" + str);
        if(it != args.end()) {
            if(it->second.is_value())
                return detail::lexical_cast<T>(it->second.value);
        }

        throw detail::arg_not_found(str + " is not an option argument");
    }

    template<typename T>
    T get_list(const std::string& str) const {
        auto it = args.find("--" + str);
        if(it != args.end()) {
            if(it->second.is_value()) {
                T result;
                std::istringstream ss(it->second.value);
                typename T::value_type x;
                while(ss >> x) {
                    detail::insert_impl(result, x);
                }

                return result;
            }
        }

        throw detail::arg_not_found(str + " is not an option argument");
    }

    #ifndef GEARS_NO_IOSTREAM

    template<typename Elem, typename Traits>
    friend auto operator<<(std::basic_ostream<Elem, Traits>& out, const program_options& po) -> decltype(out) {
        out << "usage: " << po.program_name << ' ' << po.program_usage << "\n\n";

        for(auto&& arg : po.args) {
            out << arg.second;
        }

        return out;
    }

    #endif // GEARS_NO_IOSTREAM
};
} // gears

#endif // GEARS_PROGRAM_OPTIONS_CLASS_HPP<commit_msg>Made program name configurable rather than assuming it's argv[0]<commit_after>// The MIT License (MIT)

// Copyright (c) 2012-2013 Danny Y., Rapptz

// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#ifndef GEARS_PROGRAM_OPTIONS_CLASS_HPP
#define GEARS_PROGRAM_OPTIONS_CLASS_HPP

#include <map>
#include "details.hpp"
#include "arg.hpp"

namespace gears {
class program_options {
private:
    std::map<std::string, arg> args;
    std::string program_name;
    std::string program_usage;

    int parse_value(arg& argu, char* argv[], int counter) {
        // next arg isn't a flag or option
        // intersperse values with a space separator
        if(argv[counter] != nullptr && argv[counter][0] != '-') {
            // overwrite value
            argu.value = argv[counter];
            ++counter;
        }

        while(argv[counter] != nullptr && argv[counter][0] != '-') {
            // append the value to the space separated list
            argu.value.push_back(' ');
            argu.value.append(argv[counter++]);
        }

        return counter - 1;
    }

    void parse_short_option(const std::string& option, int& i, char* argv[]) {
        for(auto&& arg : args) {

            auto pos = option.find(arg.second.short_name);

            // Single flag or option with value
            if(option.size() == 2) {
                if(pos != std::string::npos) {
                    if(arg.second.is_value()) {
                        i = parse_value(arg.second, argv, i + 1);
                        break;
                    }

                    // regular flag

                    arg.second.active = true;
                }
            }

            // Grouped character or grouped option
            else if(option.size() > 2) {

                // Grouped option
                if(arg.second.is_value() && option[1] == arg.second.short_name) {
                    arg.second.value.append(std::begin(option) + 2, std::end(option));
                    arg.second.active = true;
                    break;
                }

                // regular flag with grouped characters
                arg.second.active = pos != std::string::npos;
            }
            else {
                // Seems to be neither
                break;
            }
        }
    }
public:
    program_options() = default;

    program_options(std::initializer_list<arg> l) {
        for(auto&& i : l) {
            args.insert(std::make_pair("--" + i.name, i));
        }
    }

    arg& add(const std::string& name) {
        auto p = args.emplace(std::piecewise_construct,
                              std::forward_as_tuple("--" + name),
                              std::forward_as_tuple(name));
        return (p.first)->second;
    }

    void parse(int argc, char* argv[]) noexcept {
        std::string current;
        for(int i = 1; i < argc; ++i) {
            current = argv[i];

            // Stop parsing if it's --
            if(current == "--")
                break;

            // current arg has equal sign
            auto pos = current.find('=');
            if(pos != std::string::npos) {
                auto it = args.find(current.substr(0, pos));

                // make sure the argument is valid
                if(it != args.end()) {
                    // Override value
                    it->second.value = current.substr(pos + 1);
                }

                continue;
            }

            auto it = args.find(current);

            if(it != args.end()) {

                // value options
                if(it->second.is_value()) {
                    i = parse_value(it->second, argv, i + 1);
                }

                // regular flag

                it->second.active = true;
                continue;
            }

            // short options found
            if(current.front() == '-') {
                parse_short_option(current, i, argv);
            }
        }
    }

    bool is_active(const std::string& name) const noexcept {
        auto it = args.find("--" + name);
        if(it != args.end()) {
            return it->second.active;
        }
        return false;
    }

    program_options& usage(std::string str) noexcept {
        program_usage = std::move(str);
        return *this;
    }

    program_options& name(std::string str) noexcept {
        program_name = std::move(str);
        program_name.push_back(' ');
        return *this;
    }

    template<typename T = std::string>
    T get(const std::string& str) const {
        auto it = args.find("--" + str);
        if(it != args.end()) {
            if(it->second.is_value())
                return detail::lexical_cast<T>(it->second.value);
        }

        throw detail::arg_not_found(str + " is not an option argument");
    }

    template<typename T>
    T get_list(const std::string& str) const {
        auto it = args.find("--" + str);
        if(it != args.end()) {
            if(it->second.is_value()) {
                T result;
                std::istringstream ss(it->second.value);
                typename T::value_type x;
                while(ss >> x) {
                    detail::insert_impl(result, x);
                }

                return result;
            }
        }

        throw detail::arg_not_found(str + " is not an option argument");
    }

    #ifndef GEARS_NO_IOSTREAM

    template<typename Elem, typename Traits>
    friend auto operator<<(std::basic_ostream<Elem, Traits>& out, const program_options& po) -> decltype(out) {
        out << "usage: " << po.program_name << po.program_usage << "\n\n";

        for(auto&& arg : po.args) {
            out << arg.second;
        }

        return out;
    }

    #endif // GEARS_NO_IOSTREAM
};
} // gears

#endif // GEARS_PROGRAM_OPTIONS_CLASS_HPP<|endoftext|>


<commit_before>/*
 *  main.cpp
 *  Program:  kalarm
 *  (C) 2001, 2002 by David Jarvie  software@astrojar.org.uk
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include "kalarm.h"

#include <stdlib.h>

#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include <klocale.h>
#include <kdebug.h>

#include "kalarmapp.h"

#define PROGRAM_NAME "kalarm"

static KCmdLineOptions options[] =
{
	{ "b", 0L, 0L },
	{ "beep", I18N_NOOP("Beep when message is displayed"), 0L },
	{ "c", 0L, 0L },
	{ "color", 0L, 0L },
	{ "colour <colour>", I18N_NOOP("Message background color (name or hex 0xRRGGBB)"), 0L },
	{ "calendarURL <url>", I18N_NOOP("URL of calendar file"), 0L },
	{ "cancelEvent <eventID>", I18N_NOOP("Cancel message with the specified event ID"), 0L },
	{ "displayEvent <eventID>", I18N_NOOP("Display message with the specified event ID"), 0L },
	{ "f", 0L, 0L },
	{ "file <url>", I18N_NOOP("File to display"), 0L },
	{ "handleEvent <eventID>", I18N_NOOP("Display or cancel message with the specified event ID"), 0L },
	{ "i", 0L, 0L },
	{ "interval <minutes>", I18N_NOOP("Interval between display of repeated alarms"), 0L },
	{ "l", 0L, 0L },
	{ "late-cancel", I18N_NOOP("Cancel message if it cannot be displayed on time"), 0L },
	{ "L", 0L, 0L },
	{ "login", I18N_NOOP("Repeat message at every login"), 0L },
	{ "r", 0L, 0L },
	{ "repeat <count>", I18N_NOOP("Number of times to repeat alarm (after the initial occasion)"), 0L },
	{ "reset", I18N_NOOP("Reset the message scheduling daemon"), 0L },
	{ "stop", I18N_NOOP("Stop the message scheduling daemon"), 0L },
	{ "t", 0L, 0L },
	{ "time <time>", I18N_NOOP("Display message at 'time' [[[yyyy-]mm-]dd-]hh:mm"), 0L },
	{ "tray", I18N_NOOP("Display system tray icon"), 0L },
	{ "+[message]", I18N_NOOP("Message text to display"), 0L },
	{ 0L, 0L, 0L }
};

int main(int argc, char *argv[])
{
	KAboutData aboutData(PROGRAM_NAME, I18N_NOOP("KAlarm"),
		VERSION, I18N_NOOP("       " PROGRAM_NAME "\n"
		"       " PROGRAM_NAME " -f[bcilLrt]\n"
		"       " PROGRAM_NAME " [-bcilLrt] message\n"
		"       " PROGRAM_NAME " --reset | --stop\n"
		"       " PROGRAM_NAME " --cancelEvent eventID [--calendarURL url]\n"
		"       " PROGRAM_NAME " --displayEvent eventID [--calendarURL url]\n"
		"       " PROGRAM_NAME " --handleEvent eventID [--calendarURL url]\n"
		"       " PROGRAM_NAME " [generic_options]\n\n"
		"KDE alarm message scheduler"),
		KAboutData::License_GPL,
		"(c) 2001,2002, David Jarvie", 0L, "http://www.astrojar.org.uk/linux",
		"software@astrojar.org.uk");
	aboutData.addAuthor("David Jarvie", 0L, "software@astrojar.org.uk");

	KCmdLineArgs::init(argc, argv, &aboutData);
	KCmdLineArgs::addCmdLineOptions(options);
	KUniqueApplication::addCmdLineOptions();

	if (!KAlarmApp::start())
	{
		// An instance of the application is already running
		exit(0);
	}

	// This is the child instance
	KAlarmApp* app = KAlarmApp::getInstance();
	return app->exec();
}
<commit_msg>Update aboutData information<commit_after>/*
 *  main.cpp
 *  Program:  kalarm
 *  (C) 2001, 2002 by David Jarvie  software@astrojar.org.uk
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include "kalarm.h"

#include <stdlib.h>

#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include <klocale.h>
#include <kdebug.h>

#include "kalarmapp.h"

#define PROGRAM_NAME "kalarm"

static KCmdLineOptions options[] =
{
	{ "b", 0L, 0L },
	{ "beep", I18N_NOOP("Beep when message is displayed"), 0L },
	{ "c", 0L, 0L },
	{ "color", 0L, 0L },
	{ "colour <colour>", I18N_NOOP("Message background color (name or hex 0xRRGGBB)"), 0L },
	{ "calendarURL <url>", I18N_NOOP("URL of calendar file"), 0L },
	{ "cancelEvent <eventID>", I18N_NOOP("Cancel message with the specified event ID"), 0L },
	{ "displayEvent <eventID>", I18N_NOOP("Display message with the specified event ID"), 0L },
	{ "f", 0L, 0L },
	{ "file <url>", I18N_NOOP("File to display"), 0L },
	{ "handleEvent <eventID>", I18N_NOOP("Display or cancel message with the specified event ID"), 0L },
	{ "i", 0L, 0L },
	{ "interval <minutes>", I18N_NOOP("Interval between display of repeated alarms"), 0L },
	{ "l", 0L, 0L },
	{ "late-cancel", I18N_NOOP("Cancel message if it cannot be displayed on time"), 0L },
	{ "L", 0L, 0L },
	{ "login", I18N_NOOP("Repeat message at every login"), 0L },
	{ "r", 0L, 0L },
	{ "repeat <count>", I18N_NOOP("Number of times to repeat alarm (after the initial occasion)"), 0L },
	{ "reset", I18N_NOOP("Reset the message scheduling daemon"), 0L },
	{ "stop", I18N_NOOP("Stop the message scheduling daemon"), 0L },
	{ "t", 0L, 0L },
	{ "time <time>", I18N_NOOP("Display message at 'time' [[[yyyy-]mm-]dd-]hh:mm"), 0L },
	{ "tray", I18N_NOOP("Display system tray icon"), 0L },
	{ "+[message]", I18N_NOOP("Message text to display"), 0L },
	{ 0L, 0L, 0L }
};

int main(int argc, char *argv[])
{
	KAboutData aboutData(PROGRAM_NAME, I18N_NOOP("KAlarm"),
		VERSION, I18N_NOOP("       " PROGRAM_NAME "\n"
		"       " PROGRAM_NAME " [-bcilLrt] -f URL\n"
		"       " PROGRAM_NAME " [-bcilLrt] message\n"
		"       " PROGRAM_NAME " --tray | --reset | --stop\n"
		"       " PROGRAM_NAME " --cancelEvent eventID [--calendarURL url]\n"
		"       " PROGRAM_NAME " --displayEvent eventID [--calendarURL url]\n"
		"       " PROGRAM_NAME " --handleEvent eventID [--calendarURL url]\n"
		"       " PROGRAM_NAME " [generic_options]\n\n"
		"KDE alarm message scheduler"),
		KAboutData::License_GPL,
		"(c) 2001, 2002, David Jarvie", 0L, "http://www.astrojar.org.uk/linux",
		"software@astrojar.org.uk");
	aboutData.addAuthor("David Jarvie", 0L, "software@astrojar.org.uk");

	KCmdLineArgs::init(argc, argv, &aboutData);
	KCmdLineArgs::addCmdLineOptions(options);
	KUniqueApplication::addCmdLineOptions();

	if (!KAlarmApp::start())
	{
		// An instance of the application is already running
		exit(0);
	}

	// This is the child instance
	KAlarmApp* app = KAlarmApp::getInstance();
	return app->exec();
}
<|endoftext|>