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

  Program:   Visualization Toolkit
  Module:    TestParallelRandomStatistics.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm 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 notice for more information.

=========================================================================*/
/*
 * Copyright 2008 Sandia Corporation.
 * Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
 * license for use of this work by or on behalf of the
 * U.S. Government. Redistribution and use in source and binary forms, with
 * or without modification, are permitted provided that this Notice and any
 * statement of authorship are reproduced on all copies.
 */
// .SECTION Thanks
// Thanks to Philippe Pebay and David Thompson from Sandia National Laboratories
// for implementing this test.

#include <mpi.h>
#include <time.h>

#include "vtkDescriptiveStatistics.h"
#include "vtkPDescriptiveStatistics.h"
#include "vtkCorrelativeStatistics.h"
#include "vtkPCorrelativeStatistics.h"

#include "vtkDoubleArray.h"
#include "vtkMath.h"
#include "vtkMPIController.h"
#include "vtkStdString.h"
#include "vtkTable.h"
#include "vtkVariantArray.h"

// For debugging purposes, serial engines can be run on each slice of the distributed data set
#define DEBUG_WITH_SERIAL_STATS 0

int nVals = 1000000;

// This will be called by all processes
void RandomSampleStatistics( vtkMultiProcessController* controller, void* vtkNotUsed(arg) )
{
  // Get local rank
  int myRank = controller->GetLocalProcessId();

  // Seed random number generator
  vtkMath::RandomSeed( static_cast<int>( time( NULL ) ) * ( myRank + 1 ) );

  // Generate an input table that contains samples of mutually independent random variables over [0, 1]
  int nUniform = 2;
  int nNormal  = 2;
  int nVariables = nUniform + nNormal;

  vtkTable* inputData = vtkTable::New();
  vtkDoubleArray* doubleArray[4];
  vtkStdString columnNames[] = { "Standard Uniform 0",
                                 "Standard Uniform 1",
                                 "Standard Normal 0",
                                 "Standard Normal 1" };

  // Standard uniform samples
  for ( int c = 0; c < nUniform; ++ c )
    {
    doubleArray[c] = vtkDoubleArray::New();
    doubleArray[c]->SetNumberOfComponents( 1 );
    doubleArray[c]->SetName( columnNames[c] );

    double x;
    for ( int r = 0; r < nVals; ++ r )
      {
      x = vtkMath::Random();
      doubleArray[c]->InsertNextValue( x );
      }

    inputData->AddColumn( doubleArray[c] );
    doubleArray[c]->Delete();
    }

  // Standard normal samples
  for ( int c = nUniform; c < nVariables; ++ c )
    {
    doubleArray[c] = vtkDoubleArray::New();
    doubleArray[c]->SetNumberOfComponents( 1 );
    doubleArray[c]->SetName( columnNames[c] );

    double x;
    for ( int r = 0; r < nVals; ++ r )
      {
      x = vtkMath::Gaussian();
      doubleArray[c]->InsertNextValue( x );
      }

    inputData->AddColumn( doubleArray[c] );
    doubleArray[c]->Delete();
    }

#if DEBUG_WITH_SERIAL_STATS
  // Instantiate a (serial) descriptive statistics engine and set its ports
  vtkDescriptiveStatistics* ds = vtkDescriptiveStatistics::New();
  ds->SetInput( 0, inputData );

  // Select all columns
  for ( int c = 0; c < nVariables; ++ c )
    {
    ds->AddColumn( columnNames[c] );
    }

  // Test (serially) with Learn and Derive options only
  ds->SetLearn( true );
  ds->SetDerive( true );
  ds->SetAssess( true );
  ds->Update();

  cout << "\n## Proc "
       << myRank
       << " calculated the following statistics ( "
       << ds->GetSampleSize()
       << " entries per column ):\n";
  for ( vtkIdType r = 0; r < ds->GetOutput( 1 )->GetNumberOfRows(); ++ r )
    {
    cout << "   ";
    for ( int i = 0; i < ds->GetOutput( 1 )->GetNumberOfColumns(); ++ i )
      {
      cout << ds->GetOutput( 1 )->GetColumnName( i )
           << "="
           << ds->GetOutput( 1 )->GetValue( r, i ).ToString()
           << "  ";
      }
    cout << "\n";
    }

  // Clean up
  ds->Delete();
#endif //DEBUG_WITH_SERIAL_STATS

  // Synchronize and start clock
  controller->Barrier();
  time_t t0;
  time ( &t0 );

  // Instantiate a parallel descriptive statistics engine and set its ports
  vtkPDescriptiveStatistics* pds = vtkPDescriptiveStatistics::New();
  pds->SetInput( 0, inputData );
  vtkTable* outputData = pds->GetOutput( 0 );
  vtkTable* outputMeta = pds->GetOutput( 1 );

  // Select all columns
  for ( int c = 0; c < nVariables; ++ c )
    {
    pds->AddColumn( columnNames[c] );
    }

  // Test (in parallel) with Learn, Derive, and Assess options turned on
  pds->SetLearn( true );
  pds->SetDerive( true );
  pds->SetAssess( true );
  pds->SignedDeviationsOff(); // Use unsigned deviations
  pds->Update();

  // Synchronize and stop clock
  controller->Barrier();
  time_t t1;
  time ( &t1 );

  if ( ! controller->GetLocalProcessId() )
    {
    cout << "\n## Completed parallel calculation of descriptive statistics (with assessment):\n"
         << "   Total sample size: "
         << pds->GetSampleSize()
         << " \n"
         << "   Wall time: "
         << difftime( t1, t0 )
         << " sec.\n";

   for ( vtkIdType r = 0; r < outputMeta->GetNumberOfRows(); ++ r )
      {
      cout << "   ";
      for ( int c = 0; c < outputMeta->GetNumberOfColumns(); ++ c )
        {
        vtkStdString colName = outputMeta->GetColumnName( c );

        // Do not report M aggregates
        if ( colName[0] == 'M' && colName[1] != 'e' )
          {
          continue;
          }

        cout << colName
             << "="
             << outputMeta->GetValue( r, c ).ToString()
             << "  ";
        }
      cout << "\n";
      }
    }

  // Verify that the DISTRIBUTED standard normal samples indeed statisfy the 68-95-99.7 rule
  if ( ! controller->GetLocalProcessId() )
    {
    cout << "\n## Verifying whether the distributed standard normal samples satisfy the 68-95-99.7 rule:\n";
    }

  vtkVariantArray* relDev[2];
  relDev[0] = vtkVariantArray::SafeDownCast(
    outputData->GetColumnByName( "Relative Deviation(Standard Normal 0)" ) );
  relDev[1] = vtkVariantArray::SafeDownCast(
    outputData->GetColumnByName( "Relative Deviation(Standard Normal 1)" ) );

  if ( !relDev[0] || ! relDev[1] )
    {
    cout << "*** Error: "
         << "Empty output column(s) on process "
         << controller->GetLocalProcessId()
         << ".\n";
    }

  for ( int c = 0; c < nNormal; ++ c )
    {
    int outsideStdv_l[] = { 0, 0, 0 };
    double dev;
    int n = outputData->GetNumberOfRows();
    for ( vtkIdType r = 0; r < n; ++ r )
      {
      dev = relDev[c]->GetValue( r ).ToDouble();
      if ( dev >= 1. )
        {
        ++ outsideStdv_l[0];
        if ( dev >= 2. )
          {
          ++ outsideStdv_l[1];
          if ( dev >= 3. )
            {
            ++ outsideStdv_l[2];
            }
          }
        }
      }

    // Sum all local counters
    int outsideStdv_g[3];
    controller->AllReduce( outsideStdv_l,
                           outsideStdv_g,
                           3,
                           vtkCommunicator::SUM_OP );

    // Print out percentages of sample points within 1, 2, and 3 standard deviations of the mean.
    if ( ! controller->GetLocalProcessId() )
      {
      cout << "   "
           << outputData->GetColumnName( nUniform + c )
           << ":\n";
      for ( int i = 0; i < 3; ++ i )
        {
        cout << "      "
             << ( 1. - outsideStdv_g[i] / static_cast<double>( pds->GetSampleSize() ) ) * 100.
             << "\% within "
             << i + 1
             << " standard deviation(s) from the mean.\n";
        }
      }
    }

  // Clean up
  pds->Delete();

  // Synchronize and start clock
  controller->Barrier();
  time_t t2;
  time ( &t2 );

  // Instantiate a parallel correlative statistics engine and set its ports
  vtkPCorrelativeStatistics* pcs = vtkPCorrelativeStatistics::New();
  pcs->SetInput( 0, inputData );
  outputData = pcs->GetOutput( 0 );
  outputMeta = pcs->GetOutput( 1 );

  // Select column pairs (uniform vs. uniform, normal vs. normal)
  pcs->AddColumnPair( columnNames[0], columnNames[1] );
  pcs->AddColumnPair( columnNames[2], columnNames[3] );

  // Test (in parallel) with Learn, Derive, and Assess options turned on
  pcs->SetLearn( true );
  pcs->SetDerive( true );
  pcs->SetAssess( true );
  pcs->Update();

    // Synchronize and stop clock
  controller->Barrier();
  time_t t3;
  time ( &t3 );

  if ( ! controller->GetLocalProcessId() )
    {
    cout << "\n## Completed parallel calculation of correlative statistics (with assessment):\n"
         << "   Total sample size: "
         << pcs->GetSampleSize()
         << " \n"
         << "   Wall time: "
         << difftime( t3, t2 )
         << " sec.\n";

    for ( vtkIdType r = 0; r < outputMeta->GetNumberOfRows(); ++ r )
      {
      cout << "   ";
      for ( int c = 0; c < outputMeta->GetNumberOfColumns(); ++ c )
        {
        vtkStdString colName = outputMeta->GetColumnName( c );

        // Do not report M aggregates
        if ( colName[0] == 'M' && colName[1] != 'e' )
          {
          continue;
          }

        cout << colName
             << "="
             << outputMeta->GetValue( r, c ).ToString()
             << "  ";
        }
      cout << "\n";
      }
    }

  // Clean up
  pcs->Delete();
  inputData->Delete();
}

//----------------------------------------------------------------------------
int main( int argc, char** argv )
{
  int testValue = 0;

  // Note that this will create a vtkMPIController if MPI
  // is configured, vtkThreadedController otherwise.
  vtkMPIController* controller = vtkMPIController::New();
  controller->Initialize( &argc, &argv );

  // When using MPI, the number of processes is determined
  // by the external program which launches this application.
  // However, when using threads, we need to set it ourselves.
  if ( controller->IsA( "vtkThreadedController" ) )
    {
    // Set the number of processes to 2 for this example.
    controller->SetNumberOfProcesses( 2 );
    }

  // Check how many processes have been made available
  int numProcs = controller->GetNumberOfProcesses();
  if ( ! controller->GetLocalProcessId() )
    {
    cout << "# Running test with "
         << numProcs
         << " processes...\n";
    }

  // Execute the function named "process" on both processes
  controller->SetSingleMethod( RandomSampleStatistics, 0 );
  controller->SingleMethodExecute();

  // Clean up and exit
  if ( ! controller->GetLocalProcessId() )
    {
    cout << "\n# Test completed.\n\n";
    }

  controller->Finalize();
  controller->Delete();

  return testValue;
}
<commit_msg>COMP: Fix a method-resolution ambiguity.  Curse you, ISO!<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestParallelRandomStatistics.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm 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 notice for more information.

=========================================================================*/
/*
 * Copyright 2008 Sandia Corporation.
 * Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
 * license for use of this work by or on behalf of the
 * U.S. Government. Redistribution and use in source and binary forms, with
 * or without modification, are permitted provided that this Notice and any
 * statement of authorship are reproduced on all copies.
 */
// .SECTION Thanks
// Thanks to Philippe Pebay and David Thompson from Sandia National Laboratories
// for implementing this test.

#include <mpi.h>
#include <time.h>

#include "vtkDescriptiveStatistics.h"
#include "vtkPDescriptiveStatistics.h"
#include "vtkCorrelativeStatistics.h"
#include "vtkPCorrelativeStatistics.h"

#include "vtkDoubleArray.h"
#include "vtkMath.h"
#include "vtkMPIController.h"
#include "vtkStdString.h"
#include "vtkTable.h"
#include "vtkVariantArray.h"

// For debugging purposes, serial engines can be run on each slice of the distributed data set
#define DEBUG_WITH_SERIAL_STATS 0

int nVals = 1000000;

// This will be called by all processes
void RandomSampleStatistics( vtkMultiProcessController* controller, void* vtkNotUsed(arg) )
{
  // Get local rank
  int myRank = controller->GetLocalProcessId();

  // Seed random number generator
  vtkMath::RandomSeed( static_cast<int>( time( NULL ) ) * ( myRank + 1 ) );

  // Generate an input table that contains samples of mutually independent random variables over [0, 1]
  int nUniform = 2;
  int nNormal  = 2;
  int nVariables = nUniform + nNormal;

  vtkTable* inputData = vtkTable::New();
  vtkDoubleArray* doubleArray[4];
  vtkStdString columnNames[] = { "Standard Uniform 0",
                                 "Standard Uniform 1",
                                 "Standard Normal 0",
                                 "Standard Normal 1" };

  // Standard uniform samples
  for ( int c = 0; c < nUniform; ++ c )
    {
    doubleArray[c] = vtkDoubleArray::New();
    doubleArray[c]->SetNumberOfComponents( 1 );
    doubleArray[c]->SetName( columnNames[c] );

    double x;
    for ( int r = 0; r < nVals; ++ r )
      {
      x = vtkMath::Random();
      doubleArray[c]->InsertNextValue( x );
      }

    inputData->AddColumn( doubleArray[c] );
    doubleArray[c]->Delete();
    }

  // Standard normal samples
  for ( int c = nUniform; c < nVariables; ++ c )
    {
    doubleArray[c] = vtkDoubleArray::New();
    doubleArray[c]->SetNumberOfComponents( 1 );
    doubleArray[c]->SetName( columnNames[c] );

    double x;
    for ( int r = 0; r < nVals; ++ r )
      {
      x = vtkMath::Gaussian();
      doubleArray[c]->InsertNextValue( x );
      }

    inputData->AddColumn( doubleArray[c] );
    doubleArray[c]->Delete();
    }

#if DEBUG_WITH_SERIAL_STATS
  // Instantiate a (serial) descriptive statistics engine and set its ports
  vtkDescriptiveStatistics* ds = vtkDescriptiveStatistics::New();
  ds->SetInput( 0, inputData );

  // Select all columns
  for ( int c = 0; c < nVariables; ++ c )
    {
    ds->AddColumn( columnNames[c] );
    }

  // Test (serially) with Learn and Derive options only
  ds->SetLearn( true );
  ds->SetDerive( true );
  ds->SetAssess( true );
  ds->Update();

  cout << "\n## Proc "
       << myRank
       << " calculated the following statistics ( "
       << ds->GetSampleSize()
       << " entries per column ):\n";
  for ( vtkIdType r = 0; r < ds->GetOutput( 1 )->GetNumberOfRows(); ++ r )
    {
    cout << "   ";
    for ( int i = 0; i < ds->GetOutput( 1 )->GetNumberOfColumns(); ++ i )
      {
      cout << ds->GetOutput( 1 )->GetColumnName( i )
           << "="
           << ds->GetOutput( 1 )->GetValue( r, i ).ToString()
           << "  ";
      }
    cout << "\n";
    }

  // Clean up
  ds->Delete();
#endif //DEBUG_WITH_SERIAL_STATS

  // Synchronize and start clock
  controller->Barrier();
  time_t t0;
  time ( &t0 );

  // Instantiate a parallel descriptive statistics engine and set its ports
  vtkPDescriptiveStatistics* pds = vtkPDescriptiveStatistics::New();
  pds->SetInput( 0, inputData );
  vtkTable* outputData = pds->GetOutput( 0 );
  vtkTable* outputMeta = pds->GetOutput( 1 );

  // Select all columns
  for ( int c = 0; c < nVariables; ++ c )
    {
    pds->AddColumn( columnNames[c] );
    }

  // Test (in parallel) with Learn, Derive, and Assess options turned on
  pds->SetLearn( true );
  pds->SetDerive( true );
  pds->SetAssess( true );
  pds->SignedDeviationsOff(); // Use unsigned deviations
  pds->Update();

  // Synchronize and stop clock
  controller->Barrier();
  time_t t1;
  time ( &t1 );

  if ( ! controller->GetLocalProcessId() )
    {
    cout << "\n## Completed parallel calculation of descriptive statistics (with assessment):\n"
         << "   Total sample size: "
         << pds->GetSampleSize()
         << " \n"
         << "   Wall time: "
         << difftime( t1, t0 )
         << " sec.\n";

   for ( vtkIdType r = 0; r < outputMeta->GetNumberOfRows(); ++ r )
      {
      cout << "   ";
      for ( int c = 0; c < outputMeta->GetNumberOfColumns(); ++ c )
        {
        vtkStdString colName = outputMeta->GetColumnName( c );

        // Do not report M aggregates
        if ( colName.at(0) == 'M' && colName.at(1) != 'e' )
          {
          continue;
          }

        cout << colName
             << "="
             << outputMeta->GetValue( r, c ).ToString()
             << "  ";
        }
      cout << "\n";
      }
    }

  // Verify that the DISTRIBUTED standard normal samples indeed statisfy the 68-95-99.7 rule
  if ( ! controller->GetLocalProcessId() )
    {
    cout << "\n## Verifying whether the distributed standard normal samples satisfy the 68-95-99.7 rule:\n";
    }

  vtkVariantArray* relDev[2];
  relDev[0] = vtkVariantArray::SafeDownCast(
    outputData->GetColumnByName( "Relative Deviation(Standard Normal 0)" ) );
  relDev[1] = vtkVariantArray::SafeDownCast(
    outputData->GetColumnByName( "Relative Deviation(Standard Normal 1)" ) );

  if ( !relDev[0] || ! relDev[1] )
    {
    cout << "*** Error: "
         << "Empty output column(s) on process "
         << controller->GetLocalProcessId()
         << ".\n";
    }

  for ( int c = 0; c < nNormal; ++ c )
    {
    int outsideStdv_l[] = { 0, 0, 0 };
    double dev;
    int n = outputData->GetNumberOfRows();
    for ( vtkIdType r = 0; r < n; ++ r )
      {
      dev = relDev[c]->GetValue( r ).ToDouble();
      if ( dev >= 1. )
        {
        ++ outsideStdv_l[0];
        if ( dev >= 2. )
          {
          ++ outsideStdv_l[1];
          if ( dev >= 3. )
            {
            ++ outsideStdv_l[2];
            }
          }
        }
      }

    // Sum all local counters
    int outsideStdv_g[3];
    controller->AllReduce( outsideStdv_l,
                           outsideStdv_g,
                           3,
                           vtkCommunicator::SUM_OP );

    // Print out percentages of sample points within 1, 2, and 3 standard deviations of the mean.
    if ( ! controller->GetLocalProcessId() )
      {
      cout << "   "
           << outputData->GetColumnName( nUniform + c )
           << ":\n";
      for ( int i = 0; i < 3; ++ i )
        {
        cout << "      "
             << ( 1. - outsideStdv_g[i] / static_cast<double>( pds->GetSampleSize() ) ) * 100.
             << "\% within "
             << i + 1
             << " standard deviation(s) from the mean.\n";
        }
      }
    }

  // Clean up
  pds->Delete();

  // Synchronize and start clock
  controller->Barrier();
  time_t t2;
  time ( &t2 );

  // Instantiate a parallel correlative statistics engine and set its ports
  vtkPCorrelativeStatistics* pcs = vtkPCorrelativeStatistics::New();
  pcs->SetInput( 0, inputData );
  outputData = pcs->GetOutput( 0 );
  outputMeta = pcs->GetOutput( 1 );

  // Select column pairs (uniform vs. uniform, normal vs. normal)
  pcs->AddColumnPair( columnNames[0], columnNames[1] );
  pcs->AddColumnPair( columnNames[2], columnNames[3] );

  // Test (in parallel) with Learn, Derive, and Assess options turned on
  pcs->SetLearn( true );
  pcs->SetDerive( true );
  pcs->SetAssess( true );
  pcs->Update();

    // Synchronize and stop clock
  controller->Barrier();
  time_t t3;
  time ( &t3 );

  if ( ! controller->GetLocalProcessId() )
    {
    cout << "\n## Completed parallel calculation of correlative statistics (with assessment):\n"
         << "   Total sample size: "
         << pcs->GetSampleSize()
         << " \n"
         << "   Wall time: "
         << difftime( t3, t2 )
         << " sec.\n";

    for ( vtkIdType r = 0; r < outputMeta->GetNumberOfRows(); ++ r )
      {
      cout << "   ";
      for ( int c = 0; c < outputMeta->GetNumberOfColumns(); ++ c )
        {
        vtkStdString colName = outputMeta->GetColumnName( c );

        // Do not report M aggregates
        if ( colName.at(0) == 'M' && colName.at(1) != 'e' )
          {
          continue;
          }

        cout << colName
             << "="
             << outputMeta->GetValue( r, c ).ToString()
             << "  ";
        }
      cout << "\n";
      }
    }

  // Clean up
  pcs->Delete();
  inputData->Delete();
}

//----------------------------------------------------------------------------
int main( int argc, char** argv )
{
  int testValue = 0;

  // Note that this will create a vtkMPIController if MPI
  // is configured, vtkThreadedController otherwise.
  vtkMPIController* controller = vtkMPIController::New();
  controller->Initialize( &argc, &argv );

  // When using MPI, the number of processes is determined
  // by the external program which launches this application.
  // However, when using threads, we need to set it ourselves.
  if ( controller->IsA( "vtkThreadedController" ) )
    {
    // Set the number of processes to 2 for this example.
    controller->SetNumberOfProcesses( 2 );
    }

  // Check how many processes have been made available
  int numProcs = controller->GetNumberOfProcesses();
  if ( ! controller->GetLocalProcessId() )
    {
    cout << "# Running test with "
         << numProcs
         << " processes...\n";
    }

  // Execute the function named "process" on both processes
  controller->SetSingleMethod( RandomSampleStatistics, 0 );
  controller->SingleMethodExecute();

  // Clean up and exit
  if ( ! controller->GetLocalProcessId() )
    {
    cout << "\n# Test completed.\n\n";
    }

  controller->Finalize();
  controller->Delete();

  return testValue;
}
<|endoftext|>


<commit_before>#ifndef PRESETEDITOR_HPP
#define PRESETEDITOR_HPP

// stdlib
#include <string>
#include <functional>

// Libslic3r
#include "libslic3r.h"
#include "ConfigBase.hpp"
#include "Config.hpp"

// GUI
#include "misc_ui.hpp"

// Wx
#include <wx/treectrl.h>
#include <wx/imaglist.h>
#include <wx/panel.h>

using namespace std::string_literals;
namespace Slic3r { namespace GUI {

class PresetPage;

class PresetEditor : public wxPanel {

public:
    /// Member function to retrieve a list of options
    /// that this preset governs. Subclasses should
    /// call their own static method.
    virtual t_config_option_keys my_options() = 0;
    static t_config_option_keys options() { return t_config_option_keys {}; }

    static t_config_option_keys overridable_options() { return t_config_option_keys {}; };
    static t_config_option_keys overriding_options() { return t_config_option_keys {}; };

    virtual t_config_option_keys my_overridable_options() = 0;
    virtual t_config_option_keys my_overriding_options() = 0;

    wxSizer* sizer() { return _sizer; };
    PresetEditor(wxWindow* parent, t_config_option_keys options = {});
    PresetEditor() : PresetEditor(nullptr, {}) {};
    std::shared_ptr<Preset> current_preset;

    bool prompt_unsaved_changes();
    void select_preset_by_name(const wxString& name, bool force = false);

    /// suppress the callback when the tree selection is changed.
    bool disable_tree_sel_changed_event {false};

    void save_preset();
    std::function<void ()> on_save_preset {};
    std::function<void ()> on_value_change {};

    config_ptr config;
    PresetPage* add_options_page(const wxString& _title, const wxString& _icon = "");

    virtual wxString title() = 0;
    virtual std::string name() = 0;
protected:
    // Main sizer
    wxSizer* _sizer {nullptr};
    wxString presets;
    wxImageList* _icons {nullptr};
    wxTreeCtrl* _treectrl {nullptr};
    wxBitmapButton* _btn_save_preset {nullptr};
    wxBitmapButton* _btn_delete_preset {nullptr};
    wxChoice* _presets_choice {nullptr};
    int _iconcount {-1};

    /// Vector of PresetPage pointers; trust wxWidgets RTTI to avoid leaks
    std::vector<PresetPage*> _pages {};

    const unsigned int left_col_width {150};
    void _update_tree();
    void load_presets();

    virtual void _build() = 0;
    virtual void _update() = 0;
    virtual void _on_preset_loaded() = 0;
    void set_tooltips() {
        this->_btn_save_preset->SetToolTip(wxString(_("Save current ")) + this->title());
        this->_btn_delete_preset->SetToolTip(_("Delete this preset."));
    }
};

class PrintEditor : public PresetEditor {
public:

    PrintEditor(wxWindow* parent, t_config_option_keys options = {});
    PrintEditor() : PrintEditor(nullptr, {}) {};

    wxString title() override { return _("Print Settings"); }
    std::string name() override { return "print"s; }

    t_config_option_keys my_overridable_options() override { return PresetEditor::overridable_options(); };
    static t_config_option_keys overridable_options() { return PresetEditor::overridable_options(); };

    t_config_option_keys my_overriding_options() override { return PresetEditor::overriding_options(); };
    static t_config_option_keys overriding_options() { return PresetEditor::overriding_options(); };

    /// Static method to retrieve list of options that this preset governs.
    static t_config_option_keys options() {
        return t_config_option_keys
        {
            "layer_height"s, "first_layer_height"s,
            "adaptive_slicing"s, "adaptive_slicing_quality"s, "match_horizontal_surfaces"s,
            "perimeters"s, "spiral_vase"s,
            "top_solid_layers"s, "bottom_solid_layers"s,
            "extra_perimeters"s, "avoid_crossing_perimeters"s, "thin_walls"s, "overhangs"s,
            "seam_position"s, "external_perimeters_first"s,
            "fill_density"s, "fill_pattern"s, "top_infill_pattern"s, "bottom_infill_pattern"s, "fill_gaps"s,
            "infill_every_layers"s, "infill_only_where_needed"s,
            "solid_infill_every_layers"s, "fill_angle"s, "solid_infill_below_area"s, ""s,
            "only_retract_when_crossing_perimeters"s, "infill_first"s,
            "max_print_speed"s, "max_volumetric_speed"s,
            "perimeter_speed"s, "small_perimeter_speed"s, "external_perimeter_speed"s, "infill_speed"s, ""s,
            "solid_infill_speed"s, "top_solid_infill_speed"s, "support_material_speed"s,
            "support_material_interface_speed"s, "bridge_speed"s, "gap_fill_speed"s,
            "travel_speed"s,
            "first_layer_speed"s,
            "perimeter_acceleration"s, "infill_acceleration"s, "bridge_acceleration"s,
            "first_layer_acceleration"s, "default_acceleration"s,
            "skirts"s, "skirt_distance"s, "skirt_height"s, "min_skirt_length"s,
            "brim_connections_width"s, "brim_width"s, "interior_brim_width"s,
            "support_material"s, "support_material_threshold"s, "support_material_max_layers"s, "support_material_enforce_layers"s,
            "raft_layers"s,
            "support_material_pattern"s, "support_material_spacing"s, "support_material_angle"s, ""s,
            "support_material_interface_layers"s, "support_material_interface_spacing"s,
            "support_material_contact_distance"s, "support_material_buildplate_only"s, "dont_support_bridges"s,
            "notes"s,
            "complete_objects"s, "extruder_clearance_radius"s, "extruder_clearance_height"s,
            "gcode_comments"s, "output_filename_format"s,
            "post_process"s,
            "perimeter_extruder"s, "infill_extruder"s, "solid_infill_extruder"s,
            "support_material_extruder"s, "support_material_interface_extruder"s,
            "ooze_prevention"s, "standby_temperature_delta"s,
            "interface_shells"s, "regions_overlap"s,
            "extrusion_width"s, "first_layer_extrusion_width"s, "perimeter_extrusion_width"s, ""s,
            "external_perimeter_extrusion_width"s, "infill_extrusion_width"s, "solid_infill_extrusion_width"s,
            "top_infill_extrusion_width"s, "support_material_extrusion_width"s,
            "support_material_interface_extrusion_width"s, "infill_overlap"s, "bridge_flow_ratio"s,
            "xy_size_compensation"s, "resolution"s, "shortcuts"s, "compatible_printers"s,
            "print_settings_id"s
        };
    }

    t_config_option_keys my_options() override { return PrintEditor::options(); }

protected:
    void _update() override;
    void _build() override;
};

class PrinterEditor : public PresetEditor {
public:
    PrinterEditor(wxWindow* parent, t_config_option_keys options = {});
    PrinterEditor() : PrinterEditor(nullptr, {}) {};

    wxString title() override { return _("Printer Settings"); }
    std::string name() override { return "printer"s; }
    static t_config_option_keys overridable_options() { return t_config_option_keys
    {
        "pressure_advance"s,
        "retract_length"s, "retract_lift"s, "retract_speed"s, "retract_restart_extra"s,
        "retract_before_travel"s, "retract_layer_change"s, "wipe"s
    }; };
    static t_config_option_keys overriding_options() { return PresetEditor::overriding_options(); };

    t_config_option_keys my_overridable_options() override { return PrinterEditor::overridable_options(); };
    t_config_option_keys my_overriding_options() override { return PrinterEditor::overriding_options(); };

    static t_config_option_keys options() {
        return t_config_option_keys
        {
            "bed_shape"s, "z_offset"s, "z_steps_per_mm"s, "has_heatbed"s,
            "gcode_flavor"s, "use_relative_e_distances"s,
            "serial_port"s, "serial_speed"s,
            "host_type"s, "print_host"s, "octoprint_apikey"s,
            "use_firmware_retraction"s, "pressure_advance"s, "vibration_limit"s,
            "use_volumetric_e"s,
            "start_gcode"s, "end_gcode"s, "before_layer_gcode"s, "layer_gcode"s, "toolchange_gcode"s, "between_objects_gcode"s,
            "nozzle_diameter"s, "extruder_offset"s, "min_layer_height"s, "max_layer_height"s,
            "retract_length"s, "retract_lift"s, "retract_speed"s, "retract_restart_extra"s, "retract_before_travel"s, "retract_layer_change"s, "wipe"s,
            "retract_length_toolchange"s, "retract_restart_extra_toolchange"s, "retract_lift_above"s, "retract_lift_below"s,
            "printer_settings_id"s,
            "printer_notes"s,
            "use_set_and_wait_bed"s, "use_set_and_wait_extruder"s
        };
    }

    t_config_option_keys my_options() override { return PrinterEditor::options(); }
protected:
    void _update() override;
    void _build() override;
    const std::string LogChannel() override {return "PrinterEditor"s;} //< Which log these messages should go to.
};

class MaterialEditor : public PresetEditor {
public:

    wxString title() override { return _("Material Settings"); }
    std::string name() override { return "material"s; }
    preset_t type() override  { return preset_t::Material; };
    int typeId() override  { return static_cast<int>(preset_t::Material); };
    MaterialEditor(wxWindow* parent, t_config_option_keys options = {});
    MaterialEditor() : MaterialEditor(nullptr, {}) {};

    t_config_option_keys my_overridable_options() override { return PresetEditor::overridable_options(); };
    t_config_option_keys my_overriding_options() override { return PrinterEditor::overridable_options(); };

    static t_config_option_keys overriding_options() { return PrinterEditor::overridable_options(); };
    static t_config_option_keys overridable_options() { return PresetEditor::overridable_options(); };

    static t_config_option_keys options() {
        return t_config_option_keys
        {
            "filament_colour"s, "filament_diameter"s, "filament_notes"s, "filament_max_volumetric_speed"s, "extrusion_multiplier"s, "filament_density"s, "filament_cost"s,
            "temperature"s, "first_layer_temperature"s, "bed_temperature"s, "first_layer_bed_temperature"s,
            "fan_always_on"s, "cooling"s, "compatible_printers"s,
            "min_fan_speed"s, "max_fan_speed"s, "bridge_fan_speed"s, "disable_fan_first_layers"s,
            "fan_below_layer_time"s, "slowdown_below_layer_time"s, "min_print_speed"s,
            "start_filament_gcode"s, "end_filament_gcode"s,
            "filament_settings_id"s
        };
    }

    t_config_option_keys my_options() override { return MaterialEditor::options(); }
protected:
    void _update() override;
    void _build() override;
    const std::string LogChannel() override {return "MaterialEditor"s;} //< Which log these messages should go to.
};

class PresetPage : wxScrolledWindow {
public:
    PresetPage(wxWindow* parent, wxString _title, int _iconID) :
        wxScrolledWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL),
        title(_title), iconID(_iconID) {
            this->vsizer = new wxBoxSizer(wxVERTICAL);
            this->SetSizer(this->vsizer);
            this->SetScrollRate(ui_settings->scroll_step(), ui_settings->scroll_step());
        }
protected:
    wxSizer* vsizer {nullptr};
    wxString title {""};
    int iconID {0};
};

}} // namespace Slic3r::GUI
#endif // PRESETEDITOR_HPP
<commit_msg>Added comment for prompt_unsaved_changes<commit_after>#ifndef PRESETEDITOR_HPP
#define PRESETEDITOR_HPP

// stdlib
#include <string>
#include <functional>

// Libslic3r
#include "libslic3r.h"
#include "ConfigBase.hpp"
#include "Config.hpp"

// GUI
#include "misc_ui.hpp"

// Wx
#include <wx/treectrl.h>
#include <wx/imaglist.h>
#include <wx/panel.h>

using namespace std::string_literals;
namespace Slic3r { namespace GUI {

class PresetPage;

class PresetEditor : public wxPanel {

public:
    /// Member function to retrieve a list of options
    /// that this preset governs. Subclasses should
    /// call their own static method.
    virtual t_config_option_keys my_options() = 0;
    static t_config_option_keys options() { return t_config_option_keys {}; }

    static t_config_option_keys overridable_options() { return t_config_option_keys {}; };
    static t_config_option_keys overriding_options() { return t_config_option_keys {}; };

    virtual t_config_option_keys my_overridable_options() = 0;
    virtual t_config_option_keys my_overriding_options() = 0;

    wxSizer* sizer() { return _sizer; };
    PresetEditor(wxWindow* parent, t_config_option_keys options = {});
    PresetEditor() : PresetEditor(nullptr, {}) {};
    std::shared_ptr<Preset> current_preset;

    /// Check if there is a dirty config that is different than the loaded config.
    bool prompt_unsaved_changes();
    void select_preset_by_name(const wxString& name, bool force = false);

    /// suppress the callback when the tree selection is changed.
    bool disable_tree_sel_changed_event {false};

    void save_preset();
    std::function<void ()> on_save_preset {};
    std::function<void ()> on_value_change {};

    config_ptr config;
    PresetPage* add_options_page(const wxString& _title, const wxString& _icon = "");

    virtual wxString title() = 0;
    virtual std::string name() = 0;
protected:
    // Main sizer
    wxSizer* _sizer {nullptr};
    wxString presets;
    wxImageList* _icons {nullptr};
    wxTreeCtrl* _treectrl {nullptr};
    wxBitmapButton* _btn_save_preset {nullptr};
    wxBitmapButton* _btn_delete_preset {nullptr};
    wxChoice* _presets_choice {nullptr};
    int _iconcount {-1};

    /// Vector of PresetPage pointers; trust wxWidgets RTTI to avoid leaks
    std::vector<PresetPage*> _pages {};

    const unsigned int left_col_width {150};
    void _update_tree();
    void load_presets();

    virtual void _build() = 0;
    virtual void _update() = 0;
    virtual void _on_preset_loaded() = 0;
    void set_tooltips() {
        this->_btn_save_preset->SetToolTip(wxString(_("Save current ")) + this->title());
        this->_btn_delete_preset->SetToolTip(_("Delete this preset."));
    }
};

class PrintEditor : public PresetEditor {
public:

    PrintEditor(wxWindow* parent, t_config_option_keys options = {});
    PrintEditor() : PrintEditor(nullptr, {}) {};

    wxString title() override { return _("Print Settings"); }
    std::string name() override { return "print"s; }

    t_config_option_keys my_overridable_options() override { return PresetEditor::overridable_options(); };
    static t_config_option_keys overridable_options() { return PresetEditor::overridable_options(); };

    t_config_option_keys my_overriding_options() override { return PresetEditor::overriding_options(); };
    static t_config_option_keys overriding_options() { return PresetEditor::overriding_options(); };

    /// Static method to retrieve list of options that this preset governs.
    static t_config_option_keys options() {
        return t_config_option_keys
        {
            "layer_height"s, "first_layer_height"s,
            "adaptive_slicing"s, "adaptive_slicing_quality"s, "match_horizontal_surfaces"s,
            "perimeters"s, "spiral_vase"s,
            "top_solid_layers"s, "bottom_solid_layers"s,
            "extra_perimeters"s, "avoid_crossing_perimeters"s, "thin_walls"s, "overhangs"s,
            "seam_position"s, "external_perimeters_first"s,
            "fill_density"s, "fill_pattern"s, "top_infill_pattern"s, "bottom_infill_pattern"s, "fill_gaps"s,
            "infill_every_layers"s, "infill_only_where_needed"s,
            "solid_infill_every_layers"s, "fill_angle"s, "solid_infill_below_area"s, ""s,
            "only_retract_when_crossing_perimeters"s, "infill_first"s,
            "max_print_speed"s, "max_volumetric_speed"s,
            "perimeter_speed"s, "small_perimeter_speed"s, "external_perimeter_speed"s, "infill_speed"s, ""s,
            "solid_infill_speed"s, "top_solid_infill_speed"s, "support_material_speed"s,
            "support_material_interface_speed"s, "bridge_speed"s, "gap_fill_speed"s,
            "travel_speed"s,
            "first_layer_speed"s,
            "perimeter_acceleration"s, "infill_acceleration"s, "bridge_acceleration"s,
            "first_layer_acceleration"s, "default_acceleration"s,
            "skirts"s, "skirt_distance"s, "skirt_height"s, "min_skirt_length"s,
            "brim_connections_width"s, "brim_width"s, "interior_brim_width"s,
            "support_material"s, "support_material_threshold"s, "support_material_max_layers"s, "support_material_enforce_layers"s,
            "raft_layers"s,
            "support_material_pattern"s, "support_material_spacing"s, "support_material_angle"s, ""s,
            "support_material_interface_layers"s, "support_material_interface_spacing"s,
            "support_material_contact_distance"s, "support_material_buildplate_only"s, "dont_support_bridges"s,
            "notes"s,
            "complete_objects"s, "extruder_clearance_radius"s, "extruder_clearance_height"s,
            "gcode_comments"s, "output_filename_format"s,
            "post_process"s,
            "perimeter_extruder"s, "infill_extruder"s, "solid_infill_extruder"s,
            "support_material_extruder"s, "support_material_interface_extruder"s,
            "ooze_prevention"s, "standby_temperature_delta"s,
            "interface_shells"s, "regions_overlap"s,
            "extrusion_width"s, "first_layer_extrusion_width"s, "perimeter_extrusion_width"s, ""s,
            "external_perimeter_extrusion_width"s, "infill_extrusion_width"s, "solid_infill_extrusion_width"s,
            "top_infill_extrusion_width"s, "support_material_extrusion_width"s,
            "support_material_interface_extrusion_width"s, "infill_overlap"s, "bridge_flow_ratio"s,
            "xy_size_compensation"s, "resolution"s, "shortcuts"s, "compatible_printers"s,
            "print_settings_id"s
        };
    }

    t_config_option_keys my_options() override { return PrintEditor::options(); }

protected:
    void _update() override;
    void _build() override;
};

class PrinterEditor : public PresetEditor {
public:
    PrinterEditor(wxWindow* parent, t_config_option_keys options = {});
    PrinterEditor() : PrinterEditor(nullptr, {}) {};

    wxString title() override { return _("Printer Settings"); }
    std::string name() override { return "printer"s; }
    static t_config_option_keys overridable_options() { return t_config_option_keys
    {
        "pressure_advance"s,
        "retract_length"s, "retract_lift"s, "retract_speed"s, "retract_restart_extra"s,
        "retract_before_travel"s, "retract_layer_change"s, "wipe"s
    }; };
    static t_config_option_keys overriding_options() { return PresetEditor::overriding_options(); };

    t_config_option_keys my_overridable_options() override { return PrinterEditor::overridable_options(); };
    t_config_option_keys my_overriding_options() override { return PrinterEditor::overriding_options(); };

    static t_config_option_keys options() {
        return t_config_option_keys
        {
            "bed_shape"s, "z_offset"s, "z_steps_per_mm"s, "has_heatbed"s,
            "gcode_flavor"s, "use_relative_e_distances"s,
            "serial_port"s, "serial_speed"s,
            "host_type"s, "print_host"s, "octoprint_apikey"s,
            "use_firmware_retraction"s, "pressure_advance"s, "vibration_limit"s,
            "use_volumetric_e"s,
            "start_gcode"s, "end_gcode"s, "before_layer_gcode"s, "layer_gcode"s, "toolchange_gcode"s, "between_objects_gcode"s,
            "nozzle_diameter"s, "extruder_offset"s, "min_layer_height"s, "max_layer_height"s,
            "retract_length"s, "retract_lift"s, "retract_speed"s, "retract_restart_extra"s, "retract_before_travel"s, "retract_layer_change"s, "wipe"s,
            "retract_length_toolchange"s, "retract_restart_extra_toolchange"s, "retract_lift_above"s, "retract_lift_below"s,
            "printer_settings_id"s,
            "printer_notes"s,
            "use_set_and_wait_bed"s, "use_set_and_wait_extruder"s
        };
    }

    t_config_option_keys my_options() override { return PrinterEditor::options(); }
protected:
    void _update() override;
    void _build() override;
    const std::string LogChannel() override {return "PrinterEditor"s;} //< Which log these messages should go to.
};

class MaterialEditor : public PresetEditor {
public:

    wxString title() override { return _("Material Settings"); }
    std::string name() override { return "material"s; }
    preset_t type() override  { return preset_t::Material; };
    int typeId() override  { return static_cast<int>(preset_t::Material); };
    MaterialEditor(wxWindow* parent, t_config_option_keys options = {});
    MaterialEditor() : MaterialEditor(nullptr, {}) {};

    t_config_option_keys my_overridable_options() override { return PresetEditor::overridable_options(); };
    t_config_option_keys my_overriding_options() override { return PrinterEditor::overridable_options(); };

    static t_config_option_keys overriding_options() { return PrinterEditor::overridable_options(); };
    static t_config_option_keys overridable_options() { return PresetEditor::overridable_options(); };

    static t_config_option_keys options() {
        return t_config_option_keys
        {
            "filament_colour"s, "filament_diameter"s, "filament_notes"s, "filament_max_volumetric_speed"s, "extrusion_multiplier"s, "filament_density"s, "filament_cost"s,
            "temperature"s, "first_layer_temperature"s, "bed_temperature"s, "first_layer_bed_temperature"s,
            "fan_always_on"s, "cooling"s, "compatible_printers"s,
            "min_fan_speed"s, "max_fan_speed"s, "bridge_fan_speed"s, "disable_fan_first_layers"s,
            "fan_below_layer_time"s, "slowdown_below_layer_time"s, "min_print_speed"s,
            "start_filament_gcode"s, "end_filament_gcode"s,
            "filament_settings_id"s
        };
    }

    t_config_option_keys my_options() override { return MaterialEditor::options(); }
protected:
    void _update() override;
    void _build() override;
    const std::string LogChannel() override {return "MaterialEditor"s;} //< Which log these messages should go to.
};

class PresetPage : wxScrolledWindow {
public:
    PresetPage(wxWindow* parent, wxString _title, int _iconID) :
        wxScrolledWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL),
        title(_title), iconID(_iconID) {
            this->vsizer = new wxBoxSizer(wxVERTICAL);
            this->SetSizer(this->vsizer);
            this->SetScrollRate(ui_settings->scroll_step(), ui_settings->scroll_step());
        }
protected:
    wxSizer* vsizer {nullptr};
    wxString title {""};
    int iconID {0};
};

}} // namespace Slic3r::GUI
#endif // PRESETEDITOR_HPP
<|endoftext|>


<commit_before>#include "Genes/Stacked_Pawns_Gene.h"

#include <memory>
#include <string>

#include "Game/Board.h"
#include "Game/Piece.h"
#include "Game/Color.h"

#include "Genes/Gene.h"

double Stacked_Pawns_Gene::score_board(const Board& board, Color perspective, size_t) const
{
    double score = 0.0;

    auto own_pawn = board.piece_instance(PAWN, perspective);
    for(char file = 'a'; file <= 'h'; ++file)
    {
        int pawn_count = 0;

        for(int rank = 1; rank <= 8; ++rank)
        {
            if(board.piece_on_square(file, rank) == own_pawn)
            {
                ++pawn_count;
            }
        }

        if(pawn_count > 1)
        {
            score += pawn_count - 1;
        }
    }

    return -score/6; // negative since, presumably, stacked pawns are bad;
                     // priority can still evolve to be negative.
                     // Divide by six since six is the maximum number of pawns
                     // that can be blocked by other pawns.
}

std::unique_ptr<Gene> Stacked_Pawns_Gene::duplicate() const
{
    return std::make_unique<Stacked_Pawns_Gene>(*this);
}

std::string Stacked_Pawns_Gene::name() const
{
    return "Stacked Pawns Gene";
}
<commit_msg>Reduce search space when looking for pawns<commit_after>#include "Genes/Stacked_Pawns_Gene.h"

#include <memory>
#include <string>

#include "Game/Board.h"
#include "Game/Piece.h"
#include "Game/Color.h"

#include "Genes/Gene.h"

double Stacked_Pawns_Gene::score_board(const Board& board, Color perspective, size_t) const
{
    double score = 0.0;

    auto own_pawn = board.piece_instance(PAWN, perspective);
    for(char file = 'a'; file <= 'h'; ++file)
    {
        int pawn_count = 0;

        for(int rank = 2; rank <= 7; ++rank)
        {
            if(board.piece_on_square(file, rank) == own_pawn)
            {
                ++pawn_count;
            }
        }

        if(pawn_count > 1)
        {
            score += pawn_count - 1;
        }
    }

    return -score/6; // negative since, presumably, stacked pawns are bad;
                     // priority can still evolve to be negative.
                     // Divide by six since six is the maximum number of pawns
                     // that can be blocked by other pawns.
}

std::unique_ptr<Gene> Stacked_Pawns_Gene::duplicate() const
{
    return std::make_unique<Stacked_Pawns_Gene>(*this);
}

std::string Stacked_Pawns_Gene::name() const
{
    return "Stacked Pawns Gene";
}
<|endoftext|>


<commit_before>#include "../test.h"
#include <Eigen/Core>
#include "../../src/utils/persister.h"
#include "../../src/label.h"
#include "../../src/mesh_node.h"

TEST(Test_QObjectPersistence, SaveAndLoadASimpleString)
{
  std::string text = "example text";

  Persister::save(text, "test.xml");

  EXPECT_EQ(text, Persister::load<std::string>("test.xml"));
}

TEST(Test_QObjectPersistence, SaveAndLoadAVector)
{
  Eigen::Vector3f vector(1.0f, 1.1f, 1.2f);

  Persister::save(vector, "test.xml");
  auto loaded = Persister::load<Eigen::Vector3f>("test.xml");
  EXPECT_Vector3f_NEAR(vector, loaded, 1E-5f);
}

TEST(Test_QObjectPersistence, SaveAndLoadALabel)
{
  Label label(2, "my label 2", Eigen::Vector3f(1, 2, 3));

  Persister::save(label, "test.xml");
  auto loaded = Persister::load<Label>("test.xml");
  EXPECT_EQ(label.id, loaded.id);
  EXPECT_EQ(label.text, loaded.text);
  EXPECT_Vector3f_NEAR(label.anchorPosition, loaded.anchorPosition, 1E-5f);
}

TEST(Test_QObjectPersistence, SaveAndLoadMeshNode)
{
}

TEST(Test_QObjectPersistence, SaveAndLoadAMatrix)
{
  Eigen::Matrix4f matrix;
  matrix << 0.0f, 0.1f, 0.2f, 0.3f, 1.0f, 1.1f, 1.2f, 1.3f, 2.0f, 2.1f, 2.2f,
      2.3f, 3.0f, 3.1f, 3.2f, 3.3f;

  Persister::save(matrix, "test.xml");
  auto loaded = Persister::load<Eigen::Matrix4f>("test.xml");
  EXPECT_Matrix4f_NEAR(matrix, loaded, 1E-5f);
}
<commit_msg>Test to save and load a label pointer.<commit_after>#include "../test.h"
#include <Eigen/Core>
#include "../../src/utils/persister.h"
#include "../../src/label.h"
#include "../../src/mesh_node.h"

TEST(Test_QObjectPersistence, SaveAndLoadASimpleString)
{
  std::string text = "example text";

  Persister::save(text, "test.xml");

  EXPECT_EQ(text, Persister::load<std::string>("test.xml"));
}

TEST(Test_QObjectPersistence, SaveAndLoadAVector)
{
  Eigen::Vector3f vector(1.0f, 1.1f, 1.2f);

  Persister::save(vector, "test.xml");
  auto loaded = Persister::load<Eigen::Vector3f>("test.xml");
  EXPECT_Vector3f_NEAR(vector, loaded, 1E-5f);
}

TEST(Test_QObjectPersistence, SaveAndLoadALabel)
{
  Label label(2, "my label 2", Eigen::Vector3f(1, 2, 3));

  Persister::save(label, "test.xml");
  auto loaded = Persister::load<Label>("test.xml");
  EXPECT_EQ(label.id, loaded.id);
  EXPECT_EQ(label.text, loaded.text);
  EXPECT_Vector3f_NEAR(label.anchorPosition, loaded.anchorPosition, 1E-5f);
}

TEST(Test_QObjectPersistence, SaveAndLoadALabelPointer)
{
  auto label = new Label(2, "my label 2", Eigen::Vector3f(1, 2, 3));

  Persister::save(label, "test.xml");
  auto loaded = Persister::load<Label*>("test.xml");
  EXPECT_EQ(label->id, loaded->id);
  EXPECT_EQ(label->text, loaded->text);
  EXPECT_Vector3f_NEAR(label->anchorPosition, loaded->anchorPosition, 1E-5f);

  delete label;
  delete loaded;
}

TEST(Test_QObjectPersistence, SaveAndLoadAMatrix)
{
  Eigen::Matrix4f matrix;
  matrix << 0.0f, 0.1f, 0.2f, 0.3f, 1.0f, 1.1f, 1.2f, 1.3f, 2.0f, 2.1f, 2.2f,
      2.3f, 3.0f, 3.1f, 3.2f, 3.3f;

  Persister::save(matrix, "test.xml");
  auto loaded = Persister::load<Eigen::Matrix4f>("test.xml");
  EXPECT_Matrix4f_NEAR(matrix, loaded, 1E-5f);
}
<|endoftext|>


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

#include <assert.h>
#include <QMutexLocker>
#include <QScopedPointer>
#include <stdlib.h>
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/file/stream.hh"
#include "com/centreon/broker/io/exceptions/shutdown.hh"
#include "com/centreon/broker/io/raw.hh"
#include "com/centreon/broker/logging/logging.hh"

using namespace com::centreon::broker;
using namespace com::centreon::broker::file;

/**************************************
*                                     *
*           Private Methods           *
*                                     *
**************************************/

/**
 *  @brief Copy constructor.
 *
 *  Any call to this constructor will lead to a call to abort().
 *
 *  @param[in] s Object to copy.
 */
stream::stream(stream const& s) : io::stream(s) {
  assert(false);
  abort();
}

/**
 *  @brief Assignment operator.
 *
 *  Any call to this method will lead to a call to abort().
 *
 *  @param[in] s Object to copy.
 *
 *  @return This object.
 */
stream& stream::operator=(stream const& s) {
  (void)s;
  assert(false);
  abort();
  return (*this);
}

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

/**
 *  Constructor.
 *
 *  @param[in] filename Filename.
 *  @param[in] mode     Open mode.
 */
stream::stream(QString const& filename, QIODevice::OpenMode mode)
  : _file(filename) {
  if (!_file.open(mode))
    throw (exceptions::msg() << "file: could not open '"
             << filename << "': " << _file.errorString());
  _woffset = _file.pos();
  if (!_file.reset())
    throw (exceptions::msg() << "file: could not reset in '"
             << filename << "': " << _file.errorString());
  _roffset = _file.pos();
  _coffset = _roffset;
  _process_in = (mode & QIODevice::ReadOnly);
  _process_out = (mode & QIODevice::WriteOnly);
}

/**
 *  Destructor.
 */
stream::~stream() {
  logging::debug(logging::medium) << "file: closing '"
    << _file.fileName() << "'";
  _file.flush();
  _file.close();
  if (_woffset == _roffset) {
    logging::info(logging::high) << "file: end of file '"
      << _file.fileName() << "' reached, erasing file";
    QFile::remove(_file.fileName());
  }
  else
    logging::debug(logging::medium) << "file: not erasing '"
      << _file.fileName() << "' write offset is " << _woffset
      << " whereas read offset is " << _roffset;
}

/**
 *  Set processing flags.
 *
 *  @param[in] in  Set to true to process input events.
 *  @param[in] out Set to true to process output events.
 */
void stream::process(bool in, bool out) {
  QMutexLocker lock(&_mutex);
  _process_in = in;
  _process_out = in || !out;
  return ;
}

/**
 *  Read data from the file.
 *
 *  @return Bunch of data.
 */
QSharedPointer<io::data> stream::read() {
  // Lock mutex.
  QMutexLocker lock(&_mutex);

  // Check that read should be done.
  if (!_process_in)
    throw (io::exceptions::shutdown(!_process_in, !_process_out)
             << "file stream is shutdown");

  // Seek if necessary.
  if (_roffset != _coffset) {
    if (!_file.seek(_roffset))
      throw (exceptions::msg() << "file: could not seek for reading " \
                  "in '" << _file.fileName() << "' at offset "
               << static_cast<unsigned long long>(_roffset));
  }

  // Build data array.
  QScopedPointer<io::raw> data(new io::raw);
  data->resize(4096);

  // Read data.
  QSharedPointer<io::data> retval;
  qint64 rb(_file.read(data->QByteArray::data(), data->size()));
  if (!rb) // XXX : io::exceptions::error
    throw (io::exceptions::shutdown(true, !_process_out)
             << "file does not have any more data");
  else if (rb < 0) {
    exceptions::msg e;
    e << "file: could not read data from '"
      << _file.fileName() << "': " << _file.errorString();
    _roffset = _file.pos();
    _coffset = _roffset;
    throw (e);
  }
  else {
    data->resize(rb);
    _roffset += rb;
    _coffset = _roffset;
    retval = QSharedPointer<io::data>(data.take());
  }
  return (retval);
}

/**
 *  Write data to the file.
 *
 *  @param[in] d Data to write.
 */
void stream::write(QSharedPointer<io::data> d) {
  // Check that writing should be processed.
  if (!_process_out)
    throw (io::exceptions::shutdown(!_process_in, !_process_out)
             << "file stream is shutdown");

  if (d->type() == "com::centreon::broker::io::raw") {
    // Lock mutex.
    QMutexLocker lock(&_mutex);

    // Seek to end of file if necessary.
    if (_woffset != _coffset) {
      if (!_file.seek(_woffset))
        throw (exceptions::msg() << "file: could not seek for writing" \
                    " in '" << _file.fileName() << "' at offset "
                 << static_cast<unsigned long long>(_woffset));
    }

    // Get data.
    void* memory;
    unsigned int size;
    {
      io::raw* data(static_cast<io::raw*>(d.data()));
      memory = data->QByteArray::data();
      size = data->size();
    }

    // Debug message.
    logging::debug(logging::low) << "file: write request of "
      << size << " bytes";

    // Write data.
    while (size > 0) {
      qint64 wb(_file.write(static_cast<char*>(memory), size));
      if (wb <= 0) {
        exceptions::msg e;
        e << "file: could not write data in '" << _file.fileName()
          << "': " << _file.errorString();
        _woffset = _file.pos();
        _coffset = _woffset;
        throw (e);
      }
      size -= wb;
      _woffset += wb;
      _file.waitForBytesWritten(-1);
    }
    _coffset = _woffset;
  }
  else
    logging::info(logging::low) << "file: write request with "	\
      "invalid data (" << d->type() << ")";
  return ;
}
<commit_msg>Erase retention file as it is read.<commit_after>/*
** Copyright 2011 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/

#include <assert.h>
#include <QMutexLocker>
#include <QScopedPointer>
#include <stdlib.h>
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/file/stream.hh"
#include "com/centreon/broker/io/exceptions/shutdown.hh"
#include "com/centreon/broker/io/raw.hh"
#include "com/centreon/broker/logging/logging.hh"

using namespace com::centreon::broker;
using namespace com::centreon::broker::file;

/**************************************
*                                     *
*           Private Methods           *
*                                     *
**************************************/

/**
 *  @brief Copy constructor.
 *
 *  Any call to this constructor will lead to a call to abort().
 *
 *  @param[in] s Object to copy.
 */
stream::stream(stream const& s) : io::stream(s) {
  assert(false);
  abort();
}

/**
 *  @brief Assignment operator.
 *
 *  Any call to this method will lead to a call to abort().
 *
 *  @param[in] s Object to copy.
 *
 *  @return This object.
 */
stream& stream::operator=(stream const& s) {
  (void)s;
  assert(false);
  abort();
  return (*this);
}

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

/**
 *  Constructor.
 *
 *  @param[in] filename Filename.
 *  @param[in] mode     Open mode.
 */
stream::stream(QString const& filename, QIODevice::OpenMode mode)
  : _file(filename) {
  if (!_file.open(mode))
    throw (exceptions::msg() << "file: could not open '"
             << filename << "': " << _file.errorString());
  _woffset = _file.pos();
  if (!_file.reset())
    throw (exceptions::msg() << "file: could not reset in '"
             << filename << "': " << _file.errorString());
  _roffset = _file.pos();
  _coffset = _roffset;
  _process_in = (mode & QIODevice::ReadOnly);
  _process_out = (mode & QIODevice::WriteOnly);
}

/**
 *  Destructor.
 */
stream::~stream() {
  logging::debug(logging::medium) << "file: closing '"
    << _file.fileName() << "'";
  _file.flush();
  _file.close();
  if (_woffset == _roffset) {
    logging::info(logging::high) << "file: end of file '"
      << _file.fileName() << "' reached, erasing file";
    QFile::remove(_file.fileName());
  }
  else
    logging::debug(logging::medium) << "file: not erasing '"
      << _file.fileName() << "' write offset is " << _woffset
      << " whereas read offset is " << _roffset;
}

/**
 *  Set processing flags.
 *
 *  @param[in] in  Set to true to process input events.
 *  @param[in] out Set to true to process output events.
 */
void stream::process(bool in, bool out) {
  QMutexLocker lock(&_mutex);
  _process_in = in;
  _process_out = in || !out;
  return ;
}

/**
 *  Read data from the file.
 *
 *  @return Bunch of data.
 */
QSharedPointer<io::data> stream::read() {
  // Lock mutex.
  QMutexLocker lock(&_mutex);

  // Check that read should be done.
  if (!_process_in)
    throw (io::exceptions::shutdown(!_process_in, !_process_out)
             << "file stream is shutdown");

  // Seek if necessary.
  if (_roffset != _coffset) {
    if (!_file.seek(_roffset))
      throw (exceptions::msg() << "file: could not seek for reading " \
                  "in '" << _file.fileName() << "' at offset "
               << static_cast<unsigned long long>(_roffset));
  }

  // Build data array.
  QScopedPointer<io::raw> data(new io::raw);
  data->resize(4096);

  // Read data.
  qint64 old_roffset(_roffset);
  QSharedPointer<io::data> retval;
  qint64 rb(_file.read(data->QByteArray::data(), data->size()));
  if (!rb) // XXX : io::exceptions::error
    throw (io::exceptions::shutdown(true, !_process_out)
             << "file does not have any more data");
  else if (rb < 0) {
    exceptions::msg e;
    e << "file: could not read data from '"
      << _file.fileName() << "': " << _file.errorString();
    _roffset = _file.pos();
    _coffset = _roffset;
    throw (e);
  }
  else {
    // Process data.
    data->resize(rb);
    _roffset += rb;
    _coffset = _roffset;
    retval = QSharedPointer<io::data>(data.take());

    // Erase read data.
    if (!_file.seek(old_roffset))
      logging::error(logging::medium) << "file: erase seek failed in '"
        << _file.fileName() << "'";
    else {
      QByteArray eraser;
      eraser.fill('\n', rb);
      while (!eraser.isEmpty()) {
        rb = _file.write(eraser.data(), eraser.size());
        if (rb <= 0) {
          logging::error(logging::medium)
            << "file: erasing request failed in '" << _file.fileName()
            << "'";
          _coffset -= eraser.size();
          break ;
        }
        else
          eraser.resize(eraser.size() - rb);
      }
    }
  }
  return (retval);
}

/**
 *  Write data to the file.
 *
 *  @param[in] d Data to write.
 */
void stream::write(QSharedPointer<io::data> d) {
  // Check that writing should be processed.
  if (!_process_out)
    throw (io::exceptions::shutdown(!_process_in, !_process_out)
             << "file stream is shutdown");

  if (d->type() == "com::centreon::broker::io::raw") {
    // Lock mutex.
    QMutexLocker lock(&_mutex);

    // Seek to end of file if necessary.
    if (_woffset != _coffset) {
      if (!_file.seek(_woffset))
        throw (exceptions::msg() << "file: could not seek for writing" \
                    " in '" << _file.fileName() << "' at offset "
                 << static_cast<unsigned long long>(_woffset));
    }

    // Get data.
    void* memory;
    unsigned int size;
    {
      io::raw* data(static_cast<io::raw*>(d.data()));
      memory = data->QByteArray::data();
      size = data->size();
    }

    // Debug message.
    logging::debug(logging::low) << "file: write request of "
      << size << " bytes";

    // Write data.
    while (size > 0) {
      qint64 wb(_file.write(static_cast<char*>(memory), size));
      if (wb <= 0) {
        exceptions::msg e;
        e << "file: could not write data in '" << _file.fileName()
          << "': " << _file.errorString();
        _woffset = _file.pos();
        _coffset = _woffset;
        throw (e);
      }
      size -= wb;
      _woffset += wb;
      _file.waitForBytesWritten(-1);
    }
    _coffset = _woffset;
  }
  else
    logging::info(logging::low) << "file: write request with "	\
      "invalid data (" << d->type() << ")";
  return ;
}
<|endoftext|>


<commit_before>#pragma once

#include "Sha256.hpp"
#include "DoubleHash.hpp"

namespace Ethereum{

class DoubleSha256CheckSum
{
    public:

        template<class Iterator>
        uint32_t operator()(Iterator begin, Iterator end) const;

        template<class Data>
        uint32_t operator()(const Data &) const;

        template<class Iterator>
        uint32_t checksum(Iterator begin, Iterator end) const;

        template<class Data>
        uint32_t checksum(const Data &) const;

};

}

#include "DoubleSha256CheckSum.ipp"
<commit_msg>stdint dependency<commit_after>#pragma once

#include <stdint.h>

#include "Sha256.hpp"
#include "DoubleHash.hpp"

namespace Ethereum{

class DoubleSha256CheckSum
{
    public:

        template<class Iterator>
        uint32_t operator()(Iterator begin, Iterator end) const;

        template<class Data>
        uint32_t operator()(const Data &) const;

        template<class Iterator>
        uint32_t checksum(Iterator begin, Iterator end) const;

        template<class Data>
        uint32_t checksum(const Data &) const;

};

}

#include "DoubleSha256CheckSum.ipp"
<|endoftext|>


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

#include "config.h"
#include "core/css/parser/CSSParserImpl.h"

#include "core/css/CSSStyleSheet.h"
#include "core/css/StylePropertySet.h"
#include "core/css/StyleSheetContents.h"
#include "core/css/parser/CSSParserValues.h"
#include "core/css/parser/CSSPropertyParser.h"
#include "core/css/parser/CSSTokenizer.h"
#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "core/frame/UseCounter.h"
#include "wtf/BitArray.h"

namespace blink {

CSSParserImpl::CSSParserImpl(const CSSParserContext& context, const String& s)
: m_context(context)
{
    CSSTokenizer::tokenize(s, m_tokens);
}

bool CSSParserImpl::parseValue(MutableStylePropertySet* declaration, CSSPropertyID propertyID, const String& string, bool important, const CSSParserContext& context)
{
    CSSParserImpl parser(context, string);
    CSSRuleSourceData::Type ruleType = CSSRuleSourceData::STYLE_RULE;
    if (declaration->cssParserMode() == CSSViewportRuleMode)
        ruleType = CSSRuleSourceData::VIEWPORT_RULE;
    parser.consumeDeclarationValue(CSSParserTokenRange(parser.m_tokens), propertyID, important, ruleType);
    if (parser.m_parsedProperties.isEmpty())
        return false;
    declaration->addParsedProperties(parser.m_parsedProperties);
    return true;
}

static inline void filterProperties(bool important, const WillBeHeapVector<CSSProperty, 256>& input, WillBeHeapVector<CSSProperty, 256>& output, size_t& unusedEntries, BitArray<numCSSProperties>& seenProperties)
{
    // Add properties in reverse order so that highest priority definitions are reached first. Duplicate definitions can then be ignored when found.
    for (size_t i = input.size(); i--; ) {
        const CSSProperty& property = input[i];
        if (property.isImportant() != important)
            continue;
        const unsigned propertyIDIndex = property.id() - firstCSSProperty;
        if (seenProperties.get(propertyIDIndex))
            continue;
        seenProperties.set(propertyIDIndex);
        output[--unusedEntries] = property;
    }
}

static PassRefPtrWillBeRawPtr<ImmutableStylePropertySet> createStylePropertySet(const WillBeHeapVector<CSSProperty, 256>& parsedProperties, CSSParserMode mode)
{
    BitArray<numCSSProperties> seenProperties;
    size_t unusedEntries = parsedProperties.size();
    WillBeHeapVector<CSSProperty, 256> results(unusedEntries);

    filterProperties(true, parsedProperties, results, unusedEntries, seenProperties);
    filterProperties(false, parsedProperties, results, unusedEntries, seenProperties);

    return ImmutableStylePropertySet::create(results.data() + unusedEntries, results.size() - unusedEntries, mode);
}

PassRefPtrWillBeRawPtr<ImmutableStylePropertySet> CSSParserImpl::parseInlineStyleDeclaration(const String& string, Element* element)
{
    Document& document = element->document();
    CSSParserContext context = CSSParserContext(document.elementSheet().contents()->parserContext(), UseCounter::getFrom(&document));
    CSSParserMode mode = element->isHTMLElement() && !document.inQuirksMode() ? HTMLStandardMode : HTMLQuirksMode;
    context.setMode(mode);
    CSSParserImpl parser(context, string);
    parser.consumeDeclarationList(CSSParserTokenRange(parser.m_tokens), CSSRuleSourceData::STYLE_RULE);
    return createStylePropertySet(parser.m_parsedProperties, mode);
}

bool CSSParserImpl::parseDeclaration(MutableStylePropertySet* declaration, const String& string, const CSSParserContext& context)
{
    CSSParserImpl parser(context, string);
    CSSRuleSourceData::Type ruleType = CSSRuleSourceData::STYLE_RULE;
    if (declaration->cssParserMode() == CSSViewportRuleMode)
        ruleType = CSSRuleSourceData::VIEWPORT_RULE;
    parser.consumeDeclarationList(CSSParserTokenRange(parser.m_tokens), ruleType);
    if (parser.m_parsedProperties.isEmpty())
        return false;
    declaration->addParsedProperties(parser.m_parsedProperties);
    return true;
}

void CSSParserImpl::consumeDeclarationList(CSSParserTokenRange range, CSSRuleSourceData::Type ruleType)
{
    while (!range.atEnd()) {
        switch (range.peek().type()) {
        case CommentToken:
        case WhitespaceToken:
        case SemicolonToken:
            range.consume();
            break;
        case IdentToken: {
            const CSSParserToken* declarationStart = &range.peek();
            while (!range.atEnd() && range.peek().type() != SemicolonToken)
                range.consume();
            consumeDeclaration(range.makeSubRange(declarationStart, &range.peek()), ruleType);
            break;
        }
        default: // Parser error
            // FIXME: The spec allows at-rules in a declaration list
            while (!range.atEnd() && range.peek().type() != SemicolonToken)
                range.consume();
            break;
        }
    }
}

void CSSParserImpl::consumeDeclaration(CSSParserTokenRange range, CSSRuleSourceData::Type ruleType)
{
    ASSERT(range.peek().type() == IdentToken);
    CSSPropertyID id = range.consume().parseAsCSSPropertyID();
    range.consumeWhitespaceAndComments();
    if (range.consume().type() != ColonToken)
        return; // Parser error

    const CSSParserToken* last = range.end() - 1;
    while (last->type() == WhitespaceToken || last->type() == CommentToken)
        --last;
    if (last->type() == IdentToken && equalIgnoringCase(last->value(), "important")) {
        --last;
        while (last->type() == WhitespaceToken || last->type() == CommentToken)
            --last;
        if (last->type() == DelimiterToken && last->delimiter() == '!') {
            consumeDeclarationValue(range.makeSubRange(&range.peek(), last), id, true, ruleType);
            return;
        }
    }
    consumeDeclarationValue(range.makeSubRange(&range.peek(), range.end()), id, false, ruleType);
}

void CSSParserImpl::consumeDeclarationValue(CSSParserTokenRange range, CSSPropertyID propertyID, bool important, CSSRuleSourceData::Type ruleType)
{
    CSSParserValueList valueList(range);
    if (!valueList.size())
        return; // Parser error
    bool inViewport = ruleType == CSSRuleSourceData::VIEWPORT_RULE;
    CSSPropertyParser::parseValue(propertyID, important, &valueList, m_context, inViewport, m_parsedProperties, ruleType);
}

} // namespace blink
<commit_msg>CSS Parser: consumeDeclarationList should advance by component values<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "config.h"
#include "core/css/parser/CSSParserImpl.h"

#include "core/css/CSSStyleSheet.h"
#include "core/css/StylePropertySet.h"
#include "core/css/StyleSheetContents.h"
#include "core/css/parser/CSSParserValues.h"
#include "core/css/parser/CSSPropertyParser.h"
#include "core/css/parser/CSSTokenizer.h"
#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "core/frame/UseCounter.h"
#include "wtf/BitArray.h"

namespace blink {

CSSParserImpl::CSSParserImpl(const CSSParserContext& context, const String& s)
: m_context(context)
{
    CSSTokenizer::tokenize(s, m_tokens);
}

bool CSSParserImpl::parseValue(MutableStylePropertySet* declaration, CSSPropertyID propertyID, const String& string, bool important, const CSSParserContext& context)
{
    CSSParserImpl parser(context, string);
    CSSRuleSourceData::Type ruleType = CSSRuleSourceData::STYLE_RULE;
    if (declaration->cssParserMode() == CSSViewportRuleMode)
        ruleType = CSSRuleSourceData::VIEWPORT_RULE;
    parser.consumeDeclarationValue(CSSParserTokenRange(parser.m_tokens), propertyID, important, ruleType);
    if (parser.m_parsedProperties.isEmpty())
        return false;
    declaration->addParsedProperties(parser.m_parsedProperties);
    return true;
}

static inline void filterProperties(bool important, const WillBeHeapVector<CSSProperty, 256>& input, WillBeHeapVector<CSSProperty, 256>& output, size_t& unusedEntries, BitArray<numCSSProperties>& seenProperties)
{
    // Add properties in reverse order so that highest priority definitions are reached first. Duplicate definitions can then be ignored when found.
    for (size_t i = input.size(); i--; ) {
        const CSSProperty& property = input[i];
        if (property.isImportant() != important)
            continue;
        const unsigned propertyIDIndex = property.id() - firstCSSProperty;
        if (seenProperties.get(propertyIDIndex))
            continue;
        seenProperties.set(propertyIDIndex);
        output[--unusedEntries] = property;
    }
}

static PassRefPtrWillBeRawPtr<ImmutableStylePropertySet> createStylePropertySet(const WillBeHeapVector<CSSProperty, 256>& parsedProperties, CSSParserMode mode)
{
    BitArray<numCSSProperties> seenProperties;
    size_t unusedEntries = parsedProperties.size();
    WillBeHeapVector<CSSProperty, 256> results(unusedEntries);

    filterProperties(true, parsedProperties, results, unusedEntries, seenProperties);
    filterProperties(false, parsedProperties, results, unusedEntries, seenProperties);

    return ImmutableStylePropertySet::create(results.data() + unusedEntries, results.size() - unusedEntries, mode);
}

PassRefPtrWillBeRawPtr<ImmutableStylePropertySet> CSSParserImpl::parseInlineStyleDeclaration(const String& string, Element* element)
{
    Document& document = element->document();
    CSSParserContext context = CSSParserContext(document.elementSheet().contents()->parserContext(), UseCounter::getFrom(&document));
    CSSParserMode mode = element->isHTMLElement() && !document.inQuirksMode() ? HTMLStandardMode : HTMLQuirksMode;
    context.setMode(mode);
    CSSParserImpl parser(context, string);
    parser.consumeDeclarationList(CSSParserTokenRange(parser.m_tokens), CSSRuleSourceData::STYLE_RULE);
    return createStylePropertySet(parser.m_parsedProperties, mode);
}

bool CSSParserImpl::parseDeclaration(MutableStylePropertySet* declaration, const String& string, const CSSParserContext& context)
{
    CSSParserImpl parser(context, string);
    CSSRuleSourceData::Type ruleType = CSSRuleSourceData::STYLE_RULE;
    if (declaration->cssParserMode() == CSSViewportRuleMode)
        ruleType = CSSRuleSourceData::VIEWPORT_RULE;
    parser.consumeDeclarationList(CSSParserTokenRange(parser.m_tokens), ruleType);
    if (parser.m_parsedProperties.isEmpty())
        return false;
    declaration->addParsedProperties(parser.m_parsedProperties);
    return true;
}

void CSSParserImpl::consumeDeclarationList(CSSParserTokenRange range, CSSRuleSourceData::Type ruleType)
{
    while (!range.atEnd()) {
        switch (range.peek().type()) {
        case CommentToken:
        case WhitespaceToken:
        case SemicolonToken:
            range.consume();
            break;
        case IdentToken: {
            const CSSParserToken* declarationStart = &range.peek();
            while (!range.atEnd() && range.peek().type() != SemicolonToken)
                range.consumeComponentValue();
            consumeDeclaration(range.makeSubRange(declarationStart, &range.peek()), ruleType);
            break;
        }
        default: // Parser error
            // FIXME: The spec allows at-rules in a declaration list
            while (!range.atEnd() && range.peek().type() != SemicolonToken)
                range.consumeComponentValue();
            break;
        }
    }
}

void CSSParserImpl::consumeDeclaration(CSSParserTokenRange range, CSSRuleSourceData::Type ruleType)
{
    ASSERT(range.peek().type() == IdentToken);
    CSSPropertyID id = range.consume().parseAsCSSPropertyID();
    range.consumeWhitespaceAndComments();
    if (range.consume().type() != ColonToken)
        return; // Parser error

    const CSSParserToken* last = range.end() - 1;
    while (last->type() == WhitespaceToken || last->type() == CommentToken)
        --last;
    if (last->type() == IdentToken && equalIgnoringCase(last->value(), "important")) {
        --last;
        while (last->type() == WhitespaceToken || last->type() == CommentToken)
            --last;
        if (last->type() == DelimiterToken && last->delimiter() == '!') {
            consumeDeclarationValue(range.makeSubRange(&range.peek(), last), id, true, ruleType);
            return;
        }
    }
    consumeDeclarationValue(range.makeSubRange(&range.peek(), range.end()), id, false, ruleType);
}

void CSSParserImpl::consumeDeclarationValue(CSSParserTokenRange range, CSSPropertyID propertyID, bool important, CSSRuleSourceData::Type ruleType)
{
    CSSParserValueList valueList(range);
    if (!valueList.size())
        return; // Parser error
    bool inViewport = ruleType == CSSRuleSourceData::VIEWPORT_RULE;
    CSSPropertyParser::parseValue(propertyID, important, &valueList, m_context, inViewport, m_parsedProperties, ruleType);
}

} // namespace blink
<|endoftext|>


<commit_before>//!@Alan
//!
//! Exercise 6.12:
//! Rewrite the program from exercise 6.10 in § 6.2.1 (p. 210) to use
//! references instead of pointers to swap the value of two ints. Which
//! version do you think would be easier to use and why?
//  The version using reference is easier.
//!

#include <iostream>
#include <string>
#include <stdexcept>

using namespace std;

void swap(int& _n1, int& _n2);

int main()
{
    int n1, n2;

    cout<<"Please Enter:\n";
    while(cin>>n1>>n2)
    {
        swap(n1, n2);
        cout<<n1<<" "<<n2<<endl;
    }

    return 0;
}

void swap(int &_n1, int &_n2)
{
    int temp;
    temp = _n1;
    _n1 = _n2;
    _n2 = temp;

}
<commit_msg>Update ex6_12.cpp<commit_after>//!@Yue Wang
//!
//! Exercise 6.12:
//! Rewrite the program from exercise 6.10 in § 6.2.1 (p. 210) to use
//! references instead of pointers to swap the value of two ints. Which
//! version do you think would be easier to use and why?
//  The version using reference is easier.
//!

#include <iostream>
#include <string>
#include <stdexcept>

void swap(int& lhs, int& rhs)
{
    int temp = lhs;
    lhs = rhs;
    rhs = temp;
}

int main()
{
    int left, right;
    std::cout << "Please Enter:\n";
    while (std::cin >> left >> right)
    {
        swap(left, right);
        std::cout << left << " " << right << std::endl;
    }

    return 0;
}

<|endoftext|>


<commit_before>//
//  File:       TEST_PlatformBlock.cpp
//  Class:      TEST_PlatformBlock
//  Author:     Sebastian Odbjer
//              All code is my own except where credited to others.
//
//	Copyright (c) 2012 by Catch22. All Rights Reserved.
//  Date: 		09/10-2012
//

#include "../src/GameModel/Map/PlatformBlock.hpp"
#include "catch.hpp"

TEST_CASE("PlatformBlock", "Tests the PlatformBlock: creates some new platformblocks, checks that the values are correct")
{
	//Create the platformBlocks
	PlatformBlock platformblock1 = PlatformBlock(INCLINE, new Vector2d(0.0, 0.0));
	PlatformBlock platformblock2 = PlatformBlock(HORIZONTAL, new Vector2d(0.0, 0.0));
	PlatformBlock platformblock3 = PlatformBlock(DECLINE, new Vector2d(0.0, 0.0));

	//Check the values
	CHECK(platformblock1.getStartVector()->m_x == 0.0);
	CHECK(platformblock1.getStartVector()->m_y == 0.0);

	CHECK(platformblock1.getEndVector()->m_x == 2.0);
	CHECK(platformblock1.getEndVector()->m_y == 1.0);
	CHECK(platformblock2.getEndVector()->m_x == 2.0);
	CHECK(platformblock2.getEndVector()->m_y == 0.0);
	CHECK(platformblock3.getEndVector()->m_x == 2.0);
	CHECK(platformblock3.getEndVector()->m_y == -1.0);

	CHECK(platformblock1.getType() == INCLINE);
	CHECK(platformblock2.getType() == HORIZONTAL);
	CHECK(platformblock3.getType() == DECLINE);

}
<commit_msg>changed some pointers in the test for platformblock<commit_after>//
//  File:       TEST_PlatformBlock.cpp
//  Class:      TEST_PlatformBlock
//  Author:     Sebastian Odbjer
//              All code is my own except where credited to others.
//
//	Copyright (c) 2012 by Catch22. All Rights Reserved.
//  Date: 		09/10-2012
//
//	License: The following code is licensed under the Catch22-License
//

#include "../src/GameModel/Map/PlatformBlock.hpp"
#include "catch.hpp"

TEST_CASE("PlatformBlock", "Tests the PlatformBlock: creates some new platformblocks, checks that the values are correct")
{
	//Create the platformBlocks
	PlatformBlock platformblock1 = PlatformBlock(INCLINE, new Vector2d(0.0, 0.0));
	PlatformBlock platformblock2 = PlatformBlock(HORIZONTAL, new Vector2d(0.0, 0.0));
	PlatformBlock platformblock3 = PlatformBlock(DECLINE, new Vector2d(0.0, 0.0));

	//Check the values
	CHECK(platformblock1.getStartVector()->m_x == 0.0);
	CHECK(platformblock1.getStartVector()->m_y == 0.0);

	CHECK(platformblock1.getEndVector()->m_x == 2.0);
	CHECK(platformblock1.getEndVector()->m_y == 1.0);
	CHECK(platformblock2.getEndVector()->m_x == 2.0);
	CHECK(platformblock2.getEndVector()->m_y == 0.0);
	CHECK(platformblock3.getEndVector()->m_x == 2.0);
	CHECK(platformblock3.getEndVector()->m_y == -1.0);

	CHECK(platformblock1.getType() == INCLINE);
	CHECK(platformblock2.getType() == HORIZONTAL);
	CHECK(platformblock3.getType() == DECLINE);

}
<|endoftext|>