<commit_before>

#include "knotesapp.h"
#include "knoteconfigdlg.h"

#include <kglobal.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kstddirs.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <qfile.h>
#include <qtextstream.h>
#include <qdir.h>

KNotesApp::	KNotesApp()
{
	//make sure I copy over the knotesrc to a local/writeable file- some
	QString globalConfigFile = KGlobal::dirs()->findResource( "config", "knotesrc" );
    QString str_confdir = KGlobal::dirs()->saveLocation( "config" );
    kdDebug() << "can save config at: " << str_confdir << endl;
	QDir confdir( str_confdir );

	if( !confdir.exists( "knotesrc" ) )
	{
		//copy over the default config file...avoid some problems with session management
		QFile gconfigfile( globalConfigFile );
	    gconfigfile.open( IO_ReadOnly );

    	QFile nconfigfile( str_confdir + "knotesrc" );
    	nconfigfile.open( IO_WriteOnly );

    	QTextStream input( &gconfigfile );
    	QTextStream output( &nconfigfile );

    	for( QString curr = input.readLine(); curr != QString::null; curr = input.readLine() )
			output << curr << endl;

    	gconfigfile.close();
    	nconfigfile.close();
    	kdDebug() << "saved the default config file in KDEHOME" << endl;
	} else kdDebug() << "default config already exists" << endl;

	//create the dock widget....
	setPixmap( KGlobal::iconLoader()->loadIcon( "knotes", KIcon::Desktop ) );
	KPopupMenu* menu = contextMenu();
	menu->insertTitle( SmallIcon("knotes"), i18n("Knotes Options") );
	menu->insertItem( i18n("New Note"), this, SLOT(slotNewNote(int)) );
	menu->insertItem( i18n("Preferences..."), this, SLOT(slotPreferences(int)) );

 	//initialize saved notes, if none create a note...
	QString str_notedir = KGlobal::dirs()->saveLocation( "appdata", "notes/" );
 	QDir notedir( str_notedir );
 	QStringList notes = notedir.entryList( "*" );

 	int count = 0;
 	for( QStringList::Iterator i = notes.begin(); i != notes.end(); ++i )
 	{
 		kdDebug() << "checking file: " << *i << endl;
		if( *i != "." && *i != ".." ) //ignore these
 		{
 			QString configfile = notedir.absFilePath( *i );
 			kdDebug() << "restoring note, file: " << configfile << endl;
   			KConfig* tmp = new KConfig( configfile );
   			KNote* tmpnote = new KNote( tmp );
   			m_NoteList[*i] = tmpnote;
   			tmpnote->show();
			++count;
		}
	}

	if( count == 0 )
		slotNewNote();
}

KNotesApp::~KNotesApp()
{
}

void KNotesApp::slotNewNote( int /*id*/ )
{
	QString globalConfigFile = KGlobal::dirs()->findResource( "config", "knotesrc" );
	QString datadir = KGlobal::dirs()->saveLocation( "appdata", "notes/" );
	kdDebug() << "KNotesApp::slotNewNote, using template: " << globalConfigFile << endl;

    //find a new appropriate id for the new note...
    bool exists;
    QString thename;
    QDir appdir( datadir );
    for( int i = 1; i < 51; i++ )   //set the unjust limit to 50 notes...
    {
        thename = QString( "KNote %1" ).arg(i);
        exists = false;

        if( !appdir.exists( thename ) )
		{
			exists = false;
			break;
		}
    }

    if( exists )
    {
        QString msg = i18n(""
            "You have exeeded the arbitrary and unjustly set limit of 50 knotes.\n"
            "Please complain to the author.");
        KMessageBox::sorry( NULL, msg );
        return;
    }

    //copy the default config file to $KDEHOME/share/apps/knotes2/notes/filename
    QFile gconfigfile( globalConfigFile );
    gconfigfile.open( IO_ReadOnly );

    QFile nconfigfile( datadir + thename );
    nconfigfile.open( IO_WriteOnly );

    QTextStream input( &gconfigfile );
    QTextStream output( &nconfigfile );

    for( QString curr = input.readLine(); curr != QString::null; curr = input.readLine() )
		output << curr << endl;

    gconfigfile.close();
    nconfigfile.close();

    //then create a new KConfig object for the new note, so it can save it's own data
    KConfig* newconfig = new KConfig( datadir + thename );
    newconfig->setGroup( "Data" );
    newconfig->writeEntry("name", thename );
    newconfig->sync();

	KNote* newnote = new KNote( newconfig );

	connect( newnote, SIGNAL( sigRenamed(QString&, QString&) ),
	         this,    SLOT( slotNoteRenamed(QString&, QString&) ) );
	connect( newnote, SIGNAL( sigNewNote(int) ),
	         this,    SLOT( slotNewNote(int) ) );
	connect( newnote, SIGNAL( sigClosed(QString&) ),
	         this,    SLOT( slotNoteClosed(QString&) ) );

	m_NoteList[thename] = newnote;
	newnote->show();
}

void KNotesApp::slotNoteRenamed( QString& oldname, QString& newname )
{
	KNote* tmp = m_NoteList[oldname];
	m_NoteList[newname] = tmp;
	m_NoteList.remove( oldname );
}

void KNotesApp::slotNoteClosed( QString& name )
{
	kdDebug() << "removed note: " << name << endl;
	m_NoteList.remove( name );
}

void KNotesApp::slotPreferences( int /*id*/ )
{
	QString globalConfigFile = KGlobal::dirs()->findResource( "config", "knotesrc" );
	kdDebug() << "globalConfigFile = " << globalConfigFile << endl;
	KConfig GlobalConfig( globalConfigFile );

	//launch preferences dialog...
	KNoteConfigDlg tmpconfig( &GlobalConfig, i18n("KNotes Defaults") );
	tmpconfig.exec();
	kdDebug() << "after global settings configured" << endl;
}
#include "knotesapp.moc"
<commit_msg>Took out title of knote dock menu since KDockWidget is working correctly now<commit_after>

#include "knotesapp.h"
#include "knoteconfigdlg.h"

#include <kglobal.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kstddirs.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <qfile.h>
#include <qtextstream.h>
#include <qdir.h>

KNotesApp::	KNotesApp()
{
	//make sure I copy over the knotesrc to a local/writeable file- some
	QString globalConfigFile = KGlobal::dirs()->findResource( "config", "knotesrc" );
    QString str_confdir = KGlobal::dirs()->saveLocation( "config" );
    kdDebug() << "can save config at: " << str_confdir << endl;
	QDir confdir( str_confdir );

	if( !confdir.exists( "knotesrc" ) )
	{
		//copy over the default config file...avoid some problems with session management
		QFile gconfigfile( globalConfigFile );
	    gconfigfile.open( IO_ReadOnly );

    	QFile nconfigfile( str_confdir + "knotesrc" );
    	nconfigfile.open( IO_WriteOnly );

    	QTextStream input( &gconfigfile );
    	QTextStream output( &nconfigfile );

    	for( QString curr = input.readLine(); curr != QString::null; curr = input.readLine() )
			output << curr << endl;

    	gconfigfile.close();
    	nconfigfile.close();
    	kdDebug() << "saved the default config file in KDEHOME" << endl;
	} else kdDebug() << "default config already exists" << endl;

	//create the dock widget....
	setPixmap( KGlobal::iconLoader()->loadIcon( "knotes", KIcon::Desktop ) );
	KPopupMenu* menu = contextMenu();
	menu->insertItem( i18n("New Note"), this, SLOT(slotNewNote(int)) );
	menu->insertItem( i18n("Preferences..."), this, SLOT(slotPreferences(int)) );

 	//initialize saved notes, if none create a note...
	QString str_notedir = KGlobal::dirs()->saveLocation( "appdata", "notes/" );
 	QDir notedir( str_notedir );
 	QStringList notes = notedir.entryList( "*" );

 	int count = 0;
 	for( QStringList::Iterator i = notes.begin(); i != notes.end(); ++i )
 	{
 		kdDebug() << "checking file: " << *i << endl;
		if( *i != "." && *i != ".." ) //ignore these
 		{
 			QString configfile = notedir.absFilePath( *i );
 			kdDebug() << "restoring note, file: " << configfile << endl;
   			KConfig* tmp = new KConfig( configfile );
   			KNote* tmpnote = new KNote( tmp );
   			m_NoteList[*i] = tmpnote;
   			tmpnote->show();
			++count;
		}
	}

	if( count == 0 )
		slotNewNote();
}

KNotesApp::~KNotesApp()
{
}

void KNotesApp::slotNewNote( int /*id*/ )
{
	QString globalConfigFile = KGlobal::dirs()->findResource( "config", "knotesrc" );
	QString datadir = KGlobal::dirs()->saveLocation( "appdata", "notes/" );
	kdDebug() << "KNotesApp::slotNewNote, using template: " << globalConfigFile << endl;

    //find a new appropriate id for the new note...
    bool exists;
    QString thename;
    QDir appdir( datadir );
    for( int i = 1; i < 51; i++ )   //set the unjust limit to 50 notes...
    {
        thename = QString( "KNote %1" ).arg(i);
        exists = false;

        if( !appdir.exists( thename ) )
		{
			exists = false;
			break;
		}
    }

    if( exists )
    {
        QString msg = i18n(""
            "You have exeeded the arbitrary and unjustly set limit of 50 knotes.\n"
            "Please complain to the author.");
        KMessageBox::sorry( NULL, msg );
        return;
    }

    //copy the default config file to $KDEHOME/share/apps/knotes2/notes/filename
    QFile gconfigfile( globalConfigFile );
    gconfigfile.open( IO_ReadOnly );

    QFile nconfigfile( datadir + thename );
    nconfigfile.open( IO_WriteOnly );

    QTextStream input( &gconfigfile );
    QTextStream output( &nconfigfile );

    for( QString curr = input.readLine(); curr != QString::null; curr = input.readLine() )
		output << curr << endl;

    gconfigfile.close();
    nconfigfile.close();

    //then create a new KConfig object for the new note, so it can save it's own data
    KConfig* newconfig = new KConfig( datadir + thename );
    newconfig->setGroup( "Data" );
    newconfig->writeEntry("name", thename );
    newconfig->sync();

	KNote* newnote = new KNote( newconfig );

	connect( newnote, SIGNAL( sigRenamed(QString&, QString&) ),
	         this,    SLOT( slotNoteRenamed(QString&, QString&) ) );
	connect( newnote, SIGNAL( sigNewNote(int) ),
	         this,    SLOT( slotNewNote(int) ) );
	connect( newnote, SIGNAL( sigClosed(QString&) ),
	         this,    SLOT( slotNoteClosed(QString&) ) );

	m_NoteList[thename] = newnote;
	newnote->show();
}

void KNotesApp::slotNoteRenamed( QString& oldname, QString& newname )
{
	KNote* tmp = m_NoteList[oldname];
	m_NoteList[newname] = tmp;
	m_NoteList.remove( oldname );
}

void KNotesApp::slotNoteClosed( QString& name )
{
	kdDebug() << "removed note: " << name << endl;
	m_NoteList.remove( name );
}

void KNotesApp::slotPreferences( int /*id*/ )
{
	QString globalConfigFile = KGlobal::dirs()->findResource( "config", "knotesrc" );
	kdDebug() << "globalConfigFile = " << globalConfigFile << endl;
	KConfig GlobalConfig( globalConfigFile );

	//launch preferences dialog...
	KNoteConfigDlg tmpconfig( &GlobalConfig, i18n("KNotes Defaults") );
	tmpconfig.exec();
	kdDebug() << "after global settings configured" << endl;
}
#include "knotesapp.moc"
<|endoftext|>


<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc. 51 Franklin Street, Fifth Floor,
// Boston, MA  02110-1301  USA
//
//-----------------------------------------------------------------------el-

#include "grins_config.h"

// GRINS
#include "grins/mesh_builder.h"
#include "grins/simulation.h"
#include "grins/simulation_builder.h"
#include "grins/multiphysics_sys.h"

//libMesh
#include "libmesh/exact_solution.h"

void test_error_norm( libMesh::ExactSolution& exact_sol,
                      const std::string& system_name,
                      const std::string& var,
                      const std::string& norm,
                      const double tol,
                      int& return_flag );

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

  if( !command_line.have_variable("input") )
    {
      std::cerr << "ERROR: Must specify input file on command line with input=<file>." << std::endl;
      exit(1);
    }

  if( !command_line.have_variable("soln-data") )
    {
      std::cerr << "ERROR: Must specify solution data on command line with soln-data=<file>." << std::endl;
      exit(1);
    }

  if( !command_line.have_variable("vars") )
    {
      std::cerr << "ERROR: Must specify variables on command line with vars='var1 var2'" << std::endl;
      exit(1);
    }

  if( !command_line.have_variable("norms") )
    {
      std::cerr << "ERROR: Must specify variables on command line with norms='L2 H1'" << std::endl;
      exit(1);
    }

  // libMesh input file should be first argument
  std::string libMesh_input_filename = command_line("input", "DIE!");

  {
    std::ifstream i(libMesh_input_filename.c_str());
    if (!i)
      {
        std::cerr << "Error: Could not read from libMesh input file "
                << libMesh_input_filename << std::endl;
        exit(1);
      }
  }

  // Create our GetPot object.
  GetPot libMesh_inputfile( libMesh_input_filename );

  // Initialize libMesh library.
  libMesh::LibMeshInit libmesh_init(argc, argv);

  GRINS::SimulationBuilder sim_builder;

  GRINS::Simulation grins( libMesh_inputfile,
			   sim_builder,
                           libmesh_init.comm() );

  // Do solve here
  grins.run();

  // Get equation systems to create ExactSolution object
  std::tr1::shared_ptr<libMesh::EquationSystems> es = grins.get_equation_system();

   // Create Exact solution object and attach exact solution quantities
  libMesh::ExactSolution exact_sol(*es);

  libMesh::EquationSystems es_ref( es->get_mesh() );

  // Filename of file where comparison solution is stashed
  std::string solution_file = command_line("soln-data", "DIE!");
  es_ref.read( solution_file );

  exact_sol.attach_reference_solution( &es_ref );

  // Now grab the variables for which we want to compare
  unsigned int n_vars = command_line.vector_variable_size("vars");
  std::vector<std::string> vars(n_vars);
  for( unsigned int v = 0; v < n_vars; v++ )
    {
      vars[v] = command_line("vars", "DIE!", v);
    }

  // Now grab the norms to compute for each variable error
  unsigned int n_norms = command_line.vector_variable_size("norms");
  std::vector<std::string> norms(n_norms);
  for( unsigned int n = 0; n < n_norms; n++ )
    {
      norms[n] = command_line("norms", "DIE!", n);
      if( norms[n] != std::string("L2") &&
          norms[n] != std::string("H1") )
        {
          std::cerr << "ERROR: Invalid norm input " << norms[n] << std::endl
                    << "       Valid values are: L2" << std::endl
                    << "                         H1" << std::endl;
        }
    }

  const std::string& system_name = grins.get_multiphysics_system_name();

  // Now compute error for each variable
  for( unsigned int v = 0; v < n_vars; v++ )
    {
      exact_sol.compute_error(system_name, vars[v]);
    }

  int return_flag = 0;

  double tol = 1.0e-10;

  // Now test error for each variable, for each norm
  for( unsigned int v = 0; v < n_vars; v++ )
    {
      for( unsigned int n = 0; n < n_norms; n++ )
        {
          test_error_norm( exact_sol, system_name, vars[v], norms[n], tol, return_flag );
        }
    }

  return return_flag;
}

void test_error_norm( libMesh::ExactSolution& exact_sol,
                      const std::string& system_name,
                      const std::string& var,
                      const std::string& norm,
                      const double tol,
                      int& return_flag )
{
  // We don't set return_flag unless we are setting it 1
  // since this function gets called multiple times and we don't
  // want to overwrite a previous "fail" (return_flag = 1) with
  // a "pass" (return_flag = 0)

  double error = 0.0;

  std::cout << "==========================================================" << std::endl
            << "Checking variable " << var << " using error norm " << norm << " with tol " << tol << "...";

  if( norm == std::string("L2") )
    {
      error = exact_sol.l2_error(system_name, var);
    }
  else if( norm == std::string("H1") )
    {
      error = exact_sol.h1_error(system_name, var);
    }
  else
    {
      std::cerr << "ERROR: Invalid norm " << norm << std::endl;
      exit(1);
    }

  if( error > tol )
    {
      return_flag = 1;

      std::cerr << "Tolerance exceeded for generic regression test!" << std::endl
                << "tolerance     = " << tol << std::endl
                << "norm of error = " << error << std::endl
                << "norm type     = " << norm << std::endl
                << "var           = " << var << std::endl;
    }
  else
    {
      std::cout << "PASSED!" << std::endl
                << "==========================================================" << std::endl;
    }

  return;
}
<commit_msg>Correct error message.<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc. 51 Franklin Street, Fifth Floor,
// Boston, MA  02110-1301  USA
//
//-----------------------------------------------------------------------el-

#include "grins_config.h"

// GRINS
#include "grins/mesh_builder.h"
#include "grins/simulation.h"
#include "grins/simulation_builder.h"
#include "grins/multiphysics_sys.h"

//libMesh
#include "libmesh/exact_solution.h"

void test_error_norm( libMesh::ExactSolution& exact_sol,
                      const std::string& system_name,
                      const std::string& var,
                      const std::string& norm,
                      const double tol,
                      int& return_flag );

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

  if( !command_line.have_variable("input") )
    {
      std::cerr << "ERROR: Must specify input file on command line with input=<file>." << std::endl;
      exit(1);
    }

  if( !command_line.have_variable("soln-data") )
    {
      std::cerr << "ERROR: Must specify solution data on command line with soln-data=<file>." << std::endl;
      exit(1);
    }

  if( !command_line.have_variable("vars") )
    {
      std::cerr << "ERROR: Must specify variables on command line with vars='var1 var2'" << std::endl;
      exit(1);
    }

  if( !command_line.have_variable("norms") )
    {
      std::cerr << "ERROR: Must specify error norms on command line with norms='L2 H1'" << std::endl;
      exit(1);
    }

  // libMesh input file should be first argument
  std::string libMesh_input_filename = command_line("input", "DIE!");

  {
    std::ifstream i(libMesh_input_filename.c_str());
    if (!i)
      {
        std::cerr << "Error: Could not read from libMesh input file "
                << libMesh_input_filename << std::endl;
        exit(1);
      }
  }

  // Create our GetPot object.
  GetPot libMesh_inputfile( libMesh_input_filename );

  // Initialize libMesh library.
  libMesh::LibMeshInit libmesh_init(argc, argv);

  GRINS::SimulationBuilder sim_builder;

  GRINS::Simulation grins( libMesh_inputfile,
			   sim_builder,
                           libmesh_init.comm() );

  // Do solve here
  grins.run();

  // Get equation systems to create ExactSolution object
  std::tr1::shared_ptr<libMesh::EquationSystems> es = grins.get_equation_system();

   // Create Exact solution object and attach exact solution quantities
  libMesh::ExactSolution exact_sol(*es);

  libMesh::EquationSystems es_ref( es->get_mesh() );

  // Filename of file where comparison solution is stashed
  std::string solution_file = command_line("soln-data", "DIE!");
  es_ref.read( solution_file );

  exact_sol.attach_reference_solution( &es_ref );

  // Now grab the variables for which we want to compare
  unsigned int n_vars = command_line.vector_variable_size("vars");
  std::vector<std::string> vars(n_vars);
  for( unsigned int v = 0; v < n_vars; v++ )
    {
      vars[v] = command_line("vars", "DIE!", v);
    }

  // Now grab the norms to compute for each variable error
  unsigned int n_norms = command_line.vector_variable_size("norms");
  std::vector<std::string> norms(n_norms);
  for( unsigned int n = 0; n < n_norms; n++ )
    {
      norms[n] = command_line("norms", "DIE!", n);
      if( norms[n] != std::string("L2") &&
          norms[n] != std::string("H1") )
        {
          std::cerr << "ERROR: Invalid norm input " << norms[n] << std::endl
                    << "       Valid values are: L2" << std::endl
                    << "                         H1" << std::endl;
        }
    }

  const std::string& system_name = grins.get_multiphysics_system_name();

  // Now compute error for each variable
  for( unsigned int v = 0; v < n_vars; v++ )
    {
      exact_sol.compute_error(system_name, vars[v]);
    }

  int return_flag = 0;

  double tol = 1.0e-10;

  // Now test error for each variable, for each norm
  for( unsigned int v = 0; v < n_vars; v++ )
    {
      for( unsigned int n = 0; n < n_norms; n++ )
        {
          test_error_norm( exact_sol, system_name, vars[v], norms[n], tol, return_flag );
        }
    }

  return return_flag;
}

void test_error_norm( libMesh::ExactSolution& exact_sol,
                      const std::string& system_name,
                      const std::string& var,
                      const std::string& norm,
                      const double tol,
                      int& return_flag )
{
  // We don't set return_flag unless we are setting it 1
  // since this function gets called multiple times and we don't
  // want to overwrite a previous "fail" (return_flag = 1) with
  // a "pass" (return_flag = 0)

  double error = 0.0;

  std::cout << "==========================================================" << std::endl
            << "Checking variable " << var << " using error norm " << norm << " with tol " << tol << "...";

  if( norm == std::string("L2") )
    {
      error = exact_sol.l2_error(system_name, var);
    }
  else if( norm == std::string("H1") )
    {
      error = exact_sol.h1_error(system_name, var);
    }
  else
    {
      std::cerr << "ERROR: Invalid norm " << norm << std::endl;
      exit(1);
    }

  if( error > tol )
    {
      return_flag = 1;

      std::cerr << "Tolerance exceeded for generic regression test!" << std::endl
                << "tolerance     = " << tol << std::endl
                << "norm of error = " << error << std::endl
                << "norm type     = " << norm << std::endl
                << "var           = " << var << std::endl;
    }
  else
    {
      std::cout << "PASSED!" << std::endl
                << "==========================================================" << std::endl;
    }

  return;
}
<|endoftext|>


<commit_before>/*
    nljuk.cpp

    Kopete Now Listening To plugin

    Copyright (c) 2002,2003 by Will Stephenson <will@stevello.free-online.co.uk>
    Copyright (c) 2003 by Ismail Donmez <ismail.donmez@boun.edu.tr>
    Copyright (c) 2002,2003 by the Kopete developers  <kopete-devel@kde.org>

	Purpose:
	This class abstracts the interface to JuK by
	implementing NLMediaPlayer

    *************************************************************************
    *                                                                       *
    * This program is free software; you can redistribute it and/or modify  *
    * it under the terms of the GNU General Public License as published by  *
    * the Free Software Foundation; either version 2 of the License, or     *
    * (at your option) any later version.                                   *
    *                                                                       *
    *************************************************************************
*/

#include <kdebug.h>
#include <qstring.h>

#include "nlmediaplayer.h"
#include "nljuk.h"

NLJuk::NLJuk( DCOPClient *client ) : NLMediaPlayer()
{
	m_client = client;
	m_type = Audio;
	m_name = "JuK";
}

void NLJuk::update()
{
	m_playing = false;
	QString newTrack;

	// see if JuK is  registered with DCOP
	if (  m_client->isApplicationRegistered( "juk" ) )
	{
		// see if it's playing
		QByteArray data, replyData;
		QCString replyType;
		QString result;

		if ( m_client->call( "juk", "Player", "playingString()", data,
					replyType, replyData ) )
		{
			m_playing = true;
			QDataStream reply( replyData, IO_ReadOnly );

			if ( replyType == "QString" ) {
				reply >> result;
				m_artist = result.section("-",0,0);
				newTrack = result.section("-",1,1);
			}
		}

		if ( newTrack != m_track )
		{
			m_newTrack = true;
			m_track = newTrack;
		}
		else
			m_newTrack = false;
	}
	else
		kdDebug( 14307 ) << "Juk is not running!\n" << endl;
}

<commit_msg>detect whether or not JuK is playing from its current track time indicator<commit_after>/*
    nljuk.cpp

    Kopete Now Listening To plugin

    Copyright (c) 2002,2003 by Will Stephenson <will@stevello.free-online.co.uk>
    Copyright (c) 2003 by Ismail Donmez <ismail.donmez@boun.edu.tr>
    Copyright (c) 2002,2003 by the Kopete developers  <kopete-devel@kde.org>

	Purpose:
	This class abstracts the interface to JuK by
	implementing NLMediaPlayer

    *************************************************************************
    *                                                                       *
    * This program is free software; you can redistribute it and/or modify  *
    * it under the terms of the GNU General Public License as published by  *
    * the Free Software Foundation; either version 2 of the License, or     *
    * (at your option) any later version.                                   *
    *                                                                       *
    *************************************************************************
*/

#include <kdebug.h>
#include <qstring.h>

#include "nlmediaplayer.h"
#include "nljuk.h"

NLJuk::NLJuk( DCOPClient *client ) : NLMediaPlayer()
{
	m_client = client;
	m_type = Audio;
	m_name = "JuK";
}

void NLJuk::update()
{
	m_playing = false;
	QString newTrack;

	// see if JuK is  registered with DCOP
	if (  m_client->isApplicationRegistered( "juk" ) )
	{
		// see if it's playing
		QByteArray data, replyData;
		QCString replyType;
		QString result;

		if ( m_client->call( "juk", "Player", "currentTime()", data,
					replyType, replyData ) )
		{
			QDataStream reply( replyData, IO_ReadOnly );
			int currentTime;
			if ( replyType == "int" ) {
				reply >> currentTime;
				if ( currentTime != -1 )
					m_playing = true;
			}
		}

		if ( m_client->call( "juk", "Player", "playingString()", data,
					replyType, replyData ) )
		{
			QDataStream reply( replyData, IO_ReadOnly );

			if ( replyType == "QString" ) {
				reply >> result;
				m_artist = result.section("-",0,0);
				newTrack = result.section("-",1,1);
			}
		}

		if ( newTrack != m_track )
		{
			m_newTrack = true;
			m_track = newTrack;
		}
		else
			m_newTrack = false;
	}
	else
		kdDebug( 14307 ) << "Juk is not running!\n" << endl;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <algorithm>
#include <vector>
#include <memory>
#include "geometry.h"
#include "immintrin.h"
#include "vec.h"
#include "color.h"
#include "render_target.h"
#include "camera.h"
#include "sphere.h"
#include "plane.h"
#include "diff_geom.h"
#include "material.h"
#include "light.h"
#include "occlusion_tester.h"
#include "scene.h"

int main(int, char**){
	const uint32_t width = 800;
	const uint32_t height = 600;
	const auto scene = Scene{
		{
			std::make_shared<Sphere>(Vec3f{0}, 0.5f, 0),
			std::make_shared<Plane>(Vec3f{0, -0.5, 0}, Vec3f{0, 1, 0}, 1)
		},
		{
			std::make_shared<LambertianMaterial>(Colorf{1, 0, 0}),
			std::make_shared<LambertianMaterial>(Colorf{0, 0, 1})
		},
		PointLight{Vec3f{1, 1, -2}, Colorf{50}}
	};

	const auto camera = PerspectiveCamera{Vec3f{0, 0, -3}, Vec3f{0, 0, 0}, Vec3f{0, 1, 0},
		60.f, static_cast<float>(width) / height};
	auto target = RenderTarget{width, height};
	const auto img_dim = Vec2f_8{static_cast<float>(width), static_cast<float>(height)};

	// TODO: Z-order 4x4 blocks?
	const int n_pixels = width * height;
	for (int i = 0; i < n_pixels; i += 8){
		std::array<float, 8> pixel_x, pixel_y;
		for (int j = 0; j < 8; ++j){
			pixel_x[j] = 0.5f + i % width + j;
			pixel_y[j] = 0.5f + i / width;
		}
		const auto samples = Vec2f_8{_mm256_loadu_ps(pixel_x.data()),
			_mm256_loadu_ps(pixel_y.data())};
		Ray8 packet;
		camera.generate_rays(packet, samples / img_dim);

		DiffGeom8 dg;
		auto hits = scene.intersect(packet, dg);
		// If we hit something, shade it
		if (_mm256_movemask_ps(hits) != 0){
			auto color = Colorf_8{0};
			// How does ISPC find the unique values for its foreach_unique loop? Would like to do that
			// if it will be nicer than this
			std::array<int32_t, 8> mat_ids;
			_mm256_storeu_si256((__m256i*)mat_ids.data(), dg.material_id);
			std::unique(std::begin(mat_ids), std::end(mat_ids));
			for (const auto &i : mat_ids){
				if (i == -1){
					continue;
				}
				// Is there a better way to just get the bits of one register casted to another?
				// it seems like the or operations don't let you mix either
				const auto use_mat = _mm256_cmpeq_epi32(dg.material_id, _mm256_set1_epi32(i));
				auto shade_mask = *(__m256*)&use_mat;
				if (_mm256_movemask_ps(shade_mask) != 0){
					const auto w_o = -packet.d;
					Vec3f_8 w_i{0};
					OcclusionTester occlusion;
					const auto li = scene.light.sample(dg.point, w_i, occlusion);
					// We just need to flip the sign bit to change occluded mask to unoccluded mask since
					// only the sign bit is used by movemask and blendv
					auto unoccluded = _mm256_xor_ps(occlusion.occluded(scene), _mm256_set1_ps(-0.f));
					if (_mm256_movemask_ps(unoccluded) != 0){
						const auto c = scene.materials[i]->shade(w_o, w_i) * li
							* _mm256_max_ps(w_i.dot(dg.normal), _mm256_set1_ps(0.f));
						shade_mask = _mm256_and_ps(shade_mask, unoccluded);
						color.r = _mm256_blendv_ps(color.r, c.r, shade_mask);
						color.g = _mm256_blendv_ps(color.g, c.g, shade_mask);
						color.b = _mm256_blendv_ps(color.b, c.b, shade_mask);
					}
				}
			}
			target.write_samples(samples, color, hits);
		}
	}
	target.save_image("out.bmp");
}

<commit_msg>std::unique only removes consecutive duplicates, so sort first<commit_after>#include <iostream>
#include <algorithm>
#include <vector>
#include <memory>
#include "geometry.h"
#include "immintrin.h"
#include "vec.h"
#include "color.h"
#include "render_target.h"
#include "camera.h"
#include "sphere.h"
#include "plane.h"
#include "diff_geom.h"
#include "material.h"
#include "light.h"
#include "occlusion_tester.h"
#include "scene.h"

int main(int, char**){
	const uint32_t width = 800;
	const uint32_t height = 600;
	const auto scene = Scene{
		{
			std::make_shared<Sphere>(Vec3f{0}, 0.5f, 0),
			std::make_shared<Plane>(Vec3f{0, -0.5, 0}, Vec3f{0, 1, 0}, 1)
		},
		{
			std::make_shared<LambertianMaterial>(Colorf{1, 0, 0}),
			std::make_shared<LambertianMaterial>(Colorf{0, 0, 1})
		},
		PointLight{Vec3f{1, 1, -2}, Colorf{50}}
	};

	const auto camera = PerspectiveCamera{Vec3f{0, 0, -3}, Vec3f{0, 0, 0}, Vec3f{0, 1, 0},
		60.f, static_cast<float>(width) / height};
	auto target = RenderTarget{width, height};
	const auto img_dim = Vec2f_8{static_cast<float>(width), static_cast<float>(height)};

	// TODO: Z-order 4x4 blocks?
	const int n_pixels = width * height;
	for (int i = 0; i < n_pixels; i += 8){
		std::array<float, 8> pixel_x, pixel_y;
		for (int j = 0; j < 8; ++j){
			pixel_x[j] = 0.5f + i % width + j;
			pixel_y[j] = 0.5f + i / width;
		}
		const auto samples = Vec2f_8{_mm256_loadu_ps(pixel_x.data()),
			_mm256_loadu_ps(pixel_y.data())};
		Ray8 packet;
		camera.generate_rays(packet, samples / img_dim);

		DiffGeom8 dg;
		auto hits = scene.intersect(packet, dg);
		// If we hit something, shade it
		if (_mm256_movemask_ps(hits) != 0){
			auto color = Colorf_8{0};
			// How does ISPC find the unique values for its foreach_unique loop? Would like to do that
			// if it will be nicer than this
			std::array<int32_t, 8> mat_ids;
			_mm256_storeu_si256((__m256i*)mat_ids.data(), dg.material_id);
			// std::unique just removes consecutive repeated elements, so sort things first so we
			// don't get something like -1, 0, -1 or such
			std::sort(std::begin(mat_ids), std::end(mat_ids));
			std::unique(std::begin(mat_ids), std::end(mat_ids));
			for (const auto &i : mat_ids){
				if (i == -1){
					continue;
				}
				// Is there a better way to just get the bits of one register casted to another?
				// it seems like the or operations don't let you mix either
				const auto use_mat = _mm256_cmpeq_epi32(dg.material_id, _mm256_set1_epi32(i));
				auto shade_mask = *(__m256*)&use_mat;
				if (_mm256_movemask_ps(shade_mask) != 0){
					const auto w_o = -packet.d;
					Vec3f_8 w_i{0};
					OcclusionTester occlusion;
					const auto li = scene.light.sample(dg.point, w_i, occlusion);
					// We just need to flip the sign bit to change occluded mask to unoccluded mask since
					// only the sign bit is used by movemask and blendv
					auto unoccluded = _mm256_xor_ps(occlusion.occluded(scene), _mm256_set1_ps(-0.f));
					if (_mm256_movemask_ps(unoccluded) != 0){
						const auto c = scene.materials[i]->shade(w_o, w_i) * li
							* _mm256_max_ps(w_i.dot(dg.normal), _mm256_set1_ps(0.f));
						shade_mask = _mm256_and_ps(shade_mask, unoccluded);
						color.r = _mm256_blendv_ps(color.r, c.r, shade_mask);
						color.g = _mm256_blendv_ps(color.g, c.g, shade_mask);
						color.b = _mm256_blendv_ps(color.b, c.b, shade_mask);
					}
				}
			}
			target.write_samples(samples, color, hits);
		}
	}
	target.save_image("out.bmp");
}

<|endoftext|>


<commit_before>/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Library General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * usbpro_test.cpp
 * Allows testing of a usb pro
 * Copyright (C) 2010 Simon Newton
 */

#include <assert.h>
#include <getopt.h>
#include <string>
#include "ola/Logging.h"
#include "ola/DmxBuffer.h"
#include "ola/network/SelectServer.h"
#include "ola/network/Socket.h"
#include "plugins/usbpro/UsbProWidget.h"
#include "plugins/usbpro/UsbProWidgetListener.h"

using ola::DmxBuffer;
using ola::network::SelectServer;
using ola::plugin::usbpro::UsbProWidget;
using std::string;

class Listener: public ola::plugin::usbpro::UsbProWidgetListener {
  public:
    Listener(UsbProWidget *widget): m_widget(widget) {}
    void HandleWidgetDmx() {
      const DmxBuffer &buffer = m_widget->FetchDMX();
      OLA_INFO << (int) buffer.Get(0) << "," << (int) buffer.Get(1);

    }

  private:
    UsbProWidget *m_widget;
};

int main(int argc, char *argv[]) {
  ola::InitLogging(ola::OLA_LOG_INFO, ola::OLA_LOG_STDERR);
  string usb_path;

  static struct option long_options[] = {
    {"usb", required_argument, 0, 'u'},
    {0, 0, 0, 0}
  };

  int option_index = 0;

  while (1) {
    int c = getopt_long(argc, argv, "u:", long_options, &option_index);

    if (c == -1)
      break;

    switch (c) {
      case 0:
        break;
      case 'u':
        usb_path = optarg;
        break;
      case '?':
        break;
      default:
        break;
    }
  }

  SelectServer ss;
  UsbProWidget widget;
  assert(widget.Connect(usb_path));
  assert(ss.AddSocket(widget.GetSocket()));
  assert(widget.ChangeToReceiveMode());

  Listener listener(&widget);
  widget.SetListener(&listener);
  ss.Run();
}
<commit_msg> * make the usbpro_test output more readable.<commit_after>/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Library General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * usbpro_test.cpp
 * Allows testing of a usb pro
 * Copyright (C) 2010 Simon Newton
 */

#include <assert.h>
#include <getopt.h>
#include <string>
#include "ola/Logging.h"
#include "ola/DmxBuffer.h"
#include "ola/network/SelectServer.h"
#include "ola/network/Socket.h"
#include "plugins/usbpro/UsbProWidget.h"
#include "plugins/usbpro/UsbProWidgetListener.h"

using ola::DmxBuffer;
using ola::network::SelectServer;
using ola::plugin::usbpro::UsbProWidget;
using std::string;

class Listener: public ola::plugin::usbpro::UsbProWidgetListener {
  public:
    Listener(UsbProWidget *widget): m_widget(widget) {}
    void HandleWidgetDmx() {
      const DmxBuffer &buffer = m_widget->FetchDMX();
      OLA_INFO << buffer.ToString();
    }

  private:
    UsbProWidget *m_widget;
};

int main(int argc, char *argv[]) {
  ola::InitLogging(ola::OLA_LOG_INFO, ola::OLA_LOG_STDERR);
  string usb_path;

  static struct option long_options[] = {
    {"usb", required_argument, 0, 'u'},
    {0, 0, 0, 0}
  };

  int option_index = 0;

  while (1) {
    int c = getopt_long(argc, argv, "u:", long_options, &option_index);

    if (c == -1)
      break;

    switch (c) {
      case 0:
        break;
      case 'u':
        usb_path = optarg;
        break;
      case '?':
        break;
      default:
        break;
    }
  }

  SelectServer ss;
  UsbProWidget widget;
  assert(widget.Connect(usb_path));
  assert(ss.AddSocket(widget.GetSocket()));
  assert(widget.ChangeToReceiveMode());

  Listener listener(&widget);
  widget.SetListener(&listener);
  ss.Run();
}
<|endoftext|>


<commit_before>// Copyright (c) 2021 ASMlover. All rights reserved.
//
//  ______             __                  ___
// /\__  _\           /\ \                /\_ \
// \/_/\ \/    __     \_\ \  _____     ___\//\ \      __
//    \ \ \  /'__`\   /'_` \/\ '__`\  / __`\\ \ \   /'__`\
//     \ \ \/\ \L\.\_/\ \L\ \ \ \L\ \/\ \L\ \\_\ \_/\  __/
//      \ \_\ \__/.\_\ \___,_\ \ ,__/\ \____//\____\ \____\
//       \/_/\/__/\/_/\/__,_ /\ \ \/  \/___/ \/____/\/____/
//                             \ \_\
//                              \/_/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
//  * Redistributions of source code must retain the above copyright
//    notice, this list ofconditions and the following disclaimer.
//
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in
//    the documentation and/or other materialsprovided with the
//    distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "harness.hh"
#include "lexer.hh"

TADPOLE_TEST(TadpoleLexer) {
  using TK = tadpole::TokenKind;

#define TESTEQ(k) TADPOLE_CHECK_EQ(lex.next_token().kind(), k)
#define DUMPLEX() do {\
  for (;;) {\
    auto t = lex.next_token();\
    std::fprintf(stdout, "%-24s | %-32s | %d\n",\
        tadpole::get_kind_name(t.kind()),\
        t.as_cstring(),\
        t.lineno());\
    if (t.kind() == TK::TK_EOF)\
      break;\
  }\
} while (false)

  {
    std::string s =
      "print(\"Welcome to TADPOLE !!!\");\nvar v = 34 * 67 / 33.56 + (89 - 23.7) / 2.34;";
    tadpole::Lexer lex(s);
    DUMPLEX();
  }

  {
    std::string s = "var a = 56.78;";
    tadpole::Lexer lex(s);
    TESTEQ(TK::KW_VAR);
    TESTEQ(TK::TK_IDENTIFIER);
    TESTEQ(TK::TK_EQ);
    TESTEQ(TK::TK_NUMERIC);
    TESTEQ(TK::TK_SEMI);
    TESTEQ(TK::TK_EOF);
  }

#undef DUMPLEX
#undef TESTEQ
}
<commit_msg>:white_check_mark: test(lexer): updated the test for lexer<commit_after>// Copyright (c) 2021 ASMlover. All rights reserved.
//
//  ______             __                  ___
// /\__  _\           /\ \                /\_ \
// \/_/\ \/    __     \_\ \  _____     ___\//\ \      __
//    \ \ \  /'__`\   /'_` \/\ '__`\  / __`\\ \ \   /'__`\
//     \ \ \/\ \L\.\_/\ \L\ \ \ \L\ \/\ \L\ \\_\ \_/\  __/
//      \ \_\ \__/.\_\ \___,_\ \ ,__/\ \____//\____\ \____\
//       \/_/\/__/\/_/\/__,_ /\ \ \/  \/___/ \/____/\/____/
//                             \ \_\
//                              \/_/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
//  * Redistributions of source code must retain the above copyright
//    notice, this list ofconditions and the following disclaimer.
//
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in
//    the documentation and/or other materialsprovided with the
//    distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "harness.hh"
#include "lexer.hh"

TADPOLE_TEST(TadpoleLexer) {
  using TK = tadpole::TokenKind;

#define TESTEQ(k) TADPOLE_CHECK_EQ(lex.next_token().kind(), k)
#define DUMPLEX() do {\
  for (;;) {\
    auto t = lex.next_token();\
    std::fprintf(stdout, "%-24s | %-32s | %d\n",\
        tadpole::get_kind_name(t.kind()),\
        t.as_cstring(),\
        t.lineno());\
    if (t.kind() == TK::TK_EOF)\
      break;\
  }\
} while (false)

  {
    std::string s =
      "print(\"Welcome to TADPOLE !!!\");\nvar v = 34 * 67 / 33.56 + (89 - 23.7) / 2.34;";
    tadpole::Lexer lex(s);
    DUMPLEX();
  }

  {
    std::string s = "var a = 56.78;";
    tadpole::Lexer lex(s);
    TESTEQ(TK::KW_VAR);
    TESTEQ(TK::TK_IDENTIFIER);
    TESTEQ(TK::TK_EQ);
    TESTEQ(TK::TK_NUMERIC);
    TESTEQ(TK::TK_SEMI);
    TESTEQ(TK::TK_EOF);
  }

  {
    std::string s = "print(\"34 + 89.7 =\", 34 + 89.7);";
    tadpole::Lexer lex(s);
    TESTEQ(TK::TK_IDENTIFIER);
    TESTEQ(TK::TK_LPAREN);
    TESTEQ(TK::TK_STRING);
    TESTEQ(TK::TK_COMMA);
    TESTEQ(TK::TK_NUMERIC);
    TESTEQ(TK::TK_PLUS);
    TESTEQ(TK::TK_NUMERIC);
    TESTEQ(TK::TK_RPAREN);
    TESTEQ(TK::TK_SEMI);
    TESTEQ(TK::TK_EOF);
  }

  {
    std::string s = "fn show_message(msg) { print(msg); }";
    tadpole::Lexer lex(s);
    TESTEQ(TK::KW_FN);
    TESTEQ(TK::TK_IDENTIFIER);
    TESTEQ(TK::TK_LPAREN);
    TESTEQ(TK::TK_IDENTIFIER);
    TESTEQ(TK::TK_RPAREN);
    TESTEQ(TK::TK_LBRACE);
    TESTEQ(TK::TK_IDENTIFIER);
    TESTEQ(TK::TK_LPAREN);
    TESTEQ(TK::TK_IDENTIFIER);
    TESTEQ(TK::TK_RPAREN);
    TESTEQ(TK::TK_SEMI);
    TESTEQ(TK::TK_RBRACE);
    TESTEQ(TK::TK_EOF);
  }

  {
    std::string s = "fn do_calc() { print(23 + 45.2 * 8.78 / 0.89 - (23 + 67.9)); }";
    tadpole::Lexer lex(s);
    TESTEQ(TK::KW_FN);
    TESTEQ(TK::TK_IDENTIFIER);
    TESTEQ(TK::TK_LPAREN);
    TESTEQ(TK::TK_RPAREN);
    TESTEQ(TK::TK_LBRACE);
    TESTEQ(TK::TK_IDENTIFIER);
    TESTEQ(TK::TK_LPAREN);
    TESTEQ(TK::TK_NUMERIC);
    TESTEQ(TK::TK_PLUS);
    TESTEQ(TK::TK_NUMERIC);
    TESTEQ(TK::TK_STAR);
    TESTEQ(TK::TK_NUMERIC);
    TESTEQ(TK::TK_SLASH);
    TESTEQ(TK::TK_NUMERIC);
    TESTEQ(TK::TK_MINUS);
    TESTEQ(TK::TK_LPAREN);
    TESTEQ(TK::TK_NUMERIC);
    TESTEQ(TK::TK_PLUS);
    TESTEQ(TK::TK_NUMERIC);
    TESTEQ(TK::TK_RPAREN);
    TESTEQ(TK::TK_RPAREN);
    TESTEQ(TK::TK_SEMI);
    TESTEQ(TK::TK_RBRACE);
    TESTEQ(TK::TK_EOF);
  }

#undef DUMPLEX
#undef TESTEQ
}
<|endoftext|>


<commit_before>/// @file
/// @copyright The code is licensed under the BSD License
///            <http://opensource.org/licenses/BSD-2-Clause>,
///            Copyright (c) 2013-2015 Alexandre Hamez.
/// @author Alexandre Hamez

#include <set>

#include "mc/classic/dead_states.hh"
#include "mc/classic/filter_lt.hh"

namespace pnmc { namespace mc { namespace classic {

/*------------------------------------------------------------------------------------------------*/

SDD
dead_states(const order& o, const pn::net& net, const SDD& state_space)
{
  auto and_operands = std::set<homomorphism>{};
  auto or_operands = std::set<homomorphism>{};

  for (const auto& transition : net.transitions())
  {
    // We are only interested in pre actions.
    for (const auto& arc : transition.pre)
    {
      switch (arc.kind)
      {
        case arc::type::normal:
        case arc::type::read:
          or_operands.insert(function(o, arc.first, filter_lt{arc.second.weight}));
          break;

        case arc::type::inhibitor:
          or_operands.insert(function(o, arc.first, filter_ge{arc.second.weight}));
          break;

        default:
          throw std::runtime_error{"Post arc type for pre arc"};
      }
    }

    and_operands.insert(sum(o, or_operands.cbegin(), or_operands.cend()));
    or_operands.clear();
  }
  const auto tmp = intersection(o, and_operands.cbegin(), and_operands.cend());

  return sdd::rewrite(o, tmp)(o, state_space); // compute dead states
}
/*------------------------------------------------------------------------------------------------*/

}}} // namespace pnmc::mc::classic
<commit_msg>Fix dead states computation<commit_after>/// @file
/// @copyright The code is licensed under the BSD License
///            <http://opensource.org/licenses/BSD-2-Clause>,
///            Copyright (c) 2013-2015 Alexandre Hamez.
/// @author Alexandre Hamez

#include <set>

#include "mc/classic/dead_states.hh"
#include "mc/classic/filter_ge.hh"
#include "mc/classic/filter_lt.hh"

namespace pnmc { namespace mc { namespace classic {

/*------------------------------------------------------------------------------------------------*/

SDD
dead_states(const order& o, const pn::net& net, const SDD& state_space)
{
  auto and_operands = std::set<homomorphism>{};
  auto or_operands = std::set<homomorphism>{};

  for (const auto& transition : net.transitions())
  {
    // We are only interested in pre actions.
    for (const auto& arc : transition.pre)
    {
      switch (arc.second.kind)
      {
        case pn::arc::type::normal:
        case pn::arc::type::read:
          or_operands.insert(function(o, arc.first, filter_lt{arc.second.weight}));
          break;

        case pn::arc::type::reset:
          // Does not impose a precondition on firing.
          continue;

        case pn::arc::type::inhibitor:
          or_operands.insert(function(o, arc.first, filter_ge{arc.second.weight}));
          break;

        case pn::arc::type::stopwatch:
          throw std::runtime_error{"Unsupported stopwatch pre arc for dead states"};

        case pn::arc::type::stopwatch_inhibitor:
          throw std::runtime_error{"Unsupported stopwatch inhibitor pre arc for dead states"};
      }
    }

    and_operands.insert(sum(o, or_operands.cbegin(), or_operands.cend()));
    or_operands.clear();
  }
  const auto tmp = intersection(o, and_operands.cbegin(), and_operands.cend());

  return sdd::rewrite(o, tmp)(o, state_space); // compute dead states
}
/*------------------------------------------------------------------------------------------------*/

}}} // namespace pnmc::mc::classic
<|endoftext|>


<commit_before>// Describing expectations for a valid sparse matrix library

#ifndef SPARSELIB_CONCEPT_HPP
#define SPARSELIB_CONCEPT_HPP

#include <type_traits>
#include <iostream>

// First, some preliminaries (no predefined Concepts are supplied in library yet)
template<typename T> concept bool ForwardIterator =
    requires( T a, T b ) {
    { a != b }
    { a == b }
    { ++a }
    { *a }
};

template<typename T, typename U> concept bool DereferencesTo =
    requires( T a ) {
    { *a } -> U;
};

template<typename T, typename ...Args> concept bool ConstructibleFrom =
    std::is_constructible<T, Args...>::value;

template<typename T> concept bool ForwardIterator =
    std::is_convertible<typename std::iterator_traits<T>::iterator_category,
                        std::forward_iterator_tag>::value;

template<typename T, typename U> concept bool Same =
    std::is_same<T, U>::value;

template<typename T, typename U> concept bool IteratorRange =
    Same<T, U> && ForwardIterator<T>;

template<typename L> concept bool SparseLibrary =
    requires( typename L::sparsemat_t mat,
              typename L::lu_t lu,
              typename L::qr_t qr,
              std::ostream& os
        ) {
    // inner types we expect
    typename L::sparsemat_t;
    typename L::index_t;
    typename L::value_t;
    typename L::triplet_t;
    typename L::lu_t;
    typename L::qr_t;

    // triplets can be constructed
    requires ConstructibleFrom<typename L::triplet_t, typename L::index_t, typename L::index_t, typename L::value_t>;

    // we can construct QR and LU objects from a sparse matrix
    requires ConstructibleFrom<typename L::lu_t, typename L::sparsemat_t>;
    requires ConstructibleFrom<typename L::qr_t, typename L::sparsemat_t>;

    // The LU decomposition can perform a solve against a sparse matrix with a sparse result
    { lu.solve( mat ) } -> typename L::sparsemat_t ;

    // The QR decomposition can return a Q of a type convertible to sparse
    { qr.Q() } -> typename L::sparsemat_t;

    // The Q returned from the QR can multiply a sparse matrix on the left, producing another
    // note this does *not* require that the result be a sparse matrix - just that you can convert it to one
    { qr.Q() * mat } -> typename L::sparsemat_t;

    // you can stream out a sparse matrix
    { os << mat } -> std::ostream &;

};

#endif // SPARSELIB_CONCEPT_HPP
<commit_msg>Allow triplet type to be aggregate initializable as well as constructible<commit_after>// Describing expectations for a valid sparse matrix library

#ifndef SPARSELIB_CONCEPT_HPP
#define SPARSELIB_CONCEPT_HPP

#include <type_traits>
#include <iostream>

// First, some preliminaries (no predefined Concepts are supplied in library yet)
template<typename T> concept bool ForwardIterator =
    requires( T a, T b ) {
    { a != b }
    { a == b }
    { ++a }
    { *a }
};

template<typename T, typename U> concept bool DereferencesTo =
    requires( T a ) {
    { *a } -> U;
};

template<typename T, typename ...Args> concept bool ConstructibleFrom =
    std::is_constructible<T, Args...>::value ||     // constructors
    requires(Args... args) { { T{args...} } -> T }; // aggregate initialization

template<typename T> concept bool ForwardIterator =
    std::is_convertible<typename std::iterator_traits<T>::iterator_category,
                        std::forward_iterator_tag>::value;

template<typename T, typename U> concept bool Same =
    std::is_same<T, U>::value;

template<typename T, typename U> concept bool IteratorRange =
    Same<T, U> && ForwardIterator<T>;

template<typename L> concept bool SparseLibrary =
    requires( typename L::sparsemat_t mat,
              typename L::lu_t lu,
              typename L::qr_t qr,
              std::ostream& os
        ) {
    // inner types we expect
    typename L::sparsemat_t;
    typename L::index_t;
    typename L::value_t;
    typename L::triplet_t;
    typename L::lu_t;
    typename L::qr_t;

    // triplets can be constructed
    requires ConstructibleFrom<typename L::triplet_t, typename L::index_t, typename L::index_t, typename L::value_t>;

    // we can construct QR and LU objects from a sparse matrix
    requires ConstructibleFrom<typename L::lu_t, typename L::sparsemat_t>;
    requires ConstructibleFrom<typename L::qr_t, typename L::sparsemat_t>;

    // The LU decomposition can perform a solve against a sparse matrix with a sparse result
    { lu.solve( mat ) } -> typename L::sparsemat_t ;

    // The QR decomposition can return a Q of a type convertible to sparse
    { qr.Q() } -> typename L::sparsemat_t;

    // The Q returned from the QR can multiply a sparse matrix on the left, producing another
    // note this does *not* require that the result be a sparse matrix - just that you can convert it to one
    { qr.Q() * mat } -> typename L::sparsemat_t;

    // you can stream out a sparse matrix
    { os << mat } -> std::ostream &;

};

#endif // SPARSELIB_CONCEPT_HPP
<|endoftext|>


<commit_before>#include "HBaseOperations.h"

#include "LogEndian.h"

template <typename T>
static inline size_t size_text(const Text& text)
{
	return sizeof(T) + text.size();
}

template <typename T>
static void serialize_text(uint8_t** buffer, const Text& text)
{
	uint32_t size;

	size = qMin((uint32_t)text.size(), (uint32_t)(1UL << sizeof(T) * 8) - 1);
	*reinterpret_cast<T*>(*buffer) = LOG_ENDIAN((T)size);
	*buffer += sizeof(T);

	memcpy(*buffer, text.data(), size);
	*buffer += size;
}

static inline size_t size_smalltext(const Text& text) { return size_text<uint8_t>(text); }
static inline void serialize_smalltext(uint8_t** buffer, const Text& text) { serialize_text<uint8_t>(buffer, text); }
static inline size_t size_bigtext(const Text& text) { return size_text<uint32_t>(text); }
static inline void serialize_bigtext(uint8_t** buffer, const Text& text) { serialize_text<uint32_t>(buffer, text); }

template <typename T>
static inline void serialize_integer(uint8_t** buffer, T val)
{
	*reinterpret_cast<T*>(*buffer) = LOG_ENDIAN(val);
	*buffer += sizeof(T);
}

size_t HBaseOperation::MutateRows::size(bool deletes)
{
	size_t size = 0;
	num_rows = 0;

	size += sizeof(uint8_t); // Class
	size += size_smalltext(tableName); // Table
	size += sizeof(uint8_t); // Number of rows

	for (std::vector<BatchMutation>::const_iterator batch_mutation = row_batches.begin(); batch_mutation != row_batches.end(); batch_mutation++) {
		size_t ops_size = 0;
		std::map<std::string, std::vector<const Mutation*> > families;

		ops_size += size_bigtext(batch_mutation->row); // RowKey
		ops_size += sizeof(uint8_t); // Number of families

		for (std::vector<Mutation>::const_iterator mutation = batch_mutation->mutations.begin(); mutation != batch_mutation->mutations.end(); mutation++) {
			if (!((mutation->isDelete && deletes) || (!mutation->isDelete && !deletes)))
				continue;

			size_t pos = mutation->column.find_first_of(':');
			if (pos == std::string::npos || pos == (mutation->column.size() - 1)) {
				// TODO: WARN
				continue;
			}

			std::string family(mutation->column.substr(0, pos));

			ops_size += size_smalltext(mutation->column.substr(pos + 1)); // Qualifier
			ops_size += size_bigtext(mutation->value); // Value
			ops_size += sizeof(int64_t); // Timestamp

			std::map<std::string, std::vector<const Mutation*> >::iterator i = families.find(family);
			if (i != families.end()) {
				i->second.push_back(&*mutation);
			} else {
				std::vector<const Mutation*> mutations;
				mutations.push_back(&*mutation);
				families[family] = mutations;
			}
		}

		for (std::map<std::string, std::vector<const Mutation*> >::const_iterator i = families.begin(); i != families.end(); i++) {
			ops_size += size_smalltext(i->first); // Family
			ops_size += sizeof(uint8_t); // Number of qualifiers
		}

		if (families.size() != 0) {
			size += ops_size;
			num_rows++;
		}

		families_per_row.push_back(families);
	}

	if (!num_rows)
		return 0;

	// Align size to 64 bits
	size = (size + (sizeof(uint64_t) - 1)) & ~(sizeof(uint64_t) - 1);
	return size;
}

void HBaseOperation::MutateRows::serialize(void* buffer_, bool deletes)
{
	uint8_t* buffer = reinterpret_cast<uint8_t*>(buffer_);

	serialize_integer(&buffer, (uint8_t)(deletes ? CLASS_DELETE_BATCH : CLASS_PUT_BATCH));
//	printf("%s in table %s (%u rows)\n", deletes ? "DELETE" : "PUT", tableName.c_str(), num_rows);
	serialize_smalltext(&buffer, tableName);
	serialize_integer(&buffer, num_rows);

	std::vector<BatchMutation>::const_iterator batch_mutation = row_batches.begin();
	std::vector<std::map<std::string, std::vector<const Mutation*> > >::const_iterator families = families_per_row.begin();
	for (; batch_mutation != row_batches.end(); batch_mutation++, families++) {
		if (families->size() == 0)
			continue;

//		printf("\trow '%s' (%u families)\n", batch_mutation->row.c_str(), (uint8_t)families->size());
		serialize_bigtext(&buffer, batch_mutation->row);
		serialize_integer(&buffer, (uint8_t)families->size());

		for (std::map<std::string, std::vector<const Mutation*> >::const_iterator family = families->begin(); family != families->end(); family++) {
//			printf("\t\tfamily '%s' (%u qualifiers)\n", family->first.c_str(), (uint8_t)family->second.size());
			serialize_smalltext(&buffer, family->first);
			serialize_integer(&buffer, (uint8_t)family->second.size());

			for (std::vector<const Mutation*>::const_iterator qualifier = family->second.begin(); qualifier != family->second.end(); qualifier++) {
				size_t pos = (*qualifier)->column.find_first_of(':');
//				printf("\t\t\tqualifier '%s' value '%s' timestamp %lld\n", (*qualifier)->column.substr(pos + 1).c_str(), (*qualifier)->value.c_str(), (int64_t)timestamp);
				serialize_smalltext(&buffer, (*qualifier)->column.substr(pos + 1));
				serialize_bigtext(&buffer, (*qualifier)->value);
				serialize_integer(&buffer, (int64_t)timestamp);
			}
		}
	}
}

<commit_msg>Ignore value in deletes<commit_after>#include "HBaseOperations.h"

#include "LogEndian.h"

template <typename T>
static inline size_t size_text(const Text& text)
{
	return sizeof(T) + text.size();
}

template <typename T>
static void serialize_text(uint8_t** buffer, const Text& text)
{
	uint32_t size;

	size = qMin((uint32_t)text.size(), (uint32_t)(1UL << sizeof(T) * 8) - 1);
	*reinterpret_cast<T*>(*buffer) = LOG_ENDIAN((T)size);
	*buffer += sizeof(T);

	memcpy(*buffer, text.data(), size);
	*buffer += size;
}

static inline size_t size_smalltext(const Text& text) { return size_text<uint8_t>(text); }
static inline void serialize_smalltext(uint8_t** buffer, const Text& text) { serialize_text<uint8_t>(buffer, text); }
static inline size_t size_bigtext(const Text& text) { return size_text<uint32_t>(text); }
static inline void serialize_bigtext(uint8_t** buffer, const Text& text) { serialize_text<uint32_t>(buffer, text); }

template <typename T>
static inline void serialize_integer(uint8_t** buffer, T val)
{
	*reinterpret_cast<T*>(*buffer) = LOG_ENDIAN(val);
	*buffer += sizeof(T);
}

size_t HBaseOperation::MutateRows::size(bool deletes)
{
	size_t size = 0;
	num_rows = 0;

	size += sizeof(uint8_t); // Class
	size += size_smalltext(tableName); // Table
	size += sizeof(uint8_t); // Number of rows

	for (std::vector<BatchMutation>::const_iterator batch_mutation = row_batches.begin(); batch_mutation != row_batches.end(); batch_mutation++) {
		size_t ops_size = 0;
		std::map<std::string, std::vector<const Mutation*> > families;

		ops_size += size_bigtext(batch_mutation->row); // RowKey
		ops_size += sizeof(uint8_t); // Number of families

		for (std::vector<Mutation>::const_iterator mutation = batch_mutation->mutations.begin(); mutation != batch_mutation->mutations.end(); mutation++) {
			if (!((mutation->isDelete && deletes) || (!mutation->isDelete && !deletes)))
				continue;

			size_t pos = mutation->column.find_first_of(':');
			if (pos == std::string::npos || pos == (mutation->column.size() - 1)) {
				// TODO: WARN
				continue;
			}

			std::string family(mutation->column.substr(0, pos));

			ops_size += size_smalltext(mutation->column.substr(pos + 1)); // Qualifier
			ops_size += sizeof(int64_t); // Timestamp
			if (!deletes)
				ops_size += size_bigtext(mutation->value); // Value

			std::map<std::string, std::vector<const Mutation*> >::iterator i = families.find(family);
			if (i != families.end()) {
				i->second.push_back(&*mutation);
			} else {
				std::vector<const Mutation*> mutations;
				mutations.push_back(&*mutation);
				families[family] = mutations;
			}
		}

		for (std::map<std::string, std::vector<const Mutation*> >::const_iterator i = families.begin(); i != families.end(); i++) {
			ops_size += size_smalltext(i->first); // Family
			ops_size += sizeof(uint8_t); // Number of qualifiers
		}

		if (families.size() != 0) {
			size += ops_size;
			num_rows++;
		}

		families_per_row.push_back(families);
	}

	if (!num_rows)
		return 0;

	// Align size to 64 bits
	size = (size + (sizeof(uint64_t) - 1)) & ~(sizeof(uint64_t) - 1);
	return size;
}

void HBaseOperation::MutateRows::serialize(void* buffer_, bool deletes)
{
	uint8_t* buffer = reinterpret_cast<uint8_t*>(buffer_);

	serialize_integer(&buffer, (uint8_t)(deletes ? CLASS_DELETE_BATCH : CLASS_PUT_BATCH));
//	printf("%s in table %s (%u rows)\n", deletes ? "DELETE" : "PUT", tableName.c_str(), num_rows);
	serialize_smalltext(&buffer, tableName);
	serialize_integer(&buffer, num_rows);

	std::vector<BatchMutation>::const_iterator batch_mutation = row_batches.begin();
	std::vector<std::map<std::string, std::vector<const Mutation*> > >::const_iterator families = families_per_row.begin();
	for (; batch_mutation != row_batches.end(); batch_mutation++, families++) {
		if (families->size() == 0)
			continue;

//		printf("\trow '%s' (%u families)\n", batch_mutation->row.c_str(), (uint8_t)families->size());
		serialize_bigtext(&buffer, batch_mutation->row);
		serialize_integer(&buffer, (uint8_t)families->size());

		for (std::map<std::string, std::vector<const Mutation*> >::const_iterator family = families->begin(); family != families->end(); family++) {
//			printf("\t\tfamily '%s' (%u qualifiers)\n", family->first.c_str(), (uint8_t)family->second.size());
			serialize_smalltext(&buffer, family->first);
			serialize_integer(&buffer, (uint8_t)family->second.size());

			for (std::vector<const Mutation*>::const_iterator qualifier = family->second.begin(); qualifier != family->second.end(); qualifier++) {
				size_t pos = (*qualifier)->column.find_first_of(':');
//				printf("\t\t\tqualifier '%s' value '%s' timestamp %lld\n", (*qualifier)->column.substr(pos + 1).c_str(), (*qualifier)->value.c_str(), (int64_t)timestamp);
				serialize_smalltext(&buffer, (*qualifier)->column.substr(pos + 1));
				serialize_integer(&buffer, (int64_t)timestamp);
				if (!deletes)
					serialize_bigtext(&buffer, (*qualifier)->value);
			}
		}
	}
}

<|endoftext|>


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

#include "joynr/Settings.h"

#include <utility>
#include <boost/property_tree/ini_parser.hpp>

#include "joynr/Util.h"

namespace ptree = boost::property_tree;

namespace joynr
{

Settings::Settings() : filename(), propertyTree(), loaded(false)
{
}

Settings::Settings(const std::string& filename) : filename(filename), propertyTree(), loaded(false)
{
    try {
        ptree::read_ini(filename, propertyTree);
        loaded = true;
    } catch (const ptree::ini_parser_error& e) {
        JOYNR_LOG_ERROR(logger(), "Could not read settings file: {}", e.what());
        // The file does not exist or is an invalid format.
        // Match the behaviour of QSettings and ignore/overwrite
        // But leave loaded as false
    }
}

bool Settings::isLoaded() const
{
    return loaded;
}

bool Settings::contains(const std::string& path) const
{
    // Create a '/' delimited path
    ptree::ptree::path_type treePath = createPath(path);

    // Get the child node with the path
    const auto& child = propertyTree.get_child_optional(treePath);

    // Use boost::optional operator bool()
    return bool(child);
}

bool Settings::sync()
{
    try {
        if (contentChanged(propertyTree, filename)) {
            ptree::write_ini(filename, propertyTree);
            return true;
        } else {
            JOYNR_LOG_DEBUG(logger(),
                            "Settings file \"{}\" not updated because its content did not change",
                            filename);
        }
    } catch (const ptree::ini_parser_error& e) {
        JOYNR_LOG_ERROR(logger(),
                        "settings file \"{}\" cannot be written due to the following error: {})",
                        filename,
                        e.message());
    }
    return false;
}

void Settings::merge(const Settings& from, Settings& to, bool overwrite)
{
    const ptree::ptree& fromTree = from.propertyTree;
    ptree::ptree& toTree = to.propertyTree;

    merge(fromTree, toTree, overwrite);
    to.loaded = true;
}

bool Settings::contentChanged(const boost::property_tree::ptree& propertyTreeToCompare,
                              const std::string& iniFilename) const
{
    if (!util::fileExists(iniFilename)) {
        return true;
    }

    boost::property_tree::ptree otherPropertyTree;

    try {
        ptree::read_ini(iniFilename, otherPropertyTree);
    } catch (const ptree::ini_parser_error&) {
        return true;
    }

    return propertyTreeToCompare != otherPropertyTree;
}

void Settings::fillEmptySettingsWithDefaults(const std::string& defaultsFilename)
{
    const std::string cmakeSettingsPath = CMAKE_JOYNR_SETTINGS_INSTALL_DIR;
    Settings cmakeDefaultSettings(cmakeSettingsPath + "/" + defaultsFilename);
    Settings relativeDefaultSettings("resources/" + defaultsFilename);

    Settings::merge(relativeDefaultSettings, *this, false);
    Settings::merge(cmakeDefaultSettings, *this, false);
}

void Settings::merge(const boost::property_tree::ptree& from,
                     boost::property_tree::ptree& to,
                     bool overwrite)
{
    // Is this a single value or a subtree?
    if (!from.data().empty()) {
        // Single value
        if (overwrite || to.data().empty()) {
            to.put_value(from.data());
        }
        return;
    }

    // Subtree
    for (const auto& fromEntry : from) {
        // Does the key exist in the destination?
        auto toIt = to.find(fromEntry.first);
        if (toIt == to.not_found()) {
            ptree::ptree child;

            // Recurse into the new child
            merge(fromEntry.second, child, overwrite);

            // Create a path object because ptree uses '.' as a path delimiter
            // when strings are used
            ptree::ptree::path_type treePath = createPath(fromEntry.first);
            to.add_child(treePath, child);
        } else {
            // Recurse into the subtrees
            merge(fromEntry.second, toIt->second, overwrite);
        }
    }
}

boost::property_tree::path Settings::createPath(const std::string& path)
{
    return boost::property_tree::path(path, '/');
}

} // namespace joynr
<commit_msg>[C++] Log settings filename in Settings constructor<commit_after>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

#include "joynr/Settings.h"

#include <utility>
#include <boost/property_tree/ini_parser.hpp>

#include "joynr/Util.h"

namespace ptree = boost::property_tree;

namespace joynr
{

Settings::Settings() : filename(), propertyTree(), loaded(false)
{
}

Settings::Settings(const std::string& filename) : filename(filename), propertyTree(), loaded(false)
{
    try {
        JOYNR_LOG_INFO(logger(), "attempting to read settings file: {}", filename);
        ptree::read_ini(filename, propertyTree);
        loaded = true;
    } catch (const ptree::ini_parser_error& e) {
        JOYNR_LOG_ERROR(logger(), "Could not read settings file: {}", e.what());
        // The file does not exist or is an invalid format.
        // Match the behaviour of QSettings and ignore/overwrite
        // But leave loaded as false
    }
}

bool Settings::isLoaded() const
{
    return loaded;
}

bool Settings::contains(const std::string& path) const
{
    // Create a '/' delimited path
    ptree::ptree::path_type treePath = createPath(path);

    // Get the child node with the path
    const auto& child = propertyTree.get_child_optional(treePath);

    // Use boost::optional operator bool()
    return bool(child);
}

bool Settings::sync()
{
    try {
        if (contentChanged(propertyTree, filename)) {
            ptree::write_ini(filename, propertyTree);
            return true;
        } else {
            JOYNR_LOG_DEBUG(logger(),
                            "Settings file \"{}\" not updated because its content did not change",
                            filename);
        }
    } catch (const ptree::ini_parser_error& e) {
        JOYNR_LOG_ERROR(logger(),
                        "settings file \"{}\" cannot be written due to the following error: {})",
                        filename,
                        e.message());
    }
    return false;
}

void Settings::merge(const Settings& from, Settings& to, bool overwrite)
{
    const ptree::ptree& fromTree = from.propertyTree;
    ptree::ptree& toTree = to.propertyTree;

    merge(fromTree, toTree, overwrite);
    to.loaded = true;
}

bool Settings::contentChanged(const boost::property_tree::ptree& propertyTreeToCompare,
                              const std::string& iniFilename) const
{
    if (!util::fileExists(iniFilename)) {
        return true;
    }

    boost::property_tree::ptree otherPropertyTree;

    try {
        ptree::read_ini(iniFilename, otherPropertyTree);
    } catch (const ptree::ini_parser_error&) {
        return true;
    }

    return propertyTreeToCompare != otherPropertyTree;
}

void Settings::fillEmptySettingsWithDefaults(const std::string& defaultsFilename)
{
    const std::string cmakeSettingsPath = CMAKE_JOYNR_SETTINGS_INSTALL_DIR;
    Settings cmakeDefaultSettings(cmakeSettingsPath + "/" + defaultsFilename);
    Settings relativeDefaultSettings("resources/" + defaultsFilename);

    Settings::merge(relativeDefaultSettings, *this, false);
    Settings::merge(cmakeDefaultSettings, *this, false);
}

void Settings::merge(const boost::property_tree::ptree& from,
                     boost::property_tree::ptree& to,
                     bool overwrite)
{
    // Is this a single value or a subtree?
    if (!from.data().empty()) {
        // Single value
        if (overwrite || to.data().empty()) {
            to.put_value(from.data());
        }
        return;
    }

    // Subtree
    for (const auto& fromEntry : from) {
        // Does the key exist in the destination?
        auto toIt = to.find(fromEntry.first);
        if (toIt == to.not_found()) {
            ptree::ptree child;

            // Recurse into the new child
            merge(fromEntry.second, child, overwrite);

            // Create a path object because ptree uses '.' as a path delimiter
            // when strings are used
            ptree::ptree::path_type treePath = createPath(fromEntry.first);
            to.add_child(treePath, child);
        } else {
            // Recurse into the subtrees
            merge(fromEntry.second, toIt->second, overwrite);
        }
    }
}

boost::property_tree::path Settings::createPath(const std::string& path)
{
    return boost::property_tree::path(path, '/');
}

} // namespace joynr
<|endoftext|>


<commit_before>/*++

Module Name:

    snap.cpp

Abstract:

    Main entry point for the snap binary. Calls into the indexer, single-end aligner or
    paired-end aligner functions defined in other source files in this directory.

Authors:

    Matei Zaharia, February, 2012

Environment:
`
    User mode service.

Revision History:

    Adapted from cSNAP, which was in turn adapted from the scala prototype

--*/

#include "stdafx.h"
#include "options.h"
#include "FASTA.h"
#include "GenomeIndex.h"
#include "SingleAligner.h"
#include "PairedAligner.h"

using namespace std;

const char *SNAP_VERSION = "0.13.7";

static void usage()
{
    fprintf(stderr,
            "Usage: snap <command> [<options>]\n"
            "Commands:\n"
            "   index    build a genome index\n"
            "   single   align single-end reads\n"
            "   paired   align paired-end reads\n"
            "Type a command without arguments to see its help.\n");
    exit(1);
}

int main(int argc, const char **argv)
{
    printf("Welcome to SNAP version %s.\n\n", SNAP_VERSION);

    if (argc < 2) {
        usage();
    } else if (strcmp(argv[1], "index") == 0) {
        GenomeIndex::runIndexer(argc - 2, argv + 2);
    } else if (strcmp(argv[1], "single") == 0) {
        SingleAlignerContext single;
        single.runAlignment(argc - 2, argv + 2, SNAP_VERSION);
    } else if (strcmp(argv[1], "paired") == 0) {
        PairedAlignerContext paired;
        paired.runAlignment(argc - 2, argv + 2, SNAP_VERSION);
    } else {
        fprintf(stderr, "Invalid command: %s\n\n", argv[1]);
        usage();
    }
}
<commit_msg>Update version number, now passes picard test<commit_after>/*++

Module Name:

    snap.cpp

Abstract:

    Main entry point for the snap binary. Calls into the indexer, single-end aligner or
    paired-end aligner functions defined in other source files in this directory.

Authors:

    Matei Zaharia, February, 2012

Environment:
`
    User mode service.

Revision History:

    Adapted from cSNAP, which was in turn adapted from the scala prototype

--*/

#include "stdafx.h"
#include "options.h"
#include "FASTA.h"
#include "GenomeIndex.h"
#include "SingleAligner.h"
#include "PairedAligner.h"

using namespace std;

const char *SNAP_VERSION = "0.13.8";

static void usage()
{
    fprintf(stderr,
            "Usage: snap <command> [<options>]\n"
            "Commands:\n"
            "   index    build a genome index\n"
            "   single   align single-end reads\n"
            "   paired   align paired-end reads\n"
            "Type a command without arguments to see its help.\n");
    exit(1);
}

int main(int argc, const char **argv)
{
    printf("Welcome to SNAP version %s.\n\n", SNAP_VERSION);

    if (argc < 2) {
        usage();
    } else if (strcmp(argv[1], "index") == 0) {
        GenomeIndex::runIndexer(argc - 2, argv + 2);
    } else if (strcmp(argv[1], "single") == 0) {
        SingleAlignerContext single;
        single.runAlignment(argc - 2, argv + 2, SNAP_VERSION);
    } else if (strcmp(argv[1], "paired") == 0) {
        PairedAlignerContext paired;
        paired.runAlignment(argc - 2, argv + 2, SNAP_VERSION);
    } else {
        fprintf(stderr, "Invalid command: %s\n\n", argv[1]);
        usage();
    }
}
<|endoftext|>