<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id: AliTHn.cxx 20164 2007-08-14 15:31:50Z morsch $ */

//
// this storage container is optimized for small memory usage
//   under/over flow bins do not exist
//   sumw2 structure is float only and only create when the weight != 1
// all histogram functionality (projections, axis, ranges, etc) are taken from THnSparse by propagating
// the information up into the THnSparse structure (in the ananalysis *after* data processing and merging)
//
// the derivation from THnSparse is obviously against many OO rules. correct would be a common baseclass of THnSparse and THn.
//
// Author: Jan Fiete Grosse-Oetringhaus

#include "AliTHn.h"
#include "TList.h"
#include "TCollection.h"
#include "AliLog.h"
#include "TArrayF.h"
#include "THnSparse.h"
#include "TMath.h"

ClassImp(AliTHn)

AliTHn::AliTHn() :
  AliCFContainer(),
  fNBins(0),
  fNVars(0),
  fNSteps(0),
  fValues(0),
  fSumw2(0),
  axisCache(0)
{
  // Constructor
}

AliTHn::AliTHn(const Char_t* name, const Char_t* title,const Int_t nSelStep, const Int_t nVarIn, const Int_t* nBinIn) :
  AliCFContainer(name, title, nSelStep, nVarIn, nBinIn),
  fNBins(0),
  fNVars(nVarIn),
  fNSteps(nSelStep),
  fValues(0),
  fSumw2(0),
  axisCache(0)
{
  // Constructor

  fNBins = 1;
  for (Int_t i=0; i<fNVars; i++)
    fNBins *= nBinIn[i];

  Init();
}

void AliTHn::Init()
{
  // initialize

  fValues = new TArrayF*[fNSteps];
  fSumw2 = new TArrayF*[fNSteps];

  for (Int_t i=0; i<fNSteps; i++)
  {
    fValues[i] = 0;
    fSumw2[i] = 0;
  }
}

AliTHn::AliTHn(const AliTHn &c) :
  AliCFContainer(c),
  fNBins(c.fNBins),
  fNVars(c.fNVars),
  fNSteps(c.fNSteps),
  fValues(new TArrayF*[c.fNSteps]),
  fSumw2(new TArrayF*[c.fNSteps]),
  axisCache(0)
{
  //
  // AliTHn copy constructor
  //

  memset(fValues,0,fNSteps*sizeof(TArrayF*));
  memset(fSumw2,0,fNSteps*sizeof(TArrayF*));

  for (Int_t i=0; i<fNSteps; i++) {
    if (c.fValues[i]) fValues[i] = new TArrayF(*(c.fValues[i]));
    if (c.fSumw2[i])  fSumw2[i]  = new TArrayF(*(c.fSumw2[i]));
  }

}

AliTHn::~AliTHn()
{
  // Destructor

  DeleteContainers();

  delete[] fValues;
  delete[] fSumw2;
  delete[] axisCache;

}

void AliTHn::DeleteContainers()
{
  // delete data containers

  for (Int_t i=0; i<fNSteps; i++)
  {
    if (fValues && fValues[i])
    {
      delete fValues[i];
      fValues[i] = 0;
    }

    if (fSumw2 && fSumw2[i])
    {
      delete fSumw2[i];
      fSumw2[i] = 0;
    }
  }
}

//____________________________________________________________________
AliTHn &AliTHn::operator=(const AliTHn &c)
{
  // assigment operator

  if (this != &c) {
    AliCFContainer::operator=(c);
    fNBins=c.fNBins;
    fNVars=c.fNVars;
    if(fNSteps) {
      for(Int_t i=0; i< fNSteps; ++i) {
	delete fValues[i];
	delete fSumw2[i];
      }
      delete [] fValues;
      delete [] fSumw2;
    }
    fNSteps=c.fNSteps;
    if(fNSteps) {
      fValues=new TArrayF*[fNSteps];
      fSumw2=new TArrayF*[fNSteps];
      memset(fValues,0,fNSteps*sizeof(TArrayF*));
      memset(fSumw2,0,fNSteps*sizeof(TArrayF*));

      for (Int_t i=0; i<fNSteps; i++) {
	if (c.fValues[i]) fValues[i] = new TArrayF(*(c.fValues[i]));
	if (c.fSumw2[i])  fSumw2[i]  = new TArrayF(*(c.fSumw2[i]));
      }
    } else {
      fValues = 0;
      fSumw2 = 0;
    }
    delete [] axisCache;
    axisCache = new TAxis*[fNVars];
    memcpy(axisCache, c.axisCache, fNVars*sizeof(TAxis**));
  }
  return *this;
}

//____________________________________________________________________
void AliTHn::Copy(TObject& c) const
{
  // copy function

  AliTHn& target = (AliTHn &) c;

  AliCFContainer::Copy(target);

  target.fNSteps = fNSteps;
  target.fNBins = fNBins;
  target.fNVars = fNVars;

  target.Init();

  for (Int_t i=0; i<fNSteps; i++)
  {
    if (fValues[i])
      target.fValues[i] = new TArrayF(*(fValues[i]));
    else
      target.fValues[i] = 0;

    if (fSumw2[i])
      target.fSumw2[i] = new TArrayF(*(fSumw2[i]));
    else
      target.fSumw2[i] = 0;
  }
}

//____________________________________________________________________
Long64_t AliTHn::Merge(TCollection* list)
{
  // Merge a list of AliTHn objects with this (needed for
  // PROOF).
  // Returns the number of merged objects (including this).

  if (!list)
    return 0;

  if (list->IsEmpty())
    return 1;

  AliCFContainer::Merge(list);

  TIterator* iter = list->MakeIterator();
  TObject* obj;

  Int_t count = 0;
  while ((obj = iter->Next())) {

    AliTHn* entry = dynamic_cast<AliTHn*> (obj);
    if (entry == 0)
      continue;

    for (Int_t i=0; i<fNSteps; i++)
    {
      if (entry->fValues[i])
      {
	if (!fValues[i])
	  fValues[i] = new TArrayF(fNBins);

	for (Long64_t l = 0; l<fNBins; l++)
	  fValues[i]->GetArray()[l] += entry->fValues[i]->GetArray()[l];
      }

      if (entry->fSumw2[i])
      {
	if (!fSumw2[i])
	  fSumw2[i] = new TArrayF(fNBins);

	for (Long64_t l = 0; l<fNBins; l++)
	  fSumw2[i]->GetArray()[l] += entry->fSumw2[i]->GetArray()[l];
      }
    }

    count++;
  }

  return count+1;
}

void AliTHn::Fill(const Double_t *var, Int_t istep, Double_t weight)
{
  // fills an entry

  // fill axis cache
  if (!axisCache)
  {
    axisCache = new TAxis*[fNVars];
    for (Int_t i=0; i<fNVars; i++)
      axisCache[i] = GetAxis(i, 0);
  }

  // calculate global bin index
  Long64_t bin = 0;
  for (Int_t i=0; i<fNVars; i++)
  {
    bin *= axisCache[i]->GetNbins();

    Int_t tmpBin = axisCache[i]->FindBin(var[i]);
//     Printf("%d", tmpBin);
    // under/overflow not supported
    if (tmpBin < 1 || tmpBin > axisCache[i]->GetNbins())
      return;

    // bins start from 0 here
    bin += tmpBin - 1;
//     Printf("%lld", bin);
  }

  if (!fValues[istep])
  {
    fValues[istep] = new TArrayF(fNBins);
    AliInfo(Form("Created values container for step %d", istep));
  }

  if (weight != 1)
  {
    // initialize with already filled entries (which have been filled with weight == 1), in this case fSumw2 := fValues
    if (!fSumw2[istep])
    {
      fSumw2[istep] = new TArrayF(*fValues[istep]);
      AliInfo(Form("Created sumw2 container for step %d", istep));
    }
  }

  fValues[istep]->GetArray()[bin] += weight;
  if (fSumw2[istep])
    fSumw2[istep]->GetArray()[bin] += weight * weight;

//   Printf("%f", fValues[istep][bin]);

  // debug
//   AliCFContainer::Fill(var, istep, weight);
}

Long64_t AliTHn::GetGlobalBinIndex(const Int_t* binIdx)
{
  // calculates global bin index
  // binIdx contains TAxis bin indexes
  // here bin count starts at 0 because we do not have over/underflow bins

  Long64_t bin = 0;
  for (Int_t i=0; i<fNVars; i++)
  {
    bin *= GetAxis(i, 0)->GetNbins();
    bin += binIdx[i] - 1;
  }

  return bin;
}

void AliTHn::FillContainer(AliCFContainer* cont)
{
  // fills the information stored in the buffer in this class into the container <cont>

  for (Int_t i=0; i<fNSteps; i++)
  {
    if (!fValues[i])
      continue;

    Float_t* source = fValues[i]->GetArray();
    // if fSumw2 is not stored, the sqrt of the number of bin entries in source is filled below; otherwise we use fSumw2
    Float_t* sourceSumw2 = source;
    if (fSumw2[i])
      sourceSumw2 = fSumw2[i]->GetArray();

    THnSparse* target = cont->GetGrid(i)->GetGrid();

    Int_t* binIdx = new Int_t[fNVars];
    Int_t* nBins  = new Int_t[fNVars];
    for (Int_t j=0; j<fNVars; j++)
    {
      binIdx[j] = 1;
      nBins[j] = target->GetAxis(j)->GetNbins();
    }

    Long64_t count = 0;

    while (1)
    {
//       for (Int_t j=0; j<fNVars; j++)
// 	printf("%d ", binIdx[j]);

      Long64_t globalBin = GetGlobalBinIndex(binIdx);
//       Printf(" --> %lld", globalBin);

      if (source[globalBin] != 0)
      {
	target->SetBinContent(binIdx, source[globalBin]);
	target->SetBinError(binIdx, TMath::Sqrt(sourceSumw2[globalBin]));

	count++;
      }

      binIdx[fNVars-1]++;

      for (Int_t j=fNVars-1; j>0; j--)
      {
	if (binIdx[j] > nBins[j])
	{
	  binIdx[j] = 1;
	  binIdx[j-1]++;
	}
      }

      if (binIdx[0] > nBins[0])
	break;
    }

    AliInfo(Form("Step %d: copied %lld entries out of %lld bins", i, count, GetGlobalBinIndex(binIdx)));

    delete[] binIdx;
    delete[] nBins;
  }
}

void AliTHn::FillParent()
{
  // fills the information stored in the buffer in this class into the baseclass containers

  FillContainer(this);
}

void AliTHn::ReduceAxis()
{
  // "removes" one axis by summing over the axis and putting the entry to bin 1
  // TODO presently only implemented for the last axis

  Int_t axis = fNVars-1;

  for (Int_t i=0; i<fNSteps; i++)
  {
    if (!fValues[i])
      continue;

    Float_t* source = fValues[i]->GetArray();
    Float_t* sourceSumw2 = 0;
    if (fSumw2[i])
      sourceSumw2 = fSumw2[i]->GetArray();

    THnSparse* target = GetGrid(i)->GetGrid();

    Int_t* binIdx = new Int_t[fNVars];
    Int_t* nBins  = new Int_t[fNVars];
    for (Int_t j=0; j<fNVars; j++)
    {
      binIdx[j] = 1;
      nBins[j] = target->GetAxis(j)->GetNbins();
    }

    Long64_t count = 0;

    while (1)
    {
      // sum over axis <axis>
      Float_t sumValues = 0;
      Float_t sumSumw2 = 0;
      for (Int_t j=1; j<=nBins[axis]; j++)
      {
	binIdx[axis] = j;
	Long64_t globalBin = GetGlobalBinIndex(binIdx);
	sumValues += source[globalBin];
	source[globalBin] = 0;

	if (sourceSumw2)
	{
	  sumSumw2 += sourceSumw2[globalBin];
	  sourceSumw2[globalBin] = 0;
	}
      }
      binIdx[axis] = 1;

      Long64_t globalBin = GetGlobalBinIndex(binIdx);
      source[globalBin] = sumValues;
      if (sourceSumw2)
	sourceSumw2[globalBin] = sumSumw2;

      count++;

      // next bin
      binIdx[fNVars-2]++;

      for (Int_t j=fNVars-2; j>0; j--)
      {
	if (binIdx[j] > nBins[j])
	{
	  binIdx[j] = 1;
	  binIdx[j-1]++;
	}
      }

      if (binIdx[0] > nBins[0])
	break;
    }

    AliInfo(Form("Step %d: reduced %lld bins to %lld entries", i, GetGlobalBinIndex(binIdx), count));

    delete[] binIdx;
    delete[] nBins;
  }
}
<commit_msg>Coverity 19601<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id: AliTHn.cxx 20164 2007-08-14 15:31:50Z morsch $ */

//
// this storage container is optimized for small memory usage
//   under/over flow bins do not exist
//   sumw2 structure is float only and only create when the weight != 1
// all histogram functionality (projections, axis, ranges, etc) are taken from THnSparse by propagating
// the information up into the THnSparse structure (in the ananalysis *after* data processing and merging)
//
// the derivation from THnSparse is obviously against many OO rules. correct would be a common baseclass of THnSparse and THn.
//
// Author: Jan Fiete Grosse-Oetringhaus

#include "AliTHn.h"
#include "TList.h"
#include "TCollection.h"
#include "AliLog.h"
#include "TArrayF.h"
#include "THnSparse.h"
#include "TMath.h"

ClassImp(AliTHn)

AliTHn::AliTHn() :
  AliCFContainer(),
  fNBins(0),
  fNVars(0),
  fNSteps(0),
  fValues(0),
  fSumw2(0),
  axisCache(0)
{
  // Constructor
}

AliTHn::AliTHn(const Char_t* name, const Char_t* title,const Int_t nSelStep, const Int_t nVarIn, const Int_t* nBinIn) :
  AliCFContainer(name, title, nSelStep, nVarIn, nBinIn),
  fNBins(0),
  fNVars(nVarIn),
  fNSteps(nSelStep),
  fValues(0),
  fSumw2(0),
  axisCache(0)
{
  // Constructor

  fNBins = 1;
  for (Int_t i=0; i<fNVars; i++)
    fNBins *= nBinIn[i];

  Init();
}

void AliTHn::Init()
{
  // initialize

  fValues = new TArrayF*[fNSteps];
  fSumw2 = new TArrayF*[fNSteps];

  for (Int_t i=0; i<fNSteps; i++)
  {
    fValues[i] = 0;
    fSumw2[i] = 0;
  }
}

AliTHn::AliTHn(const AliTHn &c) :
  AliCFContainer(c),
  fNBins(c.fNBins),
  fNVars(c.fNVars),
  fNSteps(c.fNSteps),
  fValues(new TArrayF*[c.fNSteps]),
  fSumw2(new TArrayF*[c.fNSteps]),
  axisCache(0)
{
  //
  // AliTHn copy constructor
  //

  memset(fValues,0,fNSteps*sizeof(TArrayF*));
  memset(fSumw2,0,fNSteps*sizeof(TArrayF*));

  for (Int_t i=0; i<fNSteps; i++) {
    if (c.fValues[i]) fValues[i] = new TArrayF(*(c.fValues[i]));
    if (c.fSumw2[i])  fSumw2[i]  = new TArrayF(*(c.fSumw2[i]));
  }

}

AliTHn::~AliTHn()
{
  // Destructor

  DeleteContainers();

  delete[] fValues;
  delete[] fSumw2;
  delete[] axisCache;

}

void AliTHn::DeleteContainers()
{
  // delete data containers

  for (Int_t i=0; i<fNSteps; i++)
  {
    if (fValues && fValues[i])
    {
      delete fValues[i];
      fValues[i] = 0;
    }

    if (fSumw2 && fSumw2[i])
    {
      delete fSumw2[i];
      fSumw2[i] = 0;
    }
  }
}

//____________________________________________________________________
AliTHn &AliTHn::operator=(const AliTHn &c)
{
  // assigment operator

  if (this != &c) {
    AliCFContainer::operator=(c);
    fNBins=c.fNBins;
    fNVars=c.fNVars;
    if(fNSteps) {
      for(Int_t i=0; i< fNSteps; ++i) {
	delete fValues[i];
	delete fSumw2[i];
      }
      delete [] fValues;
      delete [] fSumw2;
    }
    fNSteps=c.fNSteps;
    if(fNSteps) {
      fValues=new TArrayF*[fNSteps];
      fSumw2=new TArrayF*[fNSteps];
      memset(fValues,0,fNSteps*sizeof(TArrayF*));
      memset(fSumw2,0,fNSteps*sizeof(TArrayF*));

      for (Int_t i=0; i<fNSteps; i++) {
	if (c.fValues[i]) fValues[i] = new TArrayF(*(c.fValues[i]));
	if (c.fSumw2[i])  fSumw2[i]  = new TArrayF(*(c.fSumw2[i]));
      }
    } else {
      fValues = 0;
      fSumw2 = 0;
    }
    delete [] axisCache;
    axisCache = new TAxis*[fNVars];
    memcpy(axisCache, c.axisCache, fNVars*sizeof(TAxis*));
  }
  return *this;
}

//____________________________________________________________________
void AliTHn::Copy(TObject& c) const
{
  // copy function

  AliTHn& target = (AliTHn &) c;

  AliCFContainer::Copy(target);

  target.fNSteps = fNSteps;
  target.fNBins = fNBins;
  target.fNVars = fNVars;

  target.Init();

  for (Int_t i=0; i<fNSteps; i++)
  {
    if (fValues[i])
      target.fValues[i] = new TArrayF(*(fValues[i]));
    else
      target.fValues[i] = 0;

    if (fSumw2[i])
      target.fSumw2[i] = new TArrayF(*(fSumw2[i]));
    else
      target.fSumw2[i] = 0;
  }
}

//____________________________________________________________________
Long64_t AliTHn::Merge(TCollection* list)
{
  // Merge a list of AliTHn objects with this (needed for
  // PROOF).
  // Returns the number of merged objects (including this).

  if (!list)
    return 0;

  if (list->IsEmpty())
    return 1;

  AliCFContainer::Merge(list);

  TIterator* iter = list->MakeIterator();
  TObject* obj;

  Int_t count = 0;
  while ((obj = iter->Next())) {

    AliTHn* entry = dynamic_cast<AliTHn*> (obj);
    if (entry == 0)
      continue;

    for (Int_t i=0; i<fNSteps; i++)
    {
      if (entry->fValues[i])
      {
	if (!fValues[i])
	  fValues[i] = new TArrayF(fNBins);

	for (Long64_t l = 0; l<fNBins; l++)
	  fValues[i]->GetArray()[l] += entry->fValues[i]->GetArray()[l];
      }

      if (entry->fSumw2[i])
      {
	if (!fSumw2[i])
	  fSumw2[i] = new TArrayF(fNBins);

	for (Long64_t l = 0; l<fNBins; l++)
	  fSumw2[i]->GetArray()[l] += entry->fSumw2[i]->GetArray()[l];
      }
    }

    count++;
  }

  return count+1;
}

void AliTHn::Fill(const Double_t *var, Int_t istep, Double_t weight)
{
  // fills an entry

  // fill axis cache
  if (!axisCache)
  {
    axisCache = new TAxis*[fNVars];
    for (Int_t i=0; i<fNVars; i++)
      axisCache[i] = GetAxis(i, 0);
  }

  // calculate global bin index
  Long64_t bin = 0;
  for (Int_t i=0; i<fNVars; i++)
  {
    bin *= axisCache[i]->GetNbins();

    Int_t tmpBin = axisCache[i]->FindBin(var[i]);
//     Printf("%d", tmpBin);
    // under/overflow not supported
    if (tmpBin < 1 || tmpBin > axisCache[i]->GetNbins())
      return;

    // bins start from 0 here
    bin += tmpBin - 1;
//     Printf("%lld", bin);
  }

  if (!fValues[istep])
  {
    fValues[istep] = new TArrayF(fNBins);
    AliInfo(Form("Created values container for step %d", istep));
  }

  if (weight != 1)
  {
    // initialize with already filled entries (which have been filled with weight == 1), in this case fSumw2 := fValues
    if (!fSumw2[istep])
    {
      fSumw2[istep] = new TArrayF(*fValues[istep]);
      AliInfo(Form("Created sumw2 container for step %d", istep));
    }
  }

  fValues[istep]->GetArray()[bin] += weight;
  if (fSumw2[istep])
    fSumw2[istep]->GetArray()[bin] += weight * weight;

//   Printf("%f", fValues[istep][bin]);

  // debug
//   AliCFContainer::Fill(var, istep, weight);
}

Long64_t AliTHn::GetGlobalBinIndex(const Int_t* binIdx)
{
  // calculates global bin index
  // binIdx contains TAxis bin indexes
  // here bin count starts at 0 because we do not have over/underflow bins

  Long64_t bin = 0;
  for (Int_t i=0; i<fNVars; i++)
  {
    bin *= GetAxis(i, 0)->GetNbins();
    bin += binIdx[i] - 1;
  }

  return bin;
}

void AliTHn::FillContainer(AliCFContainer* cont)
{
  // fills the information stored in the buffer in this class into the container <cont>

  for (Int_t i=0; i<fNSteps; i++)
  {
    if (!fValues[i])
      continue;

    Float_t* source = fValues[i]->GetArray();
    // if fSumw2 is not stored, the sqrt of the number of bin entries in source is filled below; otherwise we use fSumw2
    Float_t* sourceSumw2 = source;
    if (fSumw2[i])
      sourceSumw2 = fSumw2[i]->GetArray();

    THnSparse* target = cont->GetGrid(i)->GetGrid();

    Int_t* binIdx = new Int_t[fNVars];
    Int_t* nBins  = new Int_t[fNVars];
    for (Int_t j=0; j<fNVars; j++)
    {
      binIdx[j] = 1;
      nBins[j] = target->GetAxis(j)->GetNbins();
    }

    Long64_t count = 0;

    while (1)
    {
//       for (Int_t j=0; j<fNVars; j++)
// 	printf("%d ", binIdx[j]);

      Long64_t globalBin = GetGlobalBinIndex(binIdx);
//       Printf(" --> %lld", globalBin);

      if (source[globalBin] != 0)
      {
	target->SetBinContent(binIdx, source[globalBin]);
	target->SetBinError(binIdx, TMath::Sqrt(sourceSumw2[globalBin]));

	count++;
      }

      binIdx[fNVars-1]++;

      for (Int_t j=fNVars-1; j>0; j--)
      {
	if (binIdx[j] > nBins[j])
	{
	  binIdx[j] = 1;
	  binIdx[j-1]++;
	}
      }

      if (binIdx[0] > nBins[0])
	break;
    }

    AliInfo(Form("Step %d: copied %lld entries out of %lld bins", i, count, GetGlobalBinIndex(binIdx)));

    delete[] binIdx;
    delete[] nBins;
  }
}

void AliTHn::FillParent()
{
  // fills the information stored in the buffer in this class into the baseclass containers

  FillContainer(this);
}

void AliTHn::ReduceAxis()
{
  // "removes" one axis by summing over the axis and putting the entry to bin 1
  // TODO presently only implemented for the last axis

  Int_t axis = fNVars-1;

  for (Int_t i=0; i<fNSteps; i++)
  {
    if (!fValues[i])
      continue;

    Float_t* source = fValues[i]->GetArray();
    Float_t* sourceSumw2 = 0;
    if (fSumw2[i])
      sourceSumw2 = fSumw2[i]->GetArray();

    THnSparse* target = GetGrid(i)->GetGrid();

    Int_t* binIdx = new Int_t[fNVars];
    Int_t* nBins  = new Int_t[fNVars];
    for (Int_t j=0; j<fNVars; j++)
    {
      binIdx[j] = 1;
      nBins[j] = target->GetAxis(j)->GetNbins();
    }

    Long64_t count = 0;

    while (1)
    {
      // sum over axis <axis>
      Float_t sumValues = 0;
      Float_t sumSumw2 = 0;
      for (Int_t j=1; j<=nBins[axis]; j++)
      {
	binIdx[axis] = j;
	Long64_t globalBin = GetGlobalBinIndex(binIdx);
	sumValues += source[globalBin];
	source[globalBin] = 0;

	if (sourceSumw2)
	{
	  sumSumw2 += sourceSumw2[globalBin];
	  sourceSumw2[globalBin] = 0;
	}
      }
      binIdx[axis] = 1;

      Long64_t globalBin = GetGlobalBinIndex(binIdx);
      source[globalBin] = sumValues;
      if (sourceSumw2)
	sourceSumw2[globalBin] = sumSumw2;

      count++;

      // next bin
      binIdx[fNVars-2]++;

      for (Int_t j=fNVars-2; j>0; j--)
      {
	if (binIdx[j] > nBins[j])
	{
	  binIdx[j] = 1;
	  binIdx[j-1]++;
	}
      }

      if (binIdx[0] > nBins[0])
	break;
    }

    AliInfo(Form("Step %d: reduced %lld bins to %lld entries", i, GetGlobalBinIndex(binIdx), count));

    delete[] binIdx;
    delete[] nBins;
  }
}
<|endoftext|>


<commit_before>/*
** Copyright 2011-2014 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/

#include <memory>
#include <sstream>
#include "com/centreon/broker/config/parser.hh"
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/influxdb/connector.hh"
#include "com/centreon/broker/influxdb/factory.hh"

using namespace com::centreon::broker;
using namespace com::centreon::broker::influxdb;

/**************************************
*                                     *
*           Static Objects            *
*                                     *
**************************************/

/**
 *  Find a parameter in configuration.
 *
 *  @param[in] cfg Configuration object.
 *  @param[in] key Property to get.
 *
 *  @return Property value.
 */
static std::string find_param(
                     config::endpoint const& cfg,
                     QString const& key) {
  QMap<QString, QString>::const_iterator it(cfg.params.find(key));
  if (cfg.params.end() == it)
    throw (exceptions::msg() << "influxdb: no '" << key
           << "' defined for endpoint '" << cfg.name << "'");
  return (it.value().toStdString());
}

/**************************************
*                                     *
*           Public Methods            *
*                                     *
**************************************/

/**
 *  Default constructor.
 */
factory::factory() {}

/**
 *  Copy constructor.
 *
 *  @param[in] f Object to copy.
 */
factory::factory(factory const& f) : io::factory(f) {}

/**
 *  Destructor.
 */
factory::~factory() {}

/**
 *  Assignment operator.
 *
 *  @param[in] f Object to copy.
 *
 *  @return This object.
 */
factory& factory::operator=(factory const& f) {
  io::factory::operator=(f);
  return (*this);
}

/**
 *  Clone this object.
 *
 *  @return Exact copy of this factory.
 */
io::factory* factory::clone() const {
  return (new factory(*this));
}

/**
 *  Check if a configuration match the storage layer.
 *
 *  @param[in] cfg       Endpoint configuration.
 *  @param[in] is_input  true if endpoint should act as input.
 *  @param[in] is_output true if endpoint should act as output.
 *
 *  @return true if the configuration matches the storage layer.
 */
bool factory::has_endpoint(
                config::endpoint& cfg,
                bool is_input,
                bool is_output) const {
  (void)is_input;
  bool is_ifdb(!cfg.type.compare("influxdb", Qt::CaseInsensitive)
                  && is_output);
  return (is_ifdb);
}

/**
 *  Build a storage endpoint from a configuration.
 *
 *  @param[in]  cfg         Endpoint configuration.
 *  @param[in]  is_input    true if endpoint should act as input.
 *  @param[in]  is_output   true if endpoint should act as output.
 *  @param[out] is_acceptor Will be set to false.
 *
 *  @return Endpoint matching the given configuration.
 */
io::endpoint* factory::new_endpoint(
                         config::endpoint& cfg,
                         bool is_input,
                         bool is_output,
                         bool& is_acceptor) const {
  (void)is_input;
  (void)is_output;

  std::string user(find_param(cfg, "user"));
  std::string passwd(find_param(cfg, "password"));
  std::string addr(find_param(cfg, "host"));
  std::string db(find_param(cfg, "db"));

  unsigned short port(0);
  {
    std::stringstream ss;
    ss << find_param(cfg, "port");
    ss >> port;
    if (!ss.eof())
      throw (exceptions::msg() << "influxdb: couldn't parse port '" << ss.str()
             << "' defined for endpoint '" << cfg.name << "'");
  }

  unsigned int queries_per_transaction(0);
  {
    QMap<QString, QString>::const_iterator
      it(cfg.params.find("queries_per_transaction"));
    if (it != cfg.params.end())
      queries_per_transaction = it.value().toUInt();
    else
      queries_per_transaction = 1000;
  }

  std::string version;
  {
    QMap<QString, QString>::const_iterator
      it(cfg.params.find("influxdb_version"));
    if (it != cfg.params.end())
      version = it.value().toStdString();
    else
      version = "0.9";
  }

  // Connector.
  std::auto_ptr<influxdb::connector> c(new influxdb::connector);
  c->connect_to(user, passwd, addr, port, db, queries_per_transaction, version);
  is_acceptor = false;
  return (c.release());
}
<commit_msg>Influxdb: Follow documentation for configuration option.<commit_after>/*
** Copyright 2011-2014 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/

#include <memory>
#include <sstream>
#include "com/centreon/broker/config/parser.hh"
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/influxdb/connector.hh"
#include "com/centreon/broker/influxdb/factory.hh"

using namespace com::centreon::broker;
using namespace com::centreon::broker::influxdb;

/**************************************
*                                     *
*           Static Objects            *
*                                     *
**************************************/

/**
 *  Find a parameter in configuration.
 *
 *  @param[in] cfg Configuration object.
 *  @param[in] key Property to get.
 *
 *  @return Property value.
 */
static std::string find_param(
                     config::endpoint const& cfg,
                     QString const& key) {
  QMap<QString, QString>::const_iterator it(cfg.params.find(key));
  if (cfg.params.end() == it)
    throw (exceptions::msg() << "influxdb: no '" << key
           << "' defined for endpoint '" << cfg.name << "'");
  return (it.value().toStdString());
}

/**************************************
*                                     *
*           Public Methods            *
*                                     *
**************************************/

/**
 *  Default constructor.
 */
factory::factory() {}

/**
 *  Copy constructor.
 *
 *  @param[in] f Object to copy.
 */
factory::factory(factory const& f) : io::factory(f) {}

/**
 *  Destructor.
 */
factory::~factory() {}

/**
 *  Assignment operator.
 *
 *  @param[in] f Object to copy.
 *
 *  @return This object.
 */
factory& factory::operator=(factory const& f) {
  io::factory::operator=(f);
  return (*this);
}

/**
 *  Clone this object.
 *
 *  @return Exact copy of this factory.
 */
io::factory* factory::clone() const {
  return (new factory(*this));
}

/**
 *  Check if a configuration match the storage layer.
 *
 *  @param[in] cfg       Endpoint configuration.
 *  @param[in] is_input  true if endpoint should act as input.
 *  @param[in] is_output true if endpoint should act as output.
 *
 *  @return true if the configuration matches the storage layer.
 */
bool factory::has_endpoint(
                config::endpoint& cfg,
                bool is_input,
                bool is_output) const {
  (void)is_input;
  bool is_ifdb(!cfg.type.compare("influxdb", Qt::CaseInsensitive)
                  && is_output);
  return (is_ifdb);
}

/**
 *  Build a storage endpoint from a configuration.
 *
 *  @param[in]  cfg         Endpoint configuration.
 *  @param[in]  is_input    true if endpoint should act as input.
 *  @param[in]  is_output   true if endpoint should act as output.
 *  @param[out] is_acceptor Will be set to false.
 *
 *  @return Endpoint matching the given configuration.
 */
io::endpoint* factory::new_endpoint(
                         config::endpoint& cfg,
                         bool is_input,
                         bool is_output,
                         bool& is_acceptor) const {
  (void)is_input;
  (void)is_output;

  std::string user(find_param(cfg, "db_user"));
  std::string passwd(find_param(cfg, "db_password"));
  std::string addr(find_param(cfg, "db_host"));
  std::string db(find_param(cfg, "db_name"));

  unsigned short port(0);
  {
    std::stringstream ss;
    ss << find_param(cfg, "db_port");
    ss >> port;
    if (!ss.eof())
      throw (exceptions::msg() << "influxdb: couldn't parse port '" << ss.str()
             << "' defined for endpoint '" << cfg.name << "'");
  }

  unsigned int queries_per_transaction(0);
  {
    QMap<QString, QString>::const_iterator
      it(cfg.params.find("queries_per_transaction"));
    if (it != cfg.params.end())
      queries_per_transaction = it.value().toUInt();
    else
      queries_per_transaction = 1000;
  }

  std::string version;
  {
    QMap<QString, QString>::const_iterator
      it(cfg.params.find("influxdb_version"));
    if (it != cfg.params.end())
      version = it.value().toStdString();
    else
      version = "0.9";
  }

  // Connector.
  std::auto_ptr<influxdb::connector> c(new influxdb::connector);
  c->connect_to(user, passwd, addr, port, db, queries_per_transaction, version);
  is_acceptor = false;
  return (c.release());
}
<|endoftext|>


<commit_before>#include "process_splitters/Alignment.hpp"
#include "TestData.hpp"
#include "testing/TestBamRecords.hpp"

#include <sam.h>

#include <stdint.h>
#include <gtest/gtest.h>
#include <string>
#include <stdexcept>

class TestAlignment : public ::testing::Test {
    public:
        bam1_t *record1;
        bam1_t *record2;
        TestBamRecords records;

        TestAlignment() {
            record1 = records.record;
            record2 = records.record2;
        }
};

TEST_F(TestAlignment, create_from_bam) {
    Alignment test_obj(record1, records.header);
    ASSERT_EQ(test_obj.chrom, "chr21");
    ASSERT_EQ(test_obj.strand, '+');
    ASSERT_EQ(test_obj.rapos, 44877125u);
    // TODO add additional tests once we're certain about the values
}

TEST_F(TestAlignment, create_from_sa) {
    uint8_t *sa_ptr = bam_aux_get(record2, "SA") + 1; //skipping the type field
    std::string data = (char const*) sa_ptr;
    char const* beg = data.data();
    char const* end = data.data() + data.size() - 1; //subtracting off the semicolon
    Alignment test_obj(beg, end);
    ASSERT_EQ(test_obj.chrom, "chr21");
    ASSERT_EQ(test_obj.strand, '+');
    ASSERT_EQ(test_obj.rapos, 44877125u);
}

TEST_F(TestAlignment, create_from_truncated_sa) {
    uint8_t *sa_ptr = bam_aux_get(record2, "SA") + 1; //skipping the type field
    std::string data((char const*) sa_ptr, 28); //truncate the string
    ASSERT_EQ(data, "chr21,44877125,+,101S41M9S,3");
    char const* beg = data.data();
    char const* end = data.data() + data.size();

    ASSERT_THROW(Alignment test_obj(beg, end), std::runtime_error);
}

TEST_F(TestAlignment, calculate_additional_offsets) {

}

TEST_F(TestAlignment, start_diagonal) {

}

TEST_F(TestAlignment, end_diagonal) {

}

TEST_F(TestAlignment, mno) {

}

TEST_F(TestAlignment, desert) {

}

TEST_F(TestAlignment, insert_size) {

}

TEST_F(TestAlignment, should_check) {

}

<commit_msg>flesh out more tests from Alignment<commit_after>#include "process_splitters/Alignment.hpp"
#include "TestData.hpp"
#include "testing/TestBamRecords.hpp"

#include <sam.h>

#include <stdint.h>
#include <gtest/gtest.h>
#include <string>
#include <stdexcept>

class TestAlignment : public ::testing::Test {
    public:
        bam1_t *record1;
        bam1_t *record2;
        TestBamRecords records;

        TestAlignment() {
            record1 = records.record;
            record2 = records.record2;
        }
};

TEST_F(TestAlignment, create_from_bam) {
    Alignment test_obj(record1, records.header);
    ASSERT_EQ("chr21", test_obj.chrom);
    ASSERT_EQ('+', test_obj.strand);
    ASSERT_EQ(44877125u, test_obj.rapos);
    // TODO add additional tests once we're certain about the values
}

TEST_F(TestAlignment, create_from_sa) {
    uint8_t *sa_ptr = bam_aux_get(record2, "SA") + 1; //skipping the type field
    std::string data = (char const*) sa_ptr;
    char const* beg = data.data();
    char const* end = data.data() + data.size() - 1; //subtracting off the semicolon
    Alignment test_obj(beg, end);
    ASSERT_EQ("chr21", test_obj.chrom);
    ASSERT_EQ('+', test_obj.strand);
    ASSERT_EQ(44877125u, test_obj.rapos);
    ASSERT_EQ(41u, test_obj.offsets.raLen);
}

TEST_F(TestAlignment, create_from_truncated_sa) {
    uint8_t *sa_ptr = bam_aux_get(record2, "SA") + 1; //skipping the type field
    std::string data((char const*) sa_ptr, 28); //truncate the string
    ASSERT_EQ(data, "chr21,44877125,+,101S41M9S,3");
    char const* beg = data.data();
    char const* end = data.data() + data.size();

    ASSERT_THROW(Alignment test_obj(beg, end), std::runtime_error);
}

TEST_F(TestAlignment, calculate_additional_offsets) {
    AlignmentOffsets data("2H5S10M2D5M3I5M4S");
    Alignment test_obj;
    test_obj.rapos = 50u;
    test_obj.strand = '+';
    test_obj.offsets = data;
    test_obj.calculate_additional_offsets();
    ASSERT_EQ(43u, test_obj.pos);
    ASSERT_EQ(test_obj.SQO, 7);
    ASSERT_EQ(test_obj.EQO, 29);

    test_obj.strand = '-';
    test_obj.calculate_additional_offsets();
    ASSERT_EQ(75u, test_obj.pos);
    ASSERT_EQ(test_obj.SQO, 4);
    ASSERT_EQ(test_obj.EQO, 26);
}

TEST_F(TestAlignment, start_diagonal) {
    Alignment a1(record1, records.header);
    ASSERT_EQ(44877125 - 101, a1.start_diagonal());
}

TEST_F(TestAlignment, end_diagonal) {
    Alignment a1(record1, records.header);
    ASSERT_EQ((44877125 + 41) - (101 + 41), a1.end_diagonal());
}

TEST_F(TestAlignment, mno) {

}

TEST_F(TestAlignment, desert) {

}

TEST_F(TestAlignment, insert_size) {

}

TEST_F(TestAlignment, should_check) {

}

<|endoftext|>


<commit_before>/****************************************************************************
 *
 * Copyright 2018 Samsung Electronics All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 *
 ****************************************************************************/

#include <tinyara/config.h>
#include <tinyara/init.h>
#include <apps/platform/cxxinitialize.h>
#include <tinyalsa/tinyalsa.h>
#include <fcntl.h>
#include <errno.h>
#include <media/MediaRecorder.h>
#include <media/MediaRecorderObserverInterface.h>
#include <media/MediaPlayer.h>
#include <media/MediaPlayerObserverInterface.h>
#include <media/FileOutputDataSource.h>
#include <media/BufferOutputDataSource.h>
#include <media/FileInputDataSource.h>
#include <iostream>
#include <memory>

constexpr int APP_ON = 1;
constexpr int RECORDER_START = 2;
constexpr int RECORDER_PAUSE = 3;
constexpr int RECORDER_RESUME = 4;
constexpr int RECORDER_STOP = 5;
constexpr int VOLUME_UP = 6;
constexpr int VOLUME_DOWN = 7;
constexpr int PLAY_DATA = 8;
constexpr int DELETE_FILE = 9;
constexpr int APP_OFF = 0;

using namespace std;
using namespace media;
using namespace media::stream;

static const int TEST_MEDIATYPE_PCM = 0;
static const int TEST_MEDIATYPE_OPUS = 1;

static const int TEST_DATASOURCE_TYPE_FILE = 0;
static const int TEST_DATASOURCE_TYPE_BUFFER = 1;

static const char *filePath = "";

class MediaRecorderTest : public MediaRecorderObserverInterface,
						  public MediaPlayerObserverInterface,
						  public enable_shared_from_this<MediaRecorderTest>
{
public:
	void onRecordStarted(MediaRecorder& mediaRecorder)
	{
		std::cout << "onRecordStarted" << std::endl;
		if (mDataSourceType == TEST_DATASOURCE_TYPE_BUFFER) {
			mfp = fopen(filePath, "w");
			if (mfp == NULL) {
				std::cout << "FILE OPEN FAILED" << std::endl;
				return;
			}
		}
	}

	void onRecordPaused(MediaRecorder& mediaRecorder)
	{
		std::cout << "onRecordPaused" << std::endl;
	}

	void onRecordFinished(MediaRecorder& mediaRecorder)
	{
		std::cout << "onRecordFinished" << std::endl;
		if (mDataSourceType == TEST_DATASOURCE_TYPE_BUFFER && mfp != NULL) {
			fclose(mfp);
		}
		mediaRecorder.unprepare();
	}

	void onRecordStartError(MediaRecorder& mediaRecorder, recorder_error_t errCode)
	{
		std::cout << "onRecordStartError!! errCode : " << errCode << std::endl;
	}

	void onRecordPauseError(MediaRecorder& mediaRecorder, recorder_error_t errCode)
	{
		std::cout << "onRecordPauseError!! errCode : " << errCode << std::endl;
	}

	void onRecordStopError(MediaRecorder& mediaRecorder, recorder_error_t errCode)
	{
		std::cout << "onRecordStopError!! errCode : " << errCode << std::endl;
	}

	void onRecordBufferDataReached(MediaRecorder& mediaRecorder, std::shared_ptr<unsigned char> data, size_t size)
	{
		if (mfp != NULL) {
			fwrite(data, sizeof(unsigned char), size, mfp);
		}
		std::cout << "onRecordBufferDataReached, data size : " << size << std::endl;
	}

	void onPlaybackStarted(MediaPlayer &mediaPlayer)
	{
		std::cout << "onPlaybackStarted" << std::endl;
		mIsPlaying = true;
	}

	void onPlaybackFinished(MediaPlayer &mediaPlayer)
	{
		std::cout << "onPlaybackFinished" << std::endl;
		mIsPlaying = false;

		if (mMp.unprepare() != PLAYER_OK) {
			std::cout << "Mediaplayer::unprepare failed" << std::endl;
		}

		if (mMp.destroy() != PLAYER_OK) {
			std::cout << "Mediaplayer::destroy failed" << std::endl;
		}
	}

	void onPlaybackError(MediaPlayer &mediaPlayer, player_error_t error)
	{
		std::cout << "onPlaybackError" << std::endl;
	}

	void onStartError(MediaPlayer &mediaPlayer, player_error_t error)
	{
		std::cout << "onStartError" << std::endl;
	}

	void onStopError(MediaPlayer &mediaPlayer, player_error_t error)
	{
		std::cout << "onStopError" << std::endl;
	}

	void onPauseError(MediaPlayer &mediaPlayer, player_error_t error)
	{
		std::cout << "onPauseError" << std::endl;
	}

	void onPlaybackPaused(MediaPlayer &mediaPlayer)
	{
		std::cout << "onPlaybackPaused" << std::endl;
	}

	void start(const int mediaType, const int dataSourceType)
	{
		mMediaType = mediaType;
		mDataSourceType = dataSourceType;
		uint8_t volume;
		mAppRunning = true;

		while (mAppRunning) {
			printRecorderMenu();
			switch (userInput(APP_ON, DELETE_FILE)) {
			case APP_ON:
				std::cout << "SELECTED APP ON" << std::endl;
				mMr.create();
				mMr.setObserver(shared_from_this());
				break;
			case RECORDER_START:
				std::cout << "SELECTED RECORDER_START" << std::endl;
				if (mIsPaused) {
					if (mMr.start()) {
						std::cout << "START IN PAUSE STATE SUCCESS" << std::endl;
						mIsPaused = false;
					}
				} else {
					if (mMediaType == TEST_MEDIATYPE_PCM) {
						filePath = "/tmp/record.pcm";
					} else if (mMediaType == TEST_MEDIATYPE_OPUS) {
						filePath = "/tmp/record.opus";
					}

					if (mDataSourceType == TEST_DATASOURCE_TYPE_FILE) {
						mMr.setDataSource(unique_ptr<FileOutputDataSource>(
							new FileOutputDataSource(2, 16000, AUDIO_FORMAT_TYPE_S16_LE, filePath)));
					} else if (mDataSourceType == TEST_DATASOURCE_TYPE_BUFFER) {
						mMr.setDataSource(unique_ptr<BufferOutputDataSource>(new BufferOutputDataSource()));
					}

					if (mMr.setDuration(3) == RECORDER_ERROR_NONE && mMr.prepare() == RECORDER_ERROR_NONE) {
						mMr.start();
						std::cout << "START IN NONE-PAUSE STATE SUCCESS" << std::endl;
					} else {
						std::cout << "PREPARE FAILED" << std::endl;
					}
				}
				break;
			case RECORDER_PAUSE:
				std::cout << "SELECTED RECORDER_PAUSE" << std::endl;
				if (mMr.pause()) {
					mIsPaused = true;
					std::cout << "PAUSE SUCCESS" << std::endl;
				} else {
					std::cout << "PAUSE FAILED" << std::endl;
				}
				break;
			case RECORDER_RESUME:
				std::cout << "SELECTED RECORDER_RESUME" << std::endl;
				if (mMr.start()) {
					mIsPaused = false;
					std::cout << "RESUME SUCCESS" << std::endl;
				} else {
					std::cout << "RESUME FAILED" << std::endl;
				}
				break;
			case RECORDER_STOP:
				std::cout << "SELECTED RECORDER_STOP" << std::endl;
				if (mMr.stop() == RECORDER_ERROR_NONE) {
					mIsPaused = false;
					std::cout << "STOP SUCCESS" << std::endl;
				} else {
					std::cout << "STOP FAILED" << std::endl;
				}
				break;
			case PLAY_DATA:
				std::cout << "PLAY_DATA" << std::endl;
				play_data();
				break;
			case VOLUME_UP:
				cout << "VOLUME_UP is selected" << endl;
				if (mMr.getVolume(&volume) != RECORDER_ERROR_NONE) {
					cout << "MediaRecorder::getVolume failed" << endl;
				} else {
					cout << "Volume was " << (int)volume << endl;
				}
				if (mMr.setVolume(volume + 1) != RECORDER_ERROR_NONE) {
					cout << "MediaRecorder::setVolume failed" << endl;
				}
				if (mMr.getVolume(&volume) != RECORDER_ERROR_NONE) {
					cout << "MediaRecorder::getVolume failed" << endl;
				} else {
					cout << "Now, Volume is " << (int)volume << endl;
				}
				break;
			case VOLUME_DOWN:
				cout << "VOLUME_DOWN is selected" << endl;
				if (mMr.getVolume(&volume) != RECORDER_ERROR_NONE) {
					cout << "MediaRecorder::getVolume failed" << endl;
				} else {
					cout << "Volume was " << (int)volume << endl;
				}
				if (mMr.setVolume(volume - 1) != RECORDER_ERROR_NONE) {
					cout << "MediaRecorder::setVolume failed" << endl;
				}
				if (mMr.getVolume(&volume) != RECORDER_ERROR_NONE) {
					cout << "MediaRecorder::getVolume failed" << endl;
				} else {
					cout << "Now, Volume is " << (int)volume << endl;
				}
				break;
			case APP_OFF:
				std::cout << "SELECTED APP_OFF" << std::endl;
				mMr.destroy();
				mAppRunning = false;
				break;
			case DELETE_FILE:
				if (unlink(filePath) == OK) {
					std::cout << "FILE DELETED" << std::endl;
				} else {
					std::cout << "DELETE FAILED ERRPR " << errno << std::endl;
				}
				break;
			}
		}
	}

	void play_data()
	{
		if (mIsPlaying) {
			std::cout << "Already in playback" << std::endl;
			return;
		}

		std::cout << "playback " << filePath << std::endl;

		auto source = std::move(unique_ptr<FileInputDataSource>(new FileInputDataSource(filePath)));
		source->setSampleRate(16000);
		source->setChannels(2);
		source->setPcmFormat(AUDIO_FORMAT_TYPE_S16_LE);

		if (mMp.create() != PLAYER_OK) {
			std::cout << "Mediaplayer::create failed" << std::endl;
			return;
		}

		if (mMp.setObserver(shared_from_this()) != PLAYER_OK) {
			std::cout << "Mediaplayer::setObserver failed" << std::endl;
			return;
		}

		if (mMp.setDataSource(std::move(source)) != PLAYER_OK) {
			std::cout << "Mediaplayer::setDataSource failed" << std::endl;
			return;
		}

		if (mMp.prepare() != PLAYER_OK) {
			std::cout << "Mediaplayer::prepare failed" << std::endl;
			return;
		}

		if (mMp.start() != PLAYER_OK) {
			std::cout << "Mediaplayer::start failed" << std::endl;
			if (mMp.unprepare() != PLAYER_OK) {
				std::cout << "Mediaplayer::unprepare failed" << std::endl;
			}
			return;
		}
	}

	void printRecorderMenu()
	{
		std::cout << "========================================" << std::endl;
		std::cout << "1. RECORDER APP ON" << std::endl;
		std::cout << "2. RECORDER Start" << std::endl;
		std::cout << "3. RECORDER Pause" << std::endl;
		std::cout << "4. RECORDER Resume" << std::endl;
		std::cout << "5. RECORDER Stop" << std::endl;
		std::cout << "6. RECORDER Volume Up" << std::endl;
		std::cout << "7. RECORDER Volume Down" << std::endl;
		std::cout << "8. play Data" << std::endl;
		std::cout << "9. Delete file" << std::endl;
		std::cout << "0. RECORDER APP OFF" << std::endl;
		std::cout << "========================================" << std::endl;
	}

	int userInput(int min, int max)
	{
		assert(min <= max);
		int input = 0;

		std::cin >> input;
		std::cout << std::endl;

		if (!std::cin.fail()) {
			if (min <= input && input <= max) {
				std::cout << "return input" << std::endl;
				return input;
			}
		}

		std::cin.clear();
		std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

		std::cout << "Invalid Input, please try again" << std::endl;

		return input;
	}

	MediaRecorderTest() : mAppRunning(false), mIsPaused(false), mIsPlaying(false)
	{
	}
	~MediaRecorderTest()
	{
	}

private:
	bool mAppRunning;
	bool mIsPaused;
	MediaRecorder mMr;
	bool mIsPlaying;
	MediaPlayer mMp;
	FILE *mfp;
	int mMediaType;
	int mDataSourceType;
};

extern "C" {
int mediarecorder_main(int argc, char *argv[])
{
	up_cxxinitialize();

	auto mediaRecorderTest = make_shared<MediaRecorderTest>();
	mediaRecorderTest->start(TEST_MEDIATYPE_PCM, TEST_DATASOURCE_TYPE_FILE);

	return 0;
}
}
<commit_msg>media: Fix build error because of invalid type casting<commit_after>/****************************************************************************
 *
 * Copyright 2018 Samsung Electronics All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 *
 ****************************************************************************/

#include <tinyara/config.h>
#include <tinyara/init.h>
#include <apps/platform/cxxinitialize.h>
#include <tinyalsa/tinyalsa.h>
#include <fcntl.h>
#include <errno.h>
#include <media/MediaRecorder.h>
#include <media/MediaRecorderObserverInterface.h>
#include <media/MediaPlayer.h>
#include <media/MediaPlayerObserverInterface.h>
#include <media/FileOutputDataSource.h>
#include <media/BufferOutputDataSource.h>
#include <media/FileInputDataSource.h>
#include <iostream>
#include <memory>

constexpr int APP_ON = 1;
constexpr int RECORDER_START = 2;
constexpr int RECORDER_PAUSE = 3;
constexpr int RECORDER_RESUME = 4;
constexpr int RECORDER_STOP = 5;
constexpr int VOLUME_UP = 6;
constexpr int VOLUME_DOWN = 7;
constexpr int PLAY_DATA = 8;
constexpr int DELETE_FILE = 9;
constexpr int APP_OFF = 0;

using namespace std;
using namespace media;
using namespace media::stream;

static const int TEST_MEDIATYPE_PCM = 0;
static const int TEST_MEDIATYPE_OPUS = 1;

static const int TEST_DATASOURCE_TYPE_FILE = 0;
static const int TEST_DATASOURCE_TYPE_BUFFER = 1;

static const char *filePath = "";

class MediaRecorderTest : public MediaRecorderObserverInterface,
						  public MediaPlayerObserverInterface,
						  public enable_shared_from_this<MediaRecorderTest>
{
public:
	void onRecordStarted(MediaRecorder& mediaRecorder)
	{
		std::cout << "onRecordStarted" << std::endl;
		if (mDataSourceType == TEST_DATASOURCE_TYPE_BUFFER) {
			mfp = fopen(filePath, "w");
			if (mfp == NULL) {
				std::cout << "FILE OPEN FAILED" << std::endl;
				return;
			}
		}
	}

	void onRecordPaused(MediaRecorder& mediaRecorder)
	{
		std::cout << "onRecordPaused" << std::endl;
	}

	void onRecordFinished(MediaRecorder& mediaRecorder)
	{
		std::cout << "onRecordFinished" << std::endl;
		if (mDataSourceType == TEST_DATASOURCE_TYPE_BUFFER && mfp != NULL) {
			fclose(mfp);
		}
		mediaRecorder.unprepare();
	}

	void onRecordStartError(MediaRecorder& mediaRecorder, recorder_error_t errCode)
	{
		std::cout << "onRecordStartError!! errCode : " << errCode << std::endl;
	}

	void onRecordPauseError(MediaRecorder& mediaRecorder, recorder_error_t errCode)
	{
		std::cout << "onRecordPauseError!! errCode : " << errCode << std::endl;
	}

	void onRecordStopError(MediaRecorder& mediaRecorder, recorder_error_t errCode)
	{
		std::cout << "onRecordStopError!! errCode : " << errCode << std::endl;
	}

	void onRecordBufferDataReached(MediaRecorder& mediaRecorder, std::shared_ptr<unsigned char> data, size_t size)
	{
		if (mfp != NULL) {
			fwrite((const void *)data.get(), sizeof(unsigned char), size, mfp);
		}
		std::cout << "onRecordBufferDataReached, data size : " << size << std::endl;
	}

	void onPlaybackStarted(MediaPlayer &mediaPlayer)
	{
		std::cout << "onPlaybackStarted" << std::endl;
		mIsPlaying = true;
	}

	void onPlaybackFinished(MediaPlayer &mediaPlayer)
	{
		std::cout << "onPlaybackFinished" << std::endl;
		mIsPlaying = false;

		if (mMp.unprepare() != PLAYER_OK) {
			std::cout << "Mediaplayer::unprepare failed" << std::endl;
		}

		if (mMp.destroy() != PLAYER_OK) {
			std::cout << "Mediaplayer::destroy failed" << std::endl;
		}
	}

	void onPlaybackError(MediaPlayer &mediaPlayer, player_error_t error)
	{
		std::cout << "onPlaybackError" << std::endl;
	}

	void onStartError(MediaPlayer &mediaPlayer, player_error_t error)
	{
		std::cout << "onStartError" << std::endl;
	}

	void onStopError(MediaPlayer &mediaPlayer, player_error_t error)
	{
		std::cout << "onStopError" << std::endl;
	}

	void onPauseError(MediaPlayer &mediaPlayer, player_error_t error)
	{
		std::cout << "onPauseError" << std::endl;
	}

	void onPlaybackPaused(MediaPlayer &mediaPlayer)
	{
		std::cout << "onPlaybackPaused" << std::endl;
	}

	void start(const int mediaType, const int dataSourceType)
	{
		mMediaType = mediaType;
		mDataSourceType = dataSourceType;
		uint8_t volume;
		mAppRunning = true;

		while (mAppRunning) {
			printRecorderMenu();
			switch (userInput(APP_ON, DELETE_FILE)) {
			case APP_ON:
				std::cout << "SELECTED APP ON" << std::endl;
				mMr.create();
				mMr.setObserver(shared_from_this());
				break;
			case RECORDER_START:
				std::cout << "SELECTED RECORDER_START" << std::endl;
				if (mIsPaused) {
					if (mMr.start()) {
						std::cout << "START IN PAUSE STATE SUCCESS" << std::endl;
						mIsPaused = false;
					}
				} else {
					if (mMediaType == TEST_MEDIATYPE_PCM) {
						filePath = "/tmp/record.pcm";
					} else if (mMediaType == TEST_MEDIATYPE_OPUS) {
						filePath = "/tmp/record.opus";
					}

					if (mDataSourceType == TEST_DATASOURCE_TYPE_FILE) {
						mMr.setDataSource(unique_ptr<FileOutputDataSource>(
							new FileOutputDataSource(2, 16000, AUDIO_FORMAT_TYPE_S16_LE, filePath)));
					} else if (mDataSourceType == TEST_DATASOURCE_TYPE_BUFFER) {
						mMr.setDataSource(unique_ptr<BufferOutputDataSource>(new BufferOutputDataSource()));
					}

					if (mMr.setDuration(3) == RECORDER_ERROR_NONE && mMr.prepare() == RECORDER_ERROR_NONE) {
						mMr.start();
						std::cout << "START IN NONE-PAUSE STATE SUCCESS" << std::endl;
					} else {
						std::cout << "PREPARE FAILED" << std::endl;
					}
				}
				break;
			case RECORDER_PAUSE:
				std::cout << "SELECTED RECORDER_PAUSE" << std::endl;
				if (mMr.pause()) {
					mIsPaused = true;
					std::cout << "PAUSE SUCCESS" << std::endl;
				} else {
					std::cout << "PAUSE FAILED" << std::endl;
				}
				break;
			case RECORDER_RESUME:
				std::cout << "SELECTED RECORDER_RESUME" << std::endl;
				if (mMr.start()) {
					mIsPaused = false;
					std::cout << "RESUME SUCCESS" << std::endl;
				} else {
					std::cout << "RESUME FAILED" << std::endl;
				}
				break;
			case RECORDER_STOP:
				std::cout << "SELECTED RECORDER_STOP" << std::endl;
				if (mMr.stop() == RECORDER_ERROR_NONE) {
					mIsPaused = false;
					std::cout << "STOP SUCCESS" << std::endl;
				} else {
					std::cout << "STOP FAILED" << std::endl;
				}
				break;
			case PLAY_DATA:
				std::cout << "PLAY_DATA" << std::endl;
				play_data();
				break;
			case VOLUME_UP:
				cout << "VOLUME_UP is selected" << endl;
				if (mMr.getVolume(&volume) != RECORDER_ERROR_NONE) {
					cout << "MediaRecorder::getVolume failed" << endl;
				} else {
					cout << "Volume was " << (int)volume << endl;
				}
				if (mMr.setVolume(volume + 1) != RECORDER_ERROR_NONE) {
					cout << "MediaRecorder::setVolume failed" << endl;
				}
				if (mMr.getVolume(&volume) != RECORDER_ERROR_NONE) {
					cout << "MediaRecorder::getVolume failed" << endl;
				} else {
					cout << "Now, Volume is " << (int)volume << endl;
				}
				break;
			case VOLUME_DOWN:
				cout << "VOLUME_DOWN is selected" << endl;
				if (mMr.getVolume(&volume) != RECORDER_ERROR_NONE) {
					cout << "MediaRecorder::getVolume failed" << endl;
				} else {
					cout << "Volume was " << (int)volume << endl;
				}
				if (mMr.setVolume(volume - 1) != RECORDER_ERROR_NONE) {
					cout << "MediaRecorder::setVolume failed" << endl;
				}
				if (mMr.getVolume(&volume) != RECORDER_ERROR_NONE) {
					cout << "MediaRecorder::getVolume failed" << endl;
				} else {
					cout << "Now, Volume is " << (int)volume << endl;
				}
				break;
			case APP_OFF:
				std::cout << "SELECTED APP_OFF" << std::endl;
				mMr.destroy();
				mAppRunning = false;
				break;
			case DELETE_FILE:
				if (unlink(filePath) == OK) {
					std::cout << "FILE DELETED" << std::endl;
				} else {
					std::cout << "DELETE FAILED ERRPR " << errno << std::endl;
				}
				break;
			}
		}
	}

	void play_data()
	{
		if (mIsPlaying) {
			std::cout << "Already in playback" << std::endl;
			return;
		}

		std::cout << "playback " << filePath << std::endl;

		auto source = std::move(unique_ptr<FileInputDataSource>(new FileInputDataSource(filePath)));
		source->setSampleRate(16000);
		source->setChannels(2);
		source->setPcmFormat(AUDIO_FORMAT_TYPE_S16_LE);

		if (mMp.create() != PLAYER_OK) {
			std::cout << "Mediaplayer::create failed" << std::endl;
			return;
		}

		if (mMp.setObserver(shared_from_this()) != PLAYER_OK) {
			std::cout << "Mediaplayer::setObserver failed" << std::endl;
			return;
		}

		if (mMp.setDataSource(std::move(source)) != PLAYER_OK) {
			std::cout << "Mediaplayer::setDataSource failed" << std::endl;
			return;
		}

		if (mMp.prepare() != PLAYER_OK) {
			std::cout << "Mediaplayer::prepare failed" << std::endl;
			return;
		}

		if (mMp.start() != PLAYER_OK) {
			std::cout << "Mediaplayer::start failed" << std::endl;
			if (mMp.unprepare() != PLAYER_OK) {
				std::cout << "Mediaplayer::unprepare failed" << std::endl;
			}
			return;
		}
	}

	void printRecorderMenu()
	{
		std::cout << "========================================" << std::endl;
		std::cout << "1. RECORDER APP ON" << std::endl;
		std::cout << "2. RECORDER Start" << std::endl;
		std::cout << "3. RECORDER Pause" << std::endl;
		std::cout << "4. RECORDER Resume" << std::endl;
		std::cout << "5. RECORDER Stop" << std::endl;
		std::cout << "6. RECORDER Volume Up" << std::endl;
		std::cout << "7. RECORDER Volume Down" << std::endl;
		std::cout << "8. play Data" << std::endl;
		std::cout << "9. Delete file" << std::endl;
		std::cout << "0. RECORDER APP OFF" << std::endl;
		std::cout << "========================================" << std::endl;
	}

	int userInput(int min, int max)
	{
		assert(min <= max);
		int input = 0;

		std::cin >> input;
		std::cout << std::endl;

		if (!std::cin.fail()) {
			if (min <= input && input <= max) {
				std::cout << "return input" << std::endl;
				return input;
			}
		}

		std::cin.clear();
		std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

		std::cout << "Invalid Input, please try again" << std::endl;

		return input;
	}

	MediaRecorderTest() : mAppRunning(false), mIsPaused(false), mIsPlaying(false)
	{
	}
	~MediaRecorderTest()
	{
	}

private:
	bool mAppRunning;
	bool mIsPaused;
	MediaRecorder mMr;
	bool mIsPlaying;
	MediaPlayer mMp;
	FILE *mfp;
	int mMediaType;
	int mDataSourceType;
};

extern "C" {
int mediarecorder_main(int argc, char *argv[])
{
	up_cxxinitialize();

	auto mediaRecorderTest = make_shared<MediaRecorderTest>();
	mediaRecorderTest->start(TEST_MEDIATYPE_PCM, TEST_DATASOURCE_TYPE_FILE);

	return 0;
}
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/*
$Log$
Revision 1.6  2001/05/21 17:22:50  buncic
Fixed problem with missing AliConfig while reading galice.root

Revision 1.5  2001/05/16 14:57:07  alibrary
New files for folders and Stack

Revision 1.4  2000/12/20 08:39:37  fca
Support for Cerenkov and process list in Virtual MC

Revision 1.3  1999/09/29 09:24:07  fca
Introduction of the Copyright and cvs Log

*/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// aliroot                                                              //
//                                                                      //
// Main program used to create aliroot application.                     //
//                                                                      //
//                                                                      //
// To be able to communicate between the FORTRAN code of GEANT and the  //
// ROOT data structure, a number of interface routines have been        //
// developed.                                                           //
//Begin_Html
/*

*/
//End_Html
//////////////////////////////////////////////////////////////////////////

//Standard Root includes
#include <TROOT.h>
#include <TRint.h>
#include <TFile.h>
#include <AliRun.h>
#include <AliConfig.h>

#if defined __linux
//On linux Fortran wants this, so we give to it!
int xargv=0;
int xargc=0;
#endif

#if defined WIN32
  extern "C" int __fastflag=0;
  extern "C" int _pctype=0;
  extern "C" int __mb_cur_max=0;
#endif

int gcbank_[3000000];

//Initialise the Root environment
 extern void InitGui();
 VoidFuncPtr_t initfuncs[] = { InitGui, 0 };
 TROOT root("galice","The Alice/ROOT Interface", initfuncs);

//_____________________________________________________________________________
int main(int argc, char **argv)
{
  //
  // gAlice main program.
  // It creates the main Geant3 and AliRun objects.
  //
  // The Hits are written out after each track in a ROOT Tree structure TreeH,
  // of the file galice.root. There is one such tree per event. The kinematics
  // of all the particles that produce hits, together with their genealogy up
  // to the primary tracks is stared in the galice.root file in an other tree
  // TreeK of which exists one per event. Finally the information of the events
  // in the run is stored in the same file in the tree TreeE, containing the
  // run and event number, the number of vertices, tracks and primary tracks
  // in the event.

  // Create new configuration
  new AliConfig ("Folders","Alice data exchange");

  new AliRun("gAlice","The ALICE Off-line Simulation Framework");

  // Start interactive geant

  TRint *theApp = new TRint("aliroot", &argc, argv, 0, 0);

  // --- Start the event loop ---
  theApp->Run();

  return(0);
}

<commit_msg>Instantiation of AliConfig removed<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/*
$Log$
Revision 1.7  2001/05/22 11:39:48  buncic
Restored proper name for top level AliRoot folder.

Revision 1.6  2001/05/21 17:22:50  buncic
Fixed problem with missing AliConfig while reading galice.root

Revision 1.5  2001/05/16 14:57:07  alibrary
New files for folders and Stack

Revision 1.4  2000/12/20 08:39:37  fca
Support for Cerenkov and process list in Virtual MC

Revision 1.3  1999/09/29 09:24:07  fca
Introduction of the Copyright and cvs Log

*/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// aliroot                                                              //
//                                                                      //
// Main program used to create aliroot application.                     //
//                                                                      //
//                                                                      //
// To be able to communicate between the FORTRAN code of GEANT and the  //
// ROOT data structure, a number of interface routines have been        //
// developed.                                                           //
//Begin_Html
/*

*/
//End_Html
//////////////////////////////////////////////////////////////////////////

//Standard Root includes
#include <TROOT.h>
#include <TRint.h>
#include <TFile.h>
#include <AliRun.h>
#include <AliConfig.h>

#if defined __linux
//On linux Fortran wants this, so we give to it!
int xargv=0;
int xargc=0;
#endif

#if defined WIN32
  extern "C" int __fastflag=0;
  extern "C" int _pctype=0;
  extern "C" int __mb_cur_max=0;
#endif

int gcbank_[3000000];

//Initialise the Root environment
 extern void InitGui();
 VoidFuncPtr_t initfuncs[] = { InitGui, 0 };
 TROOT root("galice","The Alice/ROOT Interface", initfuncs);

//_____________________________________________________________________________
int main(int argc, char **argv)
{
  //
  // gAlice main program.
  // It creates the main Geant3 and AliRun objects.
  //
  // The Hits are written out after each track in a ROOT Tree structure TreeH,
  // of the file galice.root. There is one such tree per event. The kinematics
  // of all the particles that produce hits, together with their genealogy up
  // to the primary tracks is stared in the galice.root file in an other tree
  // TreeK of which exists one per event. Finally the information of the events
  // in the run is stored in the same file in the tree TreeE, containing the
  // run and event number, the number of vertices, tracks and primary tracks
  // in the event.

  // Create new configuration

  new AliRun("gAlice","The ALICE Off-line Simulation Framework");

  // Start interactive geant

  TRint *theApp = new TRint("aliroot", &argc, argv, 0, 0);

  // --- Start the event loop ---
  theApp->Run();

  return(0);
}

<|endoftext|>


<commit_before>// RUN: %clangxx -fsanitize=return -g %s -O3 -o %t
// RUN: not %run %t 2>&1 | FileCheck %s
// RUN: UBSAN_OPTIONS=print_stacktrace=1 not %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-%os-STACKTRACE

// CHECK: missing_return.cpp:[[@LINE+1]]:5: runtime error: execution reached the end of a value-returning function without returning a value
int f() {
// Slow stack unwinding is disabled on Darwin for now, see
// https://code.google.com/p/address-sanitizer/issues/detail?id=137
// CHECK-Linux-STACKTRACE: #0 {{.*}} in f(){{.*}}missing_return.cpp:[[@LINE-3]]
// Check for already checked line to avoid lit error reports.
// CHECK-Darwin-STACKTRACE: missing_return.cpp
}

int main(int, char **argv) {
  return f();
}
<commit_msg>[Ubsan] Fix the missing_return.cpp test to pass on FreeBSD Differential Revision: http://reviews.llvm.org/D6088<commit_after>// RUN: %clangxx -fsanitize=return -g %s -O3 -o %t
// RUN: not %run %t 2>&1 | FileCheck %s
// RUN: UBSAN_OPTIONS=print_stacktrace=1 not %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-%os-STACKTRACE

// CHECK: missing_return.cpp:[[@LINE+1]]:5: runtime error: execution reached the end of a value-returning function without returning a value
int f() {
// Slow stack unwinding is disabled on Darwin for now, see
// https://code.google.com/p/address-sanitizer/issues/detail?id=137
// CHECK-Linux-STACKTRACE: #0 {{.*}} in f(){{.*}}missing_return.cpp:[[@LINE-3]]
// CHECK-FreeBSD-STACKTRACE: #0 {{.*}} in f(void){{.*}}missing_return.cpp:[[@LINE-4]]
// Check for already checked line to avoid lit error reports.
// CHECK-Darwin-STACKTRACE: missing_return.cpp
}

int main(int, char **argv) {
  return f();
}
<|endoftext|>


<commit_before>// Copyright 2015 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef __test_communication__message_fixtures__hpp__
#define __test_communication__message_fixtures__hpp__

#include <vector>

#include <test_communication/msg/builtins.hpp>
#include <test_communication/msg/dynamic_array_primitives.hpp>
#include <test_communication/msg/empty.hpp>
#include <test_communication/msg/nested.hpp>
#include <test_communication/msg/primitives.hpp>
#include <test_communication/msg/static_array_primitives.hpp>

std::vector<test_communication::msg::Empty::Ptr>
get_messages_empty()
{
  std::vector<test_communication::msg::Empty::Ptr> messages;
  auto msg = std::make_shared<test_communication::msg::Empty>();
  messages.push_back(msg);
  return messages;
}

std::vector<test_communication::msg::Primitives::Ptr>
get_messages_primitives()
{
  std::vector<test_communication::msg::Primitives::Ptr> messages;
  {
    auto msg = std::make_shared<test_communication::msg::Primitives>();
    msg->bool_value = false;
    msg->byte_value = 0;
    msg->char_value = '\0';
    msg->float32_value = 0.0f;
    msg->float64_value = 0;
    msg->int8_value = 0;
    msg->uint8_value = 0;
    msg->int16_value = 0;
    msg->uint16_value = 0;
    msg->int32_value = 0;
    msg->uint32_value = 0;
    msg->int64_value = 0;
    msg->uint64_value = 0;
    msg->string_value = "";
    messages.push_back(msg);
  }
  {
    auto msg = std::make_shared<test_communication::msg::Primitives>();
    msg->bool_value = true;
    msg->byte_value = 255;
    msg->char_value = 0xff;
    msg->float32_value = 1.11f;
    msg->float64_value = 1.11;
    msg->int8_value = 127;
    msg->uint8_value = 255;
    msg->int16_value = 32767;
    msg->uint16_value = 65535;
    msg->int32_value = 2147483647;
    msg->uint32_value = 4294967295;
    msg->int64_value = 9223372036854775807;
    msg->uint64_value = 18446744073709551615UL;
    msg->string_value = "max value";
    messages.push_back(msg);
  }
  {
    auto msg = std::make_shared<test_communication::msg::Primitives>();
    msg->bool_value = false;
    msg->byte_value = 0;
    msg->char_value = 0x0;
    msg->float32_value = -2.22f;
    msg->float64_value = -2.22;
    msg->int8_value = -128;
    msg->uint8_value = 0;
    msg->int16_value = -32768;
    msg->uint16_value = 0;
    msg->int32_value = -2147483648;
    msg->uint32_value = 0;
    msg->int64_value = -9223372036854775808UL;
    msg->uint64_value = 0;
    msg->string_value = "min value";
    messages.push_back(msg);
  }
  return messages;
}

std::vector<test_communication::msg::StaticArrayPrimitives::Ptr>
get_messages_static_array_primitives()
{
  std::vector<test_communication::msg::StaticArrayPrimitives::Ptr> messages;
  {
    auto msg = std::make_shared<test_communication::msg::StaticArrayPrimitives>();
    msg->bool_values = {false, true, false};
    msg->byte_values = {0, 0xff, 0};
    msg->char_values = {'\0', '\255', '\0'};
    msg->float32_values = {0.0f, 1.11f, -2.22f};
    msg->float64_values = {0, 1.11, -2.22};
    msg->int8_values = {0, 127, -128};
    msg->uint8_values = {0, 255, 0};
    msg->int16_values = {0, 32767, -32768};
    msg->uint16_values = {0, 65535, 0};
    // The narrowing static cast is required to avoid build errors on Windows.
    msg->int32_values = {
      static_cast<int32_t>(0),
      static_cast<int32_t>(2147483647),
      static_cast<int32_t>(-2147483648)
    };
    msg->uint32_values = {0, 4294967295, 0};
    msg->int64_values[0] = 0;
    msg->int64_values[1] = 9223372036854775807;
    msg->int64_values[2] = -9223372036854775808UL;
    msg->uint64_values = {0, 18446744073709551615UL, 0};
    msg->string_values = {"", "max value", "min value"};
    messages.push_back(msg);
  }
  return messages;
}

std::vector<test_communication::msg::DynamicArrayPrimitives::Ptr>
get_messages_dynamic_array_primitives()
{
  std::vector<test_communication::msg::DynamicArrayPrimitives::Ptr> messages;
  {
    auto msg = std::make_shared<test_communication::msg::DynamicArrayPrimitives>();
    msg->bool_values = {{}};
    msg->byte_values = {{}};
    msg->char_values = {{}};
    msg->float32_values = {{}};
    msg->float64_values = {{}};
    msg->int8_values = {{}};
    msg->uint8_values = {{}};
    msg->int16_values = {{}};
    msg->uint16_values = {{}};
    msg->int32_values = {{}};
    msg->uint32_values = {{}};
    msg->int64_values = {{}};
    msg->uint64_values = {{}};
    msg->string_values = {{}};
    messages.push_back(msg);
  }
  {
    auto msg = std::make_shared<test_communication::msg::DynamicArrayPrimitives>();
    msg->bool_values = {{true}};
    msg->byte_values = {{0xff}};
    msg->char_values = {{'\255'}};
    msg->float32_values = {{1.11f}};
    msg->float64_values = {{1.11}};
    msg->int8_values = {{127}};
    msg->uint8_values = {{255}};
    msg->int16_values = {{32767}};
    msg->uint16_values = {{65535}};
    msg->int32_values = {{2147483647}};
    msg->uint32_values = {{4294967295}};
    msg->int64_values = {{9223372036854775807}};
    msg->uint64_values = {{18446744073709551615UL}};
    msg->string_values = {{"max value"}};
    messages.push_back(msg);
  }
  {
    auto msg = std::make_shared<test_communication::msg::DynamicArrayPrimitives>();
    msg->bool_values = {{false, true}};
    msg->byte_values = {{0, 0xff}};
    msg->char_values = {{'\0', '\255'}};
    msg->float32_values = {{0.0f, 1.11f, -2.22f}};
    msg->float64_values = {{0, 1.11, -2.22}};
    msg->int8_values = {{0, 127, -128}};
    msg->uint8_values = {{0, 255}};
    msg->int16_values = {{0, 32767, -32768}};
    msg->uint16_values = {{0, 65535}};
    // The narrowing static cast is required to avoid build errors on Windows.
    msg->int32_values = {{
      static_cast<int32_t>(0),
      static_cast<int32_t>(2147483647),
      static_cast<int32_t>(-2147483648)
    }};
    msg->uint32_values = {{0, 4294967295}};
    msg->int64_values.resize(3);
    msg->int64_values[0] = 0;
    msg->int64_values[1] = 9223372036854775807;
    msg->int64_values[2] = -9223372036854775808UL;
    msg->uint64_values = {{0, 18446744073709551615UL}};
    msg->string_values = {{"", "max value", "optional min value"}};
    messages.push_back(msg);
  }
  return messages;
}

std::vector<test_communication::msg::Nested::Ptr>
get_messages_nested()
{
  std::vector<test_communication::msg::Nested::Ptr> messages;
  auto primitive_msgs = get_messages_primitives();
  for (auto primitive_msg : primitive_msgs) {
    auto msg = std::make_shared<test_communication::msg::Nested>();
    msg->primitive_values = *primitive_msg;
    messages.push_back(msg);
  }
  return messages;
}

std::vector<test_communication::msg::Builtins::Ptr>
get_messages_builtins()
{
  std::vector<test_communication::msg::Builtins::Ptr> messages;
  {
    auto msg = std::make_shared<test_communication::msg::Builtins>();
    msg->duration_value.sec = -1234567890;
    msg->duration_value.nanosec = 123456789;
    msg->time_value.sec = -1234567890;
    msg->time_value.nanosec = 987654321;
    messages.push_back(msg);
  }
  return messages;
}

#endif  // __test_communication__message_fixtures__hpp__
<commit_msg>adjust use of braces to fix warnings with clang<commit_after>// Copyright 2015 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef __test_communication__message_fixtures__hpp__
#define __test_communication__message_fixtures__hpp__

#include <vector>

#include <test_communication/msg/builtins.hpp>
#include <test_communication/msg/dynamic_array_primitives.hpp>
#include <test_communication/msg/empty.hpp>
#include <test_communication/msg/nested.hpp>
#include <test_communication/msg/primitives.hpp>
#include <test_communication/msg/static_array_primitives.hpp>

std::vector<test_communication::msg::Empty::Ptr>
get_messages_empty()
{
  std::vector<test_communication::msg::Empty::Ptr> messages;
  auto msg = std::make_shared<test_communication::msg::Empty>();
  messages.push_back(msg);
  return messages;
}

std::vector<test_communication::msg::Primitives::Ptr>
get_messages_primitives()
{
  std::vector<test_communication::msg::Primitives::Ptr> messages;
  {
    auto msg = std::make_shared<test_communication::msg::Primitives>();
    msg->bool_value = false;
    msg->byte_value = 0;
    msg->char_value = '\0';
    msg->float32_value = 0.0f;
    msg->float64_value = 0;
    msg->int8_value = 0;
    msg->uint8_value = 0;
    msg->int16_value = 0;
    msg->uint16_value = 0;
    msg->int32_value = 0;
    msg->uint32_value = 0;
    msg->int64_value = 0;
    msg->uint64_value = 0;
    msg->string_value = "";
    messages.push_back(msg);
  }
  {
    auto msg = std::make_shared<test_communication::msg::Primitives>();
    msg->bool_value = true;
    msg->byte_value = 255;
    msg->char_value = 0xff;
    msg->float32_value = 1.11f;
    msg->float64_value = 1.11;
    msg->int8_value = 127;
    msg->uint8_value = 255;
    msg->int16_value = 32767;
    msg->uint16_value = 65535;
    msg->int32_value = 2147483647;
    msg->uint32_value = 4294967295;
    msg->int64_value = 9223372036854775807;
    msg->uint64_value = 18446744073709551615UL;
    msg->string_value = "max value";
    messages.push_back(msg);
  }
  {
    auto msg = std::make_shared<test_communication::msg::Primitives>();
    msg->bool_value = false;
    msg->byte_value = 0;
    msg->char_value = 0x0;
    msg->float32_value = -2.22f;
    msg->float64_value = -2.22;
    msg->int8_value = -128;
    msg->uint8_value = 0;
    msg->int16_value = -32768;
    msg->uint16_value = 0;
    msg->int32_value = -2147483648;
    msg->uint32_value = 0;
    msg->int64_value = -9223372036854775808UL;
    msg->uint64_value = 0;
    msg->string_value = "min value";
    messages.push_back(msg);
  }
  return messages;
}

std::vector<test_communication::msg::StaticArrayPrimitives::Ptr>
get_messages_static_array_primitives()
{
  std::vector<test_communication::msg::StaticArrayPrimitives::Ptr> messages;
  {
    auto msg = std::make_shared<test_communication::msg::StaticArrayPrimitives>();
    msg->bool_values = {{false, true, false}};
    msg->byte_values = {{0, 0xff, 0}};
    msg->char_values = {{'\0', '\255', '\0'}};
    msg->float32_values = {{0.0f, 1.11f, -2.22f}};
    msg->float64_values = {{0, 1.11, -2.22}};
    msg->int8_values = {{0, 127, -128}};
    msg->uint8_values = {{0, 255, 0}};
    msg->int16_values = {{0, 32767, -32768}};
    msg->uint16_values = {{0, 65535, 0}};
    msg->int32_values = {{
      static_cast<int32_t>(0),
      static_cast<int32_t>(2147483647),
      static_cast<int32_t>(-2147483648)
    }};
    msg->uint32_values = {{0, 4294967295, 0}};
    msg->int64_values[0] = 0;
    msg->int64_values[1] = 9223372036854775807;
    msg->int64_values[2] = -9223372036854775808UL;
    msg->uint64_values = {{0, 18446744073709551615UL, 0}};
    msg->string_values = {{"", "max value", "min value"}};
    messages.push_back(msg);
  }
  return messages;
}

std::vector<test_communication::msg::DynamicArrayPrimitives::Ptr>
get_messages_dynamic_array_primitives()
{
  std::vector<test_communication::msg::DynamicArrayPrimitives::Ptr> messages;
  {
    auto msg = std::make_shared<test_communication::msg::DynamicArrayPrimitives>();
    msg->bool_values = {{}};
    msg->byte_values = {{}};
    msg->char_values = {{}};
    msg->float32_values = {{}};
    msg->float64_values = {{}};
    msg->int8_values = {{}};
    msg->uint8_values = {{}};
    msg->int16_values = {{}};
    msg->uint16_values = {{}};
    msg->int32_values = {{}};
    msg->uint32_values = {{}};
    msg->int64_values = {{}};
    msg->uint64_values = {{}};
    msg->string_values = {{}};
    messages.push_back(msg);
  }
  {
    auto msg = std::make_shared<test_communication::msg::DynamicArrayPrimitives>();
    msg->bool_values = {true};
    msg->byte_values = {0xff};
    msg->char_values = {'\255'};
    msg->float32_values = {1.11f};
    msg->float64_values = {1.11};
    msg->int8_values = {127};
    msg->uint8_values = {255};
    msg->int16_values = {32767};
    msg->uint16_values = {65535};
    msg->int32_values = {2147483647};
    msg->uint32_values = {4294967295};
    msg->int64_values = {9223372036854775807};
    msg->uint64_values = {18446744073709551615UL};
    msg->string_values = {{"max value"}};
    messages.push_back(msg);
  }
  {
    auto msg = std::make_shared<test_communication::msg::DynamicArrayPrimitives>();
    msg->bool_values = {{false, true}};
    msg->byte_values = {{0, 0xff}};
    msg->char_values = {{'\0', '\255'}};
    msg->float32_values = {{0.0f, 1.11f, -2.22f}};
    msg->float64_values = {{0, 1.11, -2.22}};
    msg->int8_values = {{0, 127, -128}};
    msg->uint8_values = {{0, 255}};
    msg->int16_values = {{0, 32767, -32768}};
    msg->uint16_values = {{0, 65535}};
    // The narrowing static cast is required to avoid build errors on Windows.
    msg->int32_values = {{
      static_cast<int32_t>(0),
      static_cast<int32_t>(2147483647),
      static_cast<int32_t>(-2147483648)
    }};
    msg->uint32_values = {{0, 4294967295}};
    msg->int64_values.resize(3);
    msg->int64_values[0] = 0;
    msg->int64_values[1] = 9223372036854775807;
    msg->int64_values[2] = -9223372036854775808UL;
    msg->uint64_values = {{0, 18446744073709551615UL}};
    msg->string_values = {{"", "max value", "optional min value"}};
    messages.push_back(msg);
  }
  return messages;
}

std::vector<test_communication::msg::Nested::Ptr>
get_messages_nested()
{
  std::vector<test_communication::msg::Nested::Ptr> messages;
  auto primitive_msgs = get_messages_primitives();
  for (auto primitive_msg : primitive_msgs) {
    auto msg = std::make_shared<test_communication::msg::Nested>();
    msg->primitive_values = *primitive_msg;
    messages.push_back(msg);
  }
  return messages;
}

std::vector<test_communication::msg::Builtins::Ptr>
get_messages_builtins()
{
  std::vector<test_communication::msg::Builtins::Ptr> messages;
  {
    auto msg = std::make_shared<test_communication::msg::Builtins>();
    msg->duration_value.sec = -1234567890;
    msg->duration_value.nanosec = 123456789;
    msg->time_value.sec = -1234567890;
    msg->time_value.nanosec = 987654321;
    messages.push_back(msg);
  }
  return messages;
}

#endif  // __test_communication__message_fixtures__hpp__
<|endoftext|>


<commit_before>/**************************************************************
COSC 501
Elliott Plack
14 NOV 2013                            Due date: 30 NOV 2013

Problem:
	Write a program that plays the game of HANGMAN(guessing a
	mystery word).  Read a word to be guessed from a file into
	successive elements of the array WORD. The player must
	guess the letters belonging to WORD. A single guessing
	session should be terminated when either all letters have
	been guessed correctly (player wins) or a specified number
	of incorrect guesses have been made (computer wins). A run
	must consist of at least two sessions: one player wins and
	one computer wins. The player decides whether or not to
	start a new session.

***************************************************************/

#include <iomanip>
#include <iostream>
#include <fstream>
#include <string>
#include <time.h> // for random
using namespace std;

ifstream inFile;     // define ifstream to inFile command

void readString();
void initialize(unsigned long); // function to initalize everything
void guess();

// global variables
string word; // word to be read from file (the solution)
string solution; // solution (guessed by user)
unsigned long wordLength; // length of word

// functions

int main() // reads in the file and sets the functions in motion
{
	readString(); // reads the file and stores variables
	initialize(wordLength); // sends length of word to initialize function
	cout << "Let's play hangman!\n";
	guess(); // game logic

	return 0;
}

void readString()
{
	int random20 = 0; // random number
	string dictionary[20]; // 20 words to load from file

	inFile.open("Words4Hangman.txt"); // open input file

	while (inFile.good())
	{
		for (int i = 0; i < 20; i++)
		{
			inFile >> dictionary[i]; // load file and fill dict
		}
	}

	inFile.close(); // close the file

	srand((int)time(NULL)); // initialize random seed
	random20 = (rand() % 20); // set random to 20 +-

	word = dictionary[rand() % 20]; // set word = to a random letter in the dictionary
	cout << word << endl; // cheater! (testing)
	wordLength = word.size(); // size (length) of the string
}

void initialize(unsigned long wordLength)
{
	solution.assign(wordLength, '*'); // fills up the solution string (an array) with as many *s as the word length
}

void guess()
{
	char guessLetter = ' '; // letter to guess
	string solutionOld = solution; // solution string to compare with
	int winning = 0, goodGuess = 0; // variable to check if the game is won or the guess is good
	int guessesCounter = 7; // hangman countdown

	cout << solution << endl; // output solution
	cout << "Guess a letter\n";
	cin >> guessLetter;

	while ((guessesCounter > 0) && (winning == 0))
	{
		guessLetter = toupper(guessLetter); // make guess uppercase

		for (unsigned long i = 0; i < wordLength; i++) // loop through word looking for guess
		{
			if (guessLetter == word[i])
			{
				//cout << "char " << (i + 1) /* +1 because first is 0*/ << " is " << guessLetter << endl; // outputs that guess was correct
				solution[i] = guessLetter; // set the i char in solution to guessLetter
				goodGuess = 1; // sets the flag goodGuess = 1 for the logic below
			}
		}

		if (solution == word) // thus victory
		{
			winning = 1; // you won
			cout << "Victory!\n"; // quick output for testing
		}
		else if (goodGuess == 1)
		{
			cout << "Good guess!\n"
				<< solution << endl; // display positive
			goodGuess = 0; // clear flag for next run
			cout << "Enter your next guess: ";
			cin >> guessLetter;
		}
		else
		{
			guessesCounter--; // decrement guess
			cout << "The letter " << guessLetter << " does not appear in the word.\n"
				<< "You have " << guessesCounter << "remaining.\n"
				<< "Enter another letter: ";
			cin >> guessLetter;
		}
	}
}<commit_msg>added space where needed<commit_after>/**************************************************************
COSC 501
Elliott Plack
14 NOV 2013                            Due date: 30 NOV 2013

Problem:
	Write a program that plays the game of HANGMAN(guessing a
	mystery word).  Read a word to be guessed from a file into
	successive elements of the array WORD. The player must
	guess the letters belonging to WORD. A single guessing
	session should be terminated when either all letters have
	been guessed correctly (player wins) or a specified number
	of incorrect guesses have been made (computer wins). A run
	must consist of at least two sessions: one player wins and
	one computer wins. The player decides whether or not to
	start a new session.

***************************************************************/

#include <iomanip>
#include <iostream>
#include <fstream>
#include <string>
#include <time.h> // for random
using namespace std;

ifstream inFile;     // define ifstream to inFile command

void readString();
void initialize(unsigned long); // function to initalize everything
void guess();

// global variables
string word; // word to be read from file (the solution)
string solution; // solution (guessed by user)
unsigned long wordLength; // length of word

// functions

int main() // reads in the file and sets the functions in motion
{
	readString(); // reads the file and stores variables
	initialize(wordLength); // sends length of word to initialize function
	cout << "Let's play hangman!\n";
	guess(); // game logic

	return 0;
}

void readString()
{
	int random20 = 0; // random number
	string dictionary[20]; // 20 words to load from file

	inFile.open("Words4Hangman.txt"); // open input file

	while (inFile.good())
	{
		for (int i = 0; i < 20; i++)
		{
			inFile >> dictionary[i]; // load file and fill dict
		}
	}

	inFile.close(); // close the file

	srand((int)time(NULL)); // initialize random seed
	random20 = (rand() % 20); // set random to 20 +-

	word = dictionary[rand() % 20]; // set word = to a random letter in the dictionary
	cout << word << endl; // cheater! (testing)
	wordLength = word.size(); // size (length) of the string
}

void initialize(unsigned long wordLength)
{
	solution.assign(wordLength, '*'); // fills up the solution string (an array) with as many *s as the word length
}

void guess()
{
	char guessLetter = ' '; // letter to guess
	string solutionOld = solution; // solution string to compare with
	int winning = 0, goodGuess = 0; // variable to check if the game is won or the guess is good
	int guessesCounter = 7; // hangman countdown

	cout << solution << endl; // output solution
	cout << "Guess a letter\n";
	cin >> guessLetter;

	while ((guessesCounter > 0) && (winning == 0))
	{
		guessLetter = toupper(guessLetter); // make guess uppercase

		for (unsigned long i = 0; i < wordLength; i++) // loop through word looking for guess
		{
			if (guessLetter == word[i])
			{
				//cout << "char " << (i + 1) /* +1 because first is 0*/ << " is " << guessLetter << endl; // outputs that guess was correct
				solution[i] = guessLetter; // set the i char in solution to guessLetter
				goodGuess = 1; // sets the flag goodGuess = 1 for the logic below
			}
		}

		if (solution == word) // thus victory
		{
			winning = 1; // you won
			cout << "Victory!\n"; // quick output for testing
		}
		else if (goodGuess == 1)
		{
			cout << "Good guess!\n"
				<< solution << endl; // display positive
			goodGuess = 0; // clear flag for next run
			cout << "Enter your next guess: ";
			cin >> guessLetter;
		}
		else
		{
			guessesCounter--; // decrement guess
			cout << "The letter " << guessLetter << " does not appear in the word.\n"
				<< "You have " << guessesCounter << " remaining.\n"
				<< "Enter another letter: ";
			cin >> guessLetter;
		}
	}

	cout << "You are dead!\n"; // end if you run out of guesses
}<|endoftext|>