<commit_before>/*
 * $Id$
 */

#include <sys/time.h>
#include <stdio.h>
#include <fstream>
#include <map>
#include <list>
#include <iostream>
#include <sstream>
#include <cmath>
#include <set>
#include "crf.h"
#include "common.h"

using namespace std;

multimap<string, string> WNdic;

void tokenize(const string &s1, list<string> &lt);
string base_form(const string &s, const string &pos);

extern int push_stop_watch();

static string normalize(const string &s) {
  string tmp(s);
  for (size_t i = 0; i < tmp.size(); i++) {
    tmp[i] = tolower(tmp[i]);
    if (isdigit(tmp[i])) tmp[i] = '#';
  }
  return tmp;
}

static CRF_State crfstate(const vector<Token> &vt, int i) {
  CRF_State sample;

  string str = vt[i].str;

  sample.label = vt[i].pos;

  sample.add_feature("W0_" + vt[i].str);

  sample.add_feature("NW0_" + normalize(str));

  string prestr = "BOS";
  if (i > 0) prestr = vt[i - 1].str;

  string prestr2 = "BOS";
  if (i > 1) prestr2 = vt[i - 2].str;

  string poststr = "EOS";
  if (i < (int)vt.size() - 1) poststr = vt[i + 1].str;

  string poststr2 = "EOS";
  if (i < (int)vt.size() - 2) poststr2 = vt[i + 2].str;

  sample.add_feature("W-1_" + prestr);
  sample.add_feature("W+1_" + poststr);

  sample.add_feature("W-2_" + prestr2);
  sample.add_feature("W+2_" + poststr2);

  sample.add_feature("W-10_" + prestr + "_" + str);
  sample.add_feature("W0+1_" + str + "_" + poststr);
  sample.add_feature("W-1+1_" + prestr + "_" + poststr);

  for (size_t j = 1; j <= 10; j++) {
    char buf[1000];
    if (str.size() >= j) {
      sprintf(buf, "SUF%d_%s", (int)j, str.substr(str.size() - j).c_str());
      sample.add_feature(buf);
    }
    if (str.size() >= j) {
      sprintf(buf, "PRE%d_%s", (int)j, str.substr(0, j).c_str());
      sample.add_feature(buf);
    }
  }

  for (size_t j = 0; j < str.size(); j++) {
    if (isdigit(str[j])) {
      sample.add_feature("CTN_NUM");
      break;
    }
  }
  for (size_t j = 0; j < str.size(); j++) {
    if (isupper(str[j])) {
      sample.add_feature("CTN_UPP");
      break;
    }
  }
  for (size_t j = 0; j < str.size(); j++) {
    if (str[j] == '-') {
      sample.add_feature("CTN_HPN");
      break;
    }
  }
  bool allupper = true;
  for (size_t j = 0; j < str.size(); j++) {
    if (!isupper(str[j])) {
      allupper = false;
      break;
    }
  }
  if (allupper) sample.add_feature("ALL_UPP");

  if (WNdic.size() > 0) {
    const string n = normalize(str);
    for (map<string, string>::const_iterator i = WNdic.lower_bound(n);
         i != WNdic.upper_bound(n); i++) {
      sample.add_feature("WN_" + i->second);
    }
  }

  return sample;
}

int crftrain(const CRF_Model::OptimizationMethod method, CRF_Model &m,
             const vector<Sentence> &vs, double gaussian, const bool use_l1) {
  if (method != CRF_Model::BFGS && use_l1) {
    cerr << "error: L1 regularization is currently not supported in this mode. "
            "Please use other optimziation methods." << endl;
    exit(1);
  }

  for (vector<Sentence>::const_iterator i = vs.begin(); i != vs.end(); i++) {
    const Sentence &s = *i;
    CRF_Sequence cs;
    for (size_t j = 0; j < s.size(); j++) cs.add_state(crfstate(s, j));
    m.add_training_sample(cs);
  }

  if (use_l1)
    m.train(method, 0, 0, 1.0);
  else
    m.train(method, 0, gaussian);

  return 0;
}

void crf_decode_lookahead(Sentence &s, CRF_Model &m,
                          vector<map<string, double> > &tagp) {
  CRF_Sequence cs;
  for (size_t j = 0; j < s.size(); j++) cs.add_state(crfstate(s, j));

  m.decode_lookahead(cs);

  tagp.clear();
  for (size_t k = 0; k < s.size(); k++) {
    s[k].prd = cs.vs[k].label;
    map<string, double> vp;
    vp[s[k].prd] = 1.0;
    tagp.push_back(vp);
  }
}

void crf_decode_forward_backward(Sentence &s, CRF_Model &m,
                                 vector<map<string, double> > &tagp) {
  CRF_Sequence cs;
  for (size_t j = 0; j < s.size(); j++) cs.add_state(crfstate(s, j));

  m.decode_forward_backward(cs, tagp);

  for (size_t k = 0; k < s.size(); k++) s[k].prd = cs.vs[k].label;
}

void crf_decode_nbest(Sentence &s, CRF_Model &m,
                      vector<pair<double, vector<string> > > &nbest_seqs,
                      int n) {
  CRF_Sequence cs;
  for (size_t j = 0; j < s.size(); j++) cs.add_state(crfstate(s, j));

  m.decode_nbest(cs, nbest_seqs, n, 0);

  for (size_t k = 0; k < s.size(); k++) s[k].prd = cs.vs[k].label;
}

/*
 * $Log$
 */
<commit_msg>crfpos.cpp: use !empty() instead of 'size() > 0'<commit_after>/*
 * $Id$
 */

#include <sys/time.h>
#include <stdio.h>
#include <fstream>
#include <map>
#include <list>
#include <iostream>
#include <sstream>
#include <cmath>
#include <set>
#include "crf.h"
#include "common.h"

using namespace std;

multimap<string, string> WNdic;

void tokenize(const string &s1, list<string> &lt);
string base_form(const string &s, const string &pos);

extern int push_stop_watch();

static string normalize(const string &s) {
  string tmp(s);
  for (size_t i = 0; i < tmp.size(); i++) {
    tmp[i] = tolower(tmp[i]);
    if (isdigit(tmp[i])) tmp[i] = '#';
  }
  return tmp;
}

static CRF_State crfstate(const vector<Token> &vt, int i) {
  CRF_State sample;

  string str = vt[i].str;

  sample.label = vt[i].pos;

  sample.add_feature("W0_" + vt[i].str);

  sample.add_feature("NW0_" + normalize(str));

  string prestr = "BOS";
  if (i > 0) prestr = vt[i - 1].str;

  string prestr2 = "BOS";
  if (i > 1) prestr2 = vt[i - 2].str;

  string poststr = "EOS";
  if (i < (int)vt.size() - 1) poststr = vt[i + 1].str;

  string poststr2 = "EOS";
  if (i < (int)vt.size() - 2) poststr2 = vt[i + 2].str;

  sample.add_feature("W-1_" + prestr);
  sample.add_feature("W+1_" + poststr);

  sample.add_feature("W-2_" + prestr2);
  sample.add_feature("W+2_" + poststr2);

  sample.add_feature("W-10_" + prestr + "_" + str);
  sample.add_feature("W0+1_" + str + "_" + poststr);
  sample.add_feature("W-1+1_" + prestr + "_" + poststr);

  for (size_t j = 1; j <= 10; j++) {
    char buf[1000];
    if (str.size() >= j) {
      sprintf(buf, "SUF%d_%s", (int)j, str.substr(str.size() - j).c_str());
      sample.add_feature(buf);
    }
    if (str.size() >= j) {
      sprintf(buf, "PRE%d_%s", (int)j, str.substr(0, j).c_str());
      sample.add_feature(buf);
    }
  }

  for (size_t j = 0; j < str.size(); j++) {
    if (isdigit(str[j])) {
      sample.add_feature("CTN_NUM");
      break;
    }
  }
  for (size_t j = 0; j < str.size(); j++) {
    if (isupper(str[j])) {
      sample.add_feature("CTN_UPP");
      break;
    }
  }
  for (size_t j = 0; j < str.size(); j++) {
    if (str[j] == '-') {
      sample.add_feature("CTN_HPN");
      break;
    }
  }
  bool allupper = true;
  for (size_t j = 0; j < str.size(); j++) {
    if (!isupper(str[j])) {
      allupper = false;
      break;
    }
  }
  if (allupper) sample.add_feature("ALL_UPP");

  if (!WNdic.empty()) {
    const string n = normalize(str);
    for (map<string, string>::const_iterator i = WNdic.lower_bound(n);
         i != WNdic.upper_bound(n); i++) {
      sample.add_feature("WN_" + i->second);
    }
  }

  return sample;
}

int crftrain(const CRF_Model::OptimizationMethod method, CRF_Model &m,
             const vector<Sentence> &vs, double gaussian, const bool use_l1) {
  if (method != CRF_Model::BFGS && use_l1) {
    cerr << "error: L1 regularization is currently not supported in this mode. "
            "Please use other optimziation methods." << endl;
    exit(1);
  }

  for (vector<Sentence>::const_iterator i = vs.begin(); i != vs.end(); i++) {
    const Sentence &s = *i;
    CRF_Sequence cs;
    for (size_t j = 0; j < s.size(); j++) cs.add_state(crfstate(s, j));
    m.add_training_sample(cs);
  }

  if (use_l1)
    m.train(method, 0, 0, 1.0);
  else
    m.train(method, 0, gaussian);

  return 0;
}

void crf_decode_lookahead(Sentence &s, CRF_Model &m,
                          vector<map<string, double> > &tagp) {
  CRF_Sequence cs;
  for (size_t j = 0; j < s.size(); j++) cs.add_state(crfstate(s, j));

  m.decode_lookahead(cs);

  tagp.clear();
  for (size_t k = 0; k < s.size(); k++) {
    s[k].prd = cs.vs[k].label;
    map<string, double> vp;
    vp[s[k].prd] = 1.0;
    tagp.push_back(vp);
  }
}

void crf_decode_forward_backward(Sentence &s, CRF_Model &m,
                                 vector<map<string, double> > &tagp) {
  CRF_Sequence cs;
  for (size_t j = 0; j < s.size(); j++) cs.add_state(crfstate(s, j));

  m.decode_forward_backward(cs, tagp);

  for (size_t k = 0; k < s.size(); k++) s[k].prd = cs.vs[k].label;
}

void crf_decode_nbest(Sentence &s, CRF_Model &m,
                      vector<pair<double, vector<string> > > &nbest_seqs,
                      int n) {
  CRF_Sequence cs;
  for (size_t j = 0; j < s.size(); j++) cs.add_state(crfstate(s, j));

  m.decode_nbest(cs, nbest_seqs, n, 0);

  for (size_t k = 0; k < s.size(); k++) s[k].prd = cs.vs[k].label;
}

/*
 * $Log$
 */
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "otbWrapperApplicationRegistry.h"
#include "otbWrapperParameter.h"
#include "otbWrapperChoiceParameter.h"
#include "itksys/SystemTools.hxx"

/**
 * Small executable to :
 *  - find available application
 *  - get list of parameters
 *  - and fill a bash completion script
 *
 * This script can be sourced to be used, or deployed into a folder such as
 *    /etc/bash_completion.d
 * For choice parameters, the completion will propose the available choices
 */

int main(int argc, char* argv[])
{
  if (argc < 3)
    {
    std::cerr << "Usage : " << argv[0] << " module_path  output_script" << std::endl;
    return EXIT_FAILURE;
    }
  std::string module_path(argv[1]);
  std::string output_path(argv[2]);

  otb::Wrapper::ApplicationRegistry::SetApplicationPath(module_path);

  std::vector<std::string> appList = otb::Wrapper::ApplicationRegistry::GetAvailableApplications(false);

  otb::Wrapper::Application::Pointer appPtr;

  std::ofstream ofs;
  ofs.open(output_path.c_str());

  for (unsigned int i=0 ; i < appList.size() ; ++i)
    {
    appPtr = otb::Wrapper::ApplicationRegistry::CreateApplication(appList[i],false);
    if (appPtr.IsNull())
      {
      std::cout << "Error loading application "<< appList[i] << std::endl;
      return EXIT_FAILURE;
      }
    std::vector<std::string> keys = appPtr->GetParametersKeys();

    ofs << "# completion for application "<< appList[i] << std::endl;
    ofs << "_otbcli_"<<appList[i]<<"()" << std::endl;
    ofs << "{" << std::endl;

    ofs << "  local cur prev" << std::endl;
    ofs << "  COMPREPLY=()" << std::endl;
    ofs << "  _get_comp_words_by_ref cur prev" << std::endl;
    ofs << "  case \"$cur\" in" << std::endl;
    ofs << "    -*)" << std::endl;
    ofs << "      key_list=\"";
    for (unsigned int k=0 ; k < keys.size() ; k++ )
      {
      ofs << "-" << keys[k] << " ";
      }
    ofs << "\"" << std::endl;
    ofs << "      COMPREPLY=( $( compgen -W '$key_list' -- $cur) )" << std::endl;
    ofs << "      return 0" << std::endl;
    ofs << "      ;;" << std::endl;
    ofs << "  esac" << std::endl;

    // detect choice parameters
    std::vector<std::string> choiceKeys;
    for (unsigned int k=0 ; k < keys.size() ; k++ )
      {
      if ( appPtr->GetParameterType(keys[k]) == otb::Wrapper::ParameterType_Choice)
        {
        choiceKeys.push_back(keys[k]);
        }
      }
    if (choiceKeys.size())
      {
      ofs << "  case \"$prev\" in" << std::endl;
      for (unsigned int k=0 ; k < choiceKeys.size() ; k++)
        {
        ofs << "    -" << choiceKeys[k] << ")" << std::endl;
        ofs << "      key_list=\"";
        std::vector<std::string> choices = dynamic_cast<otb::Wrapper::ChoiceParameter*>(appPtr->GetParameterByKey(choiceKeys[k]))->GetChoiceKeys();
        for (unsigned int j=0 ; j < choices.size() ; j++)
          {
          ofs << choices[j];
          if (j+1 < choices.size() )
            {
            ofs << " ";
            }
          }
        ofs << "\"" << std::endl;
        ofs << "      COMPREPLY=( $( compgen -W '$key_list' -- $cur) )" << std::endl;
        ofs << "      ;;" << std::endl;
        }
      ofs << "  esac" << std::endl;
      }

    ofs << "  return 0" << std::endl;
    ofs << "}" << std::endl;
    ofs << "complete -o default -F _otbcli_" << appList[i] << " otbcli_"<< appList[i] << std::endl;
    }
  ofs.close();

  return EXIT_SUCCESS;
}
<commit_msg>ENH: improve compatibility with zsh and older bash<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "otbWrapperApplicationRegistry.h"
#include "otbWrapperParameter.h"
#include "otbWrapperChoiceParameter.h"
#include "itksys/SystemTools.hxx"

/**
 * Small executable to :
 *  - find available application
 *  - get list of parameters
 *  - and fill a bash completion script
 *
 * This script can be sourced to be used, or deployed into a folder such as
 *    /etc/bash_completion.d
 * For choice parameters, the completion will propose the available choices
 */

int main(int argc, char* argv[])
{
  if (argc < 3)
    {
    std::cerr << "Usage : " << argv[0] << " module_path  output_script" << std::endl;
    return EXIT_FAILURE;
    }
  std::string module_path(argv[1]);
  std::string output_path(argv[2]);

  otb::Wrapper::ApplicationRegistry::SetApplicationPath(module_path);

  std::vector<std::string> appList = otb::Wrapper::ApplicationRegistry::GetAvailableApplications(false);

  otb::Wrapper::Application::Pointer appPtr;

  std::ofstream ofs;
  ofs.open(output_path.c_str());

  for (unsigned int i=0 ; i < appList.size() ; ++i)
    {
    appPtr = otb::Wrapper::ApplicationRegistry::CreateApplication(appList[i],false);
    if (appPtr.IsNull())
      {
      std::cout << "Error loading application "<< appList[i] << std::endl;
      return EXIT_FAILURE;
      }
    std::vector<std::string> keys = appPtr->GetParametersKeys();

    ofs << "# completion for application "<< appList[i] << std::endl;
    ofs << "_otbcli_"<<appList[i]<<"()" << std::endl;
    ofs << "{" << std::endl;

    ofs << "  local cur prev" << std::endl;
    ofs << "  COMPREPLY=()" << std::endl;
    ofs << "  cur=\"${COMP_WORDS[COMP_CWORD]}\"" << std::endl;
    ofs << "  prev=\"${COMP_WORDS[COMP_CWORD-1]}\"" << std::endl;
    ofs << "  case \"$cur\" in" << std::endl;
    ofs << "    -*)" << std::endl;
    ofs << "      key_list=\"";
    for (unsigned int k=0 ; k < keys.size() ; k++ )
      {
      ofs << "-" << keys[k] << " ";
      }
    ofs << "\"" << std::endl;
    ofs << "      COMPREPLY=( $( compgen -W \"$key_list\" -- $cur) )" << std::endl;
    ofs << "      return 0" << std::endl;
    ofs << "      ;;" << std::endl;
    ofs << "  esac" << std::endl;

    // detect choice parameters
    std::vector<std::string> choiceKeys;
    for (unsigned int k=0 ; k < keys.size() ; k++ )
      {
      if ( appPtr->GetParameterType(keys[k]) == otb::Wrapper::ParameterType_Choice)
        {
        choiceKeys.push_back(keys[k]);
        }
      }
    if (choiceKeys.size())
      {
      ofs << "  case \"$prev\" in" << std::endl;
      for (unsigned int k=0 ; k < choiceKeys.size() ; k++)
        {
        ofs << "    -" << choiceKeys[k] << ")" << std::endl;
        ofs << "      key_list=\"";
        std::vector<std::string> choices = dynamic_cast<otb::Wrapper::ChoiceParameter*>(appPtr->GetParameterByKey(choiceKeys[k]))->GetChoiceKeys();
        for (unsigned int j=0 ; j < choices.size() ; j++)
          {
          ofs << choices[j];
          if (j+1 < choices.size() )
            {
            ofs << " ";
            }
          }
        ofs << "\"" << std::endl;
        ofs << "      COMPREPLY=( $( compgen -W \"$key_list\" -- $cur) )" << std::endl;
        ofs << "      ;;" << std::endl;
        }
      ofs << "  esac" << std::endl;
      }

    ofs << "  return 0" << std::endl;
    ofs << "}" << std::endl;
    ofs << "complete -o default -F _otbcli_" << appList[i] << " otbcli_"<< appList[i] << std::endl;
    }
  ofs.close();

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include <numeric>
#include <vector>

#include SPECIFIC_HEADER

int main(int /*argc*/, char** /*argv*/)
{
  constexpr unsigned num_entries = 1e7;
  std::vector<int> in(num_entries);
  std::iota(std::begin(in), std::end(in), 0);
  auto out = product_except(in);

  bool success = out[1] == 0;
  return !success;
}
<commit_msg>[product-except-self][vs] Fix double to unsigned error<commit_after>#include <numeric>
#include <vector>

#include SPECIFIC_HEADER

int main(int /*argc*/, char** /*argv*/)
{
  constexpr unsigned num_entries = 10000000;
  std::vector<int> in(num_entries);
  std::iota(std::begin(in), std::end(in), 0);
  auto out = product_except(in);

  bool success = out[1] == 0;
  return !success;
}
<|endoftext|>


<commit_before><commit_msg>Only allocate one event id list for EnableProviders()<commit_after><|endoftext|>


<commit_before>/*  This file is part of the KDE project
    Copyright (C) 2006 Matthias Kretz <kretz@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License version 2 as published by the Free Software Foundation.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

*/

#include "objectdescription.h"
#include "objectdescription_p.h"
#include <QString>
#include <QObject>
#include <QSet>
#include "factory.h"

namespace Phonon
{

template<ObjectDescriptionType T>
ObjectDescription<T>::ObjectDescription()
	: d( new ObjectDescriptionPrivate( -1, QString(), QString() ) )
{
}

template<ObjectDescriptionType T>
ObjectDescription<T>::ObjectDescription( int index, const QString& name, const QString& description )
	: d( new ObjectDescriptionPrivate( index, name, description ) )
{
}

template<ObjectDescriptionType T>
ObjectDescription<T>::ObjectDescription( const ObjectDescription<T>& rhs )
	: d( rhs.d )
{
}

template<ObjectDescriptionType T>
ObjectDescription<T>::~ObjectDescription()
{
}

template<ObjectDescriptionType T>
ObjectDescription<T>& ObjectDescription<T>::operator=( const ObjectDescription<T>& rhs )
{
	d = rhs.d;
	return *this;
}

template<ObjectDescriptionType T>
bool ObjectDescription<T>::operator==( const ObjectDescription<T>& otherDescription ) const
{
	return *d == *otherDescription.d;
}

template<ObjectDescriptionType T>
int ObjectDescription<T>::index() const
{
	return d->index;
}

template<ObjectDescriptionType T>
const QString& ObjectDescription<T>::name() const
{
	return d->name;
}

template<ObjectDescriptionType T>
const QString& ObjectDescription<T>::description() const
{
	return d->description;
}

template<ObjectDescriptionType T>
bool ObjectDescription<T>::isValid() const
{
	return d->index != -1;
}

template<ObjectDescriptionType T>
ObjectDescription<T> ObjectDescription<T>::fromIndex( int index )
{
	QObject* b = Factory::self()->backend();
	QSet<int> indexes;
	QMetaObject::invokeMethod( b, "objectDescriptionIndexes", Qt::DirectConnection, Q_RETURN_ARG( QSet<int>, indexes ),
			Q_ARG( ObjectDescriptionType, T ) );
	if( !indexes.contains( index ) )
		return ObjectDescription<T>(); //isValid() == false
	QString name, description;
	//int videoIndex;
	QMetaObject::invokeMethod( b, "objectDescriptionName", Qt::DirectConnection, Q_RETURN_ARG( QString, name ),
			Q_ARG( ObjectDescriptionType, T ), Q_ARG( int, index ) );
	QMetaObject::invokeMethod( b, "objectDescriptionDescription", Qt::DirectConnection, Q_RETURN_ARG( QString, description ),
			Q_ARG( ObjectDescriptionType, T ), Q_ARG( int, index ) );
	//QMetaObject::invokeMethod( b, "objectDescriptionVideoIndex", Qt::DirectConnection, Q_RETURN_ARG( qint32, videoIndex ),
			//Q_ARG( ObjectDescriptionType, T ), Q_ARG( int, index ) );
	return ObjectDescription<T>( index, name, description );
}

#define PHONON_INSTANCIATE_ALL_FUNCTIONS( T ) \
	template ObjectDescription<T> ObjectDescription<T>::fromIndex(int); \
	template int ObjectDescription<T>::index() const; \
	template QString const & ObjectDescription<T>::name() const; \
	template ObjectDescription<T>::~ObjectDescription() ; \
    template ObjectDescription<T>& ObjectDescription<T>::operator=( const ObjectDescription<T>& ); \
    template ObjectDescription<T>::ObjectDescription(); \
    template ObjectDescription<T>::ObjectDescription(const ObjectDescription<T>& ); \
    template ObjectDescription<T>::ObjectDescription( int, const QString&, const QString&  ); \
    template bool ObjectDescription<T>::operator==( const ObjectDescription<T>& ) const; \
	template const QString& ObjectDescription<T>::description() const; \
    template bool ObjectDescription<T>::isValid() const;

PHONON_INSTANCIATE_ALL_FUNCTIONS( AudioOutputDeviceType );
PHONON_INSTANCIATE_ALL_FUNCTIONS( AudioCaptureDeviceType );
PHONON_INSTANCIATE_ALL_FUNCTIONS( VideoOutputDeviceType );
PHONON_INSTANCIATE_ALL_FUNCTIONS( VideoCaptureDeviceType );
PHONON_INSTANCIATE_ALL_FUNCTIONS( AudioEffectType );
PHONON_INSTANCIATE_ALL_FUNCTIONS( VideoEffectType );
PHONON_INSTANCIATE_ALL_FUNCTIONS( AudioCodecType );
PHONON_INSTANCIATE_ALL_FUNCTIONS( VideoCodecType );
PHONON_INSTANCIATE_ALL_FUNCTIONS( ContainerFormatType );
PHONON_INSTANCIATE_ALL_FUNCTIONS( VisualizationType );

#undef PHONON_INSTANCIATE_ALL_FUNCTIONS

} //namespace Phonon
// vim: sw=4 ts=4 noet
<commit_msg>they are all mine!<commit_after>/*  This file is part of the KDE project
    Copyright (C) 2006 Matthias Kretz <kretz@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License version 2 as published by the Free Software Foundation.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

*/

#include "objectdescription.h"
#include "objectdescription_p.h"
#include <QString>
#include <QObject>
#include <QSet>
#include "factory.h"

namespace Phonon
{

template<ObjectDescriptionType T>
ObjectDescription<T>::ObjectDescription()
	: d( new ObjectDescriptionPrivate( -1, QString(), QString() ) )
{
}

template<ObjectDescriptionType T>
ObjectDescription<T>::ObjectDescription( int index, const QString& name, const QString& description )
	: d( new ObjectDescriptionPrivate( index, name, description ) )
{
}

template<ObjectDescriptionType T>
ObjectDescription<T>::ObjectDescription( const ObjectDescription<T>& rhs )
	: d( rhs.d )
{
}

template<ObjectDescriptionType T>
ObjectDescription<T>::~ObjectDescription()
{
}

template<ObjectDescriptionType T>
ObjectDescription<T>& ObjectDescription<T>::operator=( const ObjectDescription<T>& rhs )
{
	d = rhs.d;
	return *this;
}

template<ObjectDescriptionType T>
bool ObjectDescription<T>::operator==( const ObjectDescription<T>& otherDescription ) const
{
	return *d == *otherDescription.d;
}

template<ObjectDescriptionType T>
int ObjectDescription<T>::index() const
{
	return d->index;
}

template<ObjectDescriptionType T>
const QString& ObjectDescription<T>::name() const
{
	return d->name;
}

template<ObjectDescriptionType T>
const QString& ObjectDescription<T>::description() const
{
	return d->description;
}

template<ObjectDescriptionType T>
bool ObjectDescription<T>::isValid() const
{
	return d->index != -1;
}

template<ObjectDescriptionType T>
ObjectDescription<T> ObjectDescription<T>::fromIndex( int index )
{
	QObject* b = Factory::self()->backend();
	QSet<int> indexes;
	QMetaObject::invokeMethod( b, "objectDescriptionIndexes", Qt::DirectConnection, Q_RETURN_ARG( QSet<int>, indexes ),
			Q_ARG( ObjectDescriptionType, T ) );
	if( !indexes.contains( index ) )
		return ObjectDescription<T>(); //isValid() == false
	QString name, description;
	//int videoIndex;
	QMetaObject::invokeMethod( b, "objectDescriptionName", Qt::DirectConnection, Q_RETURN_ARG( QString, name ),
			Q_ARG( ObjectDescriptionType, T ), Q_ARG( int, index ) );
	QMetaObject::invokeMethod( b, "objectDescriptionDescription", Qt::DirectConnection, Q_RETURN_ARG( QString, description ),
			Q_ARG( ObjectDescriptionType, T ), Q_ARG( int, index ) );
	//QMetaObject::invokeMethod( b, "objectDescriptionVideoIndex", Qt::DirectConnection, Q_RETURN_ARG( qint32, videoIndex ),
			//Q_ARG( ObjectDescriptionType, T ), Q_ARG( int, index ) );
	return ObjectDescription<T>( index, name, description );
}

#define PHONON_INSTANCIATE_ALL_FUNCTIONS( T ) \
	template ObjectDescription<T> ObjectDescription<T>::fromIndex(int); \
	template int ObjectDescription<T>::index() const; \
	template QString const & ObjectDescription<T>::name() const; \
	template ObjectDescription<T>::~ObjectDescription() ; \
    template ObjectDescription<T>& ObjectDescription<T>::operator=( const ObjectDescription<T>& ); \
    template ObjectDescription<T>::ObjectDescription(); \
    template ObjectDescription<T>::ObjectDescription(const ObjectDescription<T>& ); \
    template ObjectDescription<T>::ObjectDescription( int, const QString&, const QString&  ); \
    template bool ObjectDescription<T>::operator==( const ObjectDescription<T>& ) const; \
	template const QString& ObjectDescription<T>::description() const; \
    template bool ObjectDescription<T>::isValid() const;

PHONON_INSTANCIATE_ALL_FUNCTIONS( AudioOutputDeviceType )
PHONON_INSTANCIATE_ALL_FUNCTIONS( AudioCaptureDeviceType )
PHONON_INSTANCIATE_ALL_FUNCTIONS( VideoOutputDeviceType )
PHONON_INSTANCIATE_ALL_FUNCTIONS( VideoCaptureDeviceType )
PHONON_INSTANCIATE_ALL_FUNCTIONS( AudioEffectType )
PHONON_INSTANCIATE_ALL_FUNCTIONS( VideoEffectType )
PHONON_INSTANCIATE_ALL_FUNCTIONS( AudioCodecType )
PHONON_INSTANCIATE_ALL_FUNCTIONS( VideoCodecType )
PHONON_INSTANCIATE_ALL_FUNCTIONS( ContainerFormatType )
PHONON_INSTANCIATE_ALL_FUNCTIONS( VisualizationType )

#undef PHONON_INSTANCIATE_ALL_FUNCTIONS

} //namespace Phonon
// vim: sw=4 ts=4 noet
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016 Aleksei Ermakov
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include <QObject>
#include <QString>
#include <QTest>

#include <QHttpEngine/QHttpRange>

class TestQHttpRange : public QObject
{
    Q_OBJECT

public:

    TestQHttpRange();

private Q_SLOTS:

    void testDefaultConstructor();
    void testAssignmentOperator();

    void testFromToLength_data();
    void testFromToLength();

    void testIsValid_data();
    void testIsValid();

    void testParseFromString_data();
    void testParseFromString();

    void testContentRange_data();
    void testContentRange();
};

TestQHttpRange::TestQHttpRange()
{
}

void TestQHttpRange::testDefaultConstructor()
{
    QHttpRange range;

    QCOMPARE(range.isValid(), false);
}

void TestQHttpRange::testAssignmentOperator()
{
    QHttpRange range;
    QHttpRange otherRange(100, 200, -1);

    range = otherRange;

    QCOMPARE(range.isValid(), true);
    QCOMPARE(range.from(), 100);
    QCOMPARE(range.to(), 200);
}

void TestQHttpRange::testFromToLength_data()
{
    QTest::addColumn<int>("inFrom");
    QTest::addColumn<int>("inTo");
    QTest::addColumn<int>("inDataSize");
    QTest::addColumn<int>("from");
    QTest::addColumn<int>("to");
    QTest::addColumn<int>("length");

    QTest::newRow("Last 500 bytes")
            << -500 << -1 << -1
            << -500 << -1 << 500;

    QTest::newRow("Last 500 bytes with 800 dataSize")
            << -500 << -1 << 800
            << 300 << 799 << 500;

    QTest::newRow("Skip first 10 bytes")
            << 10 << -1 << -1
            << 10 << -1 << -1;

    QTest::newRow("Skip first 10 bytes with 100 dataSize")
            << 10 << -1 << 100
            << 10 << 99 << 90;
}

void TestQHttpRange::testFromToLength()
{
    QFETCH(int, inFrom);
    QFETCH(int, inTo);
    QFETCH(int, inDataSize);
    QFETCH(int, from);
    QFETCH(int, to);
    QFETCH(int, length);

    QHttpRange range(inFrom, inTo, inDataSize);

    QCOMPARE(range.from(), from);
    QCOMPARE(range.to(), to);
    QCOMPARE(range.length(), length);
}

void TestQHttpRange::testIsValid_data()
{
    QTest::addColumn<int>("from");
    QTest::addColumn<int>("to");
    QTest::addColumn<int>("dataSize");
    QTest::addColumn<bool>("valid");

    QTest::newRow("Normal range")
            << 0 << 100 << -1 << true;

    QTest::newRow("Normal range with 'dataSize'")
            << 0 << 99 << 100 << true;

    QTest::newRow("Last N bytes")
            << -500 << -1 << -1 << true;

    QTest::newRow("Last N bytes with 'dataSize'")
            << -500 << -1 << 500 << true;

    QTest::newRow("Skip first N bytes")
            << 10 << -1 << -1 << true;

    QTest::newRow("Skip first N bytes with 'dataSize'")
            << 10 << -1 << 500 << true;

    QTest::newRow("OutOfBounds 'to' > 'from'")
            << 100 << 50 << -1 << false;

    QTest::newRow("OutOfBounds 'from' > 'dataSize'")
            << 100 << 200 << 150 << false;

    QTest::newRow("Last N bytes where N > 'dataSize'")
            << -500 << -1 << 499 << false;

    QTest::newRow("Skip first N bytes where N > 'dataSize'")
            << 500 << -1 << 499 << false;
}

void TestQHttpRange::testIsValid()
{
    QFETCH(int, from);
    QFETCH(int, to);
    QFETCH(int, dataSize);
    QFETCH(bool, valid);

    QHttpRange range(from, to, dataSize);

    QCOMPARE(range.isValid(), valid);
}

void TestQHttpRange::testParseFromString_data()
{
    QTest::addColumn<QString>("data");
    QTest::addColumn<int>("dataSize");
    QTest::addColumn<bool>("valid");
    QTest::addColumn<int>("from");
    QTest::addColumn<int>("to");
    QTest::addColumn<int>("length");

    QTest::newRow("Normal range")
            << "0-99" << -1
            << true << 0 << 99 << 100;

    QTest::newRow("Normal range with 'dataSize'")
            << "0-99" << 100
            << true << 0 << 99 << 100;

    QTest::newRow("Last N bytes")
            << "-256" << -1
            << true << -256 << -1 << 256;

    QTest::newRow("Last N bytes with 'dataSize'")
            << "-256" << 256
            << true << 0 << 255 << 256;

    QTest::newRow("Skip first N bytes")
            << "100-" << -1
            << true << 100 << -1 << -1;

    QTest::newRow("Skip first N bytes with 'dataSize'")
            << "100-" << 200
            << true << 100 << 199 << 100;

    QTest::newRow("OutOfBounds 'to' > 'from'")
            << "100-50" << -1
            << false;

    QTest::newRow("OutOfBounds 'from' > 'dataSize'")
            << "0-200" << 100
            << false;

    QTest::newRow("Last N bytes where N > 'dataSize'")
            << "-500" << 200
            << false;

    QTest::newRow("Skip first N bytes where N > 'dataSize'")
            << "100-" << 100
            << false;

    QTest::newRow("Bad input: '-'")
            << "-" << -1
            << false;

    QTest::newRow("Bad input: 'abc-def'")
            << "abc-def" << -1
            << false;

    QTest::newRow("Bad input: 'abcdef'")
            << "abcdef" << -1
            << false;
}

void TestQHttpRange::testParseFromString()
{
    QFETCH(QString, data);
    QFETCH(int, dataSize);
    QFETCH(bool, valid);

    QHttpRange range(data, dataSize);

    QCOMPARE(range.isValid(), valid);

    if (valid) {
        QFETCH(int, from);
        QFETCH(int, to);
        QFETCH(int, length);

        QCOMPARE(range.from(), from);
        QCOMPARE(range.to(), to);
        QCOMPARE(range.length(), length);
    }
}

void TestQHttpRange::testContentRange_data()
{
    QTest::addColumn<int>("from");
    QTest::addColumn<int>("to");
    QTest::addColumn<int>("dataSize");
    QTest::addColumn<QString>("contentRange");

    QTest::newRow("Normal range with 'dataSize'")
            << 0 << 100 << 1000
            << "0-100/1000";

    QTest::newRow("Normal range without 'dataSize'")
            << 0 << 100 << -1
            << "0-100/*";

    QTest::newRow("Invalid range with 'dataSize'")
            << 100 << 10 << 1200
            << "*/1200";

    QTest::newRow("Invalid range without 'dataSize'")
            << 100 << 10 << -1
            << "";
}

void TestQHttpRange::testContentRange()
{
    QFETCH(int, from);
    QFETCH(int, to);
    QFETCH(int, dataSize);
    QFETCH(QString, contentRange);

    QHttpRange range(from, to, dataSize);

    QCOMPARE(range.contentRange(), contentRange);
}

QTEST_MAIN(TestQHttpRange)
#include "TestQHttpRange.moc"
<commit_msg>Removed extra newline.<commit_after>/*
 * Copyright (c) 2016 Aleksei Ermakov
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include <QObject>
#include <QString>
#include <QTest>

#include <QHttpEngine/QHttpRange>

class TestQHttpRange : public QObject
{
    Q_OBJECT

public:

    TestQHttpRange();

private Q_SLOTS:

    void testDefaultConstructor();
    void testAssignmentOperator();

    void testFromToLength_data();
    void testFromToLength();

    void testIsValid_data();
    void testIsValid();

    void testParseFromString_data();
    void testParseFromString();

    void testContentRange_data();
    void testContentRange();
};

TestQHttpRange::TestQHttpRange()
{
}

void TestQHttpRange::testDefaultConstructor()
{
    QHttpRange range;

    QCOMPARE(range.isValid(), false);
}

void TestQHttpRange::testAssignmentOperator()
{
    QHttpRange range;
    QHttpRange otherRange(100, 200, -1);

    range = otherRange;

    QCOMPARE(range.isValid(), true);
    QCOMPARE(range.from(), 100);
    QCOMPARE(range.to(), 200);
}

void TestQHttpRange::testFromToLength_data()
{
    QTest::addColumn<int>("inFrom");
    QTest::addColumn<int>("inTo");
    QTest::addColumn<int>("inDataSize");
    QTest::addColumn<int>("from");
    QTest::addColumn<int>("to");
    QTest::addColumn<int>("length");

    QTest::newRow("Last 500 bytes")
            << -500 << -1 << -1
            << -500 << -1 << 500;

    QTest::newRow("Last 500 bytes with 800 dataSize")
            << -500 << -1 << 800
            << 300 << 799 << 500;

    QTest::newRow("Skip first 10 bytes")
            << 10 << -1 << -1
            << 10 << -1 << -1;

    QTest::newRow("Skip first 10 bytes with 100 dataSize")
            << 10 << -1 << 100
            << 10 << 99 << 90;
}

void TestQHttpRange::testFromToLength()
{
    QFETCH(int, inFrom);
    QFETCH(int, inTo);
    QFETCH(int, inDataSize);
    QFETCH(int, from);
    QFETCH(int, to);
    QFETCH(int, length);

    QHttpRange range(inFrom, inTo, inDataSize);

    QCOMPARE(range.from(), from);
    QCOMPARE(range.to(), to);
    QCOMPARE(range.length(), length);
}

void TestQHttpRange::testIsValid_data()
{
    QTest::addColumn<int>("from");
    QTest::addColumn<int>("to");
    QTest::addColumn<int>("dataSize");
    QTest::addColumn<bool>("valid");

    QTest::newRow("Normal range")
            << 0 << 100 << -1 << true;

    QTest::newRow("Normal range with 'dataSize'")
            << 0 << 99 << 100 << true;

    QTest::newRow("Last N bytes")
            << -500 << -1 << -1 << true;

    QTest::newRow("Last N bytes with 'dataSize'")
            << -500 << -1 << 500 << true;

    QTest::newRow("Skip first N bytes")
            << 10 << -1 << -1 << true;

    QTest::newRow("Skip first N bytes with 'dataSize'")
            << 10 << -1 << 500 << true;

    QTest::newRow("OutOfBounds 'to' > 'from'")
            << 100 << 50 << -1 << false;

    QTest::newRow("OutOfBounds 'from' > 'dataSize'")
            << 100 << 200 << 150 << false;

    QTest::newRow("Last N bytes where N > 'dataSize'")
            << -500 << -1 << 499 << false;

    QTest::newRow("Skip first N bytes where N > 'dataSize'")
            << 500 << -1 << 499 << false;
}

void TestQHttpRange::testIsValid()
{
    QFETCH(int, from);
    QFETCH(int, to);
    QFETCH(int, dataSize);
    QFETCH(bool, valid);

    QHttpRange range(from, to, dataSize);

    QCOMPARE(range.isValid(), valid);
}

void TestQHttpRange::testParseFromString_data()
{
    QTest::addColumn<QString>("data");
    QTest::addColumn<int>("dataSize");
    QTest::addColumn<bool>("valid");
    QTest::addColumn<int>("from");
    QTest::addColumn<int>("to");
    QTest::addColumn<int>("length");

    QTest::newRow("Normal range")
            << "0-99" << -1
            << true << 0 << 99 << 100;

    QTest::newRow("Normal range with 'dataSize'")
            << "0-99" << 100
            << true << 0 << 99 << 100;

    QTest::newRow("Last N bytes")
            << "-256" << -1
            << true << -256 << -1 << 256;

    QTest::newRow("Last N bytes with 'dataSize'")
            << "-256" << 256
            << true << 0 << 255 << 256;

    QTest::newRow("Skip first N bytes")
            << "100-" << -1
            << true << 100 << -1 << -1;

    QTest::newRow("Skip first N bytes with 'dataSize'")
            << "100-" << 200
            << true << 100 << 199 << 100;

    QTest::newRow("OutOfBounds 'to' > 'from'")
            << "100-50" << -1
            << false;

    QTest::newRow("OutOfBounds 'from' > 'dataSize'")
            << "0-200" << 100
            << false;

    QTest::newRow("Last N bytes where N > 'dataSize'")
            << "-500" << 200
            << false;

    QTest::newRow("Skip first N bytes where N > 'dataSize'")
            << "100-" << 100
            << false;

    QTest::newRow("Bad input: '-'")
            << "-" << -1
            << false;

    QTest::newRow("Bad input: 'abc-def'")
            << "abc-def" << -1
            << false;

    QTest::newRow("Bad input: 'abcdef'")
            << "abcdef" << -1
            << false;
}

void TestQHttpRange::testParseFromString()
{
    QFETCH(QString, data);
    QFETCH(int, dataSize);
    QFETCH(bool, valid);

    QHttpRange range(data, dataSize);

    QCOMPARE(range.isValid(), valid);

    if (valid) {
        QFETCH(int, from);
        QFETCH(int, to);
        QFETCH(int, length);

        QCOMPARE(range.from(), from);
        QCOMPARE(range.to(), to);
        QCOMPARE(range.length(), length);
    }
}

void TestQHttpRange::testContentRange_data()
{
    QTest::addColumn<int>("from");
    QTest::addColumn<int>("to");
    QTest::addColumn<int>("dataSize");
    QTest::addColumn<QString>("contentRange");

    QTest::newRow("Normal range with 'dataSize'")
            << 0 << 100 << 1000
            << "0-100/1000";

    QTest::newRow("Normal range without 'dataSize'")
            << 0 << 100 << -1
            << "0-100/*";

    QTest::newRow("Invalid range with 'dataSize'")
            << 100 << 10 << 1200
            << "*/1200";

    QTest::newRow("Invalid range without 'dataSize'")
            << 100 << 10 << -1
            << "";
}

void TestQHttpRange::testContentRange()
{
    QFETCH(int, from);
    QFETCH(int, to);
    QFETCH(int, dataSize);
    QFETCH(QString, contentRange);

    QHttpRange range(from, to, dataSize);

    QCOMPARE(range.contentRange(), contentRange);
}

QTEST_MAIN(TestQHttpRange)
#include "TestQHttpRange.moc"
<|endoftext|>


<commit_before>// Copyright (c) Facebook Inc. and Microsoft Corporation.
// Licensed under the MIT license.

#include "onnx/defs/schema.h"

using AttrType = onnx::OpSchema::AttrType;
using namespace onnx;

std::function<void(OpSchema&)> RNNDocGenerator(const char* name) {
    return [=](OpSchema& schema) {
        schema.Attr("hidden_size", "Number of neurons in the hidden layer", AttrType::INT);
        schema.Attr("direction", "Specify if the RNN is forward, reverse, or bidirectional. "
                    "Must be one of forward (default), reverse, or bidirectional.",
                    AttrType::STRING);
        schema.Attr("clip", "Cell clip threshold. Clipping bounds the elements of a tensor "
                    "in the range of [-threshold, +threshold] and is applied to the input "
                    "of activations. No clip if not specified.",
                    AttrType::FLOAT);
        schema.Input(0, "input",
                     "The input sequences packed (and potentially padded) into one 3-D "
                     "tensor with the shape of `[seq_length, batch_size, input_size]`.", "T");
        schema.Input(5, "seq_lens",
                     "Optional tensor specifying lengths of the sequences in a batch. "
                     "If not specified - assumed all sequences in the batch to have "
                     "length `seq_length`. It has shape `[batch_size]`.", "T1",
                     true /*optional*/);
        schema.Output(0, "output",
                      "A tensor that concats all the intermediate output values of the hidden."
                      "It has shape `[seq_length, num_directions, batch_size, hidden_size]`.", "T");
        schema.Output(1, "output_h",
                      "The last output value of the hidden. It has shape "
                      "`[num_directions, batch_size, hidden_size]`.", "T");
        schema.TypeConstraint("T", { "tensor(float16)", "tensor(float)", "tensor(double)" },
                              "Constrain input and output types to float tensors.");
        schema.TypeConstraint("T1", { "tensor(int32)" }, "Constrain seq_lens to integer tensor.");
    };
}

OPERATOR_SCHEMA(RNN)
    .NumInputs(3, 6)
    .NumOutputs(1, 2)
    .SetDoc(R"DOC(
Computes an one-layer simple RNN. This operator is usually supported
via some custom implementation such as CuDNN.

Notations:
`X` - input tensor
`i` - input gate
`t` - time step (t-1 means previous time step)
`Wi` - W parameter weight matrix for input gate
`Ri` - R recurrence weight matrix for input gate
`Wbi` - W parameter bias vector for input gate
`Rbi` - R parameter bias vector for input gate
`WBi` - W parameter weight matrix for backward input gate
`RBi` - R recurrence weight matrix for backward input gate
`WBbi` - WR bias vectors for backward input gate
`RBbi` - RR bias vectors for backward input gate
`ReLU(X)` - max(X, 0)
`tanh(X)` - hyperbolic tangent of X
`H` - Hidden state
`num_directions` - 2 if direction == bidirectional else 1

Equations:
  - Ht = Activation(Wi*Xt + Ri*Ht-1 + Wbi + Rbi)
)DOC")
    .Attr("activation", "The activation function for input gate. It must be "
          "one of tanh and ReLU. Default `tanh`.",
          AttrType::STRING)
    .Input(1, "W",
	   "The weight tensor for input gate. Concatenation of `Wi` and `WBi` "
           "(if bidirectional). The tensor has shape "
           "`[num_directions, hidden_size, input_size]`.", "T")
    .Input(2, "R",
	   "The recurrence weight tensor. Concatenation of `Ri` and `RBi` "
           "(if bidirectional). The tensor has shape "
	   "`[num_directions, hidden_size, hidden_size]`.", "T")
    .Input(3, "B",
	   "The bias tensor for input gate. Concatenation of `[Wbi, Rbi]` "
           "and `[WBbi, RBbi]` (if bidirectional). The tensor has shape "
           "`[num_directions, 2*hidden_size]`, Optional: If not specified - assumed "
           "to be 0.", "T",
	   true /*optional*/)
    .Input(4, "initial_h",
	   "Optional initial value of the hidden. If not specified - assumed "
	   "to be 0. It has shape `[num_directions, batch_size, hidden_size]`.",
	   "T", true /*optional*/)
    .FillUsing(RNNDocGenerator("SimpleRNN"));

OPERATOR_SCHEMA(GRU)
    .NumInputs(3, 6)
    .NumOutputs(1, 2)
    .SetDoc(R"DOC(
Computes an one-layer GRU. This operator is usually supported via some custom
implementation such as CuDNN.

Notations:
`X` - input tensor
`z` - update gate
`r` - reset gate
`h` - hidden gate
`t` - time step (t-1 means previous time step)
`W[zrh]` - W parameter weight matrix for update, reset, and hidden gates
`R[zrh]` - R recurrence weight matrix for update, reset, and hidden gates
`Wb[zrh]` - W bias vectors for update, reset, and hidden gates
`Rb[zrh]` - R bias vectors for update, reset, and hidden gates
`WB[zrh]` - W parameter weight matrix for backward update, reset, and hidden gates
`RB[zrh]` - R recurrence weight matrix for backward update, reset, and hidden gates
`WBb[zrh]` - W bias vectors for backward update, reset, and hidden gates
`RBb[zrh]` - R bias vectors for backward update, reset, and hidden gates
`tanh(X)` - hyperbolic tangent of X
`sigmoid(X)` - 1 / (1 + e^-X)
`H` - Hidden state
`num_directions` - 2 if direction == bidirectional else 1

Equations (GRU with default activations):
  - zt = sigmoid(Wz*Xt + Rz*Ht-1 + Wbz + Rbz)
  - rt = sigmoid(Wr*Xt + Rr*Ht-1 + Wbr + Rbr)
  - ht = tanh(Wh*Xt + rt*(Rh*Ht-1 + Rbh) + Wbh)
  - H = (1 - zt) (.) ht + it (.) Ht-1
)DOC")
    .Attr("activations", "A list of 3 activation functions for update, reset, and "
	  "hidden gates. The activation functions must be one of sigmoid and tanh. "
          "See the equations for default.",
          AttrType::STRINGS)
    .Input(1, "W",
	   "The weight tensor for the gates. Concatenation of `W[zrh]` and `WB[zrh]` "
	   "(if bidirectional) along dimension 0. This tensor has shape "
	   "`[num_directions, 3*hidden_size, input_size]`.", "T")
    .Input(2, "R",
	   "The recurrence weight tensor. Concatenation of `R[zrh]` and `RB[zrh]` "
	   "(if bidirectional) along dimension 0. This tensor has shape "
	   "`[num_directions, 3*hidden_size, hidden_size]`.", "T")
    .Input(3, "B",
	   "The bias tensor for the gates. Concatenation of `[Wb[zrh], Rb[zrh]]` and "
           "`[WBb[zrh], RBb[zrh]]` (if bidirectional) along dimension 0. This tensor "
           "has shape `[num_directions, 6*hidden_size]`. Optional: If not specified "
           "- assumed to be 0", "T",
	   true /*optional*/)
    .Input(4, "initial_h",
	   "Optional initial value of the hidden. If not specified - assumed "
	   "to be 0. It has shape `[num_directions, batch_size, hidden_size]`.",
	   "T", true /*optional*/)
    .FillUsing(RNNDocGenerator("GRU"));

OPERATOR_SCHEMA(LSTM)
    .NumInputs(3, 8)
    .NumOutputs(1, 2)
    .SetDoc(R"DOC(
Computes an one-layer LSTM. This operator is usually supported via some
custom implementation such as CuDNN.

Notations:
`X` - input tensor
`i` - input gate
`o` - output gate
`f` - forget gate
`c` - cell gate
`t` - time step (t-1 means previous time step)
`W[iofc]` - W parameter weight matrix for input, output, forget, and cell gates
`R[iofc]` - R recurrence weight matrix for input, output, forget, and cell gates
`Wb[iofc]` - W bias vectors for input, output, forget, and cell gates
`Rb[iofc]` - R bias vectors for input, output, forget, and cell gates
`P[iof]`  - P peephole weight matrix for input, output, and forget gates
`WB[iofc]` - W parameter weight matrix for backward input, output, forget, and cell gates
`RB[iofc]` - R recurrence weight matrix for backward input, output, forget, and cell gates
`WBb[iofc]` - W bias vectors for backward input, output, forget, and cell gates
`RBb[iofc]` - R bias vectors for backward input, output, forget, and cell gates
`PB[iof]`  - P peephole weight matrix for backward input, output, and forget gates
`tanh(X)` - hyperbolic tangent of X
`sigmoid(X)` - 1 / (1 + e^-X)
`H` - Hidden state
`num_directions` - 2 if direction == bidirectional else 1

Equations (forward LSTM with default activations and peepholes):
  - it = sigmoid(Wi*Xt + Ri*Ht-1 + Pi (.) Ct-1 + Wbi + Rbi)
  - ft = sigmoid(Wf*Xt + Rf*Ht-1 + Pf (.) Ct-1 + Wbf + Rbf)
  - ct = tanh(Wc*Xt + Rc*Ht-1 + Wbc + Rbc)
  - Ct = ft (.) Ct-1 + it (.) ct
  - ot = sigmoid(Wo*Xt + Ro*Ht-1 + Po (.) Ct + Wbo + Rbo)
  - H = ot (.) tanh(Ct)
)DOC")
    .Attr("activations", "A list of 4 activation functions for input, output, "
	  "forget, and cell gates. The activation functions must be one of sigmoid "
	  "and tanh. See the equations for default.",
          AttrType::STRINGS)
    .Attr("input_forget", "Couple the input and forget gates if 1, default 0.",
          AttrType::INT)
    .Input(1, "W",
	   "The weight tensor for the gates. Concatenation of `W[iofc]` and "
           "`WB[iofc]` (if bidirectional) along dimension 0. The tensor has shape "
	   "`[num_directions, 4*hidden_size, input_size]`.", "T")
    .Input(2, "R",
	   "The recurrence weight tensor. Concatenation of `R[iofc]` and "
	   "`RB[iofc]` (if bidirectional) along dimension 0. This tensor has shape "
           "`[num_directions, 4*hidden_size, hidden_size]`.", "T")
    .Input(3, "B",
	   "The bias tensor for input gate. Concatenation of `[Wb[iofc], Rb[iofc]]`, "
	   "and `[WBb[iofc], RBb[iofc]]` (if bidirectional) along dimension 0. This "
           "tensor has shape `[num_directions, 8*hidden_size]`. Optional: If not "
	   "specified - assumed to be 0.", "T",
	   true /*optional*/)
    .Input(4, "initial_h",
           "Optional initial value of the hidden. If not specified - assumed "
           "to be 0. It has shape `[num_directions, batch_size, hidden_size]`.",
	   "T", true /*optional*/)
    .Input(6, "initial_c",
           "Optional initial value of the cell. If not specified - assumed "
	   "to be 0. It has shape `[num_directions, batch_size, hidden_size]`.",
	   "T", true /*optional*/)
    .Input(7, "P",
	   "The weight tensor for peepholes. Concatenation of `P[iof]` and "
	   "`PB[iof]` (if bidirectional) along dimension 0. It has shape "
	   "`[num_directions, 3*hidde_size, hidden_size]`. Optional: If not specified - "
	   "assumed to be 0.", "T",
	   true /*optional*/)
    .FillUsing(RNNDocGenerator("LSTM"));
<commit_msg>Updates<commit_after>// Copyright (c) Facebook Inc. and Microsoft Corporation.
// Licensed under the MIT license.

#include "onnx/defs/schema.h"

using AttrType = onnx::OpSchema::AttrType;
using namespace onnx;

std::function<void(OpSchema&)> RNNDocGenerator(const char* name) {
    return [=](OpSchema& schema) {
        schema.Attr("hidden_size", "Number of neurons in the hidden layer", AttrType::INT);
        schema.Attr("direction", "Specify if the RNN is forward, reverse, or bidirectional. "
                    "Must be one of forward (default), reverse, or bidirectional.",
                    AttrType::STRING);
        schema.Input(0, "X",
                     "The input sequences packed (and potentially padded) into one 3-D "
                     "tensor with the shape of `[seq_length, batch_size, input_size]`.", "T");
        schema.Input(5, "seq_lens",
                     "Optional tensor specifying lengths of the sequences in a batch. "
                     "If not specified - assumed all sequences in the batch to have "
                     "length `seq_length`. It has shape `[batch_size]`.", "T1",
                     true /*optional*/);
        schema.Output(0, "Y",
                      "A tensor that concats all the intermediate output values of the hidden."
                      "It has shape `[seq_length, num_directions, batch_size, hidden_size]`.", "T");
        schema.Output(1, "Y_h",
                      "The last output value of the hidden. It has shape "
                      "`[num_directions, batch_size, hidden_size]`.", "T");
        schema.TypeConstraint("T", { "tensor(float16)", "tensor(float)", "tensor(double)" },
                              "Constrain input and output types to float tensors.");
        schema.TypeConstraint("T1", { "tensor(int32)" }, "Constrain seq_lens to integer tensor.");
    };
}

OPERATOR_SCHEMA(RNN)
    .NumInputs(3, 6)
    .NumOutputs(1, 2)
    .SetDoc(R"DOC(
Computes an one-layer simple RNN. This operator is usually supported
via some custom implementation such as CuDNN.

Notations:
`X` - input tensor
`i` - input gate
`t` - time step (t-1 means previous time step)
`Wi` - W parameter weight matrix for input gate
`Ri` - R recurrence weight matrix for input gate
`Wbi` - W parameter bias vector for input gate
`Rbi` - R parameter bias vector for input gate
`WBi` - W parameter weight matrix for backward input gate
`RBi` - R recurrence weight matrix for backward input gate
`WBbi` - WR bias vectors for backward input gate
`RBbi` - RR bias vectors for backward input gate
`ReLU(X)` - max(X, 0)
`tanh(X)` - hyperbolic tangent of X
`H` - Hidden state
`num_directions` - 2 if direction == bidirectional else 1

Equations:
  - Ht = Activation(Wi*Xt + Ri*Ht-1 + Wbi + Rbi)
)DOC")
    .Attr("activation", "The activation function for input gate. It must be "
          "one of tanh and ReLU. Default `tanh`.",
          AttrType::STRING)
    .Input(1, "W",
	   "The weight tensor for input gate. Concatenation of `Wi` and `WBi` "
           "(if bidirectional). The tensor has shape "
           "`[num_directions, hidden_size, input_size]`.", "T")
    .Input(2, "R",
	   "The recurrence weight tensor. Concatenation of `Ri` and `RBi` "
           "(if bidirectional). The tensor has shape "
	   "`[num_directions, hidden_size, hidden_size]`.", "T")
    .Input(3, "B",
	   "The bias tensor for input gate. Concatenation of `[Wbi, Rbi]` "
           "and `[WBbi, RBbi]` (if bidirectional). The tensor has shape "
           "`[num_directions, 2*hidden_size]`, Optional: If not specified - assumed "
           "to be 0.", "T",
	   true /*optional*/)
    .Input(4, "initial_h",
	   "Optional initial value of the hidden. If not specified - assumed "
	   "to be 0. It has shape `[num_directions, batch_size, hidden_size]`.",
	   "T", true /*optional*/)
    .FillUsing(RNNDocGenerator("SimpleRNN"));

OPERATOR_SCHEMA(GRU)
    .NumInputs(3, 6)
    .NumOutputs(1, 2)
    .SetDoc(R"DOC(
Computes an one-layer GRU. This operator is usually supported via some custom
implementation such as CuDNN.

Notations:
`X` - input tensor
`z` - update gate
`r` - reset gate
`h` - hidden gate
`t` - time step (t-1 means previous time step)
`W[zrh]` - W parameter weight matrix for update, reset, and hidden gates
`R[zrh]` - R recurrence weight matrix for update, reset, and hidden gates
`Wb[zrh]` - W bias vectors for update, reset, and hidden gates
`Rb[zrh]` - R bias vectors for update, reset, and hidden gates
`WB[zrh]` - W parameter weight matrix for backward update, reset, and hidden gates
`RB[zrh]` - R recurrence weight matrix for backward update, reset, and hidden gates
`WBb[zrh]` - W bias vectors for backward update, reset, and hidden gates
`RBb[zrh]` - R bias vectors for backward update, reset, and hidden gates
`tanh(X)` - hyperbolic tangent of X
`sigmoid(X)` - 1 / (1 + e^-X)
`H` - Hidden state
`num_directions` - 2 if direction == bidirectional else 1

Equations (GRU with default activations):
  - zt = sigmoid(Wz*Xt + Rz*Ht-1 + Wbz + Rbz)
  - rt = sigmoid(Wr*Xt + Rr*Ht-1 + Wbr + Rbr)
  - ht = tanh(Wh*Xt + rt*(Rh*Ht-1 + Rbh) + Wbh)
  - H = (1 - zt) (.) ht + it (.) Ht-1
)DOC")
    .Attr("activations", "A list of 3 activation functions for update, reset, and "
	  "hidden gates. The activation functions must be one of sigmoid and tanh. "
          "See the equations for default.",
          AttrType::STRINGS)
    .Input(1, "W",
	   "The weight tensor for the gates. Concatenation of `W[zrh]` and `WB[zrh]` "
	   "(if bidirectional) along dimension 0. This tensor has shape "
	   "`[num_directions, 3*hidden_size, input_size]`.", "T")
    .Input(2, "R",
	   "The recurrence weight tensor. Concatenation of `R[zrh]` and `RB[zrh]` "
	   "(if bidirectional) along dimension 0. This tensor has shape "
	   "`[num_directions, 3*hidden_size, hidden_size]`.", "T")
    .Input(3, "B",
	   "The bias tensor for the gates. Concatenation of `[Wb[zrh], Rb[zrh]]` and "
           "`[WBb[zrh], RBb[zrh]]` (if bidirectional) along dimension 0. This tensor "
           "has shape `[num_directions, 6*hidden_size]`. Optional: If not specified "
           "- assumed to be 0", "T",
	   true /*optional*/)
    .Input(4, "initial_h",
	   "Optional initial value of the hidden. If not specified - assumed "
	   "to be 0. It has shape `[num_directions, batch_size, hidden_size]`.",
	   "T", true /*optional*/)
    .FillUsing(RNNDocGenerator("GRU"));

OPERATOR_SCHEMA(LSTM)
    .NumInputs(3, 8)
    .NumOutputs(1, 2)
    .SetDoc(R"DOC(
Computes an one-layer LSTM. This operator is usually supported via some
custom implementation such as CuDNN.

Notations:
`X` - input tensor
`i` - input gate
`o` - output gate
`f` - forget gate
`c` - cell gate
`t` - time step (t-1 means previous time step)
`W[iofc]` - W parameter weight matrix for input, output, forget, and cell gates
`R[iofc]` - R recurrence weight matrix for input, output, forget, and cell gates
`Wb[iofc]` - W bias vectors for input, output, forget, and cell gates
`Rb[iofc]` - R bias vectors for input, output, forget, and cell gates
`P[iof]`  - P peephole weight matrix for input, output, and forget gates
`WB[iofc]` - W parameter weight matrix for backward input, output, forget, and cell gates
`RB[iofc]` - R recurrence weight matrix for backward input, output, forget, and cell gates
`WBb[iofc]` - W bias vectors for backward input, output, forget, and cell gates
`RBb[iofc]` - R bias vectors for backward input, output, forget, and cell gates
`PB[iof]`  - P peephole weight matrix for backward input, output, and forget gates
`tanh(X)` - hyperbolic tangent of X
`sigmoid(X)` - 1 / (1 + e^-X)
`H` - Hidden state
`num_directions` - 2 if direction == bidirectional else 1

Equations (forward LSTM with default activations and peepholes):
  - it = sigmoid(Wi*Xt + Ri*Ht-1 + Pi (.) Ct-1 + Wbi + Rbi)
  - ft = sigmoid(Wf*Xt + Rf*Ht-1 + Pf (.) Ct-1 + Wbf + Rbf)
  - ct = tanh(Wc*Xt + Rc*Ht-1 + Wbc + Rbc)
  - Ct = ft (.) Ct-1 + it (.) ct
  - ot = sigmoid(Wo*Xt + Ro*Ht-1 + Po (.) Ct + Wbo + Rbo)
  - H = ot (.) tanh(Ct)
)DOC")
    .Attr("activations", "A list of 4 activation functions for input, output, "
	  "forget, and cell gates. The activation functions must be one of sigmoid "
	  "and tanh. See the equations for default.",
          AttrType::STRINGS)
    .Attr("clip", "Cell clip threshold. Clipping bounds the elements of a tensor "
          "in the range of [-threshold, +threshold] and is applied to the input "
          "of activations. No clip if not specified.",
          AttrType::FLOAT)
    .Attr("input_forget", "Couple the input and forget gates if 1, default 0.",
          AttrType::INT)
    .Input(1, "W",
	   "The weight tensor for the gates. Concatenation of `W[iofc]` and "
           "`WB[iofc]` (if bidirectional) along dimension 0. The tensor has shape "
	   "`[num_directions, 4*hidden_size, input_size]`.", "T")
    .Input(2, "R",
	   "The recurrence weight tensor. Concatenation of `R[iofc]` and "
	   "`RB[iofc]` (if bidirectional) along dimension 0. This tensor has shape "
           "`[num_directions, 4*hidden_size, hidden_size]`.", "T")
    .Input(3, "B",
	   "The bias tensor for input gate. Concatenation of `[Wb[iofc], Rb[iofc]]`, "
	   "and `[WBb[iofc], RBb[iofc]]` (if bidirectional) along dimension 0. This "
           "tensor has shape `[num_directions, 8*hidden_size]`. Optional: If not "
	   "specified - assumed to be 0.", "T",
	   true /*optional*/)
    .Input(4, "initial_h",
           "Optional initial value of the hidden. If not specified - assumed "
           "to be 0. It has shape `[num_directions, batch_size, hidden_size]`.",
	   "T", true /*optional*/)
    .Input(6, "initial_c",
           "Optional initial value of the cell. If not specified - assumed "
	   "to be 0. It has shape `[num_directions, batch_size, hidden_size]`.",
	   "T", true /*optional*/)
    .Input(7, "P",
	   "The weight tensor for peepholes. Concatenation of `P[iof]` and "
	   "`PB[iof]` (if bidirectional) along dimension 0. It has shape "
	   "`[num_directions, 3*hidde_size, hidden_size]`. Optional: If not specified - "
	   "assumed to be 0.", "T",
	   true /*optional*/)
    .FillUsing(RNNDocGenerator("LSTM"));
<|endoftext|>


<commit_before>// $Id$

// system and C includes
#include <pcap.h>
#include <cstdio>
#include </usr/local/include/getopt.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <ifaddrs.h>
#include <stdio.h>
#include <net/if_dl.h>

// C++ includes
#include <string>
#include <iostream>
#include <set>
#include <map>
#include <algorithm>
#include <iterator>

using namespace std;

// container that keeps pairs (MAC, count) representing src
// addresses of packets ordered by MAC adress
map<string, int> src;

// same for dst addresses
map<string, int> dst;

// container that keeps pairs (MAC, count)
// representing src addresses of packets
// ordered by count of packets
multimap<int, string> src_score;

// same for dst addresses
multimap<int, string> dst_score;

// keeps list of own macs (for -r handling)
set<string> ownmacs;

bool g_verbose = false;
bool g_remote = false;
bool g_mark = false;
bool g_debug = false;
bool g_ascend = false;
bool g_percent = false;
bool g_only_dst = false;
bool g_only_src = false;

#define DEFAULT_PKT_CNT (100)
#define DEFAULT_MAC_CNT (-1)

int  pkt_cnt = DEFAULT_PKT_CNT;
int  mac_cnt = DEFAULT_MAC_CNT;
int  src_cnt;
int  dst_cnt;

void
h(u_char * useless, const struct pcap_pkthdr * pkthdr, const u_char * pkt)
{
    char buf[50];
    int  i;
    map<string, int>::iterator mit;

    for (i = 0; i < 6; i++)
        sprintf(buf+3*i, "%02x:", pkt[i]);
    buf[17] = '\0';

    string s1(buf);
    mit=src.find(s1);   // find element of src having MAC equal to s1
    if (mit == src.end()) // not found, create
        src.insert(make_pair(s1, 1));
    else // found, increase count by 1
        ++(mit -> second);

    for (i = 0; i < 6; i++)
        sprintf(buf+3*i, "%02x:", pkt[i + 6]);
    buf[17] = '\0';

    string s2(buf);
    mit=dst.find(s2);   // same for dst
    if (mit == dst.end())
        dst.insert(make_pair(s2, 1));
    else
        ++(mit -> second);

    if (g_verbose)
        cout << s1 << " ->> " << s2 << endl;
}

template<class T> class uncount
{
    int* cnt_var;
public:
    uncount(int* cv) : cnt_var(cv) {}
    void operator() (T x)
    {
        if (ownmacs.find(x.second) != ownmacs.end())
        {
            *cnt_var = *cnt_var - x.first;
            if (g_debug)
                cout << "DEBUG uncount: " << x.first << " " << *cnt_var << endl;
        }
    }
};

// utility for printing pairs to output stream
template<class T> class print
{
    ostream &os;
    int pkt_cnt;
    int mac_cnt;
    bool g_mac_cnt;
public:
    print(ostream &out, int pc, int mc) : os(out), pkt_cnt(pc), mac_cnt(mc) {
	    if (mc != DEFAULT_MAC_CNT)
		    g_mac_cnt = true;
	    else
		    g_mac_cnt = false;
    }

    void operator() (T x)
    {
        if (g_remote)
        {
            if (ownmacs.find(x.second) != ownmacs.end())
            {
                if (g_debug)
                    cout << "DEBUG: erased: " << x.second << endl;
                return;
            }
        }
        if (g_mac_cnt) {
                mac_cnt--;
                if (mac_cnt < 0)
                        return;
        }

        os << "\t" << x.first << "\t" << x.second;

        if (g_percent)
        {
            char s[10];
            sprintf(s, "%4.1f", (static_cast<double>(x.first)/pkt_cnt)*100.0);
            cout << "\t" << s << "%";
        }

        if (g_mark)
        {
            if (ownmacs.find(x.second) != ownmacs.end())
                cout << " *";
        }

        cout << endl;
    }
};

// utility for reverting pairs
template <class T, class S> class revert
{
// input:  pair (A, B)
// output: pair (B, A)
public:
    revert() {}
    pair<S, T> operator() (pair<T, S> x)
    {
        return make_pair(x.second, x.first);
    }
};

int
main(int argc, char *argv[])
{
    char           *pcap_dev = NULL;
    bpf_u_int32     net, mask;
    char            errbuff[1024];
    int             opt;
    bool            usage = false; // show usage

    char rev[255] = "$Revision$";
    rev[strlen(rev)] = '\0';
    char *revp = rev + 11; // skip prefix
    cerr << "Saker v" << revp << endl;

    while ((opt = getopt (argc, argv, "i:n:m:laphvrsdVD")) != -1)
    {
        switch (opt)
        {
        case 'i':
            pcap_dev = (char *) strdup (optarg);
            break;

		case 'n':
            pkt_cnt = atoi(optarg);
            break;

		case 'm':
            mac_cnt = atoi(optarg);
            break;

		case 'a':
            g_ascend = true;
            break;

		case 'p':
            g_percent = true;
            break;

		case 'h':
            usage = true;
            break;

		case 'v':
            g_verbose = true;
            break;

		case 'r':
            g_remote = true;
            break;

		case 'l':
            g_mark = true;
            break;

		case 'd':
			g_only_dst = true;
			if (g_only_src)
			{
				cerr << "Error: You cannot have both -d and -s." << endl;
				usage = true;
			}
			break;

		case 's':
			g_only_src = true;
			if (g_only_dst)
			{
				cerr << "Error: You cannot have both -d and -s." << endl;
				usage = true;
			}
			break;

		case 'V':
			exit(0);
            break;

		case 'D':
            g_debug = true;
            break;

		case '?':
        default:
            cerr << "Error: Unknown command line option." << endl;
            usage = true;
            break;
        }
    }

    if (usage == false && pcap_dev == NULL)
    {
        cerr << "Error: Interface not specified." << endl;
        usage = true;
    }

    if (usage)
    {
        cerr << endl
			<< "Usage: saker [-aprmvhVD] [-n num] [-m num] [-s|-d] -i <if>" << endl
            << "\t-i <if>\t\tnetwork interface" << endl
			<< "\t-h\t\tshow this info" << endl
            << "\t-n num\t\tnumber of packets to capture (default " << DEFAULT_PKT_CNT << ")" << endl
            << "\t-a\t\tascending sort (default descending)" << endl
            << "\t-m num\t\tnumber of MACs to display in summary (all by default)" << endl
            << "\t-p\t\tshow percentage" << endl
            << "\t-r\t\tcount only remote ends (exclude my MACs)" << endl
            << "\t-l\t\tmark local MACs with asterisk (see also -r)" << endl
            << "\t-s\t\tshow only source stats" << endl
            << "\t-d\t\tshow only destination stats" << endl
            << "\t-v\t\tbe verbose (e.g. output each packet)" << endl
            << "\t-V\t\tprint version and exit" << endl
            << "\t-D\t\tenable debug output (you are not supposed to understand it)" << endl;
        exit(1);
    }

// get own mac's

    struct ifaddrs *ifap, *ifaphead;
    int rtnerr;
    const struct sockaddr_dl *sdl;
    caddr_t ap;
    int alen;
    char ownmac[18] = "..:..:..:..:..:.."; // 6*2+5+1

    rtnerr = getifaddrs(&ifaphead);
    if (rtnerr)
    {
        perror("getifaddrs");
        exit(2);
    }

    if (g_verbose)
        cout << "Own MAC adresses:" << endl;
    for (ifap = ifaphead; ifap; ifap = ifap->ifa_next)
    {
        if (ifap->ifa_addr->sa_family == AF_LINK)
        {
            sdl = (const struct sockaddr_dl *) ifap->ifa_addr;
            ap = ((caddr_t)((sdl)->sdl_data + (sdl)->sdl_nlen));
            alen = sdl->sdl_alen;
            if (ap && alen > 0)
            {
                int i;
                //  printf ("%s:", ifap->ifa_name); device name
                for (i = 0; i < alen; i++, ap++)
                {
                    if (i > 0)
                        sprintf(ownmac+2+(i-1)*3,"%c%02x", ':' , 0xff&*ap);
                    else
                        sprintf(ownmac+i*3,"%02x", 0xff&*ap);
                }

                if (g_verbose)
                    cout << ownmac << endl;

                string ownmacstr(ownmac);
                ownmacs.insert(ownmacstr);
            }
        }
    }

    if (g_debug)
        copy(ownmacs.begin(), ownmacs.end(), ostream_iterator<string>(cout, "!\n"));

    freeifaddrs(ifaphead);

    // initialize pcap

    int pcap_net = pcap_lookupnet(pcap_dev, &net, &mask, errbuff);
    pcap_t *pcap_desc = pcap_open_live(pcap_dev, 100, 1, 1000, errbuff);
    if (pcap_desc == NULL) { perror("pcap_open_live"); exit(3); }

    // do the capture
    pcap_loop(pcap_desc, pkt_cnt, h, NULL);

    // report section

    if (!g_only_dst)
    {
		cout << "SRC stats:" << endl;
		src_cnt = pkt_cnt;

		// we have first to copy all stats from src, which is ordered by MAC to src_score
		// which is ordered by count, making possible printing stats ordered by count
		transform(src.begin(), src.end(), inserter(src_score, src_score.begin()), revert<string, int>());

		if (g_remote)
			for_each(src_score.begin(), src_score.end(), uncount<pair<int, string> >(&src_cnt));

		// and now we simply print stats by count :)
		if (g_ascend)
			for_each(src_score.begin(), src_score.end(), print<pair<int, string> >(cout, src_cnt, mac_cnt));
		else
			for_each(src_score.rbegin(), src_score.rend(), print<pair<int, string> >(cout, src_cnt, mac_cnt));
    }

    if (!g_only_src)
    {
		cout << "DST stats:" << endl;
		dst_cnt = pkt_cnt;

		// same for dst
		transform(dst.begin(), dst.end(), inserter(dst_score, dst_score.begin()), revert<string, int>());

		if (g_remote)
			for_each(dst_score.begin(), dst_score.end(), uncount<pair<int, string> >(&dst_cnt));

		if (g_ascend)
			for_each(dst_score.begin(), dst_score.end(), print<pair<int, string> >(cout, dst_cnt, mac_cnt));
		else
			for_each(dst_score.rbegin(), dst_score.rend(), print<pair<int, string> >(cout, dst_cnt, mac_cnt));
    }

    return 0;
}
<commit_msg>attempt to add continuous mode (-c and -t)<commit_after>// $Id$

// system and C includes
#include <pcap.h>
#include <cstdio>
#include </usr/local/include/getopt.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <ifaddrs.h>
#include <stdio.h>
#include <net/if_dl.h>

// C++ includes
#include <string>
#include <iostream>
#include <set>
#include <map>
#include <algorithm>
#include <iterator>

using namespace std;

// container that keeps pairs (MAC, count) representing src
// addresses of packets ordered by MAC adress
map<string, int> src;

// same for dst addresses
map<string, int> dst;

// container that keeps pairs (MAC, count)
// representing src addresses of packets
// ordered by count of packets
multimap<int, string> src_score;

// same for dst addresses
multimap<int, string> dst_score;

// keeps list of own macs (for -r handling)
set<string> ownmacs;

bool g_verbose = false;
bool g_remote = false;
bool g_mark = false;
bool g_debug = false;
bool g_ascend = false;
bool g_percent = false;
bool g_only_dst = false;
bool g_only_src = false;
bool g_cont = false;

#define DEFAULT_PKT_CNT (100)
#define DEFAULT_MAC_CNT (-1)
#define DEFAULT_DELAY (10)

int  pkt_cnt = DEFAULT_PKT_CNT;
int  mac_cnt = DEFAULT_MAC_CNT;
int  src_cnt;
int  dst_cnt;

void
h(u_char * useless, const struct pcap_pkthdr * pkthdr, const u_char * pkt)
{
    char buf[50];
    int  i;
    map<string, int>::iterator mit;

    for (i = 0; i < 6; i++)
        sprintf(buf+3*i, "%02x:", pkt[i]);
    buf[17] = '\0';

    string s1(buf);
    mit=src.find(s1);   // find element of src having MAC equal to s1
    if (mit == src.end()) // not found, create
        src.insert(make_pair(s1, 1));
    else // found, increase count by 1
        ++(mit -> second);

    for (i = 0; i < 6; i++)
        sprintf(buf+3*i, "%02x:", pkt[i + 6]);
    buf[17] = '\0';

    string s2(buf);
    mit=dst.find(s2);   // same for dst
    if (mit == dst.end())
        dst.insert(make_pair(s2, 1));
    else
        ++(mit -> second);

    if (g_verbose)
        cout << s1 << " ->> " << s2 << endl;
}

template<class T> class uncount
{
    int* cnt_var;
public:
    uncount(int* cv) : cnt_var(cv) {}
    void operator() (T x)
    {
        if (ownmacs.find(x.second) != ownmacs.end())
        {
            *cnt_var = *cnt_var - x.first;
            if (g_debug)
                cout << "DEBUG uncount: " << x.first << " " << *cnt_var << endl;
        }
    }
};

// utility for printing pairs to output stream
template<class T> class print
{
    ostream &os;
    int pkt_cnt;
    int mac_cnt;
    bool g_mac_cnt;
public:
    print(ostream &out, int pc, int mc) : os(out), pkt_cnt(pc), mac_cnt(mc) {
	    if (mc != DEFAULT_MAC_CNT)
		    g_mac_cnt = true;
	    else
		    g_mac_cnt = false;
    }

    void operator() (T x)
    {
        if (g_remote)
        {
            if (ownmacs.find(x.second) != ownmacs.end())
            {
                if (g_debug)
                    cout << "DEBUG: erased: " << x.second << endl;
                return;
            }
        }
        if (g_mac_cnt) {
                mac_cnt--;
                if (mac_cnt < 0)
                        return;
        }

        os << "\t" << x.first << "\t" << x.second;

        if (g_percent)
        {
            char s[10];
            sprintf(s, "%4.1f", (static_cast<double>(x.first)/pkt_cnt)*100.0);
            cout << "\t" << s << "%";
        }

        if (g_mark)
        {
            if (ownmacs.find(x.second) != ownmacs.end())
                cout << " *";
        }

        cout << endl;
    }
};

// utility for reverting pairs
template <class T, class S> class revert
{
// input:  pair (A, B)
// output: pair (B, A)
public:
    revert() {}
    pair<S, T> operator() (pair<T, S> x)
    {
        return make_pair(x.second, x.first);
    }
};

void alarm_report(int sig)
{
	report();
	alarm(time_delay);
}

void report(void)
{
    if (!g_only_dst)
    {
		cout << "SRC stats:" << endl;
		src_cnt = pkt_cnt;

		// we have first to copy all stats from src, which is ordered by MAC to src_score
		// which is ordered by count, making possible printing stats ordered by count
		transform(src.begin(), src.end(), inserter(src_score, src_score.begin()), revert<string, int>());

		if (g_remote)
			for_each(src_score.begin(), src_score.end(), uncount<pair<int, string> >(&src_cnt));

		// and now we simply print stats by count :)
		if (g_ascend)
			for_each(src_score.begin(), src_score.end(), print<pair<int, string> >(cout, src_cnt, mac_cnt));
		else
			for_each(src_score.rbegin(), src_score.rend(), print<pair<int, string> >(cout, src_cnt, mac_cnt));
    }

    if (!g_only_src)
    {
		cout << "DST stats:" << endl;
		dst_cnt = pkt_cnt;

		// same for dst
		transform(dst.begin(), dst.end(), inserter(dst_score, dst_score.begin()), revert<string, int>());

		if (g_remote)
			for_each(dst_score.begin(), dst_score.end(), uncount<pair<int, string> >(&dst_cnt));

		if (g_ascend)
			for_each(dst_score.begin(), dst_score.end(), print<pair<int, string> >(cout, dst_cnt, mac_cnt));
		else
			for_each(dst_score.rbegin(), dst_score.rend(), print<pair<int, string> >(cout, dst_cnt, mac_cnt));
    }
}

int
main(int argc, char *argv[])
{
    char           *pcap_dev = NULL;
    bpf_u_int32     net, mask;
    char            errbuff[1024];
    int             opt;
    bool            usage = false; // show usage

    char rev[255] = "$Revision$";
    rev[strlen(rev)] = '\0';
    char *revp = rev + 11; // skip prefix
    cerr << "saker v" << revp << endl;

    while ((opt = getopt (argc, argv, "i:n:m:t:claphvrsdVD")) != -1)
    {
        switch (opt)
        {
        case 'i':
            pcap_dev = (char *) strdup (optarg);
            break;

		case 'n':
            pkt_cnt = atoi(optarg);
            break;

		case 'm':
            mac_cnt = atoi(optarg);
            break;

		case 't':
            time_delay = atoi(optarg);
			if (time_delay < 1)
				time_delay = 1;
            break;

		case 'a':
            g_ascend = true;
            break;

		case 'p':
            g_percent = true;
            break;

		case 'h':
            usage = true;
            break;

		case 'v':
            g_verbose = true;
            break;

		case 'r':
            g_remote = true;
            break;

		case 'l':
            g_mark = true;
            break;

		case 'c':
            g_cont = true;
            break;

		case 'd':
			g_only_dst = true;
			if (g_only_src)
			{
				cerr << "Error: You cannot have both -d and -s." << endl;
				usage = true;
			}
			break;

		case 's':
			g_only_src = true;
			if (g_only_dst)
			{
				cerr << "Error: You cannot have both -d and -s." << endl;
				usage = true;
			}
			break;

		case 'V':
			exit(0);
            break;

		case 'D':
            g_debug = true;
            break;

		case '?':
        default:
            cerr << "Error: Unknown command line option." << endl;
            usage = true;
            break;
        }
    }

    if (usage == false && pcap_dev == NULL)
    {
        cerr << "Error: Interface not specified." << endl;
        usage = true;
    }

    if (usage)
    {
        cerr << endl
			<< "Usage: saker [-aprmvhVD] [-n num] [-m num] [-s|-d] [-c -t num] -i <if>" << endl
            << "\t-i <if>\t\tnetwork interface" << endl
			<< "\t-h\t\tshow this info" << endl
            << "\t-n num\t\tnumber of packets to capture (default " << DEFAULT_PKT_CNT << ")" << endl
            << "\t-a\t\tascending sort (default descending)" << endl
            << "\t-m num\t\tnumber of MACs to display in summary (all by default)" << endl
            << "\t-p\t\tshow percentage" << endl
            << "\t-r\t\tcount only remote ends (exclude my MACs)" << endl
            << "\t-l\t\tmark local MACs with asterisk (see also -r)" << endl
            << "\t-s\t\tshow only source stats" << endl
            << "\t-d\t\tshow only destination stats" << endl
            << "\t-c\t\tcontinuous mode" << endl
            << "\t-t\t\ttime delay for continuous mode in seconds (default "<< DEFAULT_DELAY << ")" << endl
            << "\t-v\t\tbe verbose (e.g. output each packet)" << endl
            << "\t-V\t\tprint version and exit" << endl
            << "\t-D\t\tenable debug output (you are not supposed to understand it)" << endl;
        exit(1);
    }

// get own mac's

    struct ifaddrs *ifap, *ifaphead;
    int rtnerr;
    const struct sockaddr_dl *sdl;
    caddr_t ap;
    int alen;
    char ownmac[18] = "..:..:..:..:..:.."; // 6*2+5+1

    rtnerr = getifaddrs(&ifaphead);
    if (rtnerr)
    {
        perror("getifaddrs");
        exit(2);
    }

    if (g_verbose)
        cout << "Own MAC adresses:" << endl;
    for (ifap = ifaphead; ifap; ifap = ifap->ifa_next)
    {
        if (ifap->ifa_addr->sa_family == AF_LINK)
        {
            sdl = (const struct sockaddr_dl *) ifap->ifa_addr;
            ap = ((caddr_t)((sdl)->sdl_data + (sdl)->sdl_nlen));
            alen = sdl->sdl_alen;
            if (ap && alen > 0)
            {
                int i;
                //  printf ("%s:", ifap->ifa_name); device name
                for (i = 0; i < alen; i++, ap++)
                {
                    if (i > 0)
                        sprintf(ownmac+2+(i-1)*3,"%c%02x", ':' , 0xff&*ap);
                    else
                        sprintf(ownmac+i*3,"%02x", 0xff&*ap);
                }

                if (g_verbose)
                    cout << ownmac << endl;

                string ownmacstr(ownmac);
                ownmacs.insert(ownmacstr);
            }
        }
    }

    if (g_debug)
        copy(ownmacs.begin(), ownmacs.end(), ostream_iterator<string>(cout, "!\n"));

    freeifaddrs(ifaphead);

    // initialize pcap

    int pcap_net = pcap_lookupnet(pcap_dev, &net, &mask, errbuff);
    pcap_t *pcap_desc = pcap_open_live(pcap_dev, 100, 1, 1000, errbuff);
    if (pcap_desc == NULL) { perror("pcap_open_live"); exit(3); }

	if (g_cont)
	{
		signal(SIGALRM, alarm_report);
		alarm(time_delay);
	}

	pcap_loop(pcap_desc, pkt_cnt, h, NULL);
	report();

    return 0;
}
<|endoftext|>


<commit_before>/*
Stereo Vision Algorithm Framework, Copyright(c) 2016-2018, Peng Chao
طָBy:ɣ
*/

#include "SupixSegLayer.h"
#include "../../SuperPixelSegment/svafinterface.h"

using namespace pc;

namespace svaf{

SupixSegLayer::SupixSegLayer(LayerParameter& layer) : Layer(layer)
{
	K = layer.supix_param().k();
	M = layer.supix_param().m();
	optint = layer.supix_param().optint();
	saveseg = layer.supix_param().saveseg();
	segname = layer.supix_param().segname();
}

SupixSegLayer::~SupixSegLayer()
{
}

bool SupixSegLayer::Run(vector<Block>& images, vector<Block>& disp, LayerParameter& layer, void* param){
	for (int i = 0; i < images.size(); ++i){
		Mat mat = SuperPixelSegment(images[i].image, K, M, optint, saveseg, segname);

		if (task_type == SvafApp::S_SUPIX || task_type == SvafApp::B_SUPIX){
			__bout = true;
		} else {
			__bout = false;
		}

		if (__show || __save || __bout){
			disp.push_back(Block(images[i].name + " supix", mat, __show, __save, __bout));
		}
	}
	LOG(INFO) << "superpixel map has been computed.";
	RLOG("superpixel map has been computed.");
	return true;
}

}
<commit_msg>add note for SupixSegLayer.cpp<commit_after>/*
Stereo Vision Algorithm Framework, Copyright(c) 2016-2018, Peng Chao
طָBy:ɣ
*/

#include "SupixSegLayer.h"
#include "../../SuperPixelSegment/svafinterface.h"

using namespace pc;

namespace svaf{

// 캯
SupixSegLayer::SupixSegLayer(LayerParameter& layer) : Layer(layer)
{
	// طָ
	K = layer.supix_param().k(); // K
	M = layer.supix_param().m(); // ָС
	optint = layer.supix_param().optint();	// Ƿ
	saveseg = layer.supix_param().saveseg(); // ָļ
	segname = layer.supix_param().segname();
}

//
SupixSegLayer::~SupixSegLayer()
{
}

// гطָ㷨
bool SupixSegLayer::Run(vector<Block>& images, vector<Block>& disp, LayerParameter& layer, void* param){
	for (int i = 0; i < images.size(); ++i){
		Mat mat = SuperPixelSegment(images[i].image, K, M, optint, saveseg, segname);

		if (task_type == SvafApp::S_SUPIX || task_type == SvafApp::B_SUPIX){
			__bout = true;
		} else {
			__bout = false;
		}

		if (__show || __save || __bout){
			disp.push_back(Block(images[i].name + " supix", mat, __show, __save, __bout));
		}
	}
	LOG(INFO) << "superpixel map has been computed.";
	RLOG("superpixel map has been computed.");
	return true;
}

}
<|endoftext|>


<commit_before>
#include "gtest/gtest.h"

#include "comp_math.h"
#include "composition.h"
#include "cyc_limits.h"
#include "error.h"

namespace cm = cyclus::compmath;
using cyclus::Composition;
using cyclus::CompMap;

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CompMathTest, SubSame) {
  CompMap v;
  v[922350000] = 1;
  v[922380000] = 2;

  v = cm::Sub(v, v);

  for (CompMap::iterator it = v.begin(); it != v.end(); ++it) {
    EXPECT_DOUBLE_EQ(0, it->second);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CompMathTest, SubCloseSize) {
  CompMap v;
  double qty = 0.1;
  v[922350000] = qty;

  CompMap v2(v);
  cm::Normalize(&v2, qty - cyclus::eps_rsrc());

  CompMap remainder;

  remainder = cm::Sub(v, v2);
  CompMap::iterator it;
  for (it = remainder.begin(); it != remainder.end(); ++it) {
    double expected = cyclus::eps_rsrc();
    EXPECT_FLOAT_EQ(expected, it->second);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CompMathTest, SubCloseComp) {
  double qty = 0.1;

  CompMap v;
  v[922350000] = 1;
  v[922410000] = 1;
  v[822080000] = 1;
  cm::Normalize(&v, qty);

  CompMap closev(v);
  closev[92241] -= cyclus::eps_rsrc();

  CompMap remainder;
  remainder = cm::Sub(v, closev);

  CompMap::iterator it;
  for (it = remainder.begin(); it != remainder.end(); ++it) {
    double expected = 0;
    if (it->first == 92241) {
      expected = v[92241] - closev[92241];
    }
    EXPECT_FLOAT_EQ(expected, it->second);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CompMathTest, ApplyThresholdZero) {
  // if the threshold is 0, applying the threshold should do nothing
  CompMap v;
  v[1] = 1.0;
  v[2] = 2.0;
  v[3] = 3.0;

  EXPECT_NO_THROW(cm::ApplyThreshold(&v, 0));

  CompMap::iterator it;
  for (it = v.begin(); it != v.end(); ++it) {
    EXPECT_FLOAT_EQ(v[it->first], it->second);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CompMathTest, ApplyThresholdInf) {
  CompMap v;
  v[1] = 1.0;
  v[2] = 2.0;
  v[3] = 3.0;

  // if the threshold is infinit, applying it should zero any vector
  double infty = std::numeric_limits<double>::infinity();
  EXPECT_NO_THROW(cm::ApplyThreshold(&v, infty));

  CompMap::iterator it;
  for (it = v.begin(); it != v.end(); ++it) {
    EXPECT_FLOAT_EQ(0, it->second);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CompMathTest, ApplyThresholdNegative) {
  CompMap v;
  v[1] = 1.0;
  v[2] = 2.0;
  v[3] = 3.0;

  EXPECT_THROW(cm::ApplyThreshold(&v, -1), cyclus::ValueError);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CompMathTest, ApplyThresholdMedium) {
  CompMap v;
  v[1] = 1.0;
  v[2] = 2.0;
  v[3] = 3.0;

  // if the threshold is in a reasonable range, it should zero small vals
  CompMap::iterator it;
  for (it = v.begin(); it != v.end(); ++it) {
    EXPECT_NO_THROW(cm::ApplyThreshold(&v, it->second));
    EXPECT_FLOAT_EQ(0, v[it->first]);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CompMathTest, AlmostEq) {
  CompMap v1;
  v1[1] = 0.1;
  v1[2] = 0.1;
  v1[3] = 0.1;

  CompMap v2(v1);
  CompMap::iterator it;
  for (it = v2.begin(); it != v2.end(); ++it) {
    v2[it->first] = 0.11;
  }

  EXPECT_TRUE(cm::AlmostEq(v1, v2, 0.1));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CompMathTest, AlmostEqualZeroEntry) {
  CompMap v1;
  v1[1] = 0.1;
  v1[2] = 0.1;
  v1[3] = 0.1;

  CompMap v2(v1);
  CompMap::iterator it;
  for (it = v1.begin(); it != v1.end(); ++it) {
    v1[it->first] = 0;
  }

  EXPECT_TRUE(cm::AlmostEq(v1, v2, 1.1));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CompMathTest, AlmostEqualNegThresh) {
  CompMap v1, v2;
  EXPECT_THROW(cm::AlmostEq(v1, v2, -1.0), cyclus::ValueError);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CompMathTests, SimpleAdd) {
  CompMap v1;
  v1[1] = 1.1;
  v1[2] = 2.2;
  v1[3] = 3.3;
  cm::Normalize(&v1, 1.0);
  CompMap v2(v1);
  cm::Normalize(&v2, 2.0);

  CompMap result = cm::Add(v1, v2);
  cm::Normalize(&result);
  EXPECT_TRUE(cm::AlmostEq(v1, result, 1e-15));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CompMathTests, Add) {
  CompMap v1;
  v1[1] = 1.0;
  v1[2] = 2.0;
  v1[3] = 3.0;

  CompMap v2;
  v2[1] = 1.1;
  v2[2] = 2.2;
  v2[3] = 3.3;

  CompMap expect;
  expect[1] = 2.1;
  expect[2] = 4.2;
  expect[3] = 6.3;

  CompMap result;

  result = cm::Add(v1, v2);
  EXPECT_TRUE(cm::AlmostEq(result, expect, 0));
  for (CompMap::iterator it = result.begin();
       it != result.end(); it++) {
    EXPECT_DOUBLE_EQ(it->second, expect[it->first]);
  }
}

<commit_msg>test for incorrect map iteration bug in ApplyThreshold<commit_after>
#include "gtest/gtest.h"

#include "comp_math.h"
#include "composition.h"
#include "cyc_limits.h"
#include "error.h"

namespace cm = cyclus::compmath;
using cyclus::Composition;
using cyclus::CompMap;

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CompMathTests, SubSame) {
  CompMap v;
  v[922350000] = 1;
  v[922380000] = 2;

  v = cm::Sub(v, v);

  for (CompMap::iterator it = v.begin(); it != v.end(); ++it) {
    EXPECT_DOUBLE_EQ(0, it->second);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CompMathTests, SubCloseSize) {
  CompMap v;
  double qty = 0.1;
  v[922350000] = qty;

  CompMap v2(v);
  cm::Normalize(&v2, qty - cyclus::eps_rsrc());

  CompMap remainder;

  remainder = cm::Sub(v, v2);
  CompMap::iterator it;
  for (it = remainder.begin(); it != remainder.end(); ++it) {
    double expected = cyclus::eps_rsrc();
    EXPECT_FLOAT_EQ(expected, it->second);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CompMathTests, SubCloseComp) {
  double qty = 0.1;

  CompMap v;
  v[922350000] = 1;
  v[922410000] = 1;
  v[822080000] = 1;
  cm::Normalize(&v, qty);

  CompMap closev(v);
  closev[92241] -= cyclus::eps_rsrc();

  CompMap remainder;
  remainder = cm::Sub(v, closev);

  CompMap::iterator it;
  for (it = remainder.begin(); it != remainder.end(); ++it) {
    double expected = 0;
    if (it->first == 92241) {
      expected = v[92241] - closev[92241];
    }
    EXPECT_FLOAT_EQ(expected, it->second);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CompMathTests, ApplyThresholdZero) {
  // if the threshold is 0, applying the threshold should do nothing
  CompMap v;
  v[1] = 1.0;
  v[2] = 2.0;
  v[3] = 3.0;

  EXPECT_NO_THROW(cm::ApplyThreshold(&v, 0));

  CompMap::iterator it;
  for (it = v.begin(); it != v.end(); ++it) {
    EXPECT_FLOAT_EQ(v[it->first], it->second);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CompMathTests, ApplyThresholdInf) {
  CompMap v;
  v[1] = 1.0;
  v[2] = 2.0;
  v[3] = 3.0;

  // if the threshold is infinit, applying it should zero any vector
  double infty = std::numeric_limits<double>::infinity();
  EXPECT_NO_THROW(cm::ApplyThreshold(&v, infty));

  CompMap::iterator it;
  for (it = v.begin(); it != v.end(); ++it) {
    EXPECT_FLOAT_EQ(0, it->second);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CompMathTests, ApplyThresholdNegative) {
  CompMap v;
  v[1] = 1.0;
  v[2] = 2.0;
  v[3] = 3.0;

  EXPECT_THROW(cm::ApplyThreshold(&v, -1), cyclus::ValueError);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CompMathTests, ApplyThresholdMedium) {
  CompMap v;
  v[1] = 1.0;
  v[2] = 2.0;
  v[3] = 3.0;

  // if the threshold is in a reasonable range, it should zero small vals
  CompMap::iterator it;
  for (it = v.begin(); it != v.end(); ++it) {
    EXPECT_NO_THROW(cm::ApplyThreshold(&v, it->second));
    EXPECT_FLOAT_EQ(0, v[it->first]);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CompMathTests, ApplyThresholdSeqIter) {
  // tests for a bug caused by improper iteration over CompMap
  CompMap v;
  v[0] = 2.0;
  v[1] = 0.1;
  v[2] = 0.1;
  v[3] = 0.1;
  v[4] = 3.0;

  EXPECT_NO_THROW(cm::ApplyThreshold(&v, 1.0));
  EXPECT_FLOAT_EQ(2, v[0]);
  EXPECT_FLOAT_EQ(0, v[1]);
  EXPECT_FLOAT_EQ(0, v[2]);
  EXPECT_FLOAT_EQ(0, v[3]);
  EXPECT_FLOAT_EQ(3, v[4]);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CompMathTests, AlmostEq) {
  CompMap v1;
  v1[1] = 0.1;
  v1[2] = 0.1;
  v1[3] = 0.1;

  CompMap v2(v1);
  CompMap::iterator it;
  for (it = v2.begin(); it != v2.end(); ++it) {
    v2[it->first] = 0.11;
  }

  EXPECT_TRUE(cm::AlmostEq(v1, v2, 0.1));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CompMathTests, AlmostEqualZeroEntry) {
  CompMap v1;
  v1[1] = 0.1;
  v1[2] = 0.1;
  v1[3] = 0.1;

  CompMap v2(v1);
  CompMap::iterator it;
  for (it = v1.begin(); it != v1.end(); ++it) {
    v1[it->first] = 0;
  }

  EXPECT_TRUE(cm::AlmostEq(v1, v2, 1.1));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CompMathTests, AlmostEqualNegThresh) {
  CompMap v1, v2;
  EXPECT_THROW(cm::AlmostEq(v1, v2, -1.0), cyclus::ValueError);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CompMathTests, SimpleAdd) {
  CompMap v1;
  v1[1] = 1.1;
  v1[2] = 2.2;
  v1[3] = 3.3;
  cm::Normalize(&v1, 1.0);
  CompMap v2(v1);
  cm::Normalize(&v2, 2.0);

  CompMap result = cm::Add(v1, v2);
  cm::Normalize(&result);
  EXPECT_TRUE(cm::AlmostEq(v1, result, 1e-15));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CompMathTests, Add) {
  CompMap v1;
  v1[1] = 1.0;
  v1[2] = 2.0;
  v1[3] = 3.0;

  CompMap v2;
  v2[1] = 1.1;
  v2[2] = 2.2;
  v2[3] = 3.3;

  CompMap expect;
  expect[1] = 2.1;
  expect[2] = 4.2;
  expect[3] = 6.3;

  CompMap result;

  result = cm::Add(v1, v2);
  EXPECT_TRUE(cm::AlmostEq(result, expect, 0));
  for (CompMap::iterator it = result.begin();
       it != result.end(); it++) {
    EXPECT_DOUBLE_EQ(it->second, expect[it->first]);
  }
}

<|endoftext|>