<commit_before>/*
    This file is part of KXForms.

    Copyright (c) 2006 Cornelius Schumacher <schumacher@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 as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    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 "formcreator.h"

#include "xmlbuilder.h"

#include <QDebug>

using namespace KXForms;

FormCreator::FormCreator()
{
}

QString FormCreator::create( const Schema::Document &schemaDocument )
{
  qDebug() << "---FormCreator::create()";

  mDocument = schemaDocument;

  mCollapsedForms.clear();

  XmlBuilder xml( "kxforms" );

  createForm( &xml, schemaDocument.startElement() );

  foreach ( Schema::Element element, schemaDocument.usedElements() ) {
    if ( element.identifier() != schemaDocument.startElement().identifier() ) {
      createForm( &xml, element );
    }
  }

  qDebug() << "---FormCreator::create() done";

  return xml.print();
}

void FormCreator::createForm( XmlBuilder *xml, const Schema::Element &element )
{
  if ( mCollapsedForms.contains( element.name() ) ) return;

  qDebug() << "ELEMENT" << element.name();
  XmlBuilder *form = xml->tag( "form" )->attribute( "ref", element.name() );

  form->tag( "xf:label", humanizeString( element.name() ) );

  parseAttributes( element, form );

  parseElement( element, form );
}

void FormCreator::parseAttributes( const Schema::Element &element, XmlBuilder *xml  )
{
  foreach( Schema::Relation r, element.attributeRelations() ) {
    Schema::Attribute a = mDocument.attribute( r );

    qDebug() << "  ATTRIBUTE: " << a.identifier();

    if ( a.type() == Schema::Attribute::String ) {
      XmlBuilder *input = xml->tag( "xf:input" );
      input->attribute( "ref", a.ref() );
      createLabel( input, a );
    } else if ( a.type() == Schema::Attribute::Enumeration ) {
      XmlBuilder *select1 = xml->tag( "xf:select1" );
      select1->attribute( "ref", a.ref() );
      createLabel( select1, a );
      foreach( QString value, a.enumerationValues() ) {
        XmlBuilder *item = select1->tag( "xf:item" );
        QString itemLabel;
        Hint hint = mHints.hint( element.identifier() + '/' + a.ref() );
        if ( hint.isValid() ) itemLabel = hint.enumValue( value );
        if ( itemLabel.isEmpty() ) itemLabel = humanizeString( value );
        item->tag( "xf:label", itemLabel );
        item->tag( "xf:value", value );
      }
    } else {
      qDebug() << "Unsupported type: " << a.type();
    }
  }
}

void FormCreator::parseElement( const Schema::Element &element, XmlBuilder *xml )
{
  if ( element.type() == Schema::Node::String ) {
    XmlBuilder *textArea = xml->tag( "xf:textarea" );
    textArea->attribute( "ref", "." );
    createLabel( textArea, element );
  } else if ( element.type() == Schema::Node::NormalizedString ||
              element.type() == Schema::Node::Token ) {
    XmlBuilder *input = xml->tag( "xf:input" );
    input->attribute( "ref", "." );
    createLabel( input, element );
  } else if ( element.type() == Schema::Node::ComplexType ) {
    parseComplexType( element, xml, true );
  } else {
    qDebug() << "Unsupported type: " << element.type();
  }
}

void FormCreator::parseComplexType( const Schema::Element &element, XmlBuilder *xml, bool topLevel )
{
  QString currentChoice;

  XmlBuilder *section;

  bool choiceOnly = true;
  foreach( Schema::Relation r, element.elementRelations() ) {
    if( r.choice().isEmpty() )
      choiceOnly = false;
  }

  if( !topLevel && !element.mixed() && !choiceOnly ) {
    section = xml->tag( "kxf:section" );
    createLabel( section, element );
  } /*else if( !topLevel && element.type() ==  ) {
    section = xml->tag( "kxf:section" );
    createLabel( section, element );
  } */else {
    section = xml;
  }

  XmlBuilder *list = 0;
  XmlBuilder *choice = 0;
  foreach( Schema::Relation r, element.elementRelations() ) {
    qDebug() << "  CHILD ELEMENT" << r.target();
    qDebug() << "    CHOICE" << r.choice();
    if ( r.isList() ) {
      bool isMixedList = r.choice().contains( "+" );
      if ( !list || r.choice().isEmpty() || currentChoice != r.choice() ) {
        list = section->tag( "list" );
        QString label;
        if ( isMixedList ) {
          label = "Item";
        } else {
          label = getLabel( element.identifier() + '[' + r.target() + ']' );
          if ( label.isEmpty() ) {
            label = humanizeString( r.target(), true );
          }
        }
        list->tag( "xf:label", label );
      }
      XmlBuilder *item = list->tag( "itemclass" );
      item->attribute( "ref", r.target() );
      QString itemLabel;
      itemLabel = getLabel( element.identifier() + '/' + r.target() );

      Schema::Element itemElement = mDocument.element( r );

      if ( itemLabel.isEmpty() ) {
        // Try to guess a suitable item label.
        foreach( Schema::Relation r2, itemElement.attributeRelations() ) {
          if ( r2.target() == "name" ) {
            if ( isMixedList ) {
              itemLabel = humanizeString( itemElement.name() ) + ": ";
            }
            itemLabel += "<arg ref=\"@name\"/>";
           break;
          }
        }
      }

      if ( itemLabel.isEmpty() ) {
        if ( itemElement.type() == Schema::Node::String ) {
          itemLabel += "<arg ref=\".\" truncate=\"40\"/>";
      } else if ( itemElement.type() == Schema::Node::NormalizedString ||
                 itemElement.type() == Schema::Node::Token ) {
        itemLabel += "<arg ref=\".\"/>";
        }
      }

      if ( itemLabel.isEmpty() ) itemLabel = humanizeString( r.target() );
      item->tag( "itemlabel", itemLabel );

      currentChoice = r.choice();
    } else if( !r.choice().isEmpty() ) {
      if( !choice ) {
        choice = section->tag( "xf:select1" );
        choice->tag( "xf:label",  humanizeString( element.name() ) );
      }
      Schema::Element choiceElement = mDocument.element( r );
      XmlBuilder *item = choice->tag( "xf:item" );
      QString value = choiceElement.name();
      QString itemLabel;
      Hint hint = mHints.hint( element.identifier() + '/' + choiceElement.ref() );
      if ( hint.isValid() ) itemLabel = hint.enumValue( value );
      if ( itemLabel.isEmpty() ) itemLabel = humanizeString( value );

      item->tag( "xf:label", itemLabel );
      item->tag( "xf:value", value );
    } else{
      Schema::Element textElement = mDocument.element( r.target() );
      if( textElement.type() == Schema::Node::ComplexType && !textElement.mixed() ) {
        parseComplexType( textElement, section, false );
      } else {
        XmlBuilder *textInput = 0;
        if ( textElement.type() == Schema::Node::NormalizedString ) {
          textInput = section->tag( "xf:input" );
        } else {
          textInput = section->tag( "xf:textarea" );
        }
        textInput->attribute( "ref", textElement.name() );
        createLabel( textInput, textElement );
        mCollapsedForms.append( r.target() );
      }
    }
  }
}

QString FormCreator::humanizeString( const QString &str, bool pluralize )
{
  if ( str.isEmpty() ) return str;
  QString result = str[0].toUpper() + str.mid( 1 );
  if ( pluralize ) {
    if ( result.endsWith( "y" ) ) {
      result = result.left( str.length() - 1 ) + "ies";
    } else {
      result += 's';
    }
  }

  return result;
}

void FormCreator::setHints( const Hints &hints )
{
  mHints = hints;
}

void FormCreator::mergeHints( const Hints &hints )
{
  foreach( Hint h, hints.hints() ) {
    mHints.insertHint( h );
  }
}

void FormCreator::createLabel( XmlBuilder *parent, const Schema::Node &node )
{
  parent->tag( "xf:label", getLabel( node.identifier(), node.name() ) );
}

QString FormCreator::getLabel( const QString &ref, const QString &fallback,
  bool pluralize )
{
//  qDebug() << "GETLABEL: " << ref;

  QString label;

  Hint hint = mHints.hint( ref );
  if ( hint.isValid() ) label = hint.label();

  if ( label.isEmpty() ) label = humanizeString( fallback, pluralize );

  return label;
}

Hints FormCreator::hints() const
{
  return mHints;
}
<commit_msg>Apply hints on choice elements. Create a textarea element if a complextype has no elementrelation.<commit_after>/*
    This file is part of KXForms.

    Copyright (c) 2006 Cornelius Schumacher <schumacher@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 as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    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 "formcreator.h"

#include "xmlbuilder.h"

#include <QDebug>

using namespace KXForms;

FormCreator::FormCreator()
{
}

QString FormCreator::create( const Schema::Document &schemaDocument )
{
  qDebug() << "---FormCreator::create()";

  mDocument = schemaDocument;

  mCollapsedForms.clear();

  XmlBuilder xml( "kxforms" );

  createForm( &xml, schemaDocument.startElement() );

  foreach ( Schema::Element element, schemaDocument.usedElements() ) {
    if ( element.identifier() != schemaDocument.startElement().identifier() ) {
      createForm( &xml, element );
    }
  }

  qDebug() << "---FormCreator::create() done";

  return xml.print();
}

void FormCreator::createForm( XmlBuilder *xml, const Schema::Element &element )
{
  if ( mCollapsedForms.contains( element.name() ) ) return;

  qDebug() << "ELEMENT" << element.name();
  XmlBuilder *form = xml->tag( "form" )->attribute( "ref", element.name() );

  form->tag( "xf:label", humanizeString( element.name() ) );

  parseAttributes( element, form );

  parseElement( element, form );
}

void FormCreator::parseAttributes( const Schema::Element &element, XmlBuilder *xml  )
{
  foreach( Schema::Relation r, element.attributeRelations() ) {
    Schema::Attribute a = mDocument.attribute( r );

    qDebug() << "  ATTRIBUTE: " << a.identifier();

    if ( a.type() == Schema::Attribute::String ) {
      XmlBuilder *input = xml->tag( "xf:input" );
      input->attribute( "ref", a.ref() );
      createLabel( input, a );
    } else if ( a.type() == Schema::Attribute::Enumeration ) {
      XmlBuilder *select1 = xml->tag( "xf:select1" );
      select1->attribute( "ref", a.ref() );
      createLabel( select1, a );
      foreach( QString value, a.enumerationValues() ) {
        XmlBuilder *item = select1->tag( "xf:item" );
        QString itemLabel;
        Hint hint = mHints.hint( element.identifier() + '/' + a.ref() );
        if ( hint.isValid() ) itemLabel = hint.enumValue( value );
        if ( itemLabel.isEmpty() ) itemLabel = humanizeString( value );
        item->tag( "xf:label", itemLabel );
        item->tag( "xf:value", value );
      }
    } else {
      qDebug() << "Unsupported type: " << a.type();
    }
  }
}

void FormCreator::parseElement( const Schema::Element &element, XmlBuilder *xml )
{
  if ( element.type() == Schema::Node::String ) {
    XmlBuilder *textArea = xml->tag( "xf:textarea" );
    textArea->attribute( "ref", "." );
    createLabel( textArea, element );
  } else if ( element.type() == Schema::Node::NormalizedString ||
              element.type() == Schema::Node::Token ) {
    XmlBuilder *input = xml->tag( "xf:input" );
    input->attribute( "ref", "." );
    createLabel( input, element );
  } else if ( element.type() == Schema::Node::ComplexType ) {
    parseComplexType( element, xml, true );
  } else {
    qDebug() << "Unsupported type: " << element.type();
  }
}

void FormCreator::parseComplexType( const Schema::Element &element, XmlBuilder *xml, bool topLevel )
{
  QString currentChoice;

  XmlBuilder *section;

  bool choiceOnly = true;
  foreach( Schema::Relation r, element.elementRelations() ) {
    if( r.choice().isEmpty() )
      choiceOnly = false;
  }

  if( !topLevel &&
      !element.mixed() &&
      !choiceOnly &&
      element.elementRelations().size() > 1 ) {
    section = xml->tag( "kxf:section" );
    createLabel( section, element );
  } /*else if( !topLevel && element.type() ==  ) {
    section = xml->tag( "kxf:section" );
    createLabel( section, element );
  } */else {
    section = xml;
  }

  XmlBuilder *list = 0;
  XmlBuilder *choice = 0;
  foreach( Schema::Relation r, element.elementRelations() ) {
    qDebug() << "  CHILD ELEMENT" << r.target();
    qDebug() << "    CHOICE" << r.choice();
    if ( r.isList() ) {
      bool isMixedList = r.choice().contains( "+" );
      if ( !list || r.choice().isEmpty() || currentChoice != r.choice() ) {
        list = section->tag( "list" );
        QString label;
        if ( isMixedList ) {
          label = "Item";
        } else {
          label = getLabel( element.identifier() + '[' + r.target() + ']' );
          if ( label.isEmpty() ) {
            label = humanizeString( r.target(), true );
          }
        }
        list->tag( "xf:label", label );
      }
      XmlBuilder *item = list->tag( "itemclass" );
      item->attribute( "ref", r.target() );
      QString itemLabel;
      itemLabel = getLabel( element.identifier() + '/' + r.target() );

      Schema::Element itemElement = mDocument.element( r );

      if ( itemLabel.isEmpty() ) {
        // Try to guess a suitable item label.
        foreach( Schema::Relation r2, itemElement.attributeRelations() ) {
          if ( r2.target() == "name" ) {
            if ( isMixedList ) {
              itemLabel = humanizeString( itemElement.name() ) + ": ";
            }
            itemLabel += "<arg ref=\"@name\"/>";
           break;
          }
        }
      }

      if ( itemLabel.isEmpty() ) {
        if ( itemElement.type() == Schema::Node::String ) {
          itemLabel += "<arg ref=\".\" truncate=\"40\"/>";
      } else if ( itemElement.type() == Schema::Node::NormalizedString ||
                 itemElement.type() == Schema::Node::Token ) {
        itemLabel += "<arg ref=\".\"/>";
        }
      }

      if ( itemLabel.isEmpty() ) itemLabel = humanizeString( r.target() );
      item->tag( "itemlabel", itemLabel );

      currentChoice = r.choice();
    } else if( !r.choice().isEmpty() ) {
      if( !choice ) {
        choice = section->tag( "xf:select1" );
        choice->tag( "xf:label",  getLabel( element.ref(), element.name() ) );
      }
      Schema::Element choiceElement = mDocument.element( r );
      XmlBuilder *item = choice->tag( "xf:item" );
      QString value = choiceElement.name();
      QString itemLabel = getLabel( choiceElement.ref(), choiceElement.name() );

      item->tag( "xf:label", itemLabel );
      item->tag( "xf:value", value );
    } else{
      Schema::Element textElement = mDocument.element( r.target() );
      if( textElement.type() == Schema::Node::ComplexType && !textElement.mixed() ) {
        parseComplexType( textElement, section, false );
      } else {
        XmlBuilder *textInput = 0;
        if ( textElement.type() == Schema::Node::NormalizedString ) {
          textInput = section->tag( "xf:input" );
        } else {
          textInput = section->tag( "xf:textarea" );
        }
        textInput->attribute( "ref", textElement.name() );
        createLabel( textInput, textElement );
        mCollapsedForms.append( r.target() );
      }
    }
  }
  if( element.elementRelations().size() == 0 ) {
    XmlBuilder *textInput = 0;
    textInput = section->tag( "xf:textarea" );
    textInput->attribute( "ref", element.name() );
    createLabel( textInput, element );
  }
}

QString FormCreator::humanizeString( const QString &str, bool pluralize )
{
  if ( str.isEmpty() ) return str;
  QString result = str[0].toUpper() + str.mid( 1 );
  if ( pluralize ) {
    if ( result.endsWith( "y" ) ) {
      result = result.left( str.length() - 1 ) + "ies";
    } else {
      result += 's';
    }
  }

  return result;
}

void FormCreator::setHints( const Hints &hints )
{
  mHints = hints;
}

void FormCreator::mergeHints( const Hints &hints )
{
  foreach( Hint h, hints.hints() ) {
    mHints.insertHint( h );
  }
}

void FormCreator::createLabel( XmlBuilder *parent, const Schema::Node &node )
{
  parent->tag( "xf:label", getLabel( node.identifier(), node.name() ) );
}

QString FormCreator::getLabel( const QString &ref, const QString &fallback,
  bool pluralize )
{
//  qDebug() << "GETLABEL: " << ref;

  QString label;

  Hint hint = mHints.hint( ref );

  if ( hint.isValid() ) label = hint.label();

  if ( label.isEmpty() ) label = humanizeString( fallback, pluralize );

  return label;
}

Hints FormCreator::hints() const
{
  return mHints;
}
<|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 "otbAtmosphericCorrectionParameters.h"

#include <fstream>

#include "otbAeronetFileReader.h"
#include "otbSpectralSensitivityReader.h"
#include "otbAeronetData.h"

namespace otb
{

AtmosphericCorrectionParameters
::AtmosphericCorrectionParameters()
{

  m_AtmosphericPressure  = 1030.;
  m_WaterVaporAmount     = 2.5;
  m_OzoneAmount          = 0.28;
  m_AerosolModel         = CONTINENTAL;
  m_AerosolOptical       = 0.2;
  m_AeronetFileName      = "";
  m_Day                  = 1;
  m_Month                = 1;

}

/** Get data from aeronet file*/
void
AtmosphericCorrectionParameters
::UpdateAeronetData(const std::string& file, int year, int month, int day, int hour, int minute, double epsi)
{
  if (file == "") itkExceptionMacro(<< "No Aeronet filename specified.");

  AeronetFileReader::Pointer reader = AeronetFileReader::New();
  reader->SetFileName(file);
  reader->SetDay(day);
  reader->SetMonth(month);
  reader->SetYear(year);
  reader->SetHour(hour);
  reader->SetMinute(minute);
  reader->SetEpsilon(epsi);

  reader->Update();

  m_AerosolOptical = reader->GetOutput()->GetAerosolOpticalThickness();
  m_WaterVaporAmount = reader->GetOutput()->GetWater();
}

/**PrintSelf method */
void
AtmosphericCorrectionParameters
::PrintSelf(std::ostream& os, itk::Indent indent) const
{

  os << "Atmospheric pressure  : " << m_AtmosphericPressure << std::endl;
  os << "Water vapor amount    : " << m_WaterVaporAmount << std::endl;
  os << "Ozone amount          : " << m_OzoneAmount << std::endl;
  os << "Aerosol model         : " << m_AerosolModel << std::endl;
  os << "Aerosol optical       : " << m_AerosolOptical << std::endl;

}
} // end namespace otb
<commit_msg>ENH: follow ITK guidelines and add indentation in PrintSelf method<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 "otbAtmosphericCorrectionParameters.h"

#include <fstream>

#include "otbAeronetFileReader.h"
#include "otbSpectralSensitivityReader.h"
#include "otbAeronetData.h"

namespace otb
{

AtmosphericCorrectionParameters
::AtmosphericCorrectionParameters()
{

  m_AtmosphericPressure  = 1030.;
  m_WaterVaporAmount     = 2.5;
  m_OzoneAmount          = 0.28;
  m_AerosolModel         = CONTINENTAL;
  m_AerosolOptical       = 0.2;
  m_AeronetFileName      = "";
  m_Day                  = 1;
  m_Month                = 1;

}

/** Get data from aeronet file*/
void
AtmosphericCorrectionParameters
::UpdateAeronetData(const std::string& file, int year, int month, int day, int hour, int minute, double epsi)
{
  if (file == "") itkExceptionMacro(<< "No Aeronet filename specified.");

  AeronetFileReader::Pointer reader = AeronetFileReader::New();
  reader->SetFileName(file);
  reader->SetDay(day);
  reader->SetMonth(month);
  reader->SetYear(year);
  reader->SetHour(hour);
  reader->SetMinute(minute);
  reader->SetEpsilon(epsi);

  reader->Update();

  m_AerosolOptical = reader->GetOutput()->GetAerosolOpticalThickness();
  m_WaterVaporAmount = reader->GetOutput()->GetWater();
}

/**PrintSelf method */
void
AtmosphericCorrectionParameters
::PrintSelf(std::ostream& os, itk::Indent indent) const
{

  os << indent << "Atmospheric pressure  : " << m_AtmosphericPressure << std::endl;
  os << indent << "Water vapor amount    : " << m_WaterVaporAmount << std::endl;
  os << indent << "Ozone amount          : " << m_OzoneAmount << std::endl;
  os << indent << "Aerosol model         : " << m_AerosolModel << std::endl;
  os << indent << "Aerosol optical       : " << m_AerosolOptical << std::endl;

}
} // end namespace otb
<|endoftext|>


<commit_before>#include <blackhole/formatter/string.hpp>
#include <blackhole/log.hpp>
#include <blackhole/repository.hpp>
#include <blackhole/sink/files.hpp>

using namespace blackhole;

enum class level {
    debug,
    info,
    warning,
    error
};

void init() {
    repository_t<level>::instance().configure<
        sink::files_t<
            sink::files::boost_backend_t,
            sink::rotator_t<
                sink::files::boost_backend_t,
                sink::rotation::watcher::size_t
            >
        >,
        formatter::string_t
    >();

    formatter_config_t formatter("string");
    formatter["pattern"] = "[%(timestamp)s] [%(severity)s]: %(message)s";

    sink_config_t sink("files");
    sink["path"] = "blackhole.log";
    sink["autoflush"] = true;
    sink["rotation"]["pattern"] = "blackhole.log.%N";
    sink["rotation"]["backups"] = std::uint16_t(5);
    sink["rotation"]["size"] = std::uint64_t(1024);

    frontend_config_t frontend = { formatter, sink };
    log_config_t config{ "root", { frontend } };

    repository_t<level>::instance().init(config);
}

int main(int, char**) {
    init();
    verbose_logger_t<level> log = repository_t<level>::instance().root();

    for (int i = 0; i < 10; ++i) {
    BH_LOG(log, level::debug,   "[%d] %s - done", 0, "debug");
    BH_LOG(log, level::info,    "[%d] %s - done", 1, "info");
    BH_LOG(log, level::warning, "[%d] %s - done", 2, "warning");
    BH_LOG(log, level::error,   "[%d] %s - done", 3, "error");
    }

    return 0;
}
<commit_msg>Reduced rotation rate for files example with rotation.<commit_after>#include <blackhole/formatter/string.hpp>
#include <blackhole/log.hpp>
#include <blackhole/repository.hpp>
#include <blackhole/sink/files.hpp>

using namespace blackhole;

enum class level {
    debug,
    info,
    warning,
    error
};

void init() {
    repository_t<level>::instance().configure<
        sink::files_t<
            sink::files::boost_backend_t,
            sink::rotator_t<
                sink::files::boost_backend_t,
                sink::rotation::watcher::size_t
            >
        >,
        formatter::string_t
    >();

    formatter_config_t formatter("string");
    formatter["pattern"] = "[%(timestamp)s] [%(severity)s]: %(message)s";

    sink_config_t sink("files");
    sink["path"] = "blackhole.log";
    sink["autoflush"] = true;
    sink["rotation"]["pattern"] = "blackhole.log.%N";
    sink["rotation"]["backups"] = std::uint16_t(10);
    sink["rotation"]["size"] = std::uint64_t(100 * 1024);

    frontend_config_t frontend = { formatter, sink };
    log_config_t config{ "root", { frontend } };

    repository_t<level>::instance().init(config);
}

int main(int, char**) {
    init();
    verbose_logger_t<level> log = repository_t<level>::instance().root();

    for (int i = 0; i < 32; ++i) {
    BH_LOG(log, level::debug,   "[%d] %s - done", 0, "debug");
    BH_LOG(log, level::info,    "[%d] %s - done", 1, "info");
    BH_LOG(log, level::warning, "[%d] %s - done", 2, "warning");
    BH_LOG(log, level::error,   "[%d] %s - done", 3, "error");
    }

    return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2012-2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "clientversion.h"

#include "tinyformat.h"

#include <string>

/**
 * Name of client reported in the 'version' message. Report the same name
 * for both bitcoind and bitcoin-core, to make it harder for attackers to
 * target servers or GUI users specifically.
 */
const std::string CLIENT_NAME("PolishCoin - Satoshi");

/**
 * Client version number
 */
#define CLIENT_VERSION_SUFFIX ""

/**
 * The following part of the code determines the CLIENT_BUILD variable.
 * Several mechanisms are used for this:
 * * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
 *   generated by the build environment, possibly containing the output
 *   of git-describe in a macro called BUILD_DESC
 * * secondly, if this is an exported version of the code, GIT_ARCHIVE will
 *   be defined (automatically using the export-subst git attribute), and
 *   GIT_COMMIT will contain the commit id.
 * * then, three options exist for determining CLIENT_BUILD:
 *   * if BUILD_DESC is defined, use that literally (output of git-describe)
 *   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
 *   * otherwise, use v[maj].[min].[rev].[build]-unk
 * finally CLIENT_VERSION_SUFFIX is added
 */

//! First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#include "build.h"
#endif

//! git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
#define GIT_COMMIT_ID "c99dac5"
#define GIT_COMMIT_DATE "Sat, 4 Jul 2015 20:17:16 +1000"
#endif

#define BUILD_DESC_WITH_SUFFIX(maj, min, rev, build, suffix) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix)

#define BUILD_DESC_FROM_COMMIT(maj, min, rev, build, commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit

#define BUILD_DESC_FROM_UNKNOWN(maj, min, rev, build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"

#ifndef BUILD_DESC
#ifdef BUILD_SUFFIX
#define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX)
#elif defined(GIT_COMMIT_ID)
#define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#else
#define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#endif
#endif

#ifndef BUILD_DATE
#ifdef GIT_COMMIT_DATE
#define BUILD_DATE GIT_COMMIT_DATE
#else
#define BUILD_DATE __DATE__ ", " __TIME__
#endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);

static std::string FormatVersion(int nVersion)
{
    if (nVersion % 100 == 0)
        return strprintf("%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100);
    else
        return strprintf("%d.%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100, nVersion % 100);
}

std::string FormatFullVersion()
{
    return CLIENT_BUILD;
}

/**
 * Format the subversion field according to BIP 14 spec (https://github.com/bitcoin/bips/blob/master/bip-0014.mediawiki)
 */
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
{
    std::ostringstream ss;
    ss << "/";
    ss << name << ":" << FormatVersion(nClientVersion);
    if (!comments.empty())
    {
        std::vector<std::string>::const_iterator it(comments.begin());
        ss << "(" << *it;
        for(++it; it != comments.end(); ++it)
            ss << "; " << *it;
        ss << ")";
    }
    ss << "/";
    return ss.str();
}
<commit_msg>Version<commit_after>// Copyright (c) 2012-2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "clientversion.h"

#include "tinyformat.h"

#include <string>

/**
 * Name of client reported in the 'version' message. Report the same name
 * for both bitcoind and bitcoin-core, to make it harder for attackers to
 * target servers or GUI users specifically.
 */
const std::string CLIENT_NAME("PolishCoin");

/**
 * Client version number
 */
#define CLIENT_VERSION_SUFFIX ""

/**
 * The following part of the code determines the CLIENT_BUILD variable.
 * Several mechanisms are used for this:
 * * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
 *   generated by the build environment, possibly containing the output
 *   of git-describe in a macro called BUILD_DESC
 * * secondly, if this is an exported version of the code, GIT_ARCHIVE will
 *   be defined (automatically using the export-subst git attribute), and
 *   GIT_COMMIT will contain the commit id.
 * * then, three options exist for determining CLIENT_BUILD:
 *   * if BUILD_DESC is defined, use that literally (output of git-describe)
 *   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
 *   * otherwise, use v[maj].[min].[rev].[build]-unk
 * finally CLIENT_VERSION_SUFFIX is added
 */

//! First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#include "build.h"
#endif

//! git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
#define GIT_COMMIT_ID "c99dac5"
#define GIT_COMMIT_DATE "Sat, 4 Jul 2015 20:17:16 +1000"
#endif

#define BUILD_DESC_WITH_SUFFIX(maj, min, rev, build, suffix) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix)

#define BUILD_DESC_FROM_COMMIT(maj, min, rev, build, commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit

#define BUILD_DESC_FROM_UNKNOWN(maj, min, rev, build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"

#ifndef BUILD_DESC
#ifdef BUILD_SUFFIX
#define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX)
#elif defined(GIT_COMMIT_ID)
#define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#else
#define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#endif
#endif

#ifndef BUILD_DATE
#ifdef GIT_COMMIT_DATE
#define BUILD_DATE GIT_COMMIT_DATE
#else
#define BUILD_DATE __DATE__ ", " __TIME__
#endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);

static std::string FormatVersion(int nVersion)
{
    if (nVersion % 100 == 0)
        return strprintf("%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100);
    else
        return strprintf("%d.%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100, nVersion % 100);
}

std::string FormatFullVersion()
{
    return CLIENT_BUILD;
}

/**
 * Format the subversion field according to BIP 14 spec (https://github.com/bitcoin/bips/blob/master/bip-0014.mediawiki)
 */
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
{
    std::ostringstream ss;
    ss << "/";
    ss << name << ":" << FormatVersion(nClientVersion);
    if (!comments.empty())
    {
        std::vector<std::string>::const_iterator it(comments.begin());
        ss << "(" << *it;
        for(++it; it != comments.end(); ++it)
            ss << "; " << *it;
        ss << ")";
    }
    ss << "/";
    return ss.str();
}
<|endoftext|>


<commit_before>// Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

// Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.

// Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

#include "CQMathMatrixWidget.h"

#include "copasi.h"

#include "qtUtilities.h"

#include "CopasiDataModel/CCopasiDataModel.h"
#include "report/CCopasiRootContainer.h"
#include "model/CModel.h"
#include "function/CExpression.h"

//activate display of test of symbolic derivatives
//#define _DERIV_TEST_

/**
 *  Constructs a CQMathMatrixWidget which is a child of 'parent', with the
 *  name 'name' and widget flags set to 'f'.
 */
CQMathMatrixWidget::CQMathMatrixWidget(QWidget* parent)
  : CopasiWidget(parent)
{
  setupUi(this);

  CColorScaleSimple * tcs = new CColorScaleSimple();
  mpArrayWidget1->setColorCoding(tcs);
  tcs->setMinMax(-1.5, 1.5);
  mpArrayWidget1->setColorScalingAutomatic(false);

  tcs = new CColorScaleSimple();
  mpArrayWidget2->setColorCoding(tcs);
  tcs->setMinMax(-1.5, 1.5);
  mpArrayWidget2->setColorScalingAutomatic(false);

  tcs = new CColorScaleSimple();
  mpArrayWidget3->setColorCoding(tcs);
  tcs->setMinMax(-1.5, 1.5);
  mpArrayWidget3->setColorScalingAutomatic(false);

#ifdef _DERIV_TEST_
  connect(mpDerivButton, SIGNAL(clicked()), this, SLOT(slotDerivButtonPressed()));
#else

  if (mpTabWidget->count())
    mpTabWidget->removeTab(mpTabWidget->count() - 1);

#endif
}

/*
 *  Destroys the object and frees any allocated resources
 */
CQMathMatrixWidget::~CQMathMatrixWidget()
{}

void CQMathMatrixWidget::loadMatrices()
{

  assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
  const CModel* pModel = CCopasiRootContainer::getDatamodelList()->operator[](0).getModel();

  const CArrayAnnotation * tmp;

  tmp = dynamic_cast<const CArrayAnnotation *>
        (pModel->getObject(CCopasiObjectName("Array=Stoichiometry(ann)")));
  mpArrayWidget1->setArrayAnnotation(tmp);

  tmp = dynamic_cast<const CArrayAnnotation *>
        (pModel->getObject(CCopasiObjectName("Array=Reduced stoichiometry(ann)")));
  mpArrayWidget2->setArrayAnnotation(tmp);

  tmp = dynamic_cast<const CArrayAnnotation *>
        (pModel->getObject(CCopasiObjectName("Array=Link matrix(ann)")));
  mpArrayWidget3->setArrayAnnotation(tmp);
}

void CQMathMatrixWidget::clearArrays()
{
  mpArrayWidget1->setArrayAnnotation(NULL);
  mpArrayWidget2->setArrayAnnotation(NULL);
  mpArrayWidget3->setArrayAnnotation(NULL);
}

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

bool CQMathMatrixWidget::update(ListViews::ObjectType C_UNUSED(objectType), ListViews::Action
                                C_UNUSED(action), const std::string & C_UNUSED(key))
{
  clearArrays();
  return true;
}

bool CQMathMatrixWidget::leave()
{
  return true;
}

bool CQMathMatrixWidget::enterProtected()
{
  loadMatrices();

  return true;
}

#include <qtablewidget.h>

void CQMathMatrixWidget::slotDerivButtonPressed()
{
#ifdef _DERIV_TEST_
  std::cout << "Deriv" << std::endl;

  CModel* pModel = &CCopasiRootContainer::getDatamodelList()->operator[](0).getModel();
  CEvaluationNode* tmpnode = pModel->prepareElasticity(pModel->getReactions()[0],
                             pModel->getMetabolites()[0], false);

  CEvaluationNode* tmpnode2 = pModel->prepareElasticity(pModel->getReactions()[0],
                              pModel->getMetabolites()[0], true);

  //create empty environment. Variable nodes should not occur in an expression
  std::vector<std::vector<std::string> > env;

  std::string tmpstring = tmpnode->buildMMLString(false, env);
  std::string tmpstring2 = tmpnode2->buildMMLString(false, env);

  mpMML->setBaseFontPointSize(qApp->font().pointSize());
  mpMML->setFontName(QtMmlWidget::NormalFont, qApp->font().family());

  mpMML->setContent(tmpstring.c_str());

  mpMML2->setBaseFontPointSize(qApp->font().pointSize());
  mpMML2->setFontName(QtMmlWidget::NormalFont, qApp->font().family());

  mpMML2->setContent(tmpstring2.c_str());

  QTableWidget * pTable = new QTableWidget(pModel->getReactions().size(), pModel->getMetabolites().size());
  pTable->show();

  int i, imax = pModel->getMetabolites().size();
  int j, jmax = pModel->getReactions().size();

  for (i = 0; i < imax; ++i)
    for (j = 0; j < jmax; ++j)
      {
        //CEvaluationNode* tmpnode = pModel->prepareElasticity(pModel->getReactions()[j],
        //                                                     pModel->getMetabolites()[i], false);

        CEvaluationNode* tmpnode2 = pModel->prepareElasticity(pModel->getReactions()[j],
                                    pModel->getMetabolites()[i], true);

        //evaluate
        CExpression * tmpExp = new CExpression("tmp expr", pModel);
        tmpExp->setRoot(tmpnode2);
        tmpExp->compile();
        std::cout << tmpExp->calcValue() << std::endl;

        //create empty environment. Variable nodes should not occur in an expression
        std::vector<std::vector<std::string> > env;

        //std::string tmpstring = tmpnode->buildMMLString(false, env);
        std::string tmpstring2 = tmpnode2->buildMMLString(false, env);

        QtMmlWidget* tmpmml = new QtMmlWidget();
        tmpmml->setBaseFontPointSize(qApp->font().pointSize() - 2);
        tmpmml->setFontName(QtMmlWidget::NormalFont, qApp->font().family());
        tmpmml->setContent(tmpstring2.c_str());
        pTable->setCellWidget(j, i, tmpmml);

        //tmpmml = new QtMmlWidget();
        //tmpmml->setBaseFontPointSize(qApp->font().pointSize()-2);
        //tmpmml->setFontName(QtMmlWidget::NormalFont, qApp->font().family());
        //tmpmml->setContent(tmpstring.c_str());
        //pTable->setCellWidget(i, 1, tmpmml);
      }

  pTable->resizeColumnsToContents();
  pTable->resizeRowsToContents();
#endif
}
<commit_msg>make the test code for derivatives compile again<commit_after>// Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

// Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.

// Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

#include "CQMathMatrixWidget.h"

#include "copasi.h"

#include "qtUtilities.h"

#include "CopasiDataModel/CCopasiDataModel.h"
#include "report/CCopasiRootContainer.h"
#include "model/CModel.h"
#include "function/CExpression.h"

//activate display of test of symbolic derivatives
//#define _DERIV_TEST_

/**
 *  Constructs a CQMathMatrixWidget which is a child of 'parent', with the
 *  name 'name' and widget flags set to 'f'.
 */
CQMathMatrixWidget::CQMathMatrixWidget(QWidget* parent)
  : CopasiWidget(parent)
{
  setupUi(this);

  CColorScaleSimple * tcs = new CColorScaleSimple();
  mpArrayWidget1->setColorCoding(tcs);
  tcs->setMinMax(-1.5, 1.5);
  mpArrayWidget1->setColorScalingAutomatic(false);

  tcs = new CColorScaleSimple();
  mpArrayWidget2->setColorCoding(tcs);
  tcs->setMinMax(-1.5, 1.5);
  mpArrayWidget2->setColorScalingAutomatic(false);

  tcs = new CColorScaleSimple();
  mpArrayWidget3->setColorCoding(tcs);
  tcs->setMinMax(-1.5, 1.5);
  mpArrayWidget3->setColorScalingAutomatic(false);

#ifdef _DERIV_TEST_
  connect(mpDerivButton, SIGNAL(clicked()), this, SLOT(slotDerivButtonPressed()));
#else

  if (mpTabWidget->count())
    mpTabWidget->removeTab(mpTabWidget->count() - 1);

#endif
}

/*
 *  Destroys the object and frees any allocated resources
 */
CQMathMatrixWidget::~CQMathMatrixWidget()
{}

void CQMathMatrixWidget::loadMatrices()
{

  assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
  const CModel* pModel = CCopasiRootContainer::getDatamodelList()->operator[](0).getModel();

  const CArrayAnnotation * tmp;

  tmp = dynamic_cast<const CArrayAnnotation *>
        (pModel->getObject(CCopasiObjectName("Array=Stoichiometry(ann)")));
  mpArrayWidget1->setArrayAnnotation(tmp);

  tmp = dynamic_cast<const CArrayAnnotation *>
        (pModel->getObject(CCopasiObjectName("Array=Reduced stoichiometry(ann)")));
  mpArrayWidget2->setArrayAnnotation(tmp);

  tmp = dynamic_cast<const CArrayAnnotation *>
        (pModel->getObject(CCopasiObjectName("Array=Link matrix(ann)")));
  mpArrayWidget3->setArrayAnnotation(tmp);
}

void CQMathMatrixWidget::clearArrays()
{
  mpArrayWidget1->setArrayAnnotation(NULL);
  mpArrayWidget2->setArrayAnnotation(NULL);
  mpArrayWidget3->setArrayAnnotation(NULL);
}

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

bool CQMathMatrixWidget::update(ListViews::ObjectType C_UNUSED(objectType), ListViews::Action
                                C_UNUSED(action), const std::string & C_UNUSED(key))
{
  clearArrays();
  return true;
}

bool CQMathMatrixWidget::leave()
{
  return true;
}

bool CQMathMatrixWidget::enterProtected()
{
  loadMatrices();

  return true;
}

#include <qtablewidget.h>

void CQMathMatrixWidget::slotDerivButtonPressed()
{
#ifdef _DERIV_TEST_
  std::cout << "Deriv" << std::endl;

  CModel* pModel = CCopasiRootContainer::getDatamodelList()->operator[](0).getModel();
  CEvaluationNode* tmpnode = pModel->prepareElasticity(&pModel->getReactions()[0],
                             &pModel->getMetabolites()[0], false);

  CEvaluationNode* tmpnode2 = pModel->prepareElasticity(&pModel->getReactions()[0],
                              &pModel->getMetabolites()[0], true);

  //create empty environment. Variable nodes should not occur in an expression
  std::vector<std::vector<std::string> > env;

  std::string tmpstring = tmpnode->buildMMLString(false, env);
  std::string tmpstring2 = tmpnode2->buildMMLString(false, env);

  mpMML->setBaseFontPointSize(qApp->font().pointSize());
  mpMML->setFontName(QtMmlWidget::NormalFont, qApp->font().family());

  mpMML->setContent(tmpstring.c_str());

  mpMML2->setBaseFontPointSize(qApp->font().pointSize());
  mpMML2->setFontName(QtMmlWidget::NormalFont, qApp->font().family());

  mpMML2->setContent(tmpstring2.c_str());

  QTableWidget * pTable = new QTableWidget(pModel->getReactions().size(), pModel->getMetabolites().size());
  pTable->show();

  int i, imax = pModel->getMetabolites().size();
  int j, jmax = pModel->getReactions().size();

  for (i = 0; i < imax; ++i)
    for (j = 0; j < jmax; ++j)
      {
        //CEvaluationNode* tmpnode = pModel->prepareElasticity(pModel->getReactions()[j],
        //                                                     pModel->getMetabolites()[i], false);

        CEvaluationNode* tmpnode2 = pModel->prepareElasticity(&pModel->getReactions()[j],
                                    &pModel->getMetabolites()[i], true);

        //evaluate
        CExpression * tmpExp = new CExpression("tmp expr", pModel);
        tmpExp->setRoot(tmpnode2);
        tmpExp->compile();
        std::cout << tmpExp->calcValue() << std::endl;

        //create empty environment. Variable nodes should not occur in an expression
        std::vector<std::vector<std::string> > env;

        //std::string tmpstring = tmpnode->buildMMLString(false, env);
        std::string tmpstring2 = tmpnode2->buildMMLString(false, env);

        QtMmlWidget* tmpmml = new QtMmlWidget();
        tmpmml->setBaseFontPointSize(qApp->font().pointSize() - 2);
        tmpmml->setFontName(QtMmlWidget::NormalFont, qApp->font().family());
        tmpmml->setContent(tmpstring2.c_str());
        pTable->setCellWidget(j, i, tmpmml);

        //tmpmml = new QtMmlWidget();
        //tmpmml->setBaseFontPointSize(qApp->font().pointSize()-2);
        //tmpmml->setFontName(QtMmlWidget::NormalFont, qApp->font().family());
        //tmpmml->setContent(tmpstring.c_str());
        //pTable->setCellWidget(i, 1, tmpmml);
      }

  pTable->resizeColumnsToContents();
  pTable->resizeRowsToContents();
#endif
}
<|endoftext|>


<commit_before>// CChemEqElement
//
// A class describing an element of a chemical equation
// (C) Stefan Hoops 2001
//

#include "copasi.h"
#include "CChemEq.h"

CChemEq::CChemEq(){};

CChemEq::CChemEq(const CChemEq & src)
{
  mChemicalEquation = src.mChemicalEquation;
  mChemicalEquationConverted = src.mChemicalEquationConverted;
  mSubstrates = src.mSubstrates;
  mProducts = src.mProducts;
  mBalances = src.mBalances;
}

CChemEq::~CChemEq(){cleanup();}

void CChemEq::cleanup()
{
  mSubstrates.cleanup();
  mProducts.cleanup();
  mBalances.cleanup();
}

void CChemEq::compile(CCopasiVectorN < CCompartment > & compartments)
{
  compileChemEqElements(mSubstrates, compartments);
  compileChemEqElements(mProducts, compartments);
  compileChemEqElements(mBalances, compartments);
}

void CChemEq::setChemicalEquation(const string & chemicalEquation)
{
  string Substrates, Products;

  mChemicalEquation = chemicalEquation;

  splitChemEq(Substrates, Products);

  setChemEqElements(mSubstrates, Substrates);

  setChemEqElements(mProducts, Products);

  setChemEqElements(mBalances, Substrates, CChemEq::SUBSTRATE);
  setChemEqElements(mBalances, Products);

  writeChemicalEquation();
  writeChemicalEquationConverted();
}

const string & CChemEq::getChemicalEquation() const
{return mChemicalEquation;}

const string & CChemEq::getChemicalEquationConverted() const
{return mChemicalEquationConverted;}

const CCopasiVector < CChemEqElement > & CChemEq::getSubstrates()
{return mSubstrates;}

const CCopasiVector < CChemEqElement > & CChemEq::getProducts()
{return mProducts;}

const CCopasiVector < CChemEqElement > & CChemEq::getBalances()
{return mBalances;}

CChemEqElement CChemEq::extractElement(const string & input,
				       string::size_type & pos) const
{
  CChemEqElement Element;
  string Value;

  string::size_type Start = input.find_first_not_of(" ", pos);
  string::size_type End = input.find("+", Start);
  string::size_type Multiplier = input.find("*", Start);
  string::size_type NameStart;
  string::size_type NameEnd;

  if (Multiplier == string::npos || Multiplier > End)
    {
      NameStart = Start;
      Element.setMultiplicity(1.0);
    }
  else
    {
      NameStart = input.find_first_not_of(" ",Multiplier+1);
      Value = input.substr(Start, Multiplier - Start);
      Element.setMultiplicity(atof(Value.c_str()));
    }

  NameEnd = input.find_first_of(" +", NameStart);
  if (NameStart != string::npos)
    Element.setMetaboliteName(input.substr(NameStart, NameEnd - NameStart));

  pos = (End == string::npos) ? End: End+1;
  return Element;
}

void CChemEq::addElement(CCopasiVector < CChemEqElement > & structure,
			 const CChemEqElement & element,
			 CChemEq::MetaboliteRole role)
{
  unsigned C_INT32 i;

  string Name = element.getMetaboliteName();
  for (i=0; i < structure.size(); i++)
    if (Name == structure[i]->getMetaboliteName()) break;

  if (i >= structure.size())
    {
      CChemEqElement * Element = new CChemEqElement(element);
      if (role == CChemEq::SUBSTRATE)
	Element->setMultiplicity(- Element->getMultiplicity());
      structure.add(Element);
    }
  else if (role == CChemEq::SUBSTRATE)
    structure[i]->addToMultiplicity(- element.getMultiplicity());
  else
    structure[i]->addToMultiplicity(element.getMultiplicity());
}

void CChemEq::setChemEqElements(CCopasiVector < CChemEqElement >
                                & elements,
				const string & reaction,
				CChemEq::MetaboliteRole role)
{
  string::size_type pos = 0;

  while (pos != string::npos)
    addElement(elements, extractElement(reaction, pos), role);
}

#ifdef XXXX
void CChemEq::cleanupChemEqElements(vector < CChemEqElement * > & elements)
{
  for (unsigned C_INT32 i=0; i<elements.size(); i++)
    free(elements[i]);
  elements.clear();
}
#endif // XXXX

void CChemEq::splitChemEq(string & left, string & right) const
{
  string::size_type equal = string::npos;
  string Separator[] = {"->", "=>", "=", ""};
  unsigned C_INT32 i=0;

  while (*Separator != "" && equal == string::npos)
      equal = mChemicalEquation.find(Separator[i++]);
  if (equal == string::npos) fatalError();

  right = mChemicalEquation.substr(equal+(Separator[--i].length()));
  left = mChemicalEquation.substr(0,equal);

  return;
}

void
CChemEq::compileChemEqElements(CCopasiVector < CChemEqElement > & elements,
			       CCopasiVectorN < CCompartment > & compartments)
{
  unsigned C_INT32 i, imax = elements.size();

  for (i=0; i<imax; i++)
    elements[i]->compile(compartments);
}

void CChemEq::writeChemicalEquation()
{
  string::size_type equal = string::npos;
  string Separator[] = {"->", "=>", "=", ""};
  unsigned C_INT32 i=0, j;

  while (Separator[i] != "" && equal == string::npos)
      equal = mChemicalEquation.find(Separator[i++]);
  if (equal == string::npos) fatalError();

  mChemicalEquation.erase();

  for (j=0; j<mSubstrates.size(); j++)
    {
      if (j) mChemicalEquation += " + ";
      mChemicalEquation += mSubstrates[j]->writeElement();
    }

  mChemicalEquation += " " + Separator[--i] + " ";

  for (j=0; j<mProducts.size(); j++)
    {
      if (j) mChemicalEquation += " + ";
      mChemicalEquation += mProducts[j]->writeElement();
    }

}

void CChemEq::writeChemicalEquationConverted()
{
  string::size_type equal = string::npos;
  string Separator[] = {"->", "=>", "=", ""};
  unsigned C_INT32 i=0, j, k, kmax;

  while (Separator[i] != "" && equal == string::npos)
      equal = mChemicalEquation.find(Separator[i++]);
  if (equal == string::npos) fatalError();

  mChemicalEquationConverted.erase();

  for (j=0; j<mSubstrates.size(); j++)
    {
      if (j) mChemicalEquationConverted += " + ";
      kmax = (unsigned C_INT32) mSubstrates[j]->getMultiplicity();

      for (k=0; k<kmax; k++)
	{
	  if (k) mChemicalEquationConverted += " + ";
	  mChemicalEquationConverted += mSubstrates[j]->getMetaboliteName();
	}
    }

  mChemicalEquationConverted += " " + Separator[--i] + " ";

  for (j=0; j<mProducts.size(); j++)
    {
      if (j) mChemicalEquation += " + ";
      kmax = (unsigned C_INT32) mProducts[j]->getMultiplicity();

      for (k=0; k<kmax; k++)
	{
	  if (k) mChemicalEquationConverted += " + ";
	  mChemicalEquationConverted += mProducts[j]->getMetaboliteName();
	}
    }
}

<commit_msg>Fixed error in writeChemicalEquationConverted<commit_after>// CChemEqElement
//
// A class describing an element of a chemical equation
// (C) Stefan Hoops 2001
//

#include "copasi.h"
#include "CChemEq.h"

CChemEq::CChemEq(){};

CChemEq::CChemEq(const CChemEq & src)
{
  mChemicalEquation = src.mChemicalEquation;
  mChemicalEquationConverted = src.mChemicalEquationConverted;
  mSubstrates = src.mSubstrates;
  mProducts = src.mProducts;
  mBalances = src.mBalances;
}

CChemEq::~CChemEq(){cleanup();}

void CChemEq::cleanup()
{
  mSubstrates.cleanup();
  mProducts.cleanup();
  mBalances.cleanup();
}

void CChemEq::compile(CCopasiVectorN < CCompartment > & compartments)
{
  compileChemEqElements(mSubstrates, compartments);
  compileChemEqElements(mProducts, compartments);
  compileChemEqElements(mBalances, compartments);
}

void CChemEq::setChemicalEquation(const string & chemicalEquation)
{
  string Substrates, Products;

  mChemicalEquation = chemicalEquation;

  splitChemEq(Substrates, Products);

  setChemEqElements(mSubstrates, Substrates);

  setChemEqElements(mProducts, Products);

  setChemEqElements(mBalances, Substrates, CChemEq::SUBSTRATE);
  setChemEqElements(mBalances, Products);

  writeChemicalEquation();
  writeChemicalEquationConverted();
}

const string & CChemEq::getChemicalEquation() const
{return mChemicalEquation;}

const string & CChemEq::getChemicalEquationConverted() const
{return mChemicalEquationConverted;}

const CCopasiVector < CChemEqElement > & CChemEq::getSubstrates()
{return mSubstrates;}

const CCopasiVector < CChemEqElement > & CChemEq::getProducts()
{return mProducts;}

const CCopasiVector < CChemEqElement > & CChemEq::getBalances()
{return mBalances;}

CChemEqElement CChemEq::extractElement(const string & input,
				       string::size_type & pos) const
{
  CChemEqElement Element;
  string Value;

  string::size_type Start = input.find_first_not_of(" ", pos);
  string::size_type End = input.find("+", Start);
  string::size_type Multiplier = input.find("*", Start);
  string::size_type NameStart;
  string::size_type NameEnd;

  if (Multiplier == string::npos || Multiplier > End)
    {
      NameStart = Start;
      Element.setMultiplicity(1.0);
    }
  else
    {
      NameStart = input.find_first_not_of(" ",Multiplier+1);
      Value = input.substr(Start, Multiplier - Start);
      Element.setMultiplicity(atof(Value.c_str()));
    }

  NameEnd = input.find_first_of(" +", NameStart);
  if (NameStart != string::npos)
    Element.setMetaboliteName(input.substr(NameStart, NameEnd - NameStart));

  pos = (End == string::npos) ? End: End+1;
  return Element;
}

void CChemEq::addElement(CCopasiVector < CChemEqElement > & structure,
			 const CChemEqElement & element,
			 CChemEq::MetaboliteRole role)
{
  unsigned C_INT32 i;

  string Name = element.getMetaboliteName();
  for (i=0; i < structure.size(); i++)
    if (Name == structure[i]->getMetaboliteName()) break;

  if (i >= structure.size())
    {
      CChemEqElement * Element = new CChemEqElement(element);
      if (role == CChemEq::SUBSTRATE)
	Element->setMultiplicity(- Element->getMultiplicity());
      structure.add(Element);
    }
  else if (role == CChemEq::SUBSTRATE)
    structure[i]->addToMultiplicity(- element.getMultiplicity());
  else
    structure[i]->addToMultiplicity(element.getMultiplicity());
}

void CChemEq::setChemEqElements(CCopasiVector < CChemEqElement >
                                & elements,
				const string & reaction,
				CChemEq::MetaboliteRole role)
{
  string::size_type pos = 0;

  while (pos != string::npos)
    addElement(elements, extractElement(reaction, pos), role);
}

#ifdef XXXX
void CChemEq::cleanupChemEqElements(vector < CChemEqElement * > & elements)
{
  for (unsigned C_INT32 i=0; i<elements.size(); i++)
    free(elements[i]);
  elements.clear();
}
#endif // XXXX

void CChemEq::splitChemEq(string & left, string & right) const
{
  string::size_type equal = string::npos;
  string Separator[] = {"->", "=>", "=", ""};
  unsigned C_INT32 i=0;

  while (*Separator != "" && equal == string::npos)
      equal = mChemicalEquation.find(Separator[i++]);
  if (equal == string::npos) fatalError();

  right = mChemicalEquation.substr(equal+(Separator[--i].length()));
  left = mChemicalEquation.substr(0,equal);

  return;
}

void
CChemEq::compileChemEqElements(CCopasiVector < CChemEqElement > & elements,
			       CCopasiVectorN < CCompartment > & compartments)
{
  unsigned C_INT32 i, imax = elements.size();

  for (i=0; i<imax; i++)
    elements[i]->compile(compartments);
}

void CChemEq::writeChemicalEquation()
{
  string::size_type equal = string::npos;
  string Separator[] = {"->", "=>", "=", ""};
  unsigned C_INT32 i=0, j;

  while (Separator[i] != "" && equal == string::npos)
      equal = mChemicalEquation.find(Separator[i++]);
  if (equal == string::npos) fatalError();

  mChemicalEquation.erase();

  for (j=0; j<mSubstrates.size(); j++)
    {
      if (j) mChemicalEquation += " + ";
      mChemicalEquation += mSubstrates[j]->writeElement();
    }

  mChemicalEquation += " " + Separator[--i] + " ";

  for (j=0; j<mProducts.size(); j++)
    {
      if (j) mChemicalEquation += " + ";
      mChemicalEquation += mProducts[j]->writeElement();
    }

}

void CChemEq::writeChemicalEquationConverted()
{
  string::size_type equal = string::npos;
  string Separator[] = {"->", "=>", "=", ""};
  unsigned C_INT32 i=0, j, k, kmax;

  while (Separator[i] != "" && equal == string::npos)
      equal = mChemicalEquation.find(Separator[i++]);
  if (equal == string::npos) fatalError();

  mChemicalEquationConverted.erase();

  for (j=0; j<mSubstrates.size(); j++)
    {
      if (j) mChemicalEquationConverted += " + ";
      kmax = (unsigned C_INT32) mSubstrates[j]->getMultiplicity();

      for (k=0; k<kmax; k++)
	{
	  if (k) mChemicalEquationConverted += " + ";
	  mChemicalEquationConverted += mSubstrates[j]->getMetaboliteName();
	}
    }

  mChemicalEquationConverted += " " + Separator[--i] + " ";

  for (j=0; j<mProducts.size(); j++)
    {
      if (j) mChemicalEquationConverted += " + ";
      kmax = (unsigned C_INT32) mProducts[j]->getMultiplicity();

      for (k=0; k<kmax; k++)
	{
	  if (k) mChemicalEquationConverted += " + ";
	  mChemicalEquationConverted += mProducts[j]->getMetaboliteName();
	}
    }
}

<|endoftext|>


<commit_before>/*
   This file is part of the clazy static checker.

  Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com
  Author: Sérgio Martins <sergio.martins@kdab.com>

  Copyright (C) 2015 Sergio Martins <smartins@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 as published by the Free Software Foundation; either
  version 2 of the License, or (at your option) any later version.

  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 "writingtotemporary.h"
#include "Utils.h"
#include "checkmanager.h"
#include "StringUtils.h"

#include <clang/AST/AST.h>
#include <clang/Lex/Lexer.h>

using namespace clang;
using namespace std;

WritingToTemporary::WritingToTemporary(const std::string &name, const clang::CompilerInstance &ci)
    : CheckBase(name, ci)
    , m_widenCriteria(isOptionSet("widen-criteria"))
{
}

std::vector<string> WritingToTemporary::filesToIgnore() const
{
    static const vector<string> files = { "qstring.h" };
    return files;
}

vector<string> WritingToTemporary::supportedOptions() const
{
    static const vector<string> options = { "widen-criteria" };
    return options;
}

static bool isDisallowedClass(const string &className)
{
    static const vector<string> disallowed = { "QTextCursor", "QDomElement", "KConfigGroup", "QWebElement",
                                               "QScriptValue", "QTextLine", "QTextBlock", "QDomNode" };
    return clazy_std::contains(disallowed, className);
}

static bool isKnownType(const string &className)
{
    static const vector<string> types = { "QList", "QVector", "QMap", "QHash", "QString", "QSet",
                                          "QByteArray", "QUrl", "QVarLengthArray", "QLinkedList",
                                          "QRect", "QRectF", "QBitmap", "QVector2D", "QVector3D"
                                          , "QVector4D", "QSize", "QSizeF", "QSizePolicy" };

    return clazy_std::contains(types, className);
}

void WritingToTemporary::VisitStmt(clang::Stmt *stmt)
{
    CallExpr *callExpr = dyn_cast<CallExpr>(stmt);
    if (!callExpr)
        return;

    // For a chain like getFoo().setBar(), returns {setBar(), getFoo()}
    vector<CallExpr *> callExprs = Utils::callListForChain(callExpr);
    if (callExprs.size() < 2)
        return;

    CallExpr *firstCallToBeEvaluated = callExprs.at(callExprs.size() - 1); // This is the call to getFoo()
    FunctionDecl *firstFunc = firstCallToBeEvaluated->getDirectCallee();
    if (!firstFunc)
        return;

    CallExpr *secondCallToBeEvaluated = callExprs.at(callExprs.size() - 2); // This is the call to setBar()
    FunctionDecl *secondFunc = secondCallToBeEvaluated->getDirectCallee();
    if (!secondFunc)
        return;

    CXXMethodDecl *secondMethod = dyn_cast<CXXMethodDecl>(secondFunc);
    if (!secondMethod || secondMethod->isConst() || secondMethod->isStatic())
        return;

    CXXRecordDecl *record = secondMethod->getParent();
    if (!record)
        return;

    if (isDisallowedClass(record->getNameAsString()))
        return;

    QualType qt = firstFunc->getReturnType();
    const Type *firstFuncReturnType = qt.getTypePtrOrNull();
    if (!firstFuncReturnType || firstFuncReturnType->isPointerType() || firstFuncReturnType->isReferenceType())
        return;

    qt = secondFunc->getReturnType();
    const Type *secondFuncReturnType = qt.getTypePtrOrNull();
    if (!secondFuncReturnType || !secondFuncReturnType->isVoidType())
        return;

    if (!isKnownType(record->getNameAsString()) && !stringStartsWith(secondFunc->getNameAsString(), "set") && !m_widenCriteria)
        return;

    emitWarning(stmt->getLocStart(), "Call to temporary is a no-op: " + secondFunc->getQualifiedNameAsString());
}

REGISTER_CHECK_WITH_FLAGS("writing-to-temporary", WritingToTemporary, CheckLevel0)
<commit_msg>writing-to-temporary: Add QPoint and QPointF<commit_after>/*
   This file is part of the clazy static checker.

  Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com
  Author: Sérgio Martins <sergio.martins@kdab.com>

  Copyright (C) 2015 Sergio Martins <smartins@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 as published by the Free Software Foundation; either
  version 2 of the License, or (at your option) any later version.

  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 "writingtotemporary.h"
#include "Utils.h"
#include "checkmanager.h"
#include "StringUtils.h"

#include <clang/AST/AST.h>
#include <clang/Lex/Lexer.h>

using namespace clang;
using namespace std;

WritingToTemporary::WritingToTemporary(const std::string &name, const clang::CompilerInstance &ci)
    : CheckBase(name, ci)
    , m_widenCriteria(isOptionSet("widen-criteria"))
{
}

std::vector<string> WritingToTemporary::filesToIgnore() const
{
    static const vector<string> files = { "qstring.h" };
    return files;
}

vector<string> WritingToTemporary::supportedOptions() const
{
    static const vector<string> options = { "widen-criteria" };
    return options;
}

static bool isDisallowedClass(const string &className)
{
    static const vector<string> disallowed = { "QTextCursor", "QDomElement", "KConfigGroup", "QWebElement",
                                               "QScriptValue", "QTextLine", "QTextBlock", "QDomNode" };
    return clazy_std::contains(disallowed, className);
}

static bool isKnownType(const string &className)
{
    static const vector<string> types = { "QList", "QVector", "QMap", "QHash", "QString", "QSet",
                                          "QByteArray", "QUrl", "QVarLengthArray", "QLinkedList",
                                          "QRect", "QRectF", "QBitmap", "QVector2D", "QVector3D",
                                          "QVector4D", "QSize", "QSizeF", "QSizePolicy", "QPoint",
                                          "QPointF" };

    return clazy_std::contains(types, className);
}

void WritingToTemporary::VisitStmt(clang::Stmt *stmt)
{
    CallExpr *callExpr = dyn_cast<CallExpr>(stmt);
    if (!callExpr)
        return;

    // For a chain like getFoo().setBar(), returns {setBar(), getFoo()}
    vector<CallExpr *> callExprs = Utils::callListForChain(callExpr);
    if (callExprs.size() < 2)
        return;

    CallExpr *firstCallToBeEvaluated = callExprs.at(callExprs.size() - 1); // This is the call to getFoo()
    FunctionDecl *firstFunc = firstCallToBeEvaluated->getDirectCallee();
    if (!firstFunc)
        return;

    CallExpr *secondCallToBeEvaluated = callExprs.at(callExprs.size() - 2); // This is the call to setBar()
    FunctionDecl *secondFunc = secondCallToBeEvaluated->getDirectCallee();
    if (!secondFunc)
        return;

    CXXMethodDecl *secondMethod = dyn_cast<CXXMethodDecl>(secondFunc);
    if (!secondMethod || secondMethod->isConst() || secondMethod->isStatic())
        return;

    CXXRecordDecl *record = secondMethod->getParent();
    if (!record)
        return;

    if (isDisallowedClass(record->getNameAsString()))
        return;

    QualType qt = firstFunc->getReturnType();
    const Type *firstFuncReturnType = qt.getTypePtrOrNull();
    if (!firstFuncReturnType || firstFuncReturnType->isPointerType() || firstFuncReturnType->isReferenceType())
        return;

    qt = secondFunc->getReturnType();
    const Type *secondFuncReturnType = qt.getTypePtrOrNull();
    if (!secondFuncReturnType || !secondFuncReturnType->isVoidType())
        return;

    if (!isKnownType(record->getNameAsString()) && !stringStartsWith(secondFunc->getNameAsString(), "set") && !m_widenCriteria)
        return;

    emitWarning(stmt->getLocStart(), "Call to temporary is a no-op: " + secondFunc->getQualifiedNameAsString());
}

REGISTER_CHECK_WITH_FLAGS("writing-to-temporary", WritingToTemporary, CheckLevel0)
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/filerepository.h"
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/random.h"
#include "fnord-base/thread/eventloop.h"
#include "fnord-base/thread/threadpool.h"
#include "fnord-base/thread/FixedSizeThreadPool.h"
#include "fnord-base/wallclock.h"
#include "fnord-base/VFS.h"
#include "fnord-rpc/ServerGroup.h"
#include "fnord-rpc/RPC.h"
#include "fnord-rpc/RPCClient.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-json/json.h"
#include "fnord-json/jsonrpc.h"
#include "fnord-http/httprouter.h"
#include "fnord-http/httpserver.h"
#include "fnord-http/VFSFileServlet.h"
#include "fnord-feeds/FeedService.h"
#include "fnord-feeds/RemoteFeedFactory.h"
#include "fnord-feeds/RemoteFeedReader.h"
#include "fnord-base/stats/statsdagent.h"
#include "fnord-sstable/SSTableServlet.h"
#include "fnord-logtable/LogTableServlet.h"
#include "fnord-logtable/TableRepository.h"
#include "fnord-logtable/TableJanitor.h"
#include "fnord-logtable/TableReplication.h"
#include "fnord-logtable/ArtifactReplication.h"
#include "fnord-logtable/ArtifactIndexReplication.h"
#include "fnord-logtable/NumericBoundsSummary.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "fnord-tsdb/TSDBNode.h"
#include "fnord-tsdb/TSDBServlet.h"
#include "common.h"
#include "schemas.h"
#include "ModelReplication.h"

using namespace fnord;

std::atomic<bool> shutdown_sig;
fnord::thread::EventLoop ev;

void quit(int n) {
  shutdown_sig = true;
  fnord::logInfo("cm.chunkserver", "Shutting down...");
  // FIXPAUL: wait for http server stop...
  ev.shutdown();
}

int main(int argc, const char** argv) {
  fnord::Application::init();
  fnord::Application::logToStderr();

  /* shutdown hook */
  shutdown_sig = false;
  struct sigaction sa;
  memset(&sa, 0, sizeof(struct sigaction));
  sa.sa_handler = quit;
  sigaction(SIGTERM, &sa, NULL);
  sigaction(SIGQUIT, &sa, NULL);
  sigaction(SIGINT, &sa, NULL);

  fnord::cli::FlagParser flags;

  flags.defineFlag(
      "http_port",
      fnord::cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "8000",
      "Start the public http server on this port",
      "<port>");

  flags.defineFlag(
      "datadir",
      cli::FlagParser::T_STRING,
      true,
      NULL,
      NULL,
      "datadir path",
      "<path>");

  flags.defineFlag(
      "replicate_to",
      cli::FlagParser::T_STRING,
      false,
      NULL,
      NULL,
      "url",
      "<url>");

  flags.defineFlag(
      "loglevel",
      fnord::cli::FlagParser::T_STRING,
      false,
      NULL,
      "INFO",
      "loglevel",
      "<level>");

  flags.parseArgv(argc, argv);

  Logger::get()->setMinimumLogLevel(
      strToLogLevel(flags.getString("loglevel")));

  /* args */
  auto dir = flags.getString("datadir");
  auto repl_targets = flags.getStrings("replicate_to");

  /* start http server and worker pools */
  fnord::thread::ThreadPool tpool;
  http::HTTPConnectionPool http(&ev);
  fnord::http::HTTPRouter http_router;
  fnord::http::HTTPServer http_server(&http_router, &ev);
  http_server.listen(flags.getInt("http_port"));

  auto repl_scheme = mkRef(new dht::FixedReplicationScheme());
  for (const auto& r : repl_targets) {
    repl_scheme->addHost(r);
  }

  tsdb::TSDBNode tsdb_node(dir + "/tsdb", repl_scheme.get(), &http);

  tsdb::StreamProperties config(new msg::MessageSchema(joinedSessionsSchema()));
  config.max_datafile_size = 1024 * 1024 * 512;
  config.chunk_size = Duration(3600 * 4 * kMicrosPerSecond);
  config.compaction_interval = Duration(3 * kMicrosPerSecond);
  tsdb_node.configurePrefix("joined_sessions.", config);

  tsdb::TSDBServlet tsdb_servlet(&tsdb_node);
  http_router.addRouteByPrefixMatch("/tsdb", &tsdb_servlet, &tpool);

  tsdb_node.start();
  ev.run();

  tsdb_node.stop();
  fnord::logInfo("cm.chunkserver", "Exiting...");

  exit(0);
}

<commit_msg>30s commit interval<commit_after>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/filerepository.h"
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/random.h"
#include "fnord-base/thread/eventloop.h"
#include "fnord-base/thread/threadpool.h"
#include "fnord-base/thread/FixedSizeThreadPool.h"
#include "fnord-base/wallclock.h"
#include "fnord-base/VFS.h"
#include "fnord-rpc/ServerGroup.h"
#include "fnord-rpc/RPC.h"
#include "fnord-rpc/RPCClient.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-json/json.h"
#include "fnord-json/jsonrpc.h"
#include "fnord-http/httprouter.h"
#include "fnord-http/httpserver.h"
#include "fnord-http/VFSFileServlet.h"
#include "fnord-feeds/FeedService.h"
#include "fnord-feeds/RemoteFeedFactory.h"
#include "fnord-feeds/RemoteFeedReader.h"
#include "fnord-base/stats/statsdagent.h"
#include "fnord-sstable/SSTableServlet.h"
#include "fnord-logtable/LogTableServlet.h"
#include "fnord-logtable/TableRepository.h"
#include "fnord-logtable/TableJanitor.h"
#include "fnord-logtable/TableReplication.h"
#include "fnord-logtable/ArtifactReplication.h"
#include "fnord-logtable/ArtifactIndexReplication.h"
#include "fnord-logtable/NumericBoundsSummary.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "fnord-tsdb/TSDBNode.h"
#include "fnord-tsdb/TSDBServlet.h"
#include "common.h"
#include "schemas.h"
#include "ModelReplication.h"

using namespace fnord;

std::atomic<bool> shutdown_sig;
fnord::thread::EventLoop ev;

void quit(int n) {
  shutdown_sig = true;
  fnord::logInfo("cm.chunkserver", "Shutting down...");
  // FIXPAUL: wait for http server stop...
  ev.shutdown();
}

int main(int argc, const char** argv) {
  fnord::Application::init();
  fnord::Application::logToStderr();

  /* shutdown hook */
  shutdown_sig = false;
  struct sigaction sa;
  memset(&sa, 0, sizeof(struct sigaction));
  sa.sa_handler = quit;
  sigaction(SIGTERM, &sa, NULL);
  sigaction(SIGQUIT, &sa, NULL);
  sigaction(SIGINT, &sa, NULL);

  fnord::cli::FlagParser flags;

  flags.defineFlag(
      "http_port",
      fnord::cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "8000",
      "Start the public http server on this port",
      "<port>");

  flags.defineFlag(
      "datadir",
      cli::FlagParser::T_STRING,
      true,
      NULL,
      NULL,
      "datadir path",
      "<path>");

  flags.defineFlag(
      "replicate_to",
      cli::FlagParser::T_STRING,
      false,
      NULL,
      NULL,
      "url",
      "<url>");

  flags.defineFlag(
      "loglevel",
      fnord::cli::FlagParser::T_STRING,
      false,
      NULL,
      "INFO",
      "loglevel",
      "<level>");

  flags.parseArgv(argc, argv);

  Logger::get()->setMinimumLogLevel(
      strToLogLevel(flags.getString("loglevel")));

  /* args */
  auto dir = flags.getString("datadir");
  auto repl_targets = flags.getStrings("replicate_to");

  /* start http server and worker pools */
  fnord::thread::ThreadPool tpool;
  http::HTTPConnectionPool http(&ev);
  fnord::http::HTTPRouter http_router;
  fnord::http::HTTPServer http_server(&http_router, &ev);
  http_server.listen(flags.getInt("http_port"));

  auto repl_scheme = mkRef(new dht::FixedReplicationScheme());
  for (const auto& r : repl_targets) {
    repl_scheme->addHost(r);
  }

  tsdb::TSDBNode tsdb_node(dir + "/tsdb", repl_scheme.get(), &http);

  tsdb::StreamProperties config(new msg::MessageSchema(joinedSessionsSchema()));
  config.max_datafile_size = 1024 * 1024 * 512;
  config.chunk_size = Duration(3600 * 4 * kMicrosPerSecond);
  config.compaction_interval = Duration(30 * kMicrosPerSecond);
  tsdb_node.configurePrefix("joined_sessions.", config);

  tsdb::TSDBServlet tsdb_servlet(&tsdb_node);
  http_router.addRouteByPrefixMatch("/tsdb", &tsdb_servlet, &tpool);

  tsdb_node.start();
  ev.run();

  tsdb_node.stop();
  fnord::logInfo("cm.chunkserver", "Exiting...");

  exit(0);
}

<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include <algorithm>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-base/util/SimpleRateLimit.h"
#include "fnord-base/InternMap.h"
#include "fnord-json/json.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "fnord-sstable/sstablereader.h"
#include "fnord-sstable/sstablewriter.h"
#include "fnord-sstable/SSTableColumnSchema.h"
#include "fnord-sstable/SSTableColumnReader.h"
#include "fnord-sstable/SSTableColumnWriter.h"
#include "fnord-cstable/UInt16ColumnReader.h"
#include "fnord-cstable/UInt16ColumnWriter.h"
#include "fnord-cstable/CSTableWriter.h"
#include "fnord-cstable/CSTableReader.h"
#include "common.h"
#include "CustomerNamespace.h"
#include "FeatureSchema.h"
#include "JoinedQuery.h"
#include "CTRCounter.h"
#include "analytics/AnalyticsQuery.h"
#include "analytics/CTRByPositionQuery.h"

using namespace fnord;

int main(int argc, const char** argv) {
  fnord::Application::init();
  fnord::Application::logToStderr();

  fnord::cli::FlagParser flags;

  flags.defineFlag(
      "loglevel",
      fnord::cli::FlagParser::T_STRING,
      false,
      NULL,
      "INFO",
      "loglevel",
      "<level>");

  flags.parseArgv(argc, argv);

  Logger::get()->setMinimumLogLevel(
      strToLogLevel(flags.getString("loglevel")));

  size_t debug_n = 0;
  size_t debug_z = 0;

  /* query level */
  cstable::UInt16ColumnWriter jq_page_col(1, 1);

  /* query item level */
  cstable::UInt16ColumnWriter position_col(2, 2);
  cstable::UInt16ColumnWriter clicked_col(2, 2);

  uint64_t r = 0;
  uint64_t n = 0;

  auto add_session = [&] (const cm::JoinedSession& sess) {
    ++n;

    for (const auto& q : sess.queries) {
      auto pg_str = cm::extractAttr(q.attrs, "pg");
      if (pg_str.isEmpty()) {
        jq_page_col.addNull(r, 1);
      } else {
        jq_page_col.addDatum(r, 1, std::stoul(pg_str.get()));
      }

      if (q.items.size() == 0) {
        if (r==0) ++debug_z;
        position_col.addNull(r, 1);
        clicked_col.addNull(r, 1);
      }

      for (const auto& i : q.items) {
        ++debug_n;
        if (r==0) ++debug_z;

        position_col.addDatum(r, 2, i.position);
        clicked_col.addDatum(r, 2, i.clicked);
        r = 2;
      }

      r = 1;
    }

    r = 0;
  };

  /* read input tables */
  auto sstables = flags.getArgv();
  int row_idx = 0;
  for (int tbl_idx = 0; tbl_idx < sstables.size(); ++tbl_idx) {
    const auto& sstable = sstables[tbl_idx];
    fnord::logInfo("cm.jqcolumnize", "Importing sstable: $0", sstable);

    /* read sstable header */
    sstable::SSTableReader reader(File::openFile(sstable, File::O_READ));

    if (reader.bodySize() == 0) {
      fnord::logCritical("cm.jqcolumnize", "unfinished sstable: $0", sstable);
      exit(1);
    }

    /* get sstable cursor */
    auto cursor = reader.getCursor();
    auto body_size = reader.bodySize();

    /* status line */
    util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () {
      fnord::logInfo(
          "cm.jqcolumnize",
          "[$1/$2] [$0%] Reading sstable... rows=$3",
          (size_t) ((cursor->position() / (double) body_size) * 100),
          tbl_idx + 1, sstables.size(), row_idx);
    });

    /* read sstable rows */
    for (; cursor->valid(); ++row_idx) {
      status_line.runMaybe();

      auto key = cursor->getKeyString();
      auto val = cursor->getDataBuffer();
      Option<cm::JoinedQuery> q;

      try {
        q = Some(json::fromJSON<cm::JoinedQuery>(val));
      } catch (const Exception& e) {
        fnord::logWarning("cm.jqcolumnize", e, "invalid json: $0", val.toString());
      }

      if (!q.isEmpty()) {
        cm::JoinedSession s;
        s.queries.emplace_back(q.get());
        add_session(s);
      }

      if (!cursor->next()) {
        break;
      }
    }

    status_line.runForce();
  }

  if (sstables.size() > 0) {
    cstable::CSTableWriter writer("fnord.cstable", n);
    writer.addColumn("queries.items.position", &position_col);
    writer.addColumn("queries.items.clicked", &clicked_col);
    writer.commit();
  }

  cstable::CSTableReader reader("fnord.cstable");

  auto t0 = WallClock::unixMicros();

  cm::AnalyticsQuery aq;
  cm::CTRByPositionQuery q(&aq);
  aq.scanTable(&reader);
  auto t1 = WallClock::unixMicros();
  fnord::iputs("scanned $0 rows in $1 ms", q.rowsScanned(), (t1 - t0) / 1000.0f);
  for (const auto& p : q.results()) {
    fnord::iputs(
       "pos: $0, views: $1, clicks: $2, ctr: $3",
        p.first, p.second.num_views,
        p.second.num_clicks,
        p.second.num_clicks / (double) p.second.num_views);
  }

  return 0;
}

<commit_msg>CTRByPositionQueryResult<commit_after>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include <algorithm>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-base/util/SimpleRateLimit.h"
#include "fnord-base/InternMap.h"
#include "fnord-json/json.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "fnord-sstable/sstablereader.h"
#include "fnord-sstable/sstablewriter.h"
#include "fnord-sstable/SSTableColumnSchema.h"
#include "fnord-sstable/SSTableColumnReader.h"
#include "fnord-sstable/SSTableColumnWriter.h"
#include "fnord-cstable/UInt16ColumnReader.h"
#include "fnord-cstable/UInt16ColumnWriter.h"
#include "fnord-cstable/CSTableWriter.h"
#include "fnord-cstable/CSTableReader.h"
#include "common.h"
#include "CustomerNamespace.h"
#include "FeatureSchema.h"
#include "JoinedQuery.h"
#include "CTRCounter.h"
#include "analytics/AnalyticsQuery.h"
#include "analytics/CTRByPositionQuery.h"

using namespace fnord;

int main(int argc, const char** argv) {
  fnord::Application::init();
  fnord::Application::logToStderr();

  fnord::cli::FlagParser flags;

  flags.defineFlag(
      "loglevel",
      fnord::cli::FlagParser::T_STRING,
      false,
      NULL,
      "INFO",
      "loglevel",
      "<level>");

  flags.parseArgv(argc, argv);

  Logger::get()->setMinimumLogLevel(
      strToLogLevel(flags.getString("loglevel")));

  size_t debug_n = 0;
  size_t debug_z = 0;

  /* query level */
  cstable::UInt16ColumnWriter jq_page_col(1, 1);

  /* query item level */
  cstable::UInt16ColumnWriter position_col(2, 2);
  cstable::UInt16ColumnWriter clicked_col(2, 2);

  uint64_t r = 0;
  uint64_t n = 0;

  auto add_session = [&] (const cm::JoinedSession& sess) {
    ++n;

    for (const auto& q : sess.queries) {
      auto pg_str = cm::extractAttr(q.attrs, "pg");
      if (pg_str.isEmpty()) {
        jq_page_col.addNull(r, 1);
      } else {
        jq_page_col.addDatum(r, 1, std::stoul(pg_str.get()));
      }

      if (q.items.size() == 0) {
        if (r==0) ++debug_z;
        position_col.addNull(r, 1);
        clicked_col.addNull(r, 1);
      }

      for (const auto& i : q.items) {
        ++debug_n;
        if (r==0) ++debug_z;

        position_col.addDatum(r, 2, i.position);
        clicked_col.addDatum(r, 2, i.clicked);
        r = 2;
      }

      r = 1;
    }

    r = 0;
  };

  /* read input tables */
  auto sstables = flags.getArgv();
  int row_idx = 0;
  for (int tbl_idx = 0; tbl_idx < sstables.size(); ++tbl_idx) {
    const auto& sstable = sstables[tbl_idx];
    fnord::logInfo("cm.jqcolumnize", "Importing sstable: $0", sstable);

    /* read sstable header */
    sstable::SSTableReader reader(File::openFile(sstable, File::O_READ));

    if (reader.bodySize() == 0) {
      fnord::logCritical("cm.jqcolumnize", "unfinished sstable: $0", sstable);
      exit(1);
    }

    /* get sstable cursor */
    auto cursor = reader.getCursor();
    auto body_size = reader.bodySize();

    /* status line */
    util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () {
      fnord::logInfo(
          "cm.jqcolumnize",
          "[$1/$2] [$0%] Reading sstable... rows=$3",
          (size_t) ((cursor->position() / (double) body_size) * 100),
          tbl_idx + 1, sstables.size(), row_idx);
    });

    /* read sstable rows */
    for (; cursor->valid(); ++row_idx) {
      status_line.runMaybe();

      auto key = cursor->getKeyString();
      auto val = cursor->getDataBuffer();
      Option<cm::JoinedQuery> q;

      try {
        q = Some(json::fromJSON<cm::JoinedQuery>(val));
      } catch (const Exception& e) {
        fnord::logWarning("cm.jqcolumnize", e, "invalid json: $0", val.toString());
      }

      if (!q.isEmpty()) {
        cm::JoinedSession s;
        s.queries.emplace_back(q.get());
        add_session(s);
      }

      if (!cursor->next()) {
        break;
      }
    }

    status_line.runForce();
  }

  if (sstables.size() > 0) {
    cstable::CSTableWriter writer("fnord.cstable", n);
    writer.addColumn("queries.items.position", &position_col);
    writer.addColumn("queries.items.clicked", &clicked_col);
    writer.commit();
  }

  cstable::CSTableReader reader("fnord.cstable");

  auto t0 = WallClock::unixMicros();

  cm::AnalyticsQuery aq;
  cm::CTRByPositionQueryResult res;
  cm::CTRByPositionQuery q(&aq, &res);
  aq.scanTable(&reader);
  auto t1 = WallClock::unixMicros();
  fnord::iputs("scanned $0 rows in $1 ms", res.rows_scanned, (t1 - t0) / 1000.0f);
  for (const auto& p : res.counters) {
    fnord::iputs(
       "pos: $0, views: $1, clicks: $2, ctr: $3",
        p.first, p.second.num_views,
        p.second.num_clicks,
        p.second.num_clicks / (double) p.second.num_views);
  }

  return 0;
}

<|endoftext|>


<commit_before>#include "game_object_factory.hpp"

using namespace mindscape;

engine::GameObject* GameObjectFactory::fabricate(
  GameObjectFactory::Options option,
  std::pair<int, int> coordinates,
  int priority){

  switch(option){
    case(GameObjectFactory::LITTLE_GIRL):
      return fabricate_little_girl();
    case(GameObjectFactory::FOOTER):
      return fabricate_footer();
    case(GameObjectFactory::FOX):
      return fabricate_fox();
    case(GameObjectFactory::PLATFORM):
      return fabricate_platform();
    case(GameObjectFactory::BUTTON):
      return fabricate_button();
    case(GameObjectFactory::BACKGROUND):
      return fabricate_background();
    case(GameObjectFactory::SELECT_ARROW):
      return fabricate_select_arrow();
    default:
      return NULL;
  }
}

engine::GameObject* GameObjectFactory::fabricate_footer(){
  std::cout << "NOT IMPLEMENTED YET" << std::endl;
  return NULL;
}

engine::GameObject* GameObjectFactory::fabricate_platform(){
  std::cout << "NOT IMPLEMENTED YET" << std::endl;
  return NULL;
}

engine::GameObject* GameObjectFactory::fabricate_background(){
  std::cout << "NOT IMPLEMENTED YET" << std::endl;
  return NULL;
}

engine::GameObject* GameObjectFactory::fabricate_button(){
  std::cout << "NOT IMPLEMENTED YET" << std::endl;
  return NULL;
}

engine::GameObject* GameObjectFactory::fabricate_select_arrow(){
  std::cout << "NOT IMPLEMENTED YET" << std::endl;
  return NULL;
}

engine::GameObject* GameObjectFactory::fabricate_fox(){
  std::cout << "NOT IMPLEMENTED YET" << std::endl;
  return NULL;
}

engine::GameObject* GameObjectFactory::fabricate_little_girl(){
  engine::Game& game = engine::Game::get_instance();

  std::pair<int, int> place (416, -500);

  //Creating running right animation
  engine::Animation* running_right_animation = new engine::Animation(
    game.get_renderer(),
    "../assets/images/sprites/little_girl/little_girl_running_right.png",
    false,
    std::make_pair(0, 0),
    1,1,9,0.9,true,"RIGHT"
  );
  running_right_animation->set_values(
    std::make_pair(192, 192),
    std::make_pair(192, 192),
    std::make_pair(0, 0)
  );

  //Creating running right animation
  engine::Animation* running_left_animation = new engine::Animation(
    game.get_renderer(),
    "../assets/images/sprites/little_girl/little_girl_running_left.png",
    false,
    std::make_pair(0, 0),
    1,1,9,0.9,true,"LEFT"
  );
  running_left_animation->set_values(
    std::make_pair(192, 192),
    std::make_pair(192, 192),
    std::make_pair(0, 0)
  );

  //Creating idle right animation
  engine::Animation* idle_right_animation = new engine::Animation(
    game.get_renderer(),
    "../assets/images/sprites/little_girl/little_girl_idle_right.png",
    true,
    std::make_pair(0, 0),
    1,1,10,1.5,"RIGHT"
  );
  idle_right_animation->set_values(
    std::make_pair(192, 192),
    std::make_pair(192, 192),
    std::make_pair(0, 0)
  );

  //Creating idle left animation
  engine::Animation* idle_left_animation = new engine::Animation(
    game.get_renderer(),
    "../assets/images/sprites/little_girl/little_girl_idle_left.png",
    false,
    std::make_pair(0, 0),
    1,1,10,1.5,true,"LEFT"
  );
  idle_left_animation->set_values(
    std::make_pair(192, 192),
    std::make_pair(192, 192),
    std::make_pair(0, 0)
  );

  //Creating jumping right animation
  engine::Animation* jumping_right_animation = new engine::Animation(
    game.get_renderer(),
    "../assets/images/sprites/little_girl/little_girl_jumping_right.png",
    false,
    std::make_pair(0, 0),
    1,1,5,1.5,true,"RIGHT"
  );
  jumping_right_animation->set_values(
    std::make_pair(192, 192),
    std::make_pair(192, 192),
    std::make_pair(0, 0)
  );

  //Creating jumping left animation
  engine::Animation* jumping_left_animation = new engine::Animation(
    game.get_renderer(),
    "../assets/images/sprites/little_girl/little_girl_jumping_left.png",
    false,
    std::make_pair(0, 0),
    1,1,5,1.5,true,"LEFT"
  );
  jumping_left_animation->set_values(
    std::make_pair(192, 192),
    std::make_pair(192, 192),
    std::make_pair(0, 0)
  );

  engine::GameObject* little_girl = new engine::LittleGirl("little_girl", place, 3);
  engine::Hitbox* hitbox= new engine::Hitbox("hitbox", little_girl->get_position(), std::make_pair(60, 180), std::make_pair(50,5), game.get_renderer());

  little_girl->collidable = true;
  little_girl->add_animation("running_right_animation",running_right_animation);
  little_girl->add_animation("running_left_animation",running_left_animation);
  little_girl->add_animation("idle_right_animation",idle_right_animation);
  little_girl->add_animation("idle_left_animation",idle_left_animation);
  little_girl->add_animation("jumping_right_animation",jumping_right_animation);
  little_girl->add_animation("jumping_left_animation",jumping_left_animation);
  little_girl->set_actual_animation(idle_right_animation);
  little_girl->add_component(hitbox);

  return little_girl;
}
<commit_msg>Created basic enemy attack<commit_after>#include "game_object_factory.hpp"

using namespace mindscape;

engine::GameObject* GameObjectFactory::fabricate(
  GameObjectFactory::Options option,
  std::pair<int, int> coordinates,
  int priority){

  switch(option){
    case(GameObjectFactory::LITTLE_GIRL):
      return fabricate_little_girl();
    case(GameObjectFactory::FOOTER):
      return fabricate_footer();
    case(GameObjectFactory::FOX):
      return fabricate_fox();
    case(GameObjectFactory::PLATFORM):
      return fabricate_platform();
    case(GameObjectFactory::BUTTON):
      return fabricate_button();
    case(GameObjectFactory::BACKGROUND):
      return fabricate_background();
    case(GameObjectFactory::SELECT_ARROW):
      return fabricate_select_arrow();
    default:
      return NULL;
  }
}

engine::GameObject* GameObjectFactory::fabricate_footer(){
  std::cout << "NOT IMPLEMENTED YET" << std::endl;
  return NULL;
}

engine::GameObject* GameObjectFactory::fabricate_platform(){
  std::cout << "NOT IMPLEMENTED YET" << std::endl;
  return NULL;
}

engine::GameObject* GameObjectFactory::fabricate_background(){
  std::cout << "NOT IMPLEMENTED YET" << std::endl;
  return NULL;
}

engine::GameObject* GameObjectFactory::fabricate_button(){
  std::cout << "NOT IMPLEMENTED YET" << std::endl;
  return NULL;
}

engine::GameObject* GameObjectFactory::fabricate_select_arrow(){
  std::cout << "NOT IMPLEMENTED YET" << std::endl;
  return NULL;
}

engine::GameObject* GameObjectFactory::fabricate_fox(){
  std::cout << "NOT IMPLEMENTED YET" << std::endl;
  return NULL;
}

engine::GameObject* GameObjectFactory::fabricate_little_girl(){
  engine::Game& game = engine::Game::get_instance();

  std::pair<int, int> place (416, -500);

  //Creating running right animation
  engine::Animation* running_right_animation = new engine::Animation(
    game.get_renderer(),
    "../assets/images/sprites/little_girl/little_girl_running_right.png",
    false,
    std::make_pair(0, 0),
    1,1,9,0.9,true,"RIGHT"
  );
  running_right_animation->set_values(
    std::make_pair(192, 192),
    std::make_pair(192, 192),
    std::make_pair(0, 0)
  );

  //Creating running right animation
  engine::Animation* running_left_animation = new engine::Animation(
    game.get_renderer(),
    "../assets/images/sprites/little_girl/little_girl_running_left.png",
    false,
    std::make_pair(0, 0),
    1,1,9,0.9,true,"LEFT"
  );
  running_left_animation->set_values(
    std::make_pair(192, 192),
    std::make_pair(192, 192),
    std::make_pair(0, 0)
  );

  //Creating idle right animation
  engine::Animation* idle_right_animation = new engine::Animation(
    game.get_renderer(),
    "../assets/images/sprites/little_girl/little_girl_idle_right.png",
    true,
    std::make_pair(0, 0),
    1,1,10,1.5,"RIGHT"
  );
  idle_right_animation->set_values(
    std::make_pair(192, 192),
    std::make_pair(192, 192),
    std::make_pair(0, 0)
  );

  //Creating idle left animation
  engine::Animation* idle_left_animation = new engine::Animation(
    game.get_renderer(),
    "../assets/images/sprites/little_girl/little_girl_idle_left.png",
    false,
    std::make_pair(0, 0),
    1,1,10,1.5,true,"LEFT"
  );
  idle_left_animation->set_values(
    std::make_pair(192, 192),
    std::make_pair(192, 192),
    std::make_pair(0, 0)
  );

  //Creating jumping right animation
  engine::Animation* jumping_right_animation = new engine::Animation(
    game.get_renderer(),
    "../assets/images/sprites/little_girl/little_girl_jumping_right.png",
    false,
    std::make_pair(0, 0),
    1,1,5,1.5,true,"RIGHT"
  );
  jumping_right_animation->set_values(
    std::make_pair(192, 192),
    std::make_pair(192, 192),
    std::make_pair(0, 0)
  );

  //Creating jumping left animation
  engine::Animation* jumping_left_animation = new engine::Animation(
    game.get_renderer(),
    "../assets/images/sprites/little_girl/little_girl_jumping_left.png",
    false,
    std::make_pair(0, 0),
    1,1,5,1.5,true,"LEFT"
  );
  jumping_left_animation->set_values(
    std::make_pair(192, 192),
    std::make_pair(192, 192),
    std::make_pair(0, 0)
  );

  engine::GameObject* little_girl = new engine::LittleGirl("little_girl", place, 52);
  engine::Hitbox* hitbox= new engine::Hitbox("hitbox", little_girl->get_position(), std::make_pair(60, 45), std::make_pair(50,140), game.get_renderer());

  little_girl->collidable = true;
  little_girl->add_animation("running_right_animation",running_right_animation);
  little_girl->add_animation("running_left_animation",running_left_animation);
  little_girl->add_animation("idle_right_animation",idle_right_animation);
  little_girl->add_animation("idle_left_animation",idle_left_animation);
  little_girl->add_animation("jumping_right_animation",jumping_right_animation);
  little_girl->add_animation("jumping_left_animation",jumping_left_animation);
  little_girl->set_actual_animation(idle_right_animation);
  little_girl->add_component(hitbox);

  return little_girl;
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015 Damien Tardy-Panis
 *
 * This file is subject to the terms and conditions defined in
 * file 'LICENSE', which is part of this source code package.
 **/

#include "Erzaehlmirnix.h"

#include <QDebug>
#include <QRegularExpression>
#include <QRegularExpressionMatch>

Erzaehlmirnix::Erzaehlmirnix(QObject *parent) :
    Comic(parent)
{
    m_info.id             = QString("erzaehlmirnix");
    m_info.name           = QString("Erzaehlmirnix");
    m_info.color          = QColor(188, 197, 192);
    m_info.authors        = QStringList("Nadja Hermann");
    m_info.homepage       = QUrl("https://erzaehlmirnix.wordpress.com/");
    m_info.country        = QLocale::Germany;
    m_info.language       = QLocale::German;
    m_info.endDate        = QDate::currentDate();
    m_info.stripSourceUrl = QUrl("https://erzaehlmirnix.wordpress.com/");
}

QUrl Erzaehlmirnix::extractStripImageUrl(QByteArray data)
{
    QString html(data);
    QRegularExpression reg("<img[^>]*src=\"([^\"]*erzaehlmirnix.files.wordpress.com[^\"]*)\"");
    QRegularExpressionMatch match = reg.match(html);

    if (!match.hasMatch()) {
        return QUrl();
    }

    QString src = match.captured(1);

    return QUrl(src);
}
<commit_msg>fix Erzaehlmirnix comic<commit_after>/**
 * Copyright (c) 2015 Damien Tardy-Panis
 *
 * This file is subject to the terms and conditions defined in
 * file 'LICENSE', which is part of this source code package.
 **/

#include "Erzaehlmirnix.h"

#include <QDebug>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QRegularExpressionMatchIterator>

Erzaehlmirnix::Erzaehlmirnix(QObject *parent) :
    Comic(parent)
{
    m_info.id             = QString("erzaehlmirnix");
    m_info.name           = QString("Erzaehlmirnix");
    m_info.color          = QColor(188, 197, 192);
    m_info.authors        = QStringList("Nadja Hermann");
    m_info.homepage       = QUrl("https://erzaehlmirnix.wordpress.com/");
    m_info.country        = QLocale::Germany;
    m_info.language       = QLocale::German;
    m_info.endDate        = QDate::currentDate();
    m_info.stripSourceUrl = QUrl("https://erzaehlmirnix.wordpress.com/");
}

QUrl Erzaehlmirnix::extractStripImageUrl(QByteArray data)
{
    QString html(data);
    QRegularExpression reg("<img[^>]*src=\"([^\"]*erzaehlmirnix.files.wordpress.com[^\"]*)\"");
    QRegularExpressionMatchIterator matchIterator = reg.globalMatch(html);

    if (!matchIterator.hasNext())
        return QUrl();

    matchIterator.next();

    if (!matchIterator.hasNext())
        return QUrl();

    QRegularExpressionMatch match = matchIterator.next();

    QString src = match.captured(1);

    return QUrl(src);
}
<|endoftext|>