<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/
#ifndef __itkMahalanobisDistanceMembershipFunction_hxx
#define __itkMahalanobisDistanceMembershipFunction_hxx

#include "itkMahalanobisDistanceMembershipFunction.h"

#include "vnl/vnl_vector.h"
#include "vnl/vnl_matrix.h"
#include "vnl/algo/vnl_matrix_inverse.h"

namespace itk
{
namespace Statistics
{
template< typename TVector >
MahalanobisDistanceMembershipFunction< TVector >
::MahalanobisDistanceMembershipFunction()
{
  NumericTraits<MeanVectorType>::SetLength(m_Mean, this->GetMeasurementVectorSize());
  m_Mean.Fill(0.0f);

  m_Covariance.SetSize(this->GetMeasurementVectorSize(), this->GetMeasurementVectorSize());
  m_Covariance.SetIdentity();

  m_InverseCovariance = m_Covariance;

  m_CovarianceNonsingular = true;
}

template< typename TVector >
void
MahalanobisDistanceMembershipFunction< TVector >
::SetMean(const MeanVectorType & mean)
{
  if ( this->GetMeasurementVectorSize() )
    {
    MeasurementVectorTraits::Assert(mean,
                                    this->GetMeasurementVectorSize(),
                                    "GaussianMembershipFunction::SetMean(): Size of mean vector specified does not match the size of a measurement vector.");
    }
  else
    {
    // not already set, cache the size
    this->SetMeasurementVectorSize( mean.Size() );
    }

  if ( m_Mean != mean )
    {
    m_Mean = mean;
    this->Modified();
    }
}

template< typename TVector >
void
MahalanobisDistanceMembershipFunction< TVector >
::SetCovariance(const CovarianceMatrixType & cov)
{
  // Sanity check
  if ( cov.GetVnlMatrix().rows() != cov.GetVnlMatrix().cols() )
    {
    itkExceptionMacro(<< "Covariance matrix must be square");
    }
  if ( this->GetMeasurementVectorSize() )
    {
    if ( cov.GetVnlMatrix().rows() != this->GetMeasurementVectorSize() )
      {
      itkExceptionMacro(<< "Length of measurement vectors must be"
                        << " the same as the size of the covariance.");
      }
    }
  else
    {
    // not already set, cache the size
    this->SetMeasurementVectorSize( cov.GetVnlMatrix().rows() );
    }

  if (m_Covariance == cov)
    {
    // no need to copy the matrix, compute the inverse, or the normalization
    return;
    }

  m_Covariance = cov;

  // the inverse of the covariance matrix is first computed by SVD
  vnl_matrix_inverse< double > inv_cov( m_Covariance.GetVnlMatrix() );

  // the determinant is then costless this way
  double det = inv_cov.determinant_magnitude();

  if( det < 0.)
    {
    itkExceptionMacro( << "det( m_Covariance ) < 0" );
    }

  // 1e-6 is an arbitrary value!!!
  const double singularThreshold = 1.0e-6;
  m_CovarianceNonsingular = ( det > singularThreshold );

  if( m_CovarianceNonsingular )
    {
    // allocate the memory for m_InverseCovariance matrix
    m_InverseCovariance.GetVnlMatrix() = inv_cov.inverse();
    }
  else
    {
    // define the inverse to be diagonal with large values along the
    // diagonal. value chosen so (X-M)'inv(C)*(X-M) will usually stay
    // below NumericTraits<double>::max()
    const double aLargeDouble = std::pow(NumericTraits<double>::max(), 1.0/3.0)
      / (double) this->GetMeasurementVectorSize();
    m_InverseCovariance.SetSize(this->GetMeasurementVectorSize(), this->GetMeasurementVectorSize());
    m_InverseCovariance.SetIdentity();
    m_InverseCovariance *= aLargeDouble;
    }

  this->Modified();
}

template< typename TVector >
double
MahalanobisDistanceMembershipFunction< TVector >
::Evaluate(const MeasurementVectorType & measurement) const
{
  const MeasurementVectorSizeType measurementVectorSize =
    this->GetMeasurementVectorSize();

  // Our inverse covariance is always well formed. When the covariance
  // is singular, we use a diagonal inverse covariance with a large diagnonal

  // Compute ( y - mean )
  vnl_vector< double > tempVector( measurementVectorSize );

  for ( MeasurementVectorSizeType i = 0; i < measurementVectorSize; ++i )
    {
    tempVector[i] = measurement[i] - m_Mean[i];
    }

  // temp = ( y - mean )^t * InverseCovariance * ( y - mean )
  double temp = dot_product( tempVector,
                             m_InverseCovariance.GetVnlMatrix() * tempVector );

  return temp;
}

template< typename TVector >
void
MahalanobisDistanceMembershipFunction< TVector >
::PrintSelf(std::ostream & os, Indent indent) const
{
  Superclass::PrintSelf(os, indent);

  os << indent << "Mean: " << m_Mean << std::endl;
  os << indent << "Covariance: " << std::endl;
  os << m_Covariance.GetVnlMatrix();
  os << indent << "InverseCovariance: " << std::endl;
  os << indent << m_InverseCovariance.GetVnlMatrix();
  os << indent << "Covariance nonsingular: " <<
    (m_CovarianceNonsingular ? "true" : "false") << std::endl;
}

template< typename TVector >
typename LightObject::Pointer
MahalanobisDistanceMembershipFunction< TVector >
::InternalClone() const
{
  LightObject::Pointer loPtr = Superclass::InternalClone();
  typename Self::Pointer membershipFunction =
    dynamic_cast<Self *>(loPtr.GetPointer());
  if(membershipFunction.IsNull())
    {
    itkExceptionMacro(<< "downcast to type "
                      << this->GetNameOfClass()
                      << " failed.");
    }

  membershipFunction->SetMeasurementVectorSize( this->GetMeasurementVectorSize() );
  membershipFunction->SetMean( this->GetMean() );
  membershipFunction->SetCovariance( this->GetCovariance() );

  return loPtr;
}

} // end namespace Statistics
} // end of namespace itk

#endif
<commit_msg>BUG: Remove multiple per-pixel allocations in Mahalanobis Membership<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/
#ifndef __itkMahalanobisDistanceMembershipFunction_hxx
#define __itkMahalanobisDistanceMembershipFunction_hxx

#include "itkMahalanobisDistanceMembershipFunction.h"

#include "vnl/vnl_vector.h"
#include "vnl/vnl_matrix.h"
#include "vnl/algo/vnl_matrix_inverse.h"

namespace itk
{
namespace Statistics
{
template< typename TVector >
MahalanobisDistanceMembershipFunction< TVector >
::MahalanobisDistanceMembershipFunction()
{
  NumericTraits<MeanVectorType>::SetLength(m_Mean, this->GetMeasurementVectorSize());
  m_Mean.Fill(0.0f);

  m_Covariance.SetSize(this->GetMeasurementVectorSize(), this->GetMeasurementVectorSize());
  m_Covariance.SetIdentity();

  m_InverseCovariance = m_Covariance;

  m_CovarianceNonsingular = true;
}

template< typename TVector >
void
MahalanobisDistanceMembershipFunction< TVector >
::SetMean(const MeanVectorType & mean)
{
  if ( this->GetMeasurementVectorSize() )
    {
    MeasurementVectorTraits::Assert(mean,
                                    this->GetMeasurementVectorSize(),
                                    "GaussianMembershipFunction::SetMean(): Size of mean vector specified does not match the size of a measurement vector.");
    }
  else
    {
    // not already set, cache the size
    this->SetMeasurementVectorSize( mean.Size() );
    }

  if ( m_Mean != mean )
    {
    m_Mean = mean;
    this->Modified();
    }
}

template< typename TVector >
void
MahalanobisDistanceMembershipFunction< TVector >
::SetCovariance(const CovarianceMatrixType & cov)
{
  // Sanity check
  if ( cov.GetVnlMatrix().rows() != cov.GetVnlMatrix().cols() )
    {
    itkExceptionMacro(<< "Covariance matrix must be square");
    }
  if ( this->GetMeasurementVectorSize() )
    {
    if ( cov.GetVnlMatrix().rows() != this->GetMeasurementVectorSize() )
      {
      itkExceptionMacro(<< "Length of measurement vectors must be"
                        << " the same as the size of the covariance.");
      }
    }
  else
    {
    // not already set, cache the size
    this->SetMeasurementVectorSize( cov.GetVnlMatrix().rows() );
    }

  if (m_Covariance == cov)
    {
    // no need to copy the matrix, compute the inverse, or the normalization
    return;
    }

  m_Covariance = cov;

  // the inverse of the covariance matrix is first computed by SVD
  vnl_matrix_inverse< double > inv_cov( m_Covariance.GetVnlMatrix() );

  // the determinant is then costless this way
  double det = inv_cov.determinant_magnitude();

  if( det < 0.)
    {
    itkExceptionMacro( << "det( m_Covariance ) < 0" );
    }

  // 1e-6 is an arbitrary value!!!
  const double singularThreshold = 1.0e-6;
  m_CovarianceNonsingular = ( det > singularThreshold );

  if( m_CovarianceNonsingular )
    {
    // allocate the memory for m_InverseCovariance matrix
    m_InverseCovariance.GetVnlMatrix() = inv_cov.inverse();
    }
  else
    {
    // define the inverse to be diagonal with large values along the
    // diagonal. value chosen so (X-M)'inv(C)*(X-M) will usually stay
    // below NumericTraits<double>::max()
    const double aLargeDouble = std::pow(NumericTraits<double>::max(), 1.0/3.0)
      / (double) this->GetMeasurementVectorSize();
    m_InverseCovariance.SetSize(this->GetMeasurementVectorSize(), this->GetMeasurementVectorSize());
    m_InverseCovariance.SetIdentity();
    m_InverseCovariance *= aLargeDouble;
    }

  this->Modified();
}

template< typename TVector >
double
MahalanobisDistanceMembershipFunction< TVector >
::Evaluate(const MeasurementVectorType & measurement) const
{
  const MeasurementVectorSizeType measurementVectorSize =
    this->GetMeasurementVectorSize();

  // Our inverse covariance is always well formed. When the covariance
  // is singular, we use a diagonal inverse covariance with a large diagnonal

  // temp = ( y - mean )^t * InverseCovariance * ( y - mean )
  //
  // This is manually done to remove dynamic memory allocation:
  // double temp = dot_product( tempVector,  m_InverseCovariance.GetVnlMatrix() * tempVector );
  //
  double temp = 0.0;
  for (unsigned int r = 0; r < measurementVectorSize; ++r)
    {
    double rowdot = 0.0;
    for(unsigned int c = 0; c < measurementVectorSize; ++c)
      {
      rowdot += m_InverseCovariance(r, c) * ( measurement[c] - m_Mean[c] );
      }
    temp += rowdot * ( measurement[r] - m_Mean[r] );
    }

  return temp;
}

template< typename TVector >
void
MahalanobisDistanceMembershipFunction< TVector >
::PrintSelf(std::ostream & os, Indent indent) const
{
  Superclass::PrintSelf(os, indent);

  os << indent << "Mean: " << m_Mean << std::endl;
  os << indent << "Covariance: " << std::endl;
  os << m_Covariance.GetVnlMatrix();
  os << indent << "InverseCovariance: " << std::endl;
  os << indent << m_InverseCovariance.GetVnlMatrix();
  os << indent << "Covariance nonsingular: " <<
    (m_CovarianceNonsingular ? "true" : "false") << std::endl;
}

template< typename TVector >
typename LightObject::Pointer
MahalanobisDistanceMembershipFunction< TVector >
::InternalClone() const
{
  LightObject::Pointer loPtr = Superclass::InternalClone();
  typename Self::Pointer membershipFunction =
    dynamic_cast<Self *>(loPtr.GetPointer());
  if(membershipFunction.IsNull())
    {
    itkExceptionMacro(<< "downcast to type "
                      << this->GetNameOfClass()
                      << " failed.");
    }

  membershipFunction->SetMeasurementVectorSize( this->GetMeasurementVectorSize() );
  membershipFunction->SetMean( this->GetMean() );
  membershipFunction->SetCovariance( this->GetCovariance() );

  return loPtr;
}

} // end namespace Statistics
} // end of namespace itk

#endif
<|endoftext|>


<commit_before>#include <mk_test.h>

#include "../src/Xml/XmlParser.hpp"
#include "../src/Xsl/Xsl.hpp"

#define xml_code(code) \
    ((const char *) #code)

int
main()
{
    return 0;
}
<commit_msg>Added test structure<commit_after>#include <mk_test.h>

#include "../src/Xml/XmlParser.hpp"
#include "../src/Xsl/Xsl.hpp"

#define xml_code(code) \
    ((const char *) #code)
void
testXslTransform()
{
    // xml
    std::string xmlContent (xml_code(
        <root>
            <cd>
                <title>Title A</title>
            </cd>

            <cd>
                <title>Title B</title>
            </cd>
        </root>
    ));

    Xml::Log xmlLog;

    Xml::Document * xmlDoc = Xml::parse(xmlContent, &xmlLog);

    // xsl
    std::string xslContent (xml_code(
        <xsl:stylesheet>
            <xsl:template match="cd">
                <xsl:value-of select="title" />
            </xsl:template>
        </xsl:stylesheet>
    ));
    Xml::Log xslLog;
    Xml::Document * xslDoc = Xml::parse(xslContent, &xslLog);

    delete xmlDoc;
    delete xslDoc;
}

int
main()
{
    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <string.h>
#include "../src/regexmacros.h"

using namespace std;

int main (int argc, char **argv) {
  const string rs (RE_DOT_STAR RE_NONWHITE_CHAR_CLASS RE_DOT_STAR);
  cerr << "Testing regex " << rs << endl;

  const regex nonwhite_re (rs, regex_constants::basic);

  smatch sm;
  for (char c = 33; c <= 126; ++c) {
    string s = " " + string(1,c) + " ";
    if (!regex_match (s, sm, nonwhite_re))
      exit (EXIT_FAILURE);
  }

  string w = "   ";
  if (regex_match (w, sm, nonwhite_re))
    exit (EXIT_FAILURE);

  exit (EXIT_SUCCESS);
}
<commit_msg>t/testregex.cpp<commit_after>#include <iostream>
#include <fstream>
#include <string.h>
#include "../src/regexmacros.h"

using namespace std;

int main (int argc, char **argv) {
  const string rs (RE_DOT_STAR RE_NONWHITE_CHAR_CLASS RE_DOT_STAR);
  //  cerr << "Testing regex " << rs << endl;
  const regex nonwhite_re (rs, regex_constants::basic);

  smatch sm;
  for (char c = 33; c <= 126; ++c) {
    string s = " " + string(1,c) + " ";
    if (!regex_match (s, sm, nonwhite_re))
      exit (EXIT_FAILURE);
  }

  string w = "   ";
  if (regex_match (w, sm, nonwhite_re))
    exit (EXIT_FAILURE);

  exit (EXIT_SUCCESS);
}
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
/* Patch from Trevor Smigiel                                   */
#if !defined(HPUXDEFINITIONS_HEADER_GUARD_1357924680)
#define HPUXDEFINITIONS_HEADER_GUARD_1357924680

// ---------------------------------------------------------------------------
//  A define in the build for each project is also used to control whether
//  the export keyword is from the project's viewpoint or the client's.
//  These defines provide the platform specific keywords that they need
//  to do this.
// ---------------------------------------------------------------------------

#define XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT
#define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT

#define XALAN_OLD_STREAM_HEADERS
#define XALAN_NO_IOSFWD
#define XALAN_RTTI_AVAILABLE
#define XALAN_NO_TYPEINFO
#define XALAN_SGI_BASED_STL
#define XALAN_NO_NAMESPACES
#define XALAN_XALANDOMCHAR_USHORT_MISMATCH
#define XALAN_NO_STD_ALLOCATORS

#define XALAN_BIG_ENDIAN

#endif  // HPUXDEFINITIONS_HEADER_GUARD_1357924680

<commit_msg>HP has posix thread support.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
/* Patch from Trevor Smigiel                                   */
#if !defined(HPUXDEFINITIONS_HEADER_GUARD_1357924680)
#define HPUXDEFINITIONS_HEADER_GUARD_1357924680

// ---------------------------------------------------------------------------
//  A define in the build for each project is also used to control whether
//  the export keyword is from the project's viewpoint or the client's.
//  These defines provide the platform specific keywords that they need
//  to do this.
// ---------------------------------------------------------------------------

#define XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT
#define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT

#define XALAN_OLD_STREAM_HEADERS
#define XALAN_NO_IOSFWD
#define XALAN_RTTI_AVAILABLE
#define XALAN_NO_TYPEINFO
#define XALAN_SGI_BASED_STL
#define XALAN_NO_NAMESPACES
#define XALAN_XALANDOMCHAR_USHORT_MISMATCH
#define XALAN_NO_STD_ALLOCATORS
#define XALAN_POSIX2_AVAILABLE

#define XALAN_BIG_ENDIAN

#endif  // HPUXDEFINITIONS_HEADER_GUARD_1357924680

<|endoftext|>


<commit_before>#include "wrapper_common.h"

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include "mkl_service.h"
#include "mkl_dfti.h"

template<typename Data, typename Precision, typename FFT>
inline MKL_LONG fft_1d_inplace(const MKL_LONG n, Data x[], const Precision forward_scale, const Precision backward_scale, const DFTI_CONFIG_VALUE precision, const DFTI_CONFIG_VALUE domain, FFT fft)
{
	MKL_LONG status = 0;
	DFTI_DESCRIPTOR_HANDLE descriptor = 0;
	status = DftiCreateDescriptor(&descriptor, precision, domain, 1, n);
	if (0 != status) goto failed;

	status = DftiSetValue(descriptor, DFTI_FORWARD_SCALE, forward_scale);
	if (0 != status) goto failed;

	status = DftiSetValue(descriptor, DFTI_BACKWARD_SCALE, backward_scale);
	if (0 != status) goto failed;

	status = DftiCommitDescriptor(descriptor);
	if (0 != status) goto failed;

	status = fft(descriptor, x);
	if (0 != status) goto failed;

cleanup:
	DftiFreeDescriptor(&descriptor);
	return status;

failed:
	status = 1;
	goto cleanup;
}

extern "C" {

	DLLEXPORT MKL_LONG z_fft_forward_inplace(const MKL_LONG n, const double scaling, MKL_Complex16 x[])
	{
		return fft_1d_inplace(n, x, scaling, 1.0, DFTI_DOUBLE, DFTI_COMPLEX, DftiComputeForward);
	}

	DLLEXPORT MKL_LONG c_fft_forward_inplace(const MKL_LONG n, const float scaling, MKL_Complex8 x[])
	{
		return fft_1d_inplace(n, x, scaling, 1.0f, DFTI_SINGLE, DFTI_COMPLEX, DftiComputeForward);
	}

	DLLEXPORT MKL_LONG z_fft_backward_inplace(const MKL_LONG n, const double scaling, MKL_Complex16 x[])
	{
		return fft_1d_inplace(n, x, 1.0, scaling, DFTI_DOUBLE, DFTI_COMPLEX, DftiComputeBackward);
	}

	DLLEXPORT MKL_LONG c_fft_backward_inplace(const MKL_LONG n, const float scaling, MKL_Complex8 x[])
	{
		return fft_1d_inplace(n, x, 1.0f, scaling, DFTI_SINGLE, DFTI_COMPLEX, DftiComputeBackward);
	}
}
<commit_msg>FFT: do not mask MKL error status<commit_after>#include "wrapper_common.h"

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include "mkl_service.h"
#include "mkl_dfti.h"

template<typename Data, typename Precision, typename FFT>
inline MKL_LONG fft_1d_inplace(const MKL_LONG n, Data x[], const Precision forward_scale, const Precision backward_scale, const DFTI_CONFIG_VALUE precision, const DFTI_CONFIG_VALUE domain, FFT fft)
{
	MKL_LONG status = 0;
	DFTI_DESCRIPTOR_HANDLE descriptor = 0;
	status = DftiCreateDescriptor(&descriptor, precision, domain, 1, n);
	if (0 != status) goto cleanup;

	status = DftiSetValue(descriptor, DFTI_FORWARD_SCALE, forward_scale);
	if (0 != status) goto cleanup;

	status = DftiSetValue(descriptor, DFTI_BACKWARD_SCALE, backward_scale);
	if (0 != status) goto cleanup;

	status = DftiCommitDescriptor(descriptor);
	if (0 != status) goto cleanup;

	status = fft(descriptor, x);
	if (0 != status) goto cleanup;

cleanup:
	DftiFreeDescriptor(&descriptor);
	return status;
}

extern "C" {

	DLLEXPORT MKL_LONG z_fft_forward_inplace(const MKL_LONG n, const double scaling, MKL_Complex16 x[])
	{
		return fft_1d_inplace(n, x, scaling, 1.0, DFTI_DOUBLE, DFTI_COMPLEX, DftiComputeForward);
	}

	DLLEXPORT MKL_LONG c_fft_forward_inplace(const MKL_LONG n, const float scaling, MKL_Complex8 x[])
	{
		return fft_1d_inplace(n, x, scaling, 1.0f, DFTI_SINGLE, DFTI_COMPLEX, DftiComputeForward);
	}

	DLLEXPORT MKL_LONG z_fft_backward_inplace(const MKL_LONG n, const double scaling, MKL_Complex16 x[])
	{
		return fft_1d_inplace(n, x, 1.0, scaling, DFTI_DOUBLE, DFTI_COMPLEX, DftiComputeBackward);
	}

	DLLEXPORT MKL_LONG c_fft_backward_inplace(const MKL_LONG n, const float scaling, MKL_Complex8 x[])
	{
		return fft_1d_inplace(n, x, 1.0f, scaling, DFTI_SINGLE, DFTI_COMPLEX, DftiComputeBackward);
	}
}
<|endoftext|>


<commit_before>/*-
 * Copyright (c) 2015 Masayoshi Mizutani <mizutani@sfc.wide.ad.jp>
 * 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 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 FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <string.h>
#include "./gtest.h"
#include "../src/fluent/message.hpp"

TEST(Message, basic) {
  fluent::Message::Map *obj = new fluent::Message::Map();
  msgpack::sbuffer sbuf;
  msgpack::packer<msgpack::sbuffer> pkr(&sbuf);

  EXPECT_TRUE(obj->set("abc", 1));

  /*
    require 'msgpack'; a=[]; {'abc'=>1}.to_msgpack.each_byte{|v|
    a.push(sprintf("0x%02X", v))};puts "{#{a.join(', ')}};"
  */
  uint8_t data[] = {0x81, 0xa3, 0x61, 0x62, 0x63, 0x01};
  obj->to_msgpack(&pkr);
  EXPECT_EQ(sbuf.size(), sizeof(data));
  EXPECT_TRUE(0 == memcmp(sbuf.data(), data, sizeof(data)));

}

TEST(Message, Map) {
  fluent::Message::Map *obj = new fluent::Message::Map();
  msgpack::sbuffer sbuf;
  msgpack::packer<msgpack::sbuffer> pkr(&sbuf);

  // Bool
  EXPECT_TRUE(obj->set("bool", true));
  // Float
  EXPECT_TRUE(obj->set("float", 34.567));
  // Fixnum
  EXPECT_TRUE(obj->set("int", 2345));
  // String
  EXPECT_TRUE(obj->set("str", "test"));

  /*
    d = {'bool'=>true, 'float'=>34.567, 'int'=>2345, 'str'=>'test', }
    require 'msgpack'; a=[]; d.to_msgpack.each_byte{|v|
    a.push(sprintf("0x%02X", v))};puts "{#{a.join(', ')}};"
  */
  uint8_t expect[] = {0x84, 0xA4, 0x62, 0x6F, 0x6F, 0x6C, 0xC3, 0xA5,
                      0x66, 0x6C, 0x6F, 0x61, 0x74, 0xCB, 0x40, 0x41,
                      0x48, 0x93, 0x74, 0xBC, 0x6A, 0x7F, 0xA3, 0x69,
                      0x6E, 0x74, 0xCD, 0x09, 0x29, 0xA3, 0x73, 0x74,
                      0x72, 0xA4, 0x74, 0x65, 0x73, 0x74};

  obj->to_msgpack(&pkr);
  EXPECT_EQ(sbuf.size(), sizeof(expect));
  EXPECT_TRUE(0 == memcmp(sbuf.data(), expect, sizeof(expect)));
}

TEST(Message, Array) {
  fluent::Message::Array *obj = new fluent::Message::Array();
  msgpack::sbuffer sbuf;
  msgpack::packer<msgpack::sbuffer> pkr(&sbuf);

  // Bool
  obj->push(true);
  // Float
  obj->push(34.567);
  // Fixnum
  obj->push(2345);
  // String
  obj->push("test");

  /*
    d = [true, 34.567, 2345, 'test']
    require 'msgpack'; a=[]; d.to_msgpack.each_byte{|v|
    a.push(sprintf("0x%02X", v))};puts "{#{a.join(', ')}};"
  */

  uint8_t expect[] = {0x94, 0xC3, 0xCB, 0x40, 0x41, 0x48, 0x93, 0x74,
                      0xBC, 0x6A, 0x7F, 0xCD, 0x09, 0x29, 0xA4, 0x74,
                      0x65, 0x73, 0x74};

  obj->to_msgpack(&pkr);
  EXPECT_EQ(sbuf.size(), sizeof(expect));
  EXPECT_TRUE(0 == memcmp(sbuf.data(), expect, sizeof(expect)));
}

TEST(Message, NestArray) {
  fluent::Message::Array *obj = new fluent::Message::Array();
  msgpack::sbuffer sbuf;
  msgpack::packer<msgpack::sbuffer> pkr(&sbuf);
  obj->push("a");  // ["a"]
  fluent::Message::Array *arr = obj->retain_array(); // ["a", []]
  arr->push("b"); // ["a", ["b"]]
  arr->push(1);   // ["a", ["b", 1]]
  fluent::Message::Map *map = obj->retain_map();  // ["a", ["b", 1], {}]
  map->set("c", 1); // ["a", ["b", 1], {"c": 1}}]

  /*
    d=["a",["b", 1],{"c"=>1}]
    require 'msgpack'; a=[]; d.to_msgpack.each_byte{|v|
    a.push(sprintf("0x%02X", v))};puts "{#{a.join(', ')}};"
   */
  uint8_t expect[] = {0x93, 0xA1, 0x61, 0x92, 0xA1, 0x62, 0x01, 0x81,
                      0xA1, 0x63, 0x01};

  obj->to_msgpack(&pkr);
  EXPECT_EQ(sbuf.size(), sizeof(expect));
  EXPECT_TRUE(0 == memcmp(sbuf.data(), expect, sizeof(expect)));
}

TEST(Message, NestMap) {
  fluent::Message::Map *obj = new fluent::Message::Map();
  msgpack::sbuffer sbuf;
  msgpack::packer<msgpack::sbuffer> pkr(&sbuf);

  obj->set("a", 1);  // {"a":1}
  fluent::Message::Array *arr = obj->retain_array("b"); // {"a":1, "b": []}
  arr->push(2); // {"a":1, "b": [2]}
  arr->push(3); // {"a":1, "b": [2, 3]}
  fluent::Message::Map *map = obj->retain_map("c");
  // {"a":1, "b": [2, 3], "c": {}}
  map->set("d", 4);   // {"a":1, "b": [2, 3], "c": {"d":4}}

  /*
    d={"a"=>1, "b"=>[2,3], "c"=>{"d"=>4}}
    require 'msgpack'; a=[]; d.to_msgpack.each_byte{|v|
    a.push(sprintf("0x%02X", v))};puts "{#{a.join(', ')}};"
   */
    uint8_t expect[] = {0x83, 0xA1, 0x61, 0x01, 0xA1, 0x62, 0x92, 0x02,
                        0x03, 0xA1, 0x63, 0x81, 0xA1, 0x64, 0x04};

  obj->to_msgpack(&pkr);
  EXPECT_EQ(sbuf.size(), sizeof(expect));
  EXPECT_TRUE(0 == memcmp(sbuf.data(), expect, sizeof(expect)));
}

TEST(Message, link) {
  // TODO: add tests
}
<commit_msg>add Fixture as MessageTest to test Message, and overwrite test<commit_after>/*-
 * Copyright (c) 2015 Masayoshi Mizutani <mizutani@sfc.wide.ad.jp>
 * 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 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 FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <signal.h>
#include "./gtest.h"
#include "../src/fluent/message.hpp"
#include "../src/debug.h"

class MessageTest : public ::testing::Test {
private:
  enum { RP = 0, WP = 1 };

protected:
  msgpack::sbuffer sbuf_;
  msgpack::packer<msgpack::sbuffer> pkr_;
  MessageTest() : pkr_(&(this->sbuf_)) {}
  virtual ~MessageTest() {}
  virtual void SetUp() {}
  virtual void TearDown() {}

  std::string encode_msgpack(const std::string ruby_code) {
    std::stringstream ss;
    ss << "d=" << ruby_code << ";" <<
      "require 'msgpack'; a=[]; STDOUT.write(d.to_msgpack) ";

    int pipe_c2p[2], pipe_p2c[2];
    pipe(pipe_c2p);
    pipe(pipe_p2c);

    pid_t pid = fork();
    if (pid == 0) {
      // Running as child.
      std::vector<std::string> arg = {"ruby"};
      char **argv = new char*[arg.size() + 1];
      for (size_t i = 0; i < arg.size(); i++) {
        argv[i] = const_cast<char*>(arg[i].c_str());
      }
      argv[arg.size()] = NULL;

      close(pipe_p2c[WP]);
      close(pipe_c2p[RP]);

      dup2(pipe_p2c[RP], 0);
      dup2(pipe_c2p[WP], 1);
      close(pipe_p2c[RP]);
      close(pipe_c2p[WP]);

      if (execvp("ruby", static_cast<char *const *>(argv)) < 0) {
        perror("execvp");
      }
    }

    // Running as parent.
    write(pipe_p2c[WP], ss.str().c_str(), ss.str().length());
    close(pipe_p2c[WP]);
    char buf[BUFSIZ];
    int stat;
    int rsize = read(pipe_c2p[RP], buf, BUFSIZ);
    int rc = waitpid(pid, &stat, 0);
    EXPECT_EQ(pid, rc);

    std::string res(buf, rsize);
    return res;
  }
};

TEST(Message, basic) {
  fluent::Message::Map *obj = new fluent::Message::Map();
  msgpack::sbuffer sbuf;
  msgpack::packer<msgpack::sbuffer> pkr(&sbuf);

  EXPECT_TRUE(obj->set("abc", 1));

  /*
    require 'msgpack'; a=[]; {'abc'=>1}.to_msgpack.each_byte{|v|
    a.push(sprintf("0x%02X", v))};puts "{#{a.join(', ')}};"
  */
  uint8_t data[] = {0x81, 0xa3, 0x61, 0x62, 0x63, 0x01};
  obj->to_msgpack(&pkr);
  EXPECT_EQ(sbuf.size(), sizeof(data));
  EXPECT_TRUE(0 == memcmp(sbuf.data(), data, sizeof(data)));
}

TEST(Message, Map) {
  fluent::Message::Map *obj = new fluent::Message::Map();
  msgpack::sbuffer sbuf;
  msgpack::packer<msgpack::sbuffer> pkr(&sbuf);

  // Bool
  EXPECT_TRUE(obj->set("bool", true));
  // Float
  EXPECT_TRUE(obj->set("float", 34.567));
  // Fixnum
  EXPECT_TRUE(obj->set("int", 2345));
  // String
  EXPECT_TRUE(obj->set("str", "test"));

  /*
    d = {'bool'=>true, 'float'=>34.567, 'int'=>2345, 'str'=>'test', }
    require 'msgpack'; a=[]; d.to_msgpack.each_byte{|v|
    a.push(sprintf("0x%02X", v))};puts "{#{a.join(', ')}};"
  */
  uint8_t expect[] = {0x84, 0xA4, 0x62, 0x6F, 0x6F, 0x6C, 0xC3, 0xA5,
                      0x66, 0x6C, 0x6F, 0x61, 0x74, 0xCB, 0x40, 0x41,
                      0x48, 0x93, 0x74, 0xBC, 0x6A, 0x7F, 0xA3, 0x69,
                      0x6E, 0x74, 0xCD, 0x09, 0x29, 0xA3, 0x73, 0x74,
                      0x72, 0xA4, 0x74, 0x65, 0x73, 0x74};

  obj->to_msgpack(&pkr);
  EXPECT_EQ(sbuf.size(), sizeof(expect));
  EXPECT_TRUE(0 == memcmp(sbuf.data(), expect, sizeof(expect)));
}

TEST(Message, Array) {
  fluent::Message::Array *obj = new fluent::Message::Array();
  msgpack::sbuffer sbuf;
  msgpack::packer<msgpack::sbuffer> pkr(&sbuf);

  // Bool
  obj->push(true);
  // Float
  obj->push(34.567);
  // Fixnum
  obj->push(2345);
  // String
  obj->push("test");

  /*
    d = [true, 34.567, 2345, 'test']
    require 'msgpack'; a=[]; d.to_msgpack.each_byte{|v|
    a.push(sprintf("0x%02X", v))};puts "{#{a.join(', ')}};"
  */

  uint8_t expect[] = {0x94, 0xC3, 0xCB, 0x40, 0x41, 0x48, 0x93, 0x74,
                      0xBC, 0x6A, 0x7F, 0xCD, 0x09, 0x29, 0xA4, 0x74,
                      0x65, 0x73, 0x74};

  obj->to_msgpack(&pkr);
  EXPECT_EQ(sbuf.size(), sizeof(expect));
  EXPECT_TRUE(0 == memcmp(sbuf.data(), expect, sizeof(expect)));
}

TEST(Message, NestArray) {
  fluent::Message::Array *obj = new fluent::Message::Array();
  msgpack::sbuffer sbuf;
  msgpack::packer<msgpack::sbuffer> pkr(&sbuf);
  obj->push("a");  // ["a"]
  fluent::Message::Array *arr = obj->retain_array(); // ["a", []]
  ASSERT_TRUE(arr != nullptr);
  arr->push("b"); // ["a", ["b"]]
  arr->push(1);   // ["a", ["b", 1]]
  fluent::Message::Map *map = obj->retain_map();  // ["a", ["b", 1], {}]
  ASSERT_TRUE(map != nullptr);
  map->set("c", 1); // ["a", ["b", 1], {"c": 1}}]

  /*
    d=["a",["b", 1],{"c"=>1}]
    require 'msgpack'; a=[]; d.to_msgpack.each_byte{|v|
    a.push(sprintf("0x%02X", v))};puts "{#{a.join(', ')}};"
   */
  uint8_t expect[] = {0x93, 0xA1, 0x61, 0x92, 0xA1, 0x62, 0x01, 0x81,
                      0xA1, 0x63, 0x01};

  obj->to_msgpack(&pkr);
  EXPECT_EQ(sbuf.size(), sizeof(expect));
  EXPECT_TRUE(0 == memcmp(sbuf.data(), expect, sizeof(expect)));
}

TEST(Message, NestMap) {
  fluent::Message::Map *obj = new fluent::Message::Map();
  msgpack::sbuffer sbuf;
  msgpack::packer<msgpack::sbuffer> pkr(&sbuf);

  obj->set("a", 1);  // {"a":1}
  fluent::Message::Array *arr = obj->retain_array("b"); // {"a":1, "b": []}
  ASSERT_TRUE(arr != nullptr);
  arr->push(2); // {"a":1, "b": [2]}
  arr->push(3); // {"a":1, "b": [2, 3]}
  fluent::Message::Map *map = obj->retain_map("c");
  // {"a":1, "b": [2, 3], "c": {}}
  ASSERT_TRUE(map != nullptr);
  map->set("d", 4);   // {"a":1, "b": [2, 3], "c": {"d":4}}

  /*
    d={"a"=>1, "b"=>[2,3], "c"=>{"d"=>4}}
    require 'msgpack'; a=[]; d.to_msgpack.each_byte{|v|
    a.push(sprintf("0x%02X", v))};puts "{#{a.join(', ')}};"
   */
  uint8_t expect[] = {0x83, 0xA1, 0x61, 0x01, 0xA1, 0x62, 0x92, 0x02,
                      0x03, 0xA1, 0x63, 0x81, 0xA1, 0x64, 0x04};

  obj->to_msgpack(&pkr);
  EXPECT_EQ(sbuf.size(), sizeof(expect));
  EXPECT_TRUE(0 == memcmp(sbuf.data(), expect, sizeof(expect)));
}

TEST_F(MessageTest, NotOverwriteMap) {
  fluent::Message::Map *obj = new fluent::Message::Map();

  EXPECT_TRUE(obj->set("a", 1));
  EXPECT_FALSE(obj->set("a", 2));

  std::string expect = encode_msgpack("{'a'=>1}");

  obj->to_msgpack(&pkr_);
  EXPECT_EQ(sbuf_.size(), expect.length());
  EXPECT_TRUE(0 == memcmp(sbuf_.data(), expect.data(), sbuf_.size()));
}

TEST(Message, link) {
  // TODO: add tests
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ppapi/tests/test_var.h"

#include "ppapi/c/ppb_var.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/var.h"
#include "ppapi/tests/test_instance.h"

static uint32_t kInvalidLength = static_cast<uint32_t>(-1);

REGISTER_TEST_CASE(Var);

bool TestVar::Init() {
  var_interface_ = reinterpret_cast<PPB_Var const*>(
      pp::Module::Get()->GetBrowserInterface(PPB_VAR_INTERFACE));
  return !!var_interface_;
}

void TestVar::RunTest() {
  instance_->LogTest("InvalidUtf8", TestInvalidUtf8());
  instance_->LogTest("NullInputInUtf8Conversion",
                     TestNullInputInUtf8Conversion());
  instance_->LogTest("ValidUtf8", TestValidUtf8());
  instance_->LogTest("Utf8WithEmbeddedNulls", TestUtf8WithEmbeddedNulls());
  instance_->LogTest("VarToUtf8ForWrongType", TestVarToUtf8ForWrongType());
}

std::string TestVar::TestInvalidUtf8() {
  // utf8じゃない (japanese for "is not utf8") in shift-jis encoding.
  static const char kSjisString[] = "utf8\x82\xb6\x82\xe1\x82\xc8\x82\xa2";
  pp::Var sjis(kSjisString);
  if (!sjis.is_null())
    return "Non-UTF8 string permitted.";

  return "";
}

std::string TestVar::TestNullInputInUtf8Conversion() {
  // This test talks directly to the C interface to access edge cases that
  // cannot be exercised via the C++ interface.
  PP_Var converted_string;

  // 0-length string should not dereference input string, and should produce
  // an empty string.
  converted_string = var_interface_->VarFromUtf8(NULL, 0);
  if (converted_string.type != PP_VARTYPE_STRING) {
    return "Expected 0 length to return empty string.";
  }

  // Now convert it back.
  uint32_t length = kInvalidLength;
  const char* result = NULL;
  result = var_interface_->VarToUtf8(converted_string, &length);
  if (length != 0) {
    return "Expected 0 length string on conversion.";
  }
  if (result == NULL) {
    return "Expected a non-null result for 0-lengthed string from VarToUtf8.";
  }

  return "";
}

std::string TestVar::TestValidUtf8() {
  // From UTF8 string -> PP_Var.
  // Chinese for "I am utf8."
  static const char kValidUtf8[] = "\xe6\x88\x91\xe6\x98\xafutf8.";
  pp::Var converted_string(kValidUtf8);

  if (converted_string.is_null())
    return "Unable to convert valid utf8 to var.";

  // Since we're already here, test PP_Var back to UTF8 string.
  std::string returned_string = converted_string.AsString();

  // We need to check against 1 less than sizeof because the resulting string
  // is technically not NULL terminated by API design.
  if (returned_string.size() != sizeof(kValidUtf8) - 1) {
    return "Unable to convert utf8 string back from var.";
  }
  if (returned_string != kValidUtf8) {
    return "String mismatches on conversion back from PP_Var.";
  }

  return "";
}

std::string TestVar::TestUtf8WithEmbeddedNulls() {
  // From UTF8 string with embedded nulls -> PP_Var.
  // Chinese for "also utf8."
  static const char kUtf8WithEmbededNull[] = "\xe6\xb9\x9f\xe6\x98\xaf\0utf8.";
  std::string orig_string(kUtf8WithEmbededNull,
                          sizeof(kUtf8WithEmbededNull) -1);
  pp::Var converted_string(orig_string);

  if (converted_string.is_null())
    return "Unable to convert utf8 with embedded nulls to var.";

  // Since we're already here, test PP_Var back to UTF8 string.
  std::string returned_string = converted_string.AsString();

  if (returned_string.size() != orig_string.size()) {
    return "Unable to convert utf8 with embedded nulls back from var.";
  }
  if (returned_string != orig_string) {
    return "String mismatches on conversion back from PP_Var.";
  }

  return "";
}

std::string TestVar::TestVarToUtf8ForWrongType() {
  uint32_t length = kInvalidLength;
  const char* result = NULL;
  result = var_interface_->VarToUtf8(PP_MakeVoid(), &length);
  if (length != 0) {
    return "Expected 0 on string conversion from Void var.";
  }
  if (result != NULL) {
    return "Expected NULL on string conversion from Void var.";
  }

  length = kInvalidLength;
  result = NULL;
  result = var_interface_->VarToUtf8(PP_MakeNull(), &length);
  if (length != 0) {
    return "Expected 0 on string conversion from Null var.";
  }
  if (result != NULL) {
    return "Expected NULL on string conversion from Null var.";
  }

  length = kInvalidLength;
  result = NULL;
  result = var_interface_->VarToUtf8(PP_MakeBool(true), &length);
  if (length != 0) {
    return "Expected 0 on string conversion from Bool var.";
  }
  if (result != NULL) {
    return "Expected NULL on string conversion from Bool var.";
  }

  length = kInvalidLength;
  result = NULL;
  result = var_interface_->VarToUtf8(PP_MakeInt32(1), &length);
  if (length != 0) {
    return "Expected 0 on string conversion from Int32 var.";
  }
  if (result != NULL) {
    return "Expected NULL on string conversion from Int32 var.";
  }

  length = kInvalidLength;
  result = NULL;
  result = var_interface_->VarToUtf8(PP_MakeDouble(1.0), &length);
  if (length != 0) {
    return "Expected 0 on string conversion from Double var.";
  }
  if (result != NULL) {
    return "Expected NULL on string conversion from Double var.";
  }

  return "";
}
<commit_msg>Fix the test build.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ppapi/tests/test_var.h"

#include "ppapi/c/ppb_var.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/var.h"
#include "ppapi/tests/testing_instance.h"

static uint32_t kInvalidLength = static_cast<uint32_t>(-1);

REGISTER_TEST_CASE(Var);

bool TestVar::Init() {
  var_interface_ = reinterpret_cast<PPB_Var const*>(
      pp::Module::Get()->GetBrowserInterface(PPB_VAR_INTERFACE));
  return !!var_interface_;
}

void TestVar::RunTest() {
  instance_->LogTest("InvalidUtf8", TestInvalidUtf8());
  instance_->LogTest("NullInputInUtf8Conversion",
                     TestNullInputInUtf8Conversion());
  instance_->LogTest("ValidUtf8", TestValidUtf8());
  instance_->LogTest("Utf8WithEmbeddedNulls", TestUtf8WithEmbeddedNulls());
  instance_->LogTest("VarToUtf8ForWrongType", TestVarToUtf8ForWrongType());
}

std::string TestVar::TestInvalidUtf8() {
  // utf8じゃない (japanese for "is not utf8") in shift-jis encoding.
  static const char kSjisString[] = "utf8\x82\xb6\x82\xe1\x82\xc8\x82\xa2";
  pp::Var sjis(kSjisString);
  if (!sjis.is_null())
    return "Non-UTF8 string permitted.";

  return "";
}

std::string TestVar::TestNullInputInUtf8Conversion() {
  // This test talks directly to the C interface to access edge cases that
  // cannot be exercised via the C++ interface.
  PP_Var converted_string;

  // 0-length string should not dereference input string, and should produce
  // an empty string.
  converted_string = var_interface_->VarFromUtf8(NULL, 0);
  if (converted_string.type != PP_VARTYPE_STRING) {
    return "Expected 0 length to return empty string.";
  }

  // Now convert it back.
  uint32_t length = kInvalidLength;
  const char* result = NULL;
  result = var_interface_->VarToUtf8(converted_string, &length);
  if (length != 0) {
    return "Expected 0 length string on conversion.";
  }
  if (result == NULL) {
    return "Expected a non-null result for 0-lengthed string from VarToUtf8.";
  }

  return "";
}

std::string TestVar::TestValidUtf8() {
  // From UTF8 string -> PP_Var.
  // Chinese for "I am utf8."
  static const char kValidUtf8[] = "\xe6\x88\x91\xe6\x98\xafutf8.";
  pp::Var converted_string(kValidUtf8);

  if (converted_string.is_null())
    return "Unable to convert valid utf8 to var.";

  // Since we're already here, test PP_Var back to UTF8 string.
  std::string returned_string = converted_string.AsString();

  // We need to check against 1 less than sizeof because the resulting string
  // is technically not NULL terminated by API design.
  if (returned_string.size() != sizeof(kValidUtf8) - 1) {
    return "Unable to convert utf8 string back from var.";
  }
  if (returned_string != kValidUtf8) {
    return "String mismatches on conversion back from PP_Var.";
  }

  return "";
}

std::string TestVar::TestUtf8WithEmbeddedNulls() {
  // From UTF8 string with embedded nulls -> PP_Var.
  // Chinese for "also utf8."
  static const char kUtf8WithEmbededNull[] = "\xe6\xb9\x9f\xe6\x98\xaf\0utf8.";
  std::string orig_string(kUtf8WithEmbededNull,
                          sizeof(kUtf8WithEmbededNull) -1);
  pp::Var converted_string(orig_string);

  if (converted_string.is_null())
    return "Unable to convert utf8 with embedded nulls to var.";

  // Since we're already here, test PP_Var back to UTF8 string.
  std::string returned_string = converted_string.AsString();

  if (returned_string.size() != orig_string.size()) {
    return "Unable to convert utf8 with embedded nulls back from var.";
  }
  if (returned_string != orig_string) {
    return "String mismatches on conversion back from PP_Var.";
  }

  return "";
}

std::string TestVar::TestVarToUtf8ForWrongType() {
  uint32_t length = kInvalidLength;
  const char* result = NULL;
  result = var_interface_->VarToUtf8(PP_MakeVoid(), &length);
  if (length != 0) {
    return "Expected 0 on string conversion from Void var.";
  }
  if (result != NULL) {
    return "Expected NULL on string conversion from Void var.";
  }

  length = kInvalidLength;
  result = NULL;
  result = var_interface_->VarToUtf8(PP_MakeNull(), &length);
  if (length != 0) {
    return "Expected 0 on string conversion from Null var.";
  }
  if (result != NULL) {
    return "Expected NULL on string conversion from Null var.";
  }

  length = kInvalidLength;
  result = NULL;
  result = var_interface_->VarToUtf8(PP_MakeBool(true), &length);
  if (length != 0) {
    return "Expected 0 on string conversion from Bool var.";
  }
  if (result != NULL) {
    return "Expected NULL on string conversion from Bool var.";
  }

  length = kInvalidLength;
  result = NULL;
  result = var_interface_->VarToUtf8(PP_MakeInt32(1), &length);
  if (length != 0) {
    return "Expected 0 on string conversion from Int32 var.";
  }
  if (result != NULL) {
    return "Expected NULL on string conversion from Int32 var.";
  }

  length = kInvalidLength;
  result = NULL;
  result = var_interface_->VarToUtf8(PP_MakeDouble(1.0), &length);
  if (length != 0) {
    return "Expected 0 on string conversion from Double var.";
  }
  if (result != NULL) {
    return "Expected NULL on string conversion from Double var.";
  }

  return "";
}
<|endoftext|>


<commit_before>#include <PCU.h>
#include <MeshSim.h>
#include <SimPartitionedMesh.h>
#include <SimUtil.h>
#include <apfSIM.h>
#include <apfMDS.h>
#include <gmi.h>
#include <gmi_sim.h>
#include <apf.h>
#include <apfConvert.h>
#include <apfMesh2.h>
#include <ma.h>
#include <cassert>
#include <cstdlib>
#include <iostream>

static void fixMatches(apf::Mesh2* m)
{
  if (m->hasMatching()) {
    if (apf::alignMdsMatches(m))
      printf("fixed misaligned matches\n");
    else
      printf("matches were aligned\n");
    assert( ! apf::alignMdsMatches(m));
  }
}

static void fixPyramids(apf::Mesh2* m)
{
  if (m->getDimension() != 3)
    return; /* no pyramids exist in 2D */
  if (apf::countEntitiesOfType(m, apf::Mesh::HEX))
    return; /* meshadapt can't even look at hexes */
  ma::Input* in = ma::configureIdentity(m);
  in->shouldCleanupLayer = true;
  ma::adapt(in);
}

static void postConvert(apf::Mesh2* m)
{
  fixMatches(m);
  fixPyramids(m);
  m->verify();
}

int main(int argc, char** argv)
{
  MPI_Init(&argc, &argv);
  PCU_Comm_Init();
  if (argc != 4) {
    if(0==PCU_Comm_Self())
      std::cerr << "usage: " << argv[0] << " <model file> <simmetrix mesh> <scorec mesh>\n";
    return EXIT_FAILURE;
  }
  SimUtil_start();
  Sim_readLicenseFile(NULL);
  SimPartitionedMesh_start(&argc,&argv);
  gmi_sim_start();
  gmi_register_sim();
  pProgress progress = Progress_new();
  Progress_setDefaultCallback(progress);

  gmi_model* mdl = gmi_load(argv[1]);
  pGModel simModel = gmi_export_sim(mdl);
  pParMesh sim_mesh = PM_load(argv[2], sthreadNone, simModel, progress);
  apf::Mesh* simApfMesh = apf::createMesh(sim_mesh);

  apf::Mesh2* mesh = apf::createMdsMesh(mdl, simApfMesh);
  apf::printStats(mesh);
  apf::destroyMesh(simApfMesh);
  M_release(sim_mesh);
  postConvert(mesh);
  mesh->writeNative(argv[3]);

  mesh->destroyNative();
  apf::destroyMesh(mesh);

  Progress_delete(progress);
  gmi_sim_stop();
  SimPartitionedMesh_stop();
  Sim_unregisterAllKeys();
  SimUtil_stop();
  PCU_Comm_Free();
  MPI_Finalize();
}
<commit_msg>added --no-pyramid-fix option to convert<commit_after>#include <PCU.h>
#include <MeshSim.h>
#include <SimPartitionedMesh.h>
#include <SimUtil.h>
#include <apfSIM.h>
#include <apfMDS.h>
#include <gmi.h>
#include <gmi_sim.h>
#include <apf.h>
#include <apfConvert.h>
#include <apfMesh2.h>
#include <ma.h>
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <iostream>

static void fixMatches(apf::Mesh2* m)
{
  if (m->hasMatching()) {
    if (apf::alignMdsMatches(m))
      printf("fixed misaligned matches\n");
    else
      printf("matches were aligned\n");
    assert( ! apf::alignMdsMatches(m));
  }
}

static void fixPyramids(apf::Mesh2* m)
{
  if (m->getDimension() != 3)
    return; /* no pyramids exist in 2D */
  if (apf::countEntitiesOfType(m, apf::Mesh::HEX))
    return; /* meshadapt can't even look at hexes */
  ma::Input* in = ma::configureIdentity(m);
  in->shouldCleanupLayer = true;
  ma::adapt(in);
}

int main(int argc, char** argv)
{
  MPI_Init(&argc, &argv);
  PCU_Comm_Init();
  SimUtil_start();
  Sim_readLicenseFile(NULL);
  SimPartitionedMesh_start(&argc,&argv);

  const char* gmi_path = NULL;
  const char* sms_path = NULL;
  const char* smb_path = NULL;
  bool should_fix_pyramids = true;
  bool found_bad_arg = false;

  for (int i = 1; i < argc; ++i) {
    if (!gmi_path) {
      gmi_path = argv[i];
    } else if (!sms_path) {
      sms_path = argv[i];
    } else if (!smb_path) {
      smb_path = argv[i];
    } else if (!strcmp(argv[i], "--no-pyramid-fix")) {
      should_fix_pyramids = false;
    } else {
      if(!PCU_Comm_Self())
        std::cerr << "bad argument \"" << argv[i] << "\"\n";
      found_bad_arg = true;
    }
  }

  if (!gmi_path || !sms_path || !smb_path || found_bad_arg) {
    if(!PCU_Comm_Self()) {
      std::cerr << "usage: " << argv[0] << " [options] <model file> <simmetrix mesh> <scorec mesh>\n";
      std::cerr << "options:\n";
      std::cerr << "  --no-pyramid-fix           Disable quad-connected pyramid tetrahedronization\n";
    }
    return EXIT_FAILURE;
  }

  gmi_sim_start();
  gmi_register_sim();
  pProgress progress = Progress_new();
  Progress_setDefaultCallback(progress);

  gmi_model* mdl = gmi_load(gmi_path);
  pGModel simModel = gmi_export_sim(mdl);
  pParMesh sim_mesh = PM_load(sms_path, sthreadNone, simModel, progress);
  apf::Mesh* simApfMesh = apf::createMesh(sim_mesh);

  apf::Mesh2* mesh = apf::createMdsMesh(mdl, simApfMesh);
  apf::printStats(mesh);
  apf::destroyMesh(simApfMesh);
  M_release(sim_mesh);
  fixMatches(mesh);
  if (should_fix_pyramids) fixPyramids(mesh);
  mesh->verify();
  mesh->writeNative(smb_path);

  mesh->destroyNative();
  apf::destroyMesh(mesh);

  Progress_delete(progress);
  gmi_sim_stop();
  SimPartitionedMesh_stop();
  Sim_unregisterAllKeys();
  SimUtil_stop();
  PCU_Comm_Free();
  MPI_Finalize();
}
<|endoftext|>


<commit_before>#include <silicium/future.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/asio/io_service.hpp>

#if SILICIUM_HAS_FUTURE
#include <boost/asio/spawn.hpp>

BOOST_AUTO_TEST_CASE(future_default_constructor)
{
	Si::future<int> f;
}

BOOST_AUTO_TEST_CASE(ready_future)
{
	Si::future<int> f = Si::make_ready_future(5);
	boost::asio::io_service io;
	bool got_result = false;
	f.async_wait(io.wrap([&got_result](int result)
	{
		BOOST_REQUIRE(!got_result);
		BOOST_CHECK_EQUAL(5, result);
		got_result = true;
	}));
	BOOST_CHECK(!got_result);
	io.run();
	BOOST_CHECK(got_result);
}

#if BOOST_VERSION >= 105800
//asio::spawn should be immediately resumable since 1.58
BOOST_AUTO_TEST_CASE(future_async_wait_in_asio_spawn)
{
	Si::future<int> f = Si::make_ready_future(5);
	boost::asio::io_service io;
	bool got_result = false;
	boost::asio::spawn(io, [&got_result, &f](boost::asio::yield_context yield)
	{
		BOOST_REQUIRE(!got_result);
		int result = f.async_wait(yield);
		BOOST_CHECK_EQUAL(5, result);
		got_result = true;
	});
	BOOST_CHECK(!got_result);
	io.run();
	BOOST_CHECK(got_result);
}
#endif
#endif
<commit_msg>avoid asio::spawn when exceptions are disabled<commit_after>#include <silicium/future.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/asio/io_service.hpp>

#if SILICIUM_HAS_FUTURE

//asio::spawn should be immediately resumable since 1.58
#define SILICIUM_TEST_SPAWN ((BOOST_VERSION >= 105800) && SILICIUM_HAS_EXCEPTIONS)

#if SILICIUM_TEST_SPAWN
#include <boost/asio/spawn.hpp>
#endif

BOOST_AUTO_TEST_CASE(future_default_constructor)
{
	Si::future<int> f;
}

BOOST_AUTO_TEST_CASE(ready_future)
{
	Si::future<int> f = Si::make_ready_future(5);
	boost::asio::io_service io;
	bool got_result = false;
	f.async_wait(io.wrap([&got_result](int result)
	{
		BOOST_REQUIRE(!got_result);
		BOOST_CHECK_EQUAL(5, result);
		got_result = true;
	}));
	BOOST_CHECK(!got_result);
	io.run();
	BOOST_CHECK(got_result);
}

#if SILICIUM_TEST_SPAWN
BOOST_AUTO_TEST_CASE(future_async_wait_in_asio_spawn)
{
	Si::future<int> f = Si::make_ready_future(5);
	boost::asio::io_service io;
	bool got_result = false;
	boost::asio::spawn(io, [&got_result, &f](boost::asio::yield_context yield)
	{
		BOOST_REQUIRE(!got_result);
		int result = f.async_wait(yield);
		BOOST_CHECK_EQUAL(5, result);
		got_result = true;
	});
	BOOST_CHECK(!got_result);
	io.run();
	BOOST_CHECK(got_result);
}
#endif
#endif
<|endoftext|>


<commit_before>/////////////////////////////////////////////////////////////////////////
//
// 'ORGANIZATION AND SIMULTANEOUS FITS' RooFit tutorial macro #513
//
//  Illustration use of RooCustomizer and RooSimWSTool interface
//  in factory workspace tool in a complex standalone B physics example
//
// 04/2009 - Wouter Verkerke
//
/////////////////////////////////////////////////////////////////////////

#ifndef __CINT__
#include "RooGlobalFunc.h"
#endif
#include "RooRealVar.h"
#include "RooDataSet.h"
#include "RooGaussian.h"
#include "RooConstVar.h"
#include "RooChebychev.h"
#include "RooAddPdf.h"
#include "RooWorkspace.h"
#include "RooPlot.h"
#include "TCanvas.h"
#include "TAxis.h"
using namespace RooFit ;

void rf513_wsfactory_tools()
{
  RooWorkspace* w = new RooWorkspace("w") ;

  // B u i l d   a   c o m p l e x   e x a m p l e   p . d . f .
  // -----------------------------------------------------------

  // Make signal model for CPV: A bmixing decay function in t (convoluted with a triple Gaussian resolution model)
  //                            times a Gaussian function the reconstructed mass
  w->factory("PROD::sig(  BMixDecay::sig_t( dt[-20,20], mixState[mixed=1,unmix=-1], tagFlav[B0=1,B0bar=-1], "
                                             "tau[1.54], dm[0.472], w[0.05], dw[0],"
                                             "AddModel::gm({GaussModel(dt,biasC[-10,10],sigmaC[0.1,3],dterr[0.01,0.2]),"
                                                     	   "GaussModel(dt,0,sigmaT[3,10]),"
                                                           "GaussModel(dt,0,20)},{fracC[0,1],fracT[0,1]}),"
                                             "DoubleSided ),"
                           "Gaussian::sig_m( mes[5.20,5.30], mB0[5.20,5.30], sigmB0[0.01,0.05] )") ;

  // Make background component: A plain decay function in t times an Argus function in the reconstructed mass
  w->factory("PROD::bkg(  Decay::bkg_t( dt, tau, gm, DoubleSided),"
                         "ArgusBG::bkg_m( mes, 5.291, k[-100,-10])") ;

  // Make composite model from the signal and background component
  w->factory("SUM::model( Nsig[5000,0,10000]*sig, NBkg[500,0,10000]*bkg )") ;

  // E x a m p l e   o f   R o o S i m W S T o o l   i n t e r f a c e
  // ------------------------------------------------------------------

  // Introduce a flavour tagging category tagCat as observable with 4 states corresponding
  // to 4 flavour tagging techniques with different performance that require different
  // parameterizations of the fit model
  //
  // RooSimWSTool operation:
  //     - Make 4 clones of model (for each tagCat) state, that will gain an individual
  //       copy of parameters w,dw and biasC. The other parameters remain common
  //     - Make a simultaneous p.d.f. of the 4 clones assigning each to the appropriate
  //       state of the tagCat index category

  // RooSimWSTool is interfaced as meta-type SIMCLONE in the factory. The $SplitParam()
  // argument maps to the SplitParam() named argument in the RooSimWSTool constructor
  w->factory("SIMCLONE::model_sim( model, $SplitParam({w,dw,biasC},tagCat[Lep,Kao,NT1,NT2]))") ;

  // E x a m p l e   o f   R o o C u s t o m i z e r   i n t e r f a c e
  // -------------------------------------------------------------------
  //
  // Class RooCustomizer makes clones of existing p.d.f.s with certain prescribed
  // modifications (branch of leaf node replacements)
  //
  // Here we take our model (the original before RooSimWSTool modifications)
  // and request that the parameter w (the mistag rate) is replaced with
  // an expression-based function that calculates w in terms of the Dilution
  // parameter D that is defined as D = 1-2*w

  // Make a clone model_D of original 'model' replacing 'w' with 'expr('0.5-D/2',D[0,1])'
  w->factory("EDIT::model_D(model, w=expr('0.5-D/2',D[0,1]) )") ;

  // Print workspace contents
  w->Print() ;

  // Make workspace visible on command line
  gDirectory->Add(w) ;
}

<commit_msg><commit_after>/////////////////////////////////////////////////////////////////////////
//
// 'ORGANIZATION AND SIMULTANEOUS FITS' RooFit tutorial macro #513
//
//  Illustration use of RooCustomizer and RooSimWSTool interface
//  in factory workspace tool in a complex standalone B physics example
//
// 04/2009 - Wouter Verkerke
//
/////////////////////////////////////////////////////////////////////////

#ifndef __CINT__
#include "RooGlobalFunc.h"
#endif
#include "RooRealVar.h"
#include "RooDataSet.h"
#include "RooGaussian.h"
#include "RooConstVar.h"
#include "RooChebychev.h"
#include "RooAddPdf.h"
#include "RooWorkspace.h"
#include "RooPlot.h"
#include "TCanvas.h"
#include "TAxis.h"
using namespace RooFit ;

void rf513_wsfactory_tools()
{
  RooWorkspace* w = new RooWorkspace("w") ;

  // B u i l d   a   c o m p l e x   e x a m p l e   p . d . f .
  // -----------------------------------------------------------

  // Make signal model for CPV: A bmixing decay function in t (convoluted with a triple Gaussian resolution model)
  //                            times a Gaussian function the reconstructed mass
  w->factory("PROD::sig(  BMixDecay::sig_t( dt[-20,20], mixState[mixed=1,unmix=-1], tagFlav[B0=1,B0bar=-1], "
                                             "tau[1.54], dm[0.472], w[0.05], dw[0],"
                                             "AddModel::gm({GaussModel(dt,biasC[-10,10],sigmaC[0.1,3],dterr[0.01,0.2]),"
                                                     	   "GaussModel(dt,0,sigmaT[3,10]),"
                                                           "GaussModel(dt,0,20)},{fracC[0,1],fracT[0,1]}),"
                                             "DoubleSided ),"
                           "Gaussian::sig_m( mes[5.20,5.30], mB0[5.20,5.30], sigmB0[0.01,0.05] ))") ;

  // Make background component: A plain decay function in t times an Argus function in the reconstructed mass
  w->factory("PROD::bkg(  Decay::bkg_t( dt, tau, gm, DoubleSided),"
                         "ArgusBG::bkg_m( mes, 5.291, k[-100,-10]))") ;

  // Make composite model from the signal and background component
  w->factory("SUM::model( Nsig[5000,0,10000]*sig, NBkg[500,0,10000]*bkg )") ;

  // E x a m p l e   o f   R o o S i m W S T o o l   i n t e r f a c e
  // ------------------------------------------------------------------

  // Introduce a flavour tagging category tagCat as observable with 4 states corresponding
  // to 4 flavour tagging techniques with different performance that require different
  // parameterizations of the fit model
  //
  // RooSimWSTool operation:
  //     - Make 4 clones of model (for each tagCat) state, that will gain an individual
  //       copy of parameters w,dw and biasC. The other parameters remain common
  //     - Make a simultaneous p.d.f. of the 4 clones assigning each to the appropriate
  //       state of the tagCat index category

  // RooSimWSTool is interfaced as meta-type SIMCLONE in the factory. The $SplitParam()
  // argument maps to the SplitParam() named argument in the RooSimWSTool constructor
  w->factory("SIMCLONE::model_sim( model, $SplitParam({w,dw,biasC},tagCat[Lep,Kao,NT1,NT2]))") ;

  // E x a m p l e   o f   R o o C u s t o m i z e r   i n t e r f a c e
  // -------------------------------------------------------------------
  //
  // Class RooCustomizer makes clones of existing p.d.f.s with certain prescribed
  // modifications (branch of leaf node replacements)
  //
  // Here we take our model (the original before RooSimWSTool modifications)
  // and request that the parameter w (the mistag rate) is replaced with
  // an expression-based function that calculates w in terms of the Dilution
  // parameter D that is defined as D = 1-2*w

  // Make a clone model_D of original 'model' replacing 'w' with 'expr('0.5-D/2',D[0,1])'
  w->factory("EDIT::model_D(model, w=expr('0.5-D/2',D[0,1]) )") ;

  // Print workspace contents
  w->Print() ;

  // Make workspace visible on command line
  gDirectory->Add(w) ;
}

<|endoftext|>


<commit_before>#include <thin3d/thin3d.h>

#include "base/logging.h"
#include "image/zim_load.h"
#include "image/png_load.h"
#include "file/vfs.h"

static const char * const glsl_fsTexCol =
"varying vec4 oColor0;\n"
"varying vec2 oTexCoord0;\n"
"uniform sampler2D Sampler0;\n"
"void main() { gl_FragColor = oColor0 * texture2D(Sampler0, oTexCoord0); }\n";

static const char * const hlslFsTexCol =
"struct PS_INPUT { float4 color : COLOR0; float2 uv : TEXCOORD0; };\n"
"sampler2D Sampler0 : register(s0);\n"
"float4 main(PS_INPUT input) : COLOR0 {\n"
"  return input.color * tex2D(Sampler0, input.uv);\n"
"}\n";

static const char * const glsl_fsCol =
"varying vec4 oColor0;\n"
"void main() { gl_FragColor = oColor0; }\n";

static const char * const hlslFsCol =
"struct PS_INPUT { float4 color : COLOR0; };\n"
"float4 main(PS_INPUT input) : COLOR0 {\n"
"  return input.color;\n"
"}\n";

static const char * const glsl_vsCol =
"attribute vec3 Position;\n"
"attribute vec4 Color0;\n"
"varying vec4 oColor0;\n"
"uniform mat4 WorldViewProj;\n"
"void main() {\n"
"  gl_Position = WorldViewProj * vec4(Position, 1.0);\n"
"  oColor0 = Color0;\n"
"}";

static const char * const hlslVsCol =
"struct VS_INPUT { float3 Position : POSITION; float4 Color0 : COLOR0; };\n"
"struct VS_OUTPUT { float4 Position : POSITION; float4 Color0 : COLOR0; };\n"
"float4x4 WorldViewProj;\n"
"VS_OUTPUT main(VS_INPUT input) {\n"
"  VS_OUTPUT output;\n"
"  output.Position = mul(float4(input.Position, 1.0), WorldViewProj);\n"
"  output.Color0 = input.Color0;\n"
"  return output;\n"
"}\n";

static const char * const glsl_vsTexCol =
"attribute vec3 Position;\n"
"attribute vec4 Color0;\n"
"attribute vec2 TexCoord0;\n"
"varying vec4 oColor0;\n"
"varying vec2 oTexCoord0;\n"
"uniform mat4 WorldViewProj;\n"
"void main() {\n"
"  gl_Position = WorldViewProj * vec4(Position, 1.0);\n"
"  oColor0 = Color0;\n"
"  oTexCoord0 = TexCoord0;\n"
"}\n";

static const char * const hlslVsTexCol =
"struct VS_INPUT { float3 Position : POSITION; float2 Texcoord0 : TEXCOORD0; float4 Color0 : COLOR0; };\n"
"struct VS_OUTPUT { float4 Position : POSITION; float2 Texcoord0 : TEXCOORD0; float4 Color0 : COLOR0; };\n"
"float4x4 WorldViewProj;\n"
"VS_OUTPUT main(VS_INPUT input) {\n"
"  VS_OUTPUT output;\n"
"  output.Position = mul(float4(input.Position, 1.0), WorldViewProj);\n"
"  output.Texcoord0 = input.Texcoord0;\n"
"  output.Color0 = input.Color0;\n"
"  return output;\n"
"}\n";

void Thin3DContext::CreatePresets() {
	// Build prebuilt objects
	T3DBlendStateDesc off = { false };
	T3DBlendStateDesc additive = { true, T3DBlendEquation::ADD, T3DBlendFactor::ONE, T3DBlendFactor::ONE, T3DBlendEquation::ADD, T3DBlendFactor::ONE, T3DBlendFactor::ZERO };
	T3DBlendStateDesc standard_alpha = { true, T3DBlendEquation::ADD, T3DBlendFactor::SRC_ALPHA, T3DBlendFactor::ONE_MINUS_SRC_ALPHA, T3DBlendEquation::ADD, T3DBlendFactor::ONE, T3DBlendFactor::ZERO };
	T3DBlendStateDesc premul_alpha = { true, T3DBlendEquation::ADD, T3DBlendFactor::ONE, T3DBlendFactor::ONE_MINUS_SRC_ALPHA, T3DBlendEquation::ADD, T3DBlendFactor::ONE, T3DBlendFactor::ZERO };

	bsPresets_[BS_OFF] = CreateBlendState(off);
	bsPresets_[BS_ADDITIVE] = CreateBlendState(additive);
	bsPresets_[BS_STANDARD_ALPHA] = CreateBlendState(standard_alpha);
	bsPresets_[BS_PREMUL_ALPHA] = CreateBlendState(premul_alpha);

	vsPresets_[VS_TEXTURE_COLOR_2D] = CreateVertexShader(glsl_vsTexCol, hlslVsTexCol);
	vsPresets_[VS_COLOR_2D] = CreateVertexShader(glsl_vsCol, hlslVsCol);

	fsPresets_[FS_TEXTURE_COLOR_2D] = CreateFragmentShader(glsl_fsTexCol, hlslFsTexCol);
	fsPresets_[FS_COLOR_2D] = CreateFragmentShader(glsl_fsCol, hlslFsCol);

	ssPresets_[SS_TEXTURE_COLOR_2D] = CreateShaderSet(vsPresets_[VS_TEXTURE_COLOR_2D], fsPresets_[FS_TEXTURE_COLOR_2D]);
	ssPresets_[SS_COLOR_2D] = CreateShaderSet(vsPresets_[VS_COLOR_2D], fsPresets_[FS_COLOR_2D]);
}

Thin3DContext::~Thin3DContext() {
	for (int i = 0; i < VS_MAX_PRESET; i++) {
		if (vsPresets_[i]) {
			vsPresets_[i]->Release();
		}
	}
	for (int i = 0; i < FS_MAX_PRESET; i++) {
		if (fsPresets_[i]) {
			fsPresets_[i]->Release();
		}
	}
	for (int i = 0; i < BS_MAX_PRESET; i++) {
		if (bsPresets_[i]) {
			bsPresets_[i]->Release();
		}
	}
	for (int i = 0; i < SS_MAX_PRESET; i++) {
		if (ssPresets_[i]) {
			ssPresets_[i]->Release();
		}
	}
}

static T3DImageFormat ZimToT3DFormat(int zim) {
	switch (zim) {
	case ZIM_ETC1: return T3DImageFormat::ETC1;
	case ZIM_RGBA8888: return T3DImageFormat::RGBA8888;
	case ZIM_LUMINANCE: return T3DImageFormat::LUMINANCE;
	default: return T3DImageFormat::RGBA8888;
	}
}

bool Thin3DTexture::LoadFromFileData(const uint8_t *data, size_t dataSize, T3DImageType type) {
	int width[16], height[16], zim_flags;
	uint8_t *image[16] = { nullptr };

	int num_levels = LoadZIMPtr(data, dataSize, width, height, &zim_flags, image);
	if (num_levels == 0) {
		return false;
	}

	T3DImageFormat fmt = ZimToT3DFormat(zim_flags & ZIM_FORMAT_MASK);

	// TODO: Cube map / 3D texture / texture array support

	Create(LINEAR2D, fmt, width[0], height[0], 1, num_levels);

	for (int i = 0; i < num_levels; i++) {
		SetImageData(0, 0, 0, width[i], height[i], 1, i, width[i] * 4, image[i]);
		free(image[i]);
	}

	Finalize(zim_flags);
	return true;
}

bool Thin3DTexture::LoadFromFile(const std::string &filename, T3DImageType type) {
	filename_ = "";
	size_t fileSize;
	uint8_t *buffer = VFSReadFile(filename.c_str(), &fileSize);
	if (!buffer) {
		return false;
	}
	bool retval = LoadFromFileData(buffer, fileSize, type);
	if (retval) {
		filename_ = filename;
	}
	delete[] buffer;
	return retval;
}

Thin3DTexture *Thin3DContext::CreateTextureFromFile(const char *filename, T3DImageType type) {
	Thin3DTexture *tex = CreateTexture();
	if (!tex->LoadFromFile(filename, type)) {
		tex->Release();
		return NULL;
	} else {
		return tex;
	}
}

T3DImageType DetectImageFileType(const uint8_t *data, size_t size) {
	if (!memcmp(data, "ZIMG", 4)) {
		return ZIM;
	} else if (!memcmp(data, "\x89\x50\x4E\x47", 4)) {
		return PNG;
	} else if (!memcmp(data, "\xff\xd8\xff\xe0", 4)) {
		return JPEG;
	} else {
		return TYPE_UNKNOWN;
	}
}

// TODO: Remove the code duplication between this and LoadFromFileData
Thin3DTexture *Thin3DContext::CreateTextureFromFileData(const uint8_t *data, int size, T3DImageType type) {
	int width[16], height[16], zim_flags = 0;
	uint8_t *image[16] = { nullptr };

	int num_levels = 0;
	T3DImageFormat fmt;

	if (type == DETECT) {
		type = DetectImageFileType(data, size);
	}
	if (type == TYPE_UNKNOWN) {
		ELOG("File has unknown format");
		return nullptr;
	}

	switch (type) {
	case ZIM:
		num_levels = LoadZIMPtr((const uint8_t *)data, size, width, height, &zim_flags, image);
		fmt = ZimToT3DFormat(zim_flags & ZIM_FORMAT_MASK);
		break;

	case PNG:
		if (1 != pngLoadPtr((const unsigned char *)data, size, &width[0], &height[0], &image[0], false)) {
			return NULL;
		}
		num_levels = 1;
		fmt = RGBA8888;
		break;

	default:
		ELOG("Unknown image format");
		return nullptr;
	}

	if (num_levels == 0) {
		return NULL;
	}

	Thin3DTexture *tex = CreateTexture(LINEAR2D, fmt, width[0], height[0], 1, num_levels);
	for (int i = 0; i < num_levels; i++) {
		tex->SetImageData(0, 0, 0, width[i], height[i], 1, i, width[i] * 4, image[i]);
		free(image[i]);
	}

	tex->Finalize(zim_flags);
	return tex;
}
<commit_msg>Linux buildfix.<commit_after>#include <string.h>
#include <thin3d/thin3d.h>

#include "base/logging.h"
#include "image/zim_load.h"
#include "image/png_load.h"
#include "file/vfs.h"

static const char * const glsl_fsTexCol =
"varying vec4 oColor0;\n"
"varying vec2 oTexCoord0;\n"
"uniform sampler2D Sampler0;\n"
"void main() { gl_FragColor = oColor0 * texture2D(Sampler0, oTexCoord0); }\n";

static const char * const hlslFsTexCol =
"struct PS_INPUT { float4 color : COLOR0; float2 uv : TEXCOORD0; };\n"
"sampler2D Sampler0 : register(s0);\n"
"float4 main(PS_INPUT input) : COLOR0 {\n"
"  return input.color * tex2D(Sampler0, input.uv);\n"
"}\n";

static const char * const glsl_fsCol =
"varying vec4 oColor0;\n"
"void main() { gl_FragColor = oColor0; }\n";

static const char * const hlslFsCol =
"struct PS_INPUT { float4 color : COLOR0; };\n"
"float4 main(PS_INPUT input) : COLOR0 {\n"
"  return input.color;\n"
"}\n";

static const char * const glsl_vsCol =
"attribute vec3 Position;\n"
"attribute vec4 Color0;\n"
"varying vec4 oColor0;\n"
"uniform mat4 WorldViewProj;\n"
"void main() {\n"
"  gl_Position = WorldViewProj * vec4(Position, 1.0);\n"
"  oColor0 = Color0;\n"
"}";

static const char * const hlslVsCol =
"struct VS_INPUT { float3 Position : POSITION; float4 Color0 : COLOR0; };\n"
"struct VS_OUTPUT { float4 Position : POSITION; float4 Color0 : COLOR0; };\n"
"float4x4 WorldViewProj;\n"
"VS_OUTPUT main(VS_INPUT input) {\n"
"  VS_OUTPUT output;\n"
"  output.Position = mul(float4(input.Position, 1.0), WorldViewProj);\n"
"  output.Color0 = input.Color0;\n"
"  return output;\n"
"}\n";

static const char * const glsl_vsTexCol =
"attribute vec3 Position;\n"
"attribute vec4 Color0;\n"
"attribute vec2 TexCoord0;\n"
"varying vec4 oColor0;\n"
"varying vec2 oTexCoord0;\n"
"uniform mat4 WorldViewProj;\n"
"void main() {\n"
"  gl_Position = WorldViewProj * vec4(Position, 1.0);\n"
"  oColor0 = Color0;\n"
"  oTexCoord0 = TexCoord0;\n"
"}\n";

static const char * const hlslVsTexCol =
"struct VS_INPUT { float3 Position : POSITION; float2 Texcoord0 : TEXCOORD0; float4 Color0 : COLOR0; };\n"
"struct VS_OUTPUT { float4 Position : POSITION; float2 Texcoord0 : TEXCOORD0; float4 Color0 : COLOR0; };\n"
"float4x4 WorldViewProj;\n"
"VS_OUTPUT main(VS_INPUT input) {\n"
"  VS_OUTPUT output;\n"
"  output.Position = mul(float4(input.Position, 1.0), WorldViewProj);\n"
"  output.Texcoord0 = input.Texcoord0;\n"
"  output.Color0 = input.Color0;\n"
"  return output;\n"
"}\n";

void Thin3DContext::CreatePresets() {
	// Build prebuilt objects
	T3DBlendStateDesc off = { false };
	T3DBlendStateDesc additive = { true, T3DBlendEquation::ADD, T3DBlendFactor::ONE, T3DBlendFactor::ONE, T3DBlendEquation::ADD, T3DBlendFactor::ONE, T3DBlendFactor::ZERO };
	T3DBlendStateDesc standard_alpha = { true, T3DBlendEquation::ADD, T3DBlendFactor::SRC_ALPHA, T3DBlendFactor::ONE_MINUS_SRC_ALPHA, T3DBlendEquation::ADD, T3DBlendFactor::ONE, T3DBlendFactor::ZERO };
	T3DBlendStateDesc premul_alpha = { true, T3DBlendEquation::ADD, T3DBlendFactor::ONE, T3DBlendFactor::ONE_MINUS_SRC_ALPHA, T3DBlendEquation::ADD, T3DBlendFactor::ONE, T3DBlendFactor::ZERO };

	bsPresets_[BS_OFF] = CreateBlendState(off);
	bsPresets_[BS_ADDITIVE] = CreateBlendState(additive);
	bsPresets_[BS_STANDARD_ALPHA] = CreateBlendState(standard_alpha);
	bsPresets_[BS_PREMUL_ALPHA] = CreateBlendState(premul_alpha);

	vsPresets_[VS_TEXTURE_COLOR_2D] = CreateVertexShader(glsl_vsTexCol, hlslVsTexCol);
	vsPresets_[VS_COLOR_2D] = CreateVertexShader(glsl_vsCol, hlslVsCol);

	fsPresets_[FS_TEXTURE_COLOR_2D] = CreateFragmentShader(glsl_fsTexCol, hlslFsTexCol);
	fsPresets_[FS_COLOR_2D] = CreateFragmentShader(glsl_fsCol, hlslFsCol);

	ssPresets_[SS_TEXTURE_COLOR_2D] = CreateShaderSet(vsPresets_[VS_TEXTURE_COLOR_2D], fsPresets_[FS_TEXTURE_COLOR_2D]);
	ssPresets_[SS_COLOR_2D] = CreateShaderSet(vsPresets_[VS_COLOR_2D], fsPresets_[FS_COLOR_2D]);
}

Thin3DContext::~Thin3DContext() {
	for (int i = 0; i < VS_MAX_PRESET; i++) {
		if (vsPresets_[i]) {
			vsPresets_[i]->Release();
		}
	}
	for (int i = 0; i < FS_MAX_PRESET; i++) {
		if (fsPresets_[i]) {
			fsPresets_[i]->Release();
		}
	}
	for (int i = 0; i < BS_MAX_PRESET; i++) {
		if (bsPresets_[i]) {
			bsPresets_[i]->Release();
		}
	}
	for (int i = 0; i < SS_MAX_PRESET; i++) {
		if (ssPresets_[i]) {
			ssPresets_[i]->Release();
		}
	}
}

static T3DImageFormat ZimToT3DFormat(int zim) {
	switch (zim) {
	case ZIM_ETC1: return T3DImageFormat::ETC1;
	case ZIM_RGBA8888: return T3DImageFormat::RGBA8888;
	case ZIM_LUMINANCE: return T3DImageFormat::LUMINANCE;
	default: return T3DImageFormat::RGBA8888;
	}
}

bool Thin3DTexture::LoadFromFileData(const uint8_t *data, size_t dataSize, T3DImageType type) {
	int width[16], height[16], zim_flags;
	uint8_t *image[16] = { nullptr };

	int num_levels = LoadZIMPtr(data, dataSize, width, height, &zim_flags, image);
	if (num_levels == 0) {
		return false;
	}

	T3DImageFormat fmt = ZimToT3DFormat(zim_flags & ZIM_FORMAT_MASK);

	// TODO: Cube map / 3D texture / texture array support

	Create(LINEAR2D, fmt, width[0], height[0], 1, num_levels);

	for (int i = 0; i < num_levels; i++) {
		SetImageData(0, 0, 0, width[i], height[i], 1, i, width[i] * 4, image[i]);
		free(image[i]);
	}

	Finalize(zim_flags);
	return true;
}

bool Thin3DTexture::LoadFromFile(const std::string &filename, T3DImageType type) {
	filename_ = "";
	size_t fileSize;
	uint8_t *buffer = VFSReadFile(filename.c_str(), &fileSize);
	if (!buffer) {
		return false;
	}
	bool retval = LoadFromFileData(buffer, fileSize, type);
	if (retval) {
		filename_ = filename;
	}
	delete[] buffer;
	return retval;
}

Thin3DTexture *Thin3DContext::CreateTextureFromFile(const char *filename, T3DImageType type) {
	Thin3DTexture *tex = CreateTexture();
	if (!tex->LoadFromFile(filename, type)) {
		tex->Release();
		return NULL;
	} else {
		return tex;
	}
}

T3DImageType DetectImageFileType(const uint8_t *data, size_t size) {
	if (!memcmp(data, "ZIMG", 4)) {
		return ZIM;
	} else if (!memcmp(data, "\x89\x50\x4E\x47", 4)) {
		return PNG;
	} else if (!memcmp(data, "\xff\xd8\xff\xe0", 4)) {
		return JPEG;
	} else {
		return TYPE_UNKNOWN;
	}
}

// TODO: Remove the code duplication between this and LoadFromFileData
Thin3DTexture *Thin3DContext::CreateTextureFromFileData(const uint8_t *data, int size, T3DImageType type) {
	int width[16], height[16], zim_flags = 0;
	uint8_t *image[16] = { nullptr };

	int num_levels = 0;
	T3DImageFormat fmt;

	if (type == DETECT) {
		type = DetectImageFileType(data, size);
	}
	if (type == TYPE_UNKNOWN) {
		ELOG("File has unknown format");
		return nullptr;
	}

	switch (type) {
	case ZIM:
		num_levels = LoadZIMPtr((const uint8_t *)data, size, width, height, &zim_flags, image);
		fmt = ZimToT3DFormat(zim_flags & ZIM_FORMAT_MASK);
		break;

	case PNG:
		if (1 != pngLoadPtr((const unsigned char *)data, size, &width[0], &height[0], &image[0], false)) {
			return NULL;
		}
		num_levels = 1;
		fmt = RGBA8888;
		break;

	default:
		ELOG("Unknown image format");
		return nullptr;
	}

	if (num_levels == 0) {
		return NULL;
	}

	Thin3DTexture *tex = CreateTexture(LINEAR2D, fmt, width[0], height[0], 1, num_levels);
	for (int i = 0; i < num_levels; i++) {
		tex->SetImageData(0, 0, 0, width[i], height[i], 1, i, width[i] * 4, image[i]);
		free(image[i]);
	}

	tex->Finalize(zim_flags);
	return tex;
}
<|endoftext|>


<commit_before>#include <cassert>
#include <cstdlib>
#include <fstream>
#include <functional>
#include <iostream>
#include <random>
#include <sstream>
#include <vector>

#include "miopen/db_record.hpp"
#include "test.hpp"

namespace miopen {
namespace tests {

struct TestData
{
    int x;
    int y;

    TestData()
    {
        const int seed = 42;

        static std::mt19937 rng(seed);
        static std::uniform_int_distribution<std::mt19937::result_type> dist{};

        x = dist(rng);
        y = dist(rng);
    }

    TestData(int x_, int y_) : x(x_), y(y_) {}

    void Serialize(std::ostream& s) const
    {
        static const auto sep = ',';
        s << x << sep << y;
    }

    void LegacySerialize(std::ostream& s) const
    {
        Serialize(s);
        s << ",l";
    }

    bool Deserialize(const std::string& s)
    {
        static const auto sep = ',';
        TestData t;
        std::istringstream ss(s);

        auto success = DeserializeField(ss, &t.x, sep) && DeserializeField(ss, &t.y, sep);

        if(!success)
            return false;

        *this = t;
        return true;
    }

    bool LegacyDeserialize(const std::string& s) { return Deserialize(s); }
    bool operator==(const TestData& other) const { return x == other.x && y == other.y; }

    private:
    inline static bool DeserializeField(std::istream& from, int* ret, char separator)
    {
        std::string part;

        if(!std::getline(from, part, separator))
            return false;

        const auto start = part.c_str();
        char* end;
        auto value = std::strtol(start, &end, 10);

        if(start == end)
            return false;

        *ret = value;
        return true;
    }
};

std::ostream& operator<<(std::ostream& s, const TestData& td)
{
    s << "x: " << td.x << ", y: " << td.y;
    return s;
}

struct TestValues
{
    TestData key{
        1, 2,
    };
    TestData value0{
        3, 4,
    };
    TestData value1{
        5, 6,
    };
    std::string id0 = "0";
    std::string id1 = "1";
};

class DbRecordTest
{
    public:
    virtual ~DbRecordTest() { std::remove(TempFilePath()); }

    protected:
    static const char* TempFilePath() { return "/tmp/dbread.test.temp.pdb"; }
};

class DbRecordReadTest : public DbRecordTest
{
    public:
    inline void Run()
    {
        TestValues v;

        std::ostringstream ss_vals;
        ss_vals << v.key.x << ',' << v.key.y << '=' << v.id1 << ':' << v.value1.x << ','
                << v.value1.y << ';' << v.id0 << ':' << v.value0.x << ',' << v.value0.y;

        std::ofstream(TempFilePath()) << ss_vals.str() << std::endl;

        TestData read0, read1;

        {
            DbRecord record(TempFilePath(), v.key);

            EXPECT(record.Load(v.id0, read0));
            EXPECT(record.Load(v.id1, read1));
        }

        EXPECT_EQUAL(v.value0, read0);
        EXPECT_EQUAL(v.value1, read1);
    }
};

class DbRecordWriteTest : public DbRecordTest
{
    public:
    inline void Run()
    {
        TestValues v;

        std::ostringstream ss_vals;
        ss_vals << v.key.x << ',' << v.key.y << '=' << v.id1 << ':' << v.value1.x << ','
                << v.value1.y << ';' << v.id0 << ':' << v.value0.x << ',' << v.value0.y;

        (void)std::ofstream(TempFilePath());

        {
            DbRecord record(TempFilePath(), v.key);

            EXPECT(record.Store(v.id0, v.value0));
            EXPECT(record.Store(v.id1, v.value1));
        }

        std::string read;

        EXPECT(std::getline(std::ifstream(TempFilePath()), read).good());
        EXPECT_EQUAL(read, ss_vals.str());
    }
};

class DbRecordLegacyReadTest : public DbRecordTest
{
    public:
    inline void Run()
    {
        TestValues v;

        std::ostringstream ss_vals;
        ss_vals << v.key.x << ',' << v.key.y << ",l " << v.value0.x << ',' << v.value0.y;

        std::ofstream(TempFilePath()) << ss_vals.str() << std::endl;

        TestData read;

        {
            DbRecord record(TempFilePath(), v.key, true);

            auto legacy_id = "ConvOclDirectFwd"; // const from db_record.cpp
            EXPECT(record.Load(legacy_id, read));
        }

        EXPECT_EQUAL(v.value0, read);
    }
};

} // namespace miopen
} // namespace tests

int main()
{
    miopen::tests::DbRecordReadTest().Run();
    miopen::tests::DbRecordWriteTest().Run();
    miopen::tests::DbRecordLegacyReadTest().Run();

    return 0;
}
<commit_msg>Added more tests<commit_after>#include <cassert>
#include <cstdlib>
#include <fstream>
#include <functional>
#include <iostream>
#include <random>
#include <sstream>
#include <vector>

#include "miopen/db_record.hpp"
#include "test.hpp"

namespace miopen {
namespace tests {

struct TestData
{
    int x;
    int y;

    TestData()
    {
        const int seed = 42;

        static std::mt19937 rng(seed);
        static std::uniform_int_distribution<std::mt19937::result_type> dist{};

        x = dist(rng);
        y = dist(rng);
    }

    TestData(int x_, int y_) : x(x_), y(y_) {}

    void Serialize(std::ostream& s) const
    {
        static const auto sep = ',';
        s << x << sep << y;
    }

    void LegacySerialize(std::ostream& s) const
    {
        Serialize(s);
        s << ",l";
    }

    bool Deserialize(const std::string& s)
    {
        static const auto sep = ',';
        TestData t;
        std::istringstream ss(s);

        auto success = DeserializeField(ss, &t.x, sep) && DeserializeField(ss, &t.y, sep);

        if(!success)
            return false;

        *this = t;
        return true;
    }

    bool LegacyDeserialize(const std::string& s) { return Deserialize(s); }
    bool operator==(const TestData& other) const { return x == other.x && y == other.y; }

    private:
    inline static bool DeserializeField(std::istream& from, int* ret, char separator)
    {
        std::string part;

        if(!std::getline(from, part, separator))
            return false;

        const auto start = part.c_str();
        char* end;
        auto value = std::strtol(start, &end, 10);

        if(start == end)
            return false;

        *ret = value;
        return true;
    }
};

std::ostream& operator<<(std::ostream& s, const TestData& td)
{
    s << "x: " << td.x << ", y: " << td.y;
    return s;
}

class DbRecordTest
{
    public:
    virtual ~DbRecordTest() { std::remove(TempFilePath()); }

    protected:
    static const TestData key;
    static const TestData value0;
    static const TestData value1;
    static const char* const id0;
    static const char* const id1;
    static const char* const missing_id;
    static const char* const legacy_id;

    static const char* TempFilePath() { return "/tmp/dbread.test.temp.pdb"; }
};

const TestData DbRecordTest::key(1, 2);
const TestData DbRecordTest::value0(3, 4);
const TestData DbRecordTest::value1(5, 6);
const char* const DbRecordTest::id0        = "0";
const char* const DbRecordTest::id1        = "1";
const char* const DbRecordTest::missing_id = "2";
const char* const DbRecordTest::legacy_id  = "ConvOclDirectFwd"; // const from db_record.cpp

class DbRecordReadTest : public DbRecordTest
{
    public:
    inline void Run()
    {
        std::ostringstream ss_vals;
        ss_vals << key.x << ',' << key.y << '=' << id1 << ':' << value1.x << ',' << value1.y << ';'
                << id0 << ':' << value0.x << ',' << value0.y;

        std::ofstream(TempFilePath()) << ss_vals.str() << std::endl;

        TestData read0, read1;

        {
            DbRecord record(TempFilePath(), key);

            EXPECT(record.Load(id0, read0));
            EXPECT(record.Load(id1, read1));
        }

        EXPECT_EQUAL(value0, read0);
        EXPECT_EQUAL(value1, read1);
    }
};

class DbRecordWriteTest : public DbRecordTest
{
    public:
    inline void Run()
    {
        std::ostringstream ss_vals;
        ss_vals << key.x << ',' << key.y << '=' << id1 << ':' << value1.x << ',' << value1.y << ';'
                << id0 << ':' << value0.x << ',' << value0.y;

        (void)std::ofstream(TempFilePath());

        {
            DbRecord record(TempFilePath(), key);

            EXPECT(record.Store(id0, value0));
            EXPECT(record.Store(id1, value1));
        }

        std::string read;

        EXPECT(std::getline(std::ifstream(TempFilePath()), read).good());
        EXPECT_EQUAL(read, ss_vals.str());
    }
};

class DbRecordLegacyReadTest : public DbRecordTest
{
    public:
    inline void Run()
    {
        std::ostringstream ss_vals;
        ss_vals << key.x << ',' << key.y << ",l " << value0.x << ',' << value0.y;

        std::ofstream(TempFilePath()) << ss_vals.str() << std::endl;

        TestData read;

        {
            DbRecord record(TempFilePath(), key, true);

            EXPECT(record.Load(legacy_id, read));
        }

        EXPECT_EQUAL(value0, read);
    }
};

class DbRecordOperationsTest : public DbRecordTest
{
    public:
    inline void Run()
    {
        (void)std::ofstream(TempFilePath()); // To suppress warning in logs.

        {
            DbRecord record(TempFilePath(), key);

            EXPECT(record.Store(id0, value0));
            EXPECT(record.Store(id1, value0));

            // Rewritting existing value with other.
            EXPECT(record.Store(id1, value1));

            // Rewritting existing value with same. In fact no DB manipulation should be performed
            // inside of store in such case.
            EXPECT(record.Store(id1, value1));
        }

        TestData read0, read1, read_missing, read_missing_cmp(read_missing);

        {
            DbRecord record(TempFilePath(), key);

            // Loading by id not present in record should execute well but return false as nothing
            // was read.
            EXPECT(!record.Load(missing_id, read_missing));

            // In such case value should not be changed.
            EXPECT_EQUAL(read_missing, read_missing_cmp);

            EXPECT(record.Load(id0, read0));
            EXPECT(record.Load(id1, read1));
        }

        EXPECT_EQUAL(read0, value0);
        EXPECT_EQUAL(read1, value1);
    }
};

} // namespace tests
} // namespace miopen

int main()
{
    miopen::tests::DbRecordReadTest().Run();
    miopen::tests::DbRecordWriteTest().Run();
    miopen::tests::DbRecordLegacyReadTest().Run();
    miopen::tests::DbRecordOperationsTest().Run();

    return 0;
}
<|endoftext|>


<commit_before>#include "test.h"

int main() {

	const u32 MAX = 50;

	rangetree<u16, u16> tree;

	u16 x, y;

	for (x = 0; x < MAX; x++) {
		for (y = 0; y < MAX; y++) {
			tree.add(x, y, 0);
		}
	}

	tree.finalize();

	// With points in every coordinate, we can easily calculate the counts

	for (x = 10; x < MAX; x += 10) {
		for (y = 10; y < MAX; y += 10) {
			const u32 count = tree.count(1, x, 1, y);
			const u32 calc = x*y;

			if (count != calc)
				fail("Got %u, expected %u\n", count, calc);
		}
	}

	return 0;
}
<commit_msg>Push period up to 100<commit_after>#include "test.h"

int main() {

	const u32 MAX = 100;

	rangetree<u16, u16> tree;

	u16 x, y;

	for (x = 0; x < MAX; x++) {
		for (y = 0; y < MAX; y++) {
			tree.add(x, y, 0);
		}
	}

	tree.finalize();

	// With points in every coordinate, we can easily calculate the counts

	for (x = 10; x < MAX; x += 10) {
		for (y = 10; y < MAX; y += 10) {
			const u32 count = tree.count(1, x, 1, y);
			const u32 calc = x*y;

			if (count != calc)
				fail("Got %u, expected %u\n", count, calc);
		}
	}

	return 0;
}
<|endoftext|>