<commit_before>#include "Moose.h"
#include "Factory.h"

//kernels
///////////////////////////////////////////////////////////////
//      solid mechanics                                      //
///////////////////////////////////////////////////////////////
#include "SolidMechXFalcon.h"
#include "SolidMechYFalcon.h"
#include "SolidMechZFalcon.h"
#include "SolidMechImplicitEuler.h"

#include "SolidMechTempCoupleXFalcon.h"
#include "SolidMechTempCoupleYFalcon.h"
#include "SolidMechTempCoupleZFalcon.h"

#include "SolidMechPoroCoupleX.h"
#include "SolidMechPoroCoupleY.h"
#include "SolidMechPoroCoupleZ.h"

///////////////////////////////////////////////////////////////
//      Single phase formulation: pressure & temperature     //
///////////////////////////////////////////////////////////////
#include "TemperatureTimeDerivative.h"
#include "TemperatureTimeDerivativeFluid.h"
#include "TemperatureTimeDerivativeSolid.h"
#include "TemperatureDiffusion.h"
#include "TemperatureConvection.h"

#include "MassFluxTimeDerivative_PT.h"
#include "WaterMassFluxPressure_PT.h"
#include "WaterMassFluxElevation_PT.h"

//////////////////////////////////////////////////////////////
//       Two phase formulation: pressure & enthalpy         //
//////////////////////////////////////////////////////////////
#include "MassFluxTimeDerivative.h"
#include "WaterMassFluxPressure.h"
#include "SteamMassFluxPressure.h"
#include "WaterMassFluxElevation.h"

#include "EnthalpyTimeDerivative.h"
#include "EnthalpyDiffusion.h"
#include "EnthalpyConvectionWater.h"
#include "EnthalpyConvectionSteam.h"

//auxkernels
#include "CoupledDensityAux_PT.h"          // water density as function of (P,T)
#include "CoupledDdensityDTAux_PT.h"       // derivative of water density to T at const P
#include "CoupledDdensityDPAux_PT.h"       // derivative of water density to P at const T

#include "CoupledTemperatureAux.h"         // T as functon of (P,H) -two phase formulation
#include "CoupledWaterSaturationAux.h"     // Sw as functon of (P,H) -two phase formulation
#include "CoupledDensityAux.h"             // mixed density as functon of (P,H) -two phase formulation

#include "CoupledWaterDensityAux.h"        // water density functon of (P,H) -two phase formulation
#include "CoupledWaterViscosityAux.h"      // water viscosity functon of (P,T) - used by both PT and PH formaulations
#include "CoupledSteamDensityAux.h"        // steam density functon of (P,H) -two phase formulation
#include "CoupledSteamViscosityAux.h"      // steam viscosity functon of (P,T) - used by PH formaulations

#include "CoupledWaterEnthalpyAux.h"       //water enthalpy as function of (P,H) (MJ/kg)
#include "CoupledSteamEnthalpyAux.h"       //steam enthalpy as function of (P,H) (MJ/kg)
#include "CoupledDsteamenthalpydH_PAux.h"  //derivative of steam enthalpy to H at const P: 1 (steam only ); 0 otherwise
#include "CoupledDwaterenthalpydH_PAux.h"  //derivative of water enthalpy to H at const P: 1 (water only ); 0 otherwise

#include "CoupledDdensityDTAux.h"          //derivative of mixed density to T at const P, not used now
#include "CoupledDdensityDPAux.h"          //derivative of mixed density to P at const H,
#include "CoupledDdensityDHAux.h"          //derivative of mixed density to H at const P,
#include "CoupledDTDH_PAux.h"              //derivative of T to H at const P

#include "AnalyticalADE1D.h"
#include "VelocityAux.h"
#include "CoupledPorosityMaterialAux.h"
#include "StressStrainDamageComputeAux.h"

//BCs
#include "PressureNeumannBC2.h"
#include "GravityNeumannBC.h"
#include "OutFlowBC.h"
#include "StepDirichletBC.h"

//materials
#include "PorousMedia.h"
#include "FluidFlow.h"
#include "HeatTransport.h"
#include "SolidMechanics.h"
#include "Geothermal.h"

namespace Falcon
{
  void registerObjects()
  {
    Moose::registerObjects();

//mechanics
    registerNamedKernel(SolidMechXFalcon, "SolidMechXFalcon");
    registerNamedKernel(SolidMechYFalcon, "SolidMechYFalcon");
    registerNamedKernel(SolidMechZFalcon, "SolidMechZFalcon");
    registerKernel(SolidMechImplicitEuler);

    registerNamedKernel(SolidMechTempCoupleXFalcon, "SolidMechTempCoupleX");
    registerNamedKernel(SolidMechTempCoupleYFalcon, "SolidMechTempCoupleY");
    registerNamedKernel(SolidMechTempCoupleZFalcon, "SolidMechTempCoupleZ");

    registerKernel(SolidMechPoroCoupleX);
    registerKernel(SolidMechPoroCoupleY);
    registerKernel(SolidMechPoroCoupleZ);
//heat transport-PT formulation, single phase only
    registerKernel(TemperatureTimeDerivative);
    registerKernel(TemperatureTimeDerivativeFluid);
    registerKernel(TemperatureTimeDerivativeSolid);
    registerKernel(TemperatureDiffusion);
    registerKernel(TemperatureConvection);
//fluid-mass flow-single phase formulation
    registerKernel(MassFluxTimeDerivative_PT);
    registerKernel(WaterMassFluxPressure_PT);
    registerKernel(WaterMassFluxElevation_PT);
//fluid-mass flow-two phase formulation
    registerKernel(MassFluxTimeDerivative);
    registerKernel(WaterMassFluxPressure);
    registerKernel(SteamMassFluxPressure);
    registerKernel(WaterMassFluxElevation);
//energy
    registerKernel(EnthalpyTimeDerivative);
    registerKernel(EnthalpyDiffusion);
    registerKernel(EnthalpyConvectionWater);
    registerKernel(EnthalpyConvectionSteam);

//auxkernels
    registerAux(CoupledDdensityDTAux_PT);
    registerAux(CoupledDdensityDPAux_PT);
    registerAux(CoupledDensityAux_PT);
    registerAux(CoupledWaterSaturationAux);
    registerAux(CoupledDdensityDHAux);
    registerAux(CoupledDTDH_PAux);
    registerAux(CoupledDdensityDPAux);
    registerAux( CoupledDdensityDTAux);
    registerAux(CoupledDensityAux);
    registerAux(CoupledWaterDensityAux);
    registerAux(CoupledWaterViscosityAux);
    registerAux(CoupledWaterEnthalpyAux);
    registerAux(CoupledSteamDensityAux);
    registerAux(CoupledSteamViscosityAux);
    registerAux(CoupledSteamEnthalpyAux);
    registerAux(CoupledDwaterenthalpydH_PAux);
    registerAux(CoupledDsteamenthalpydH_PAux);
    registerAux(CoupledTemperatureAux);

    registerAux(AnalyticalADE1D);
    registerAux(VelocityAux);
    registerAux(CoupledPorosityMaterialAux);
    registerAux(StressStrainDamageComputeAux);

//BCs
    registerNamedBoundaryCondition(PressureNeumannBC2, "PressureNeumannBC");
    registerBoundaryCondition(GravityNeumannBC);
    registerBoundaryCondition(OutFlowBC);
    registerBoundaryCondition(StepDirichletBC);

//materials
    registerMaterial(PorousMedia);
    registerMaterial(FluidFlow);
    registerMaterial(HeatTransport);
    registerMaterial(SolidMechanics);
    registerMaterial(Geothermal);
  }
}
<commit_msg>test now passed<commit_after>#include "Moose.h"
#include "Factory.h"

//kernels
///////////////////////////////////////////////////////////////
//      solid mechanics                                      //
///////////////////////////////////////////////////////////////
#include "SolidMechXFalcon.h"
#include "SolidMechYFalcon.h"
#include "SolidMechZFalcon.h"
#include "SolidMechImplicitEuler.h"

#include "SolidMechTempCoupleXFalcon.h"
#include "SolidMechTempCoupleYFalcon.h"
#include "SolidMechTempCoupleZFalcon.h"

#include "SolidMechPoroCoupleX.h"
#include "SolidMechPoroCoupleY.h"
#include "SolidMechPoroCoupleZ.h"

///////////////////////////////////////////////////////////////
//      Single phase formulation: pressure & temperature     //
///////////////////////////////////////////////////////////////
#include "TemperatureTimeDerivative.h"
#include "TemperatureTimeDerivativeFluid.h"
#include "TemperatureTimeDerivativeSolid.h"
#include "TemperatureDiffusion.h"
#include "TemperatureConvection.h"

#include "MassFluxTimeDerivative_PT.h"
#include "WaterMassFluxPressure_PT.h"
#include "WaterMassFluxElevation_PT.h"

//////////////////////////////////////////////////////////////
//       Two phase formulation: pressure & enthalpy         //
//////////////////////////////////////////////////////////////
#include "MassFluxTimeDerivative.h"
#include "WaterMassFluxPressure.h"
#include "SteamMassFluxPressure.h"
#include "WaterMassFluxElevation.h"

#include "EnthalpyTimeDerivative.h"
#include "EnthalpyDiffusion.h"
#include "EnthalpyConvectionWater.h"
#include "EnthalpyConvectionSteam.h"

//auxkernels
#include "CoupledDensityAux_PT.h"          // water density as function of (P,T)
#include "CoupledDdensityDTAux_PT.h"       // derivative of water density to T at const P
#include "CoupledDdensityDPAux_PT.h"       // derivative of water density to P at const T

#include "CoupledTemperatureAux.h"         // T as functon of (P,H) -two phase formulation
#include "CoupledWaterSaturationAux.h"     // Sw as functon of (P,H) -two phase formulation
#include "CoupledDensityAux.h"             // mixed density as functon of (P,H) -two phase formulation

#include "CoupledWaterDensityAux.h"        // water density functon of (P,H) -two phase formulation
#include "CoupledWaterViscosityAux.h"      // water viscosity functon of (P,T) - used by both PT and PH formaulations
#include "CoupledSteamDensityAux.h"        // steam density functon of (P,H) -two phase formulation
#include "CoupledSteamViscosityAux.h"      // steam viscosity functon of (P,T) - used by PH formaulations

#include "CoupledWaterEnthalpyAux.h"       //water enthalpy as function of (P,H) (MJ/kg)
#include "CoupledSteamEnthalpyAux.h"       //steam enthalpy as function of (P,H) (MJ/kg)
#include "CoupledDsteamenthalpydH_PAux.h"  //derivative of steam enthalpy to H at const P: 1 (steam only ); 0 otherwise
#include "CoupledDwaterenthalpydH_PAux.h"  //derivative of water enthalpy to H at const P: 1 (water only ); 0 otherwise

#include "CoupledDdensityDTAux.h"          //derivative of mixed density to T at const P, not used now
#include "CoupledDdensityDPAux.h"          //derivative of mixed density to P at const H,
#include "CoupledDdensityDHAux.h"          //derivative of mixed density to H at const P,
#include "CoupledDTDH_PAux.h"              //derivative of T to H at const P

#include "AnalyticalADE1D.h"
#include "VelocityAux.h"
#include "CoupledPorosityMaterialAux.h"
#include "StressStrainDamageComputeAux.h"

//BCs
#include "PressureNeumannBC2.h"
#include "GravityNeumannBC.h"
#include "OutFlowBC.h"
#include "StepDirichletBC.h"

//materials
#include "Constant.h"
#include "PorousMedia.h"
#include "FluidFlow.h"
#include "HeatTransport.h"
#include "SolidMechanics.h"
#include "Geothermal.h"

namespace Falcon
{
  void registerObjects()
  {
    Moose::registerObjects();

//mechanics
    registerNamedKernel(SolidMechXFalcon, "SolidMechXFalcon");
    registerNamedKernel(SolidMechYFalcon, "SolidMechYFalcon");
    registerNamedKernel(SolidMechZFalcon, "SolidMechZFalcon");
    registerKernel(SolidMechImplicitEuler);

    registerNamedKernel(SolidMechTempCoupleXFalcon, "SolidMechTempCoupleX");
    registerNamedKernel(SolidMechTempCoupleYFalcon, "SolidMechTempCoupleY");
    registerNamedKernel(SolidMechTempCoupleZFalcon, "SolidMechTempCoupleZ");

    registerKernel(SolidMechPoroCoupleX);
    registerKernel(SolidMechPoroCoupleY);
    registerKernel(SolidMechPoroCoupleZ);
//heat transport-PT formulation, single phase only
    registerKernel(TemperatureTimeDerivative);
    registerKernel(TemperatureTimeDerivativeFluid);
    registerKernel(TemperatureTimeDerivativeSolid);
    registerKernel(TemperatureDiffusion);
    registerKernel(TemperatureConvection);
//fluid-mass flow-single phase formulation
    registerKernel(MassFluxTimeDerivative_PT);
    registerKernel(WaterMassFluxPressure_PT);
    registerKernel(WaterMassFluxElevation_PT);
//fluid-mass flow-two phase formulation
    registerKernel(MassFluxTimeDerivative);
    registerKernel(WaterMassFluxPressure);
    registerKernel(SteamMassFluxPressure);
    registerKernel(WaterMassFluxElevation);
//energy
    registerKernel(EnthalpyTimeDerivative);
    registerKernel(EnthalpyDiffusion);
    registerKernel(EnthalpyConvectionWater);
    registerKernel(EnthalpyConvectionSteam);

//auxkernels
    registerAux(CoupledDdensityDTAux_PT);
    registerAux(CoupledDdensityDPAux_PT);
    registerAux(CoupledDensityAux_PT);
    registerAux(CoupledWaterSaturationAux);
    registerAux(CoupledDdensityDHAux);
    registerAux(CoupledDTDH_PAux);
    registerAux(CoupledDdensityDPAux);
    registerAux( CoupledDdensityDTAux);
    registerAux(CoupledDensityAux);
    registerAux(CoupledWaterDensityAux);
    registerAux(CoupledWaterViscosityAux);
    registerAux(CoupledWaterEnthalpyAux);
    registerAux(CoupledSteamDensityAux);
    registerAux(CoupledSteamViscosityAux);
    registerAux(CoupledSteamEnthalpyAux);
    registerAux(CoupledDwaterenthalpydH_PAux);
    registerAux(CoupledDsteamenthalpydH_PAux);
    registerAux(CoupledTemperatureAux);

    registerAux(AnalyticalADE1D);
    registerAux(VelocityAux);
    registerAux(CoupledPorosityMaterialAux);
    registerAux(StressStrainDamageComputeAux);

//BCs
    registerNamedBoundaryCondition(PressureNeumannBC2, "PressureNeumannBC");
    registerBoundaryCondition(GravityNeumannBC);
    registerBoundaryCondition(OutFlowBC);
    registerBoundaryCondition(StepDirichletBC);

//materials
    registerMaterial(Constant);
    registerMaterial(PorousMedia);
    registerMaterial(FluidFlow);
    registerMaterial(HeatTransport);
    registerMaterial(SolidMechanics);
    registerMaterial(Geothermal);
  }
}
<|endoftext|>


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

#ifndef NDEBUG
#include "config.h"
#include "check_size.h"
#define STATIC_ASSERT(...)
// #define STATIC_ASSERT static_assert
#define CHECK_MAX_SIZE(max_size, name) \
	STATIC_ASSERT((max_size) >= (sizeof name), "Object is too big!"); \
	if ((max_size) < (sizeof name)) { \
		std::cerr << "sizeof" << #name << " = " << (sizeof name) << std::endl; \
	}

#include "allocator.h"
#include "base_x.hh"
#include "bloom_filter.hh"
#include "compressor_deflate.h"
#include "compressor_lz4.h"
#include "database.h"
#include "database_handler.h"
#include "database_pool.h"
#include "database_wal.h"
#include "debouncer.h"
#include "endpoint.h"
#include "logger.h"
#include "manager.h"
#include "msgpack.h"
#include "node.h"
#include "query_dsl.h"
#include "queue.h"
#include "remote_protocol.h"
#include "replication.h"
#include "schema.h"
#include "schemas_lru.h"
#include "script.h"
#include "storage.h"
#include "threadpool.hh"
#include "url_parser.h"
#include "url_parser.h"
#include "booleanParser/BooleanParser.h"
#include "chaipp/chaipp.h"
#include "cuuid/uuid.h"
#include "geospatial/geometry.h"
#include "geospatial/geospatial.h"
#include "geospatial/intersection.h"
#include "geospatial/multicircle.h"
#include "geospatial/multiconvex.h"
#include "geospatial/multipoint.h"
#include "geospatial/multipolygon.h"
#include "geospatial/point.h"
#include "geospatial/polygon.h"
#include "metrics/basic_string_metric.h"
#include "metrics/jaccard.h"
#include "metrics/jaro.h"
#include "metrics/jaro_winkler.h"
#include "metrics/lcsubsequence.h"
#include "metrics/lcsubstr.h"
#include "metrics/levenshtein.h"
#include "metrics/sorensen_dice.h"
#include "metrics/soundex_metric.h"
#include "multivalue/aggregation.h"
#include "multivalue/aggregation_bucket.h"
#include "multivalue/aggregation_metric.h"
#include "multivalue/geospatialrange.h"
#include "multivalue/keymaker.h"
#include "multivalue/range.h"
#include "phonetic/english_soundex.h"
#include "phonetic/french_soundex.h"
#include "phonetic/german_soundex.h"
#include "phonetic/spanish_soundex.h"
#include "server/http.h"
#include "server/http_server.h"
#include "server/http_client.h"
#include "server/binary.h"
#include "server/binary_server.h"
#include "server/binary_client.h"
#include "server/raft.h"
#include "server/discovery.h"
#include "server/server.h"
#include "v8pp/v8pp.h"

#define TINY 8
#define SMALL 128
#define REGULAR 1024
#define BIG 5 * 1024
#define LARGE 20 * 1024

void
check_size()
{

// allocator.h
CHECK_MAX_SIZE(TINY, (allocator::VanillaAllocator))
CHECK_MAX_SIZE(TINY, (allocator::TrackedAllocator))

// base_x.hh
CHECK_MAX_SIZE(TINY, (BaseX))
CHECK_MAX_SIZE(TINY, (Base2))
CHECK_MAX_SIZE(TINY, (Base8))
CHECK_MAX_SIZE(TINY, (Base11))
CHECK_MAX_SIZE(TINY, (Base16))
CHECK_MAX_SIZE(TINY, (Base32))
CHECK_MAX_SIZE(TINY, (Base36))
CHECK_MAX_SIZE(TINY, (Base58))
CHECK_MAX_SIZE(TINY, (Base59))
CHECK_MAX_SIZE(TINY, (Base62))
CHECK_MAX_SIZE(TINY, (Base64))
CHECK_MAX_SIZE(TINY, (Base66))

// bloom_filter.hh
CHECK_MAX_SIZE(SMALL, (BloomFilter<>))

// compressor_deflate.h
CHECK_MAX_SIZE(SMALL, (DeflateCompressData))
CHECK_MAX_SIZE(SMALL, (DeflateCompressFile))
CHECK_MAX_SIZE(SMALL, (DeflateDecompressData))
CHECK_MAX_SIZE(SMALL, (DeflateDecompressFile))

// compressor_lz4.h
CHECK_MAX_SIZE(SMALL, (LZ4CompressData))
CHECK_MAX_SIZE(SMALL, (LZ4CompressFile))
CHECK_MAX_SIZE(SMALL, (LZ4DecompressData))
CHECK_MAX_SIZE(SMALL, (LZ4DecompressFile))

// database.h
CHECK_MAX_SIZE(SMALL, (Database))

// database_handler.h
CHECK_MAX_SIZE(SMALL, (Data))
CHECK_MAX_SIZE(SMALL, (Database))
CHECK_MAX_SIZE(SMALL, (DatabaseHandler))
CHECK_MAX_SIZE(SMALL, (Document))
CHECK_MAX_SIZE(SMALL, (MSet))

// database_pool.h
CHECK_MAX_SIZE(SMALL, (DatabaseCount))
CHECK_MAX_SIZE(SMALL, (DatabaseQueue))
CHECK_MAX_SIZE(SMALL, (DatabasesLRU))
CHECK_MAX_SIZE(SMALL, (DatabasePool))

// database_wal.h
CHECK_MAX_SIZE(BIG, (WalHeader))
CHECK_MAX_SIZE(TINY, (WalBinHeader))
CHECK_MAX_SIZE(TINY, (WalBinFooter))
CHECK_MAX_SIZE(SMALL, (DatabaseWAL))

// debouncer.h
// CHECK_MAX_SIZE(SMALL, (Debouncer<int, 0, 0, 0, void(*)(), int>))

// endpoint.h
CHECK_MAX_SIZE(SMALL, (Endpoint))
CHECK_MAX_SIZE(SMALL, (Endpoints))

// logger.h
CHECK_MAX_SIZE(SMALL, (Logging))

// manager.h
CHECK_MAX_SIZE(SMALL, (XapiandManager))

// msgpack.h
CHECK_MAX_SIZE(SMALL, (MsgPack))

// node.h
CHECK_MAX_SIZE(SMALL, (Node))

// query_dsl.h
CHECK_MAX_SIZE(SMALL, (QueryDSL))

// queue.h
CHECK_MAX_SIZE(SMALL, (queue::Queue<int>))

// remote_protocol.h
CHECK_MAX_SIZE(SMALL, (RemoteProtocol))

// replication.h
CHECK_MAX_SIZE(SMALL, (Replication))

// schema.h
CHECK_MAX_SIZE(SMALL, (Schema))

// schemas_lru.h
CHECK_MAX_SIZE(SMALL, (SchemasLRU))

// script.h
CHECK_MAX_SIZE(SMALL, (Script))

// storage.h
CHECK_MAX_SIZE(SMALL, (Storage<StorageHeader, StorageBinHeader, StorageBinFooter>))

// threadpool.hh
CHECK_MAX_SIZE(SMALL, (ThreadPool<>))

// url_parser.h
CHECK_MAX_SIZE(SMALL, (QueryParser))
CHECK_MAX_SIZE(SMALL, (PathParser))

// booleanParser/BooleanParser.h
CHECK_MAX_SIZE(SMALL, (BooleanTree))

// cuuid/uuid.h
CHECK_MAX_SIZE(SMALL, (UUID))

// geospatial/geometry.h
CHECK_MAX_SIZE(SMALL, (Constraint))
CHECK_MAX_SIZE(SMALL, (Geometry))
// geospatial/geospatial.h
CHECK_MAX_SIZE(SMALL, (GeoSpatial))
// geospatial/intersection.h
CHECK_MAX_SIZE(SMALL, (Intersection))
// geospatial/multicircle.h
CHECK_MAX_SIZE(SMALL, (MultiCircle))
// geospatial/multiconvex.h
CHECK_MAX_SIZE(SMALL, (MultiConvex))
// geospatial/multipoint.h
CHECK_MAX_SIZE(SMALL, (MultiPoint))
// geospatial/multipolygon.h
CHECK_MAX_SIZE(SMALL, (MultiPolygon))
// geospatial/point.h
CHECK_MAX_SIZE(SMALL, (Point))
// geospatial/polygon.h
CHECK_MAX_SIZE(SMALL, (Polygon))

// metrics/basic_string_metric.h
CHECK_MAX_SIZE(SMALL, (Counter))
// metrics/jaccard.h
CHECK_MAX_SIZE(SMALL, (Jaccard))
// metrics/jaro.h
CHECK_MAX_SIZE(SMALL, (Jaro))
// metrics/jaro_winkler.h
CHECK_MAX_SIZE(SMALL, (Jaro_Winkler))
// metrics/lcsubsequence.h
CHECK_MAX_SIZE(SMALL, (LCSubsequence))
// metrics/lcsubstr.h
CHECK_MAX_SIZE(SMALL, (LCSubstr))
// metrics/levenshtein.h
CHECK_MAX_SIZE(SMALL, (Levenshtein))
// metrics/sorensen_dice.h
CHECK_MAX_SIZE(SMALL, (Sorensen_Dice))
// metrics/soundex_metric.h
// CHECK_MAX_SIZE(SMALL, (SoundexMetric))

// multivalue/aggregation.h
CHECK_MAX_SIZE(SMALL, (Aggregation))
CHECK_MAX_SIZE(SMALL, (AggregationMatchSpy))

// multivalue/aggregation_bucket.h
CHECK_MAX_SIZE(SMALL, (BucketAggregation))
CHECK_MAX_SIZE(SMALL, (ValueAggregation))
CHECK_MAX_SIZE(SMALL, (HistogramAggregation))
CHECK_MAX_SIZE(SMALL, (RangeAggregation))
CHECK_MAX_SIZE(SMALL, (FilterAggregation))

// multivalue/aggregation_metric.h
CHECK_MAX_SIZE(SMALL, (ValueHandle))
CHECK_MAX_SIZE(SMALL, (SubAggregation))
CHECK_MAX_SIZE(SMALL, (HandledSubAggregation))
CHECK_MAX_SIZE(SMALL, (MetricCount))
CHECK_MAX_SIZE(SMALL, (MetricSum))
CHECK_MAX_SIZE(SMALL, (MetricAvg))
CHECK_MAX_SIZE(SMALL, (MetricMin))
CHECK_MAX_SIZE(SMALL, (MetricMax))
CHECK_MAX_SIZE(SMALL, (MetricVariance))
CHECK_MAX_SIZE(SMALL, (MetricSTD))
CHECK_MAX_SIZE(SMALL, (MetricMedian))
CHECK_MAX_SIZE(SMALL, (MetricMode))
CHECK_MAX_SIZE(SMALL, (MetricStats))
CHECK_MAX_SIZE(SMALL, (MetricExtendedStats))

// multivalue/geospatialrange.h
CHECK_MAX_SIZE(SMALL, (GeoSpatialRange))

// multivalue/keymaker.h
CHECK_MAX_SIZE(SMALL, (Multi_MultiValueKeyMaker))

// multivalue/range.h
CHECK_MAX_SIZE(SMALL, (MultipleValueRange))
CHECK_MAX_SIZE(SMALL, (MultipleValueGE))
CHECK_MAX_SIZE(SMALL, (MultipleValueLE))

// phonetic
CHECK_MAX_SIZE(SMALL, (SoundexEnglish))
CHECK_MAX_SIZE(SMALL, (SoundexFrench))
CHECK_MAX_SIZE(SMALL, (SoundexGerman))
CHECK_MAX_SIZE(SMALL, (SoundexSpanish))

// server/http.h
CHECK_MAX_SIZE(SMALL, (Http))

// server/http_server.h
CHECK_MAX_SIZE(SMALL, (HttpServer))

// server/http_client.h
CHECK_MAX_SIZE(SMALL, (HttpClient))

// server/binary.h
CHECK_MAX_SIZE(SMALL, (Binary))

// server/binary_server.h
CHECK_MAX_SIZE(SMALL, (BinaryServer))

// server/binary_client.h
CHECK_MAX_SIZE(SMALL, (BinaryClient))

// server/raft.h
CHECK_MAX_SIZE(SMALL, (Raft))

// server/discovery.h
CHECK_MAX_SIZE(SMALL, (Discovery))

// server/server.h
CHECK_MAX_SIZE(SMALL, (XapiandServer))

#if XAPIAND_CHAISCRIPT
// chaipp/chaipp.h
CHECK_MAX_SIZE(SMALL, (chaipp::Processor))
#endif

#if XAPIAND_V8
// v8pp/v8pp.h
CHECK_MAX_SIZE(SMALL, (v8pp::Processor))
#endif

}

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

#ifndef NDEBUG
#include "config.h"
#include "check_size.h"
#define STATIC_ASSERT(...)
// #define STATIC_ASSERT static_assert
#define CHECK_MAX_SIZE(max_size, name) \
	STATIC_ASSERT((max_size) >= (sizeof name), "Object is too big!"); \
	if ((max_size) < (sizeof name)) { \
		std::cerr << "sizeof" << #name << " = " << (sizeof name) << std::endl; \
	}

#include "allocator.h"
#include "base_x.hh"
#include "bloom_filter.hh"
#include "compressor_deflate.h"
#include "compressor_lz4.h"
#include "database.h"
#include "database_handler.h"
#include "database_pool.h"
#include "database_wal.h"
#include "debouncer.h"
#include "endpoint.h"
#include "logger.h"
#include "manager.h"
#include "msgpack.h"
#include "node.h"
#include "query_dsl.h"
#include "queue.h"
#include "remote_protocol.h"
#include "replication.h"
#include "schema.h"
#include "schemas_lru.h"
#include "script.h"
#include "storage.h"
#include "threadpool.hh"
#include "url_parser.h"
#include "url_parser.h"
#include "booleanParser/BooleanParser.h"
#include "chaipp/chaipp.h"
#include "cuuid/uuid.h"
#include "geospatial/geometry.h"
#include "geospatial/geospatial.h"
#include "geospatial/intersection.h"
#include "geospatial/multicircle.h"
#include "geospatial/multiconvex.h"
#include "geospatial/multipoint.h"
#include "geospatial/multipolygon.h"
#include "geospatial/point.h"
#include "geospatial/polygon.h"
#include "metrics/basic_string_metric.h"
#include "metrics/jaccard.h"
#include "metrics/jaro.h"
#include "metrics/jaro_winkler.h"
#include "metrics/lcsubsequence.h"
#include "metrics/lcsubstr.h"
#include "metrics/levenshtein.h"
#include "metrics/sorensen_dice.h"
#include "metrics/soundex_metric.h"
#include "multivalue/aggregation.h"
#include "multivalue/aggregation_bucket.h"
#include "multivalue/aggregation_metric.h"
#include "multivalue/geospatialrange.h"
#include "multivalue/keymaker.h"
#include "multivalue/range.h"
#include "phonetic/english_soundex.h"
#include "phonetic/french_soundex.h"
#include "phonetic/german_soundex.h"
#include "phonetic/spanish_soundex.h"
#include "server/http.h"
#include "server/http_server.h"
#include "server/http_client.h"
#include "server/binary.h"
#include "server/binary_server.h"
#include "server/binary_client.h"
#include "server/raft.h"
#include "server/discovery.h"
#include "server/server.h"
#include "v8pp/v8pp.h"

#define TINY 8
#define SMALL 128
#define REGULAR 1024
#define BIG 5 * 1024
#define LARGE 20 * 1024

void
check_size()
{

// allocator.h
CHECK_MAX_SIZE(TINY, (allocator::VanillaAllocator))
CHECK_MAX_SIZE(TINY, (allocator::TrackedAllocator))

// base_x.hh
CHECK_MAX_SIZE(TINY, (BaseX))
CHECK_MAX_SIZE(TINY, (Base2))
CHECK_MAX_SIZE(TINY, (Base8))
CHECK_MAX_SIZE(TINY, (Base11))
CHECK_MAX_SIZE(TINY, (Base16))
CHECK_MAX_SIZE(TINY, (Base32))
CHECK_MAX_SIZE(TINY, (Base36))
CHECK_MAX_SIZE(TINY, (Base58))
CHECK_MAX_SIZE(TINY, (Base59))
CHECK_MAX_SIZE(TINY, (Base62))
CHECK_MAX_SIZE(TINY, (Base64))
CHECK_MAX_SIZE(TINY, (Base66))

// bloom_filter.hh
CHECK_MAX_SIZE(SMALL, (BloomFilter<>))

// compressor_deflate.h
CHECK_MAX_SIZE(SMALL, (DeflateCompressData))
CHECK_MAX_SIZE(SMALL, (DeflateCompressFile))
CHECK_MAX_SIZE(SMALL, (DeflateDecompressData))
CHECK_MAX_SIZE(SMALL, (DeflateDecompressFile))

// compressor_lz4.h
CHECK_MAX_SIZE(SMALL, (LZ4CompressData))
CHECK_MAX_SIZE(SMALL, (LZ4CompressFile))
CHECK_MAX_SIZE(SMALL, (LZ4DecompressData))
CHECK_MAX_SIZE(SMALL, (LZ4DecompressFile))

// database.h
CHECK_MAX_SIZE(SMALL, (Database))

// database_handler.h
CHECK_MAX_SIZE(SMALL, (Data))
CHECK_MAX_SIZE(SMALL, (DatabaseHandler))
CHECK_MAX_SIZE(SMALL, (Document))
CHECK_MAX_SIZE(SMALL, (MSet))

// database_pool.h
CHECK_MAX_SIZE(SMALL, (DatabaseCount))
CHECK_MAX_SIZE(SMALL, (DatabaseQueue))
CHECK_MAX_SIZE(SMALL, (DatabasesLRU))
CHECK_MAX_SIZE(SMALL, (DatabasePool))

// database_wal.h
CHECK_MAX_SIZE(BIG, (WalHeader))
CHECK_MAX_SIZE(TINY, (WalBinHeader))
CHECK_MAX_SIZE(TINY, (WalBinFooter))
CHECK_MAX_SIZE(SMALL, (DatabaseWAL))

// debouncer.h
// CHECK_MAX_SIZE(SMALL, (Debouncer<int, 0, 0, 0, void(*)(), int>))

// endpoint.h
CHECK_MAX_SIZE(SMALL, (Endpoint))
CHECK_MAX_SIZE(SMALL, (Endpoints))

// logger.h
CHECK_MAX_SIZE(SMALL, (Logging))

// manager.h
CHECK_MAX_SIZE(SMALL, (XapiandManager))

// msgpack.h
CHECK_MAX_SIZE(SMALL, (MsgPack))

// node.h
CHECK_MAX_SIZE(SMALL, (Node))

// query_dsl.h
CHECK_MAX_SIZE(SMALL, (QueryDSL))

// queue.h
CHECK_MAX_SIZE(SMALL, (queue::Queue<int>))

// remote_protocol.h
CHECK_MAX_SIZE(SMALL, (RemoteProtocol))

// replication.h
CHECK_MAX_SIZE(SMALL, (Replication))

// schema.h
CHECK_MAX_SIZE(SMALL, (Schema))

// schemas_lru.h
CHECK_MAX_SIZE(SMALL, (SchemasLRU))

// script.h
CHECK_MAX_SIZE(SMALL, (Script))

// storage.h
CHECK_MAX_SIZE(SMALL, (Storage<StorageHeader, StorageBinHeader, StorageBinFooter>))

// threadpool.hh
CHECK_MAX_SIZE(SMALL, (ThreadPool<>))

// url_parser.h
CHECK_MAX_SIZE(SMALL, (QueryParser))
CHECK_MAX_SIZE(SMALL, (PathParser))

// booleanParser/BooleanParser.h
CHECK_MAX_SIZE(SMALL, (BooleanTree))

// cuuid/uuid.h
CHECK_MAX_SIZE(SMALL, (UUID))

// geospatial/geometry.h
CHECK_MAX_SIZE(SMALL, (Constraint))
CHECK_MAX_SIZE(SMALL, (Geometry))
// geospatial/geospatial.h
CHECK_MAX_SIZE(SMALL, (GeoSpatial))
// geospatial/intersection.h
CHECK_MAX_SIZE(SMALL, (Intersection))
// geospatial/multicircle.h
CHECK_MAX_SIZE(SMALL, (MultiCircle))
// geospatial/multiconvex.h
CHECK_MAX_SIZE(SMALL, (MultiConvex))
// geospatial/multipoint.h
CHECK_MAX_SIZE(SMALL, (MultiPoint))
// geospatial/multipolygon.h
CHECK_MAX_SIZE(SMALL, (MultiPolygon))
// geospatial/point.h
CHECK_MAX_SIZE(SMALL, (Point))
// geospatial/polygon.h
CHECK_MAX_SIZE(SMALL, (Polygon))

// metrics/basic_string_metric.h
CHECK_MAX_SIZE(SMALL, (Counter))
// metrics/jaccard.h
CHECK_MAX_SIZE(SMALL, (Jaccard))
// metrics/jaro.h
CHECK_MAX_SIZE(SMALL, (Jaro))
// metrics/jaro_winkler.h
CHECK_MAX_SIZE(SMALL, (Jaro_Winkler))
// metrics/lcsubsequence.h
CHECK_MAX_SIZE(SMALL, (LCSubsequence))
// metrics/lcsubstr.h
CHECK_MAX_SIZE(SMALL, (LCSubstr))
// metrics/levenshtein.h
CHECK_MAX_SIZE(SMALL, (Levenshtein))
// metrics/sorensen_dice.h
CHECK_MAX_SIZE(SMALL, (Sorensen_Dice))
// metrics/soundex_metric.h
// CHECK_MAX_SIZE(SMALL, (SoundexMetric))

// multivalue/aggregation.h
CHECK_MAX_SIZE(SMALL, (Aggregation))
CHECK_MAX_SIZE(SMALL, (AggregationMatchSpy))

// multivalue/aggregation_bucket.h
CHECK_MAX_SIZE(SMALL, (BucketAggregation))
CHECK_MAX_SIZE(SMALL, (ValueAggregation))
CHECK_MAX_SIZE(SMALL, (HistogramAggregation))
CHECK_MAX_SIZE(SMALL, (RangeAggregation))
CHECK_MAX_SIZE(SMALL, (FilterAggregation))

// multivalue/aggregation_metric.h
CHECK_MAX_SIZE(SMALL, (ValueHandle))
CHECK_MAX_SIZE(SMALL, (SubAggregation))
CHECK_MAX_SIZE(SMALL, (HandledSubAggregation))
CHECK_MAX_SIZE(SMALL, (MetricCount))
CHECK_MAX_SIZE(SMALL, (MetricSum))
CHECK_MAX_SIZE(SMALL, (MetricAvg))
CHECK_MAX_SIZE(SMALL, (MetricMin))
CHECK_MAX_SIZE(SMALL, (MetricMax))
CHECK_MAX_SIZE(SMALL, (MetricVariance))
CHECK_MAX_SIZE(SMALL, (MetricSTD))
CHECK_MAX_SIZE(SMALL, (MetricMedian))
CHECK_MAX_SIZE(SMALL, (MetricMode))
CHECK_MAX_SIZE(SMALL, (MetricStats))
CHECK_MAX_SIZE(SMALL, (MetricExtendedStats))

// multivalue/geospatialrange.h
CHECK_MAX_SIZE(SMALL, (GeoSpatialRange))

// multivalue/keymaker.h
CHECK_MAX_SIZE(SMALL, (Multi_MultiValueKeyMaker))

// multivalue/range.h
CHECK_MAX_SIZE(SMALL, (MultipleValueRange))
CHECK_MAX_SIZE(SMALL, (MultipleValueGE))
CHECK_MAX_SIZE(SMALL, (MultipleValueLE))

// phonetic
CHECK_MAX_SIZE(SMALL, (SoundexEnglish))
CHECK_MAX_SIZE(SMALL, (SoundexFrench))
CHECK_MAX_SIZE(SMALL, (SoundexGerman))
CHECK_MAX_SIZE(SMALL, (SoundexSpanish))

// server/http.h
CHECK_MAX_SIZE(SMALL, (Http))

// server/http_server.h
CHECK_MAX_SIZE(SMALL, (HttpServer))

// server/http_client.h
CHECK_MAX_SIZE(SMALL, (HttpClient))

// server/binary.h
CHECK_MAX_SIZE(SMALL, (Binary))

// server/binary_server.h
CHECK_MAX_SIZE(SMALL, (BinaryServer))

// server/binary_client.h
CHECK_MAX_SIZE(SMALL, (BinaryClient))

// server/raft.h
CHECK_MAX_SIZE(SMALL, (Raft))

// server/discovery.h
CHECK_MAX_SIZE(SMALL, (Discovery))

// server/server.h
CHECK_MAX_SIZE(SMALL, (XapiandServer))

#if XAPIAND_CHAISCRIPT
// chaipp/chaipp.h
CHECK_MAX_SIZE(SMALL, (chaipp::Processor))
#endif

#if XAPIAND_V8
// v8pp/v8pp.h
CHECK_MAX_SIZE(SMALL, (v8pp::Processor))
#endif

}

#endif
<|endoftext|>


<commit_before>
#include "journal/player.hpp"

#include <list>
#include <string>
#include <vector>

#include "benchmark/benchmark.h"
#include "gtest/gtest.h"
#include "journal/method.hpp"
#include "journal/profiles.hpp"
#include "journal/recorder.hpp"
#include "ksp_plugin/interface.hpp"
#include "serialization/journal.pb.h"

namespace principia {
namespace journal {

// The benchmark is only run if --gtest_filter=PlayerTest.Benchmarks
void BM_PlayForReal(benchmark::State& state) {  // NOLINT(runtime/references)
  while (state.KeepRunning()) {
    Player player(
        R"(P:\Public Mockingbird\Principia\Journals\JOURNAL.20160502-200332)");
    int count = 0;
    while (player.Play()) {
      ++count;
      LOG_IF(ERROR, (count % 100'000) == 0)
          << count << " journal entries replayed";
    }
  }
}

BENCHMARK(BM_PlayForReal);

class PlayerTest : public ::testing::Test {
 protected:
  PlayerTest()
      : test_info_(testing::UnitTest::GetInstance()->current_test_info()),
        test_case_name_(test_info_->test_case_name()),
        test_name_(test_info_->name()),
        plugin_(interface::principia__NewPlugin(1, 2)),
        recorder_(new Recorder(test_name_ + ".journal.hex")) {
    Recorder::Activate(recorder_);
  }

  ~PlayerTest() override {
    Recorder::Deactivate();
  }

  template<typename Profile>
  void RunIfAppropriate(serialization::Method const& method_in,
                        serialization::Method const& method_out_return,
                        Player& player) {
    player.RunIfAppropriate<Profile>(method_in, method_out_return);
  }

  ::testing::TestInfo const* const test_info_;
  std::string const test_case_name_;
  std::string const test_name_;
  std::unique_ptr<ksp_plugin::Plugin> plugin_;
  Recorder* recorder_;
};

TEST_F(PlayerTest, PlayTiny) {
  {
    Method<NewPlugin> method_in({1, 2});
    method_in.Return(plugin_.get());
  }
  {
    const ksp_plugin::Plugin* plugin = plugin_.get();
    Method<DeletePlugin> method_in({&plugin}, {&plugin});
    method_in.Return();
  }

  Player player(test_name_ + ".journal.hex");

  // Replay the journal.  Note that the journal doesn't grow as we replay
  // because we didn't call principia__ActivateRecorder so there is no active
  // journal in the ksp_plugin assembly.
  int count = 0;
  while (player.Play()) {
    ++count;
  }
  EXPECT_EQ(2, count);
}

// This test (a.k.a. benchmark) is only run if the --gtest_filter flag names it
// explicitly.
TEST_F(PlayerTest, Benchmarks) {
  if (testing::FLAGS_gtest_filter == test_case_name_ + "." + test_name_) {
    benchmark::RunSpecifiedBenchmarks();
  }
}

#if 0
// This test is only run if the --gtest_filter flag names it explicitly.
TEST_F(PlayerTest, Debug) {
  if (testing::FLAGS_gtest_filter == test_case_name_ + "." + test_name_) {
    // An example of how journalling may be used for debugging.  You must set
    // |path| and fill the |method_in| and |method_out_return| protocol buffers.
    std::string path =
        R"(P:\Public Mockingbird\Principia\Journals\JOURNAL.20160502-200332)";
    Player player(path);
    int count = 0;
    while (player.Play()) {
      ++count;
      LOG_IF(ERROR, (count % 100'000) == 0) << count
                                            << " journal entries replayed";
    }
    LOG(ERROR) << count << " journal entries in total";

    //serialization::Method method_in;
    //auto* extension = method_in.MutableExtension(
    //    serialization::SerializePlugin::extension);
    //auto* in = extension->mutable_in();
    //in->set_plugin(850673856);
    //in->set_serializer(0);
    //serialization::Method method_out_return;
    //method_out_return.MutableExtension(
    //    serialization::SerializePlugin::extension);
    //RunIfAppropriate<SerializePlugin>(method_in, method_out_return, player);
  }
}
#endif

}  // namespace journal
}  // namespace principia
<commit_msg>Silly renaming.<commit_after>
#include "journal/player.hpp"

#include <list>
#include <string>
#include <vector>

#include "benchmark/benchmark.h"
#include "gtest/gtest.h"
#include "journal/method.hpp"
#include "journal/profiles.hpp"
#include "journal/recorder.hpp"
#include "ksp_plugin/interface.hpp"
#include "serialization/journal.pb.h"

namespace principia {
namespace journal {

// The benchmark is only run if --gtest_filter=PlayerTest.Benchmarks
void BM_PlayForReal(benchmark::State& state) {  // NOLINT(runtime/references)
  while (state.KeepRunning()) {
    Player player(
        R"(P:\Public Mockingbird\Principia\Journals\JOURNAL.20160502-200332)");
    int count = 0;
    while (player.Play()) {
      ++count;
      LOG_IF(ERROR, (count % 100'000) == 0)
          << count << " journal entries replayed";
    }
  }
}

BENCHMARK(BM_PlayForReal);

class PlayerTest : public ::testing::Test {
 protected:
  PlayerTest()
      : test_info_(testing::UnitTest::GetInstance()->current_test_info()),
        test_case_name_(test_info_->test_case_name()),
        test_name_(test_info_->name()),
        plugin_(interface::principia__NewPlugin(1, 2)),
        recorder_(new Recorder(test_name_ + ".journal.hex")) {
    Recorder::Activate(recorder_);
  }

  ~PlayerTest() override {
    Recorder::Deactivate();
  }

  template<typename Profile>
  void RunIfAppropriate(serialization::Method const& method_in,
                        serialization::Method const& method_out_return,
                        Player& player) {
    player.RunIfAppropriate<Profile>(method_in, method_out_return);
  }

  ::testing::TestInfo const* const test_info_;
  std::string const test_case_name_;
  std::string const test_name_;
  std::unique_ptr<ksp_plugin::Plugin> plugin_;
  Recorder* recorder_;
};

TEST_F(PlayerTest, PlayTiny) {
  {
    Method<NewPlugin> m({1, 2});
    m.Return(plugin_.get());
  }
  {
    const ksp_plugin::Plugin* plugin = plugin_.get();
    Method<DeletePlugin> m({&plugin}, {&plugin});
    m.Return();
  }

  Player player(test_name_ + ".journal.hex");

  // Replay the journal.  Note that the journal doesn't grow as we replay
  // because we didn't call principia__ActivateRecorder so there is no active
  // journal in the ksp_plugin assembly.
  int count = 0;
  while (player.Play()) {
    ++count;
  }
  EXPECT_EQ(2, count);
}

// This test (a.k.a. benchmark) is only run if the --gtest_filter flag names it
// explicitly.
TEST_F(PlayerTest, Benchmarks) {
  if (testing::FLAGS_gtest_filter == test_case_name_ + "." + test_name_) {
    benchmark::RunSpecifiedBenchmarks();
  }
}

#if 0
// This test is only run if the --gtest_filter flag names it explicitly.
TEST_F(PlayerTest, Debug) {
  if (testing::FLAGS_gtest_filter == test_case_name_ + "." + test_name_) {
    // An example of how journalling may be used for debugging.  You must set
    // |path| and fill the |method_in| and |method_out_return| protocol buffers.
    std::string path =
        R"(P:\Public Mockingbird\Principia\Journals\JOURNAL.20160502-200332)";
    Player player(path);
    int count = 0;
    while (player.Play()) {
      ++count;
      LOG_IF(ERROR, (count % 100'000) == 0) << count
                                            << " journal entries replayed";
    }
    LOG(ERROR) << count << " journal entries in total";

    //serialization::Method method_in;
    //auto* extension = method_in.MutableExtension(
    //    serialization::SerializePlugin::extension);
    //auto* in = extension->mutable_in();
    //in->set_plugin(850673856);
    //in->set_serializer(0);
    //serialization::Method method_out_return;
    //method_out_return.MutableExtension(
    //    serialization::SerializePlugin::extension);
    //RunIfAppropriate<SerializePlugin>(method_in, method_out_return, player);
  }
}
#endif

}  // namespace journal
}  // namespace principia
<|endoftext|>


<commit_before>// Copyright 2015-2020 Elviss Strazdins. All rights reserved.

#ifndef OUZEL_OUZELPROJECT_HPP
#define OUZEL_OUZELPROJECT_HPP

#include <fstream>
#include "Asset.hpp"
#include "Target.hpp"
#include "storage/FileSystem.hpp"
#include "utils/Json.hpp"

namespace ouzel
{
    class ProjectError final: public std::logic_error
    {
    public:
        explicit ProjectError(const std::string& str): std::logic_error(str) {}
        explicit ProjectError(const char* str): std::logic_error(str) {}
    };

    class Project final
    {
    public:
        Project(const storage::Path& initPath):
            path{initPath}
        {
            storage::Path directoryPath = path.getDirectory();

            std::ifstream f(path, std::ios::binary);
            std::vector<char> data{std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>()};

            json::Value j = json::parse(data);
            name = j["name"].as<std::string>();
            identifier = j["identifier"].as<std::string>();
            organization = j["organization"].as<std::string>();

            ouzelPath = j["ouzelPath"].as<std::string>();

            if (j.hasMember("targets"))
                for (const auto& targetObject : j["targets"])
                {
                    const auto platform = stringToPlatform(targetObject["platform"].as<std::string>());
                    const auto targetName = targetObject.hasMember("name") ? targetObject["name"].as<std::string>() : name + ' ' + toString(platform);

                    for (const auto& otherTarget : targets)
                        if (otherTarget.name == targetName)
                            throw ProjectError("Name of the target must be unique");

                    targets.emplace_back(platform, targetName);
                }

            sourcePath = j["sourcePath"].as<std::string>();

            for (const auto& sourceFile : j["sourceFiles"])
                sourceFiles.push_back(sourceFile.as<std::string>());

            assetsPath = j["assetsPath"].as<std::string>();

            for (const auto& assetObject : j["assets"])
            {
                const auto assetPath(assetsPath / assetObject["path"].as<std::string>());
                const auto assetName = assetObject.hasMember("name") ?
                    assetObject["name"].as<std::string>() : assetPath.getStem();

                const Asset::Type assetType = stringToAssetType(assetObject["type"].as<std::string>());

                assets.emplace_back(assetPath,
                                    assetName,
                                    assetType,
                                    assetObject.hasMember("mipmaps") ? assetObject["mipmaps"].as<bool>() : false);
            }
        }

        const storage::Path& getPath() const noexcept { return path; }
        const std::string& getName() const noexcept { return name; }
        const std::string& getIdentifier() const noexcept { return identifier; }
        const std::string& getOrganization() const noexcept { return organization; }
        const storage::Path& getOuzelPath() const noexcept { return ouzelPath; }
        const storage::Path& getSourcePath() const noexcept { return sourcePath; }
        const std::vector<Target>& getTargets() const noexcept { return targets; }
        const std::vector<storage::Path>& getSourceFiles() const noexcept { return sourceFiles; }
        const storage::Path& getAssetsPath() const noexcept { return assetsPath; }
        const std::vector<Asset>& getAssets() const noexcept { return assets; }

        void exportAssets(const std::string& target) const
        {
            for (const auto& asset : assets)
            {
                const storage::Path assetPath = assetsPath / asset.path;

                storage::Path resourceName = asset.path;
                resourceName.replaceExtension("otexture");
                const storage::Path resourcePath = assetPath / resourceName;

                // TODO: check if input file exists
                // TODO: check if output file exists and is older than the input file
                // TODO: export input file to output file
            }
        }

    private:
        const storage::Path path;
        std::string name;
        std::string identifier;
        std::string organization;
        storage::Path ouzelPath;
        storage::Path sourcePath;
        std::vector<Target> targets;
        std::vector<storage::Path> sourceFiles;
        storage::Path assetsPath;
        std::vector<Asset> assets;
    };
}

#endif // OUZELPROJECT_HPP
<commit_msg>Fix the ouzel tool<commit_after>// Copyright 2015-2020 Elviss Strazdins. All rights reserved.

#ifndef OUZEL_OUZELPROJECT_HPP
#define OUZEL_OUZELPROJECT_HPP

#include <fstream>
#include "Asset.hpp"
#include "Target.hpp"
#include "storage/FileSystem.hpp"
#include "utils/Json.hpp"

namespace ouzel
{
    class ProjectError final: public std::logic_error
    {
    public:
        explicit ProjectError(const std::string& str): std::logic_error(str) {}
        explicit ProjectError(const char* str): std::logic_error(str) {}
    };

    class Project final
    {
    public:
        Project(const storage::Path& initPath):
            path{initPath}
        {
            storage::Path directoryPath = path.getDirectory();

            std::ifstream f(path, std::ios::binary);
            std::vector<char> data{std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>()};

            json::Value j = json::parse(data);
            name = j["name"].as<std::string>();
            identifier = j["identifier"].as<std::string>();
            organization = j["organization"].as<std::string>();

            ouzelPath = j["ouzelPath"].as<std::string>();

            if (j.hasMember("targets"))
                for (const auto& targetObject : j["targets"])
                {
                    const auto platform = stringToPlatform(targetObject["platform"].as<std::string>());
                    const auto targetName = targetObject.hasMember("name") ? targetObject["name"].as<std::string>() : name + ' ' + toString(platform);

                    for (const auto& otherTarget : targets)
                        if (otherTarget.name == targetName)
                            throw ProjectError("Name of the target must be unique");

                    targets.emplace_back(platform, targetName);
                }

            sourcePath = j["sourcePath"].as<std::string>();

            for (const auto& sourceFile : j["sourceFiles"])
                sourceFiles.push_back(sourceFile.as<std::string>());

            assetsPath = j["assetsPath"].as<std::string>();

            for (const auto& assetObject : j["assets"])
            {
                const auto assetPath(assetsPath / assetObject["path"].as<std::string>());
                const auto assetName = assetObject.hasMember("name") ?
                    assetObject["name"].as<std::string>() : std::string(assetPath.getStem());

                const Asset::Type assetType = stringToAssetType(assetObject["type"].as<std::string>());

                assets.emplace_back(assetPath,
                                    assetName,
                                    assetType,
                                    assetObject.hasMember("mipmaps") ? assetObject["mipmaps"].as<bool>() : false);
            }
        }

        const storage::Path& getPath() const noexcept { return path; }
        const std::string& getName() const noexcept { return name; }
        const std::string& getIdentifier() const noexcept { return identifier; }
        const std::string& getOrganization() const noexcept { return organization; }
        const storage::Path& getOuzelPath() const noexcept { return ouzelPath; }
        const storage::Path& getSourcePath() const noexcept { return sourcePath; }
        const std::vector<Target>& getTargets() const noexcept { return targets; }
        const std::vector<storage::Path>& getSourceFiles() const noexcept { return sourceFiles; }
        const storage::Path& getAssetsPath() const noexcept { return assetsPath; }
        const std::vector<Asset>& getAssets() const noexcept { return assets; }

        void exportAssets(const std::string& target) const
        {
            for (const auto& asset : assets)
            {
                const storage::Path assetPath = assetsPath / asset.path;

                storage::Path resourceName = asset.path;
                resourceName.replaceExtension("otexture");
                const storage::Path resourcePath = assetPath / resourceName;

                // TODO: check if input file exists
                // TODO: check if output file exists and is older than the input file
                // TODO: export input file to output file
            }
        }

    private:
        const storage::Path path;
        std::string name;
        std::string identifier;
        std::string organization;
        storage::Path ouzelPath;
        storage::Path sourcePath;
        std::vector<Target> targets;
        std::vector<storage::Path> sourceFiles;
        storage::Path assetsPath;
        std::vector<Asset> assets;
    };
}

#endif // OUZELPROJECT_HPP
<|endoftext|>


<commit_before>#include <thread>
#include <set>
#include <signal.h>

#include <cl/cl.h>
#include <ev3/servo.h>

using namespace std;
using namespace ev3dev;

cl::arg<std::string> port(
  ev3dev::OUTPUT_A,
  cl::name("port"),
  cl::desc("Port the motor is attached to."));

cl::arg<float> period(
  4.0f,
  cl::name("period"),
  cl::desc("Sine wave period, in s."));
cl::arg<float> amplitude(
  180.0f,
  cl::name("amplitude"),
  cl::desc("Sine wave amplitude."));
cl::boolean square_wave(
  cl::name("square-wave"),
  cl::desc("Use a square wave instead of a sine wave."));

cl::boolean use_servo(
  cl::name("servo"),
  cl::desc("Use the ev3cv::servo class."));

cl::group ev3cv_group("ev3cv::servo settings");
cl::arg<vector3i> K(
  vector3i(5000, 5000, 200),
  cl::name("K"),
  cl::desc("PID parameters Kp, Ki, Kd."),
  ev3cv_group);

cl::group ev3dev_group("ev3dev::motor settings");
cl::arg<std::string> regulation_mode(
  "off",
  cl::name("regulation-mode"),
  ev3dev_group);
cl::arg<std::string> stop_mode(
  "coast",
  cl::name("stop-mode"),
  ev3dev_group);
cl::arg<int> pulses_per_second_setpoint(
  700,
  cl::name("pulses-per-second-setpoint"),
  ev3dev_group);
cl::arg<int> duty_cycle_setpoint(
  100,
  cl::name("duty-cycle-setpoint"),
  ev3dev_group);

int setpoint_fn(int ms) {
  float sp = sin(ms*2.0f*pi/(period*1000.0f));
  if (square_wave)
    sp = sp < 0.0f ? -1.0f : 1.0f;
  return sp*amplitude;
}

// Test and benchmark estimate_trajectory.
int main(int argc, const char **argv) {
  cl::parse(argv[0], argc - 1, argv + 1);

  typedef chrono::high_resolution_clock clock;
  chrono::milliseconds T(20);

  if (use_servo) {
    // Use ev3cv::servo.
    servo m(*port);
    m.controller().set_K(K->x, K->y, K->z);
    m.run();

    auto t0 = clock::now();
    for (auto t = t0; ; t += T) {
      int ms = chrono::duration_cast<chrono::milliseconds>(t - t0).count();
      m.set_position_setpoint(setpoint_fn(ms));
      this_thread::sleep_until(t);
    }
  } else {
    // To compare against the stock controller
    motor m(*port);
    m.reset();
    m.set_run_mode(motor::run_mode_position);
    m.set_regulation_mode(regulation_mode);
    m.set_pulses_per_second_setpoint(pulses_per_second_setpoint);
    m.set_duty_cycle_setpoint(duty_cycle_setpoint);
    m.set_stop_mode(stop_mode);

    auto t0 = clock::now();
    for (auto t = t0; ; t += T) {
      int ms = chrono::duration_cast<chrono::milliseconds>(t - t0).count();
      m.set_position_setpoint(setpoint_fn(ms));
      m.run();
      this_thread::sleep_until(t);
    }
  }
  return 0;
}

<commit_msg>Use another motor as input to control the servo<commit_after>#include <thread>
#include <set>
#include <signal.h>

#include <cl/cl.h>
#include <ev3/servo.h>

using namespace std;
using namespace ev3dev;

cl::arg<std::string> output_port(
  ev3dev::OUTPUT_A,
  cl::name("output-port"),
  cl::desc("Port the motor is attached to."));

cl::arg<std::string> input_port(
  ev3dev::OUTPUT_D,
  cl::name("input-port"),
  cl::desc("Port the tacho is attached to."));

cl::boolean use_servo(
  cl::name("servo"),
  cl::desc("Use the ev3cv::servo class."));

cl::arg<float> scale(
  1.0f,
  cl::name("scale"),
  cl::desc("Relative scale of the motion between the input and output."));

cl::group ev3cv_group("ev3cv::servo settings");
cl::arg<vector3i> K(
  vector3i(5000, 5000, 200),
  cl::name("K"),
  cl::desc("PID parameters Kp, Ki, Kd."),
  ev3cv_group);

cl::group ev3dev_group("ev3dev::motor settings");
cl::arg<std::string> regulation_mode(
  "off",
  cl::name("regulation-mode"),
  ev3dev_group);
cl::arg<std::string> stop_mode(
  "hold",
  cl::name("stop-mode"),
  ev3dev_group);
cl::arg<int> ramp_up(
  0,
  cl::name("ramp-up"),
  ev3dev_group);
cl::arg<int> ramp_down(
  0,
  cl::name("ramp-down"),
  ev3dev_group);
cl::arg<int> pulses_per_second_setpoint(
  700,
  cl::name("pulses-per-second-setpoint"),
  ev3dev_group);
cl::arg<int> duty_cycle_setpoint(
  100,
  cl::name("duty-cycle-setpoint"),
  ev3dev_group);

// Test and benchmark estimate_trajectory.
int main(int argc, const char **argv) {
  cl::parse(argv[0], argc - 1, argv + 1);

  typedef chrono::high_resolution_clock clock;
  chrono::milliseconds T(20);

  motor in(*input_port);
  in.reset();

  cout << "Turn the motor connected to port " << *input_port << "..." << endl;

  if (use_servo) {
    // Use ev3cv::servo.
    servo m(*output_port);
    m.controller().set_K(K->x, K->y, K->z);
    m.run();

    for (auto t = clock::now(); ; t += T) {
      m.set_position_setpoint(in.position()*scale);
      this_thread::sleep_until(t);
    }
  } else {
    // Compare against the stock controller
    motor m(*output_port);
    m.reset();
    m.set_run_mode(motor::run_mode_position);
    m.set_regulation_mode(regulation_mode);
    m.set_pulses_per_second_setpoint(pulses_per_second_setpoint);
    m.set_duty_cycle_setpoint(duty_cycle_setpoint);
    m.set_stop_mode(stop_mode);
    m.set_ramp_up(ramp_up);
    m.set_ramp_down(ramp_down);

    for (auto t = clock::now(); ; t += T) {
      m.set_position_setpoint(in.position()*scale);
      m.run();
      this_thread::sleep_until(t);
    }
  }
  return 0;
}

<|endoftext|>


<commit_before>#include "sonardatasourceserial.h"
#include "sonarreturndata.h"
#include "qextserialport.h"
#include "module_scanningsonar.h"
#include "sonarswitchcommand.h"

SonarDataSourceSerial::SonarDataSourceSerial(Module_ScanningSonar& parent)
    : SonarDataSource(parent)
{
    logger = Log4Qt::Logger::logger("SonarSerialReader");
    configurePort();
}

const SonarReturnData SonarDataSourceSerial::getNextPacket()
{
    logger->debug("Sending switch data command.");

    SonarSwitchCommand cmd;

    cmd.range = parent.getSettingsValue("range").toInt();
    cmd.startGain = parent.getSettingsValue("gain").toInt();
    cmd.trainAngle = parent.getSettingsValue("trainAngle").toInt();
    cmd.sectorWidth = parent.getSettingsValue("sectorWidth").toInt();
    cmd.stepSize = parent.getSettingsValue("stepSize").toInt();
    cmd.pulseLength = parent.getSettingsValue("pulseLength").toInt();
    cmd.dataPoints = parent.getSettingsValue("dataPoints").toInt();
    cmd.switchDelay = parent.getSettingsValue("switchDelay").toInt();
    cmd.frequency = parent.getSettingsValue("frequency").toInt();

    QByteArray sendArray = cmd.toSerialCmd();

    logger->trace("Sending: " + QString(sendArray.toHex()));
    port->write(sendArray);

    QByteArray retData;

    int expectedLength;
    logger->debug("dataPoints:"+QString::number(parent.getSettingsValue("dataPoints").toInt()));
    if (parent.getSettingsValue("dataPoints").toInt()==50)
        expectedLength = 513;
    else
        expectedLength = 265;

    int timeout = 1000; // if takes longer than a second, just drop the packet
    while(timeout>0 && (retData.length()==0 || retData[retData.length()-1] != (char)0xFC)) {
        QByteArray ret = port->read(expectedLength - retData.length());
        retData.append(ret);
        parent.msleep(5); timeout -= 5;
    }
    if (expectedLength - retData.length()>0) {
        logger->error("Received less than expected: "+QString::number(expectedLength - retData.length())+" bytes missing; expected="+QString::number(expectedLength));
    } else {
        logger->debug("received full packet");
    }

    logger->trace("Received in total: " + QString(retData.toHex()));

    SonarReturnData d(cmd,retData);

    return d;
}

void SonarDataSourceSerial::configurePort()
{
    logger->info("Configuring serial port");
    PortSettings s;
    s.BaudRate = BAUD115200;
    s.DataBits = DATA_8;
    s.StopBits = STOP_1;
    s.Parity = PAR_NONE;
    s.Timeout_Millisec = 1;
    port = new QextSerialPort(parent.getSettingsValue("serialPort").toString(), s,QextSerialPort::Polling);
    bool ret = port->open(QextSerialPort::ReadWrite);
    if (ret)
        logger->debug("Opened serial port!");
    else
        parent.setHealthToSick("Could not open serial port '"+parent.getSettingsValue("serialPort").toString()+"'");
}

bool SonarDataSourceSerial::isOpen()
{
    return port && port->isOpen();
}

SonarDataSourceSerial::~SonarDataSourceSerial()
{
}

void SonarDataSourceSerial::stop()
{
    logger->debug("Closing serial port.");
    if (port != NULL) {
        port->close();
        delete port;
        port = NULL;
    }
}
<commit_msg>fix: 850khz sonar<commit_after>#include "sonardatasourceserial.h"
#include "sonarreturndata.h"
#include "qextserialport.h"
#include "module_scanningsonar.h"
#include "sonarswitchcommand.h"

SonarDataSourceSerial::SonarDataSourceSerial(Module_ScanningSonar& parent)
    : SonarDataSource(parent)
{
    logger = Log4Qt::Logger::logger("SonarSerialReader");
    configurePort();
}

const SonarReturnData SonarDataSourceSerial::getNextPacket()
{
    logger->debug("Sending switch data command.");

    SonarSwitchCommand cmd;

    cmd.range = parent.getSettingsValue("range").toInt();
    cmd.startGain = parent.getSettingsValue("gain").toInt();
    cmd.trainAngle = parent.getSettingsValue("trainAngle").toInt();
    cmd.sectorWidth = parent.getSettingsValue("sectorWidth").toInt();
    cmd.stepSize = parent.getSettingsValue("stepSize").toInt();
    cmd.pulseLength = parent.getSettingsValue("pulseLength").toInt();
    cmd.dataPoints = parent.getSettingsValue("dataPoints").toInt();
    cmd.switchDelay = parent.getSettingsValue("switchDelay").toInt();
    cmd.frequency = parent.getSettingsValue("frequency").toInt() ? 0 : 135;

    QByteArray sendArray = cmd.toSerialCmd();

    logger->trace("Sending: " + QString(sendArray.toHex()));
    port->write(sendArray);

    QByteArray retData;

    int expectedLength;
    logger->debug("dataPoints:"+QString::number(parent.getSettingsValue("dataPoints").toInt()));
    if (parent.getSettingsValue("dataPoints").toInt()==50)
        expectedLength = 513;
    else
        expectedLength = 265;

    int timeout = 1000; // if takes longer than a second, just drop the packet
    while(timeout>0 && (retData.length()==0 || retData[retData.length()-1] != (char)0xFC)) {
        QByteArray ret = port->read(expectedLength - retData.length());
        retData.append(ret);
        parent.msleep(5); timeout -= 5;
    }
    if (expectedLength - retData.length()>0) {
        logger->error("Received less than expected: "+QString::number(expectedLength - retData.length())+" bytes missing; expected="+QString::number(expectedLength));
    } else {
        logger->debug("received full packet");
    }

    logger->trace("Received in total: " + QString(retData.toHex()));

    SonarReturnData d(cmd,retData);

    return d;
}

void SonarDataSourceSerial::configurePort()
{
    logger->info("Configuring serial port");
    PortSettings s;
    s.BaudRate = BAUD115200;
    s.DataBits = DATA_8;
    s.StopBits = STOP_1;
    s.Parity = PAR_NONE;
    s.Timeout_Millisec = 1;
    port = new QextSerialPort(parent.getSettingsValue("serialPort").toString(), s,QextSerialPort::Polling);
    bool ret = port->open(QextSerialPort::ReadWrite);
    if (ret)
        logger->debug("Opened serial port!");
    else
        parent.setHealthToSick("Could not open serial port '"+parent.getSettingsValue("serialPort").toString()+"'");
}

bool SonarDataSourceSerial::isOpen()
{
    return port && port->isOpen();
}

SonarDataSourceSerial::~SonarDataSourceSerial()
{
}

void SonarDataSourceSerial::stop()
{
    logger->debug("Closing serial port.");
    if (port != NULL) {
        port->close();
        delete port;
        port = NULL;
    }
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013, Quarkslab
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * - Neither the name of Quarkslab nor the names of its contributors may be used
 * to endorse or promote products derived from this software without specific
 * prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <leeloo/ip_list_intervals.h>
#include <iostream>

int compare_intervals(leeloo::ip_list_intervals const& l, uint32_t const* const ref, size_t const ninter)
{
	if (l.intervals().size() != ninter) {
		std::cerr << "bad number of intervals" << std::endl;
		return 1;
	}
	int ret = 0;
	size_t i = 0;
	for (auto const& it: l.intervals()) {
		if ((it.lower() != ref[2*i]) ||
			(it.upper() != ref[2*i+1])) {
			std::cerr << "invalid interval at index " << i << std::endl;
			ret = 1;
		}
		i++;
	}
	return ret;
}

int main()
{
	int ret = 0;

	leeloo::ip_list_intervals l;
	l.add("10.1-2.4-5.6-7");
	l.add("192.168.0.0/24");
	l.add("10.0.0.1");
	l.add("10.0.0.2");
	l.add("192.168.0.1");
	l.add("172.16.0/24");
	l.add("10.1.1.1");

	uint32_t intervals_before[] = {
		0xa010406, 0xa010408,   // 10.1.4.6-7
		0xa010506, 0xa010508,   // 1O.1.5.6-7
		0xa020406, 0xa020408,   // 10.2.4.6-7
		0xa020506, 0xa020508,   // 10.2.5.6-7
		0xc0a80000, 0xc0a80100, // 192.168.0.0/24
		0xa000001, 0xa000002,   // 10.0.0.1
		0xa000002, 0xa000003,   // 10.0.0.2
		0xc0a80001, 0xc0a80002, // 192.168.0.1
		0xac100000, 0xac100100, // 172.16.0/24
		0xa010101, 0xa010102    // 10.1.1.1
	};

	ret = compare_intervals(l, intervals_before, sizeof(intervals_before)/(2*sizeof(uint32_t)));

	l.aggregate();

	uint32_t intervals_after[] = {
		0xa000001, 0xa000003,
		0xa010101, 0xa010102,
		0xa010406, 0xa010408,
		0xa010506, 0xa010508,
		0xa020406, 0xa020408,
		0xa020506, 0xa020508,
		0xac100000, 0xac100100,
		0xc0a80000, 0xc0a80100
	};

	ret = compare_intervals(l, intervals_after, sizeof(intervals_after)/(2*sizeof(uint32_t)));

	return ret;
}
<commit_msg>Remove unicode character<commit_after>/*
 * Copyright (c) 2013, Quarkslab
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * - Neither the name of Quarkslab nor the names of its contributors may be used
 * to endorse or promote products derived from this software without specific
 * prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <leeloo/ip_list_intervals.h>
#include <iostream>

int compare_intervals(leeloo::ip_list_intervals const& l, uint32_t const* const ref, size_t const ninter)
{
	if (l.intervals().size() != ninter) {
		std::cerr << "bad number of intervals" << std::endl;
		return 1;
	}
	int ret = 0;
	size_t i = 0;
	for (auto const& it: l.intervals()) {
		if ((it.lower() != ref[2*i]) ||
			(it.upper() != ref[2*i+1])) {
			std::cerr << "invalid interval at index " << i << std::endl;
			ret = 1;
		}
		i++;
	}
	return ret;
}

int main()
{
	int ret = 0;

	leeloo::ip_list_intervals l;
	l.add("10.1-2.4-5.6-7");
	l.add("192.168.0.0/24");
	l.add("10.0.0.1");
	l.add("10.0.0.2");
	l.add("192.168.0.1");
	l.add("172.16.0/24");
	l.add("10.1.1.1");

	uint32_t intervals_before[] = {
		0xa010406, 0xa010408,   // 10.1.4.6-7
		0xa010506, 0xa010508,   // 1O.1.5.6-7
		0xa020406, 0xa020408,   // 10.2.4.6-7
		0xa020506, 0xa020508,   // 10.2.5.6-7
		0xc0a80000, 0xc0a80100, // 192.168.0.0/24
		0xa000001, 0xa000002,   // 10.0.0.1
		0xa000002, 0xa000003,   // 10.0.0.2
		0xc0a80001, 0xc0a80002, // 192.168.0.1
		0xac100000, 0xac100100, // 172.16.0/24
		0xa010101, 0xa010102    // 10.1.1.1
	};

	ret = compare_intervals(l, intervals_before, sizeof(intervals_before)/(2*sizeof(uint32_t)));

	l.aggregate();

	uint32_t intervals_after[] = {
		0xa000001, 0xa000003,
		0xa010101, 0xa010102,
		0xa010406, 0xa010408,
		0xa010506, 0xa010508,
		0xa020406, 0xa020408,
		0xa020506, 0xa020508,
		0xac100000, 0xac100100,
		0xc0a80000, 0xc0a80100
	};

	ret = compare_intervals(l, intervals_after, sizeof(intervals_after)/(2*sizeof(uint32_t)));

	return ret;
}
<|endoftext|>


<commit_before>// Time:  O(n)
// Space: O(h)

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
private:
    bool getNumber(const string &data, int *start, int *num) {
        if (data[*start] == '#') {
            *start += 2;  // Skip "# ".
            return false;
        }

        for (*num = 0; isdigit(data[*start]); ++(*start)) {
            *num = *num * 10 + data[*start] - '0';
        }
        ++(*start);  // Skip " ".

        return true;
    }

    void deserializeHelper(const string& data,
                           int *start,  TreeNode **root) {
        int num;
        if (!getNumber(data, start, &num)) {
            *root = nullptr;
        } else {
            *root = new TreeNode(num);
            deserializeHelper(data, start, &((*root)->left));
            deserializeHelper(data, start, &((*root)->right));
        }
    }

    void serializeHelper(const TreeNode *root, string *prev) {
        if (!root)  {
            prev->append("# ");
        } else {
            prev->append(to_string(root->val) + " ");
            serializeHelper(root->left, prev);
            serializeHelper(root->right, prev);
        }
    }

public:
    /**
     * This method will be invoked first, you should design your own algorithm
     * to serialize a binary tree which denote by a root node to a string which
     * can be easily deserialized by your own "deserialize" method later.
     */
    string serialize(TreeNode *root) {
        string output;
        serializeHelper(root, &output);
        return output;
    }

    /**
     * This method will be invoked second, the argument data is what exactly
     * you serialized at method "serialize", that means the data is not given by
     * system, it's given by your own serialize method. So the format of data is
     * designed by yourself, and deserialize it here as you serialize it in
     * "serialize" method.
     */
    TreeNode *deserialize(string data) {
        TreeNode *root = nullptr;
        int start = 0;
        deserializeHelper(data, &start, &root);
        return root;
    }
};
<commit_msg>Update binary-tree-serialization.cpp<commit_after>// Time:  O(n)
// Space: O(h)

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
private:
    bool getNumber(const string &data, int *start, int *num) {
        if (data[*start] == '#') {
            *start += 2;  // Skip "# ".
            return false;
        }

        for (*num = 0; isdigit(data[*start]); ++(*start)) {
            *num = *num * 10 + data[*start] - '0';
        }
        ++(*start);  // Skip " ".

        return true;
    }

    void deserializeHelper(const string& data,
                           int *start,  TreeNode **root) {
        int num;
        if (!getNumber(data, start, &num)) {
            *root = nullptr;
        } else {
            *root = new TreeNode(num);
            deserializeHelper(data, start, &((*root)->left));
            deserializeHelper(data, start, &((*root)->right));
        }
    }

    void serializeHelper(const TreeNode *root, string *prev) {
        if (!root)  {
            prev->append("# ");
        } else {
            prev->append(to_string(root->val).append(" "));
            serializeHelper(root->left, prev);
            serializeHelper(root->right, prev);
        }
    }

public:
    /**
     * This method will be invoked first, you should design your own algorithm
     * to serialize a binary tree which denote by a root node to a string which
     * can be easily deserialized by your own "deserialize" method later.
     */
    string serialize(TreeNode *root) {
        string output;
        serializeHelper(root, &output);
        return output;
    }

    /**
     * This method will be invoked second, the argument data is what exactly
     * you serialized at method "serialize", that means the data is not given by
     * system, it's given by your own serialize method. So the format of data is
     * designed by yourself, and deserialize it here as you serialize it in
     * "serialize" method.
     */
    TreeNode *deserialize(string data) {
        TreeNode *root = nullptr;
        int start = 0;
        deserializeHelper(data, &start, &root);
        return root;
    }
};
<|endoftext|>


<commit_before>/*
 * FogLAMP "scale" filter plugin.
 *
 * Copyright (c) 2018 Dianomic Systems
 *
 * Released under the Apache 2.0 Licence
 *
 * Author: Massimiliano Pinto
 */

#include <plugin_api.h>
#include <config_category.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <string>
#include <iostream>
#include <filter_plugin.h>
#include <filter.h>
#include <reading_set.h>

#define FILTER_NAME "scale"
#define SCALE_FACTOR "100"
#define DEFAULT_CONFIG "{\"plugin\" : { \"description\" : \"Scale filter plugin\", " \
                       		"\"type\" : \"string\", " \
				"\"default\" : \"" FILTER_NAME "\" }, " \
			 "\"enable\": {\"description\": \"A switch that can be used to enable or disable execution of " \
					 "the scale filter.\", " \
				"\"type\": \"boolean\", " \
				"\"default\": \"false\" }, " \
			"\"factor\" : {\"description\" : \"Scale factor for a reading value.\", " \
				"\"type\": \"integer\", " \
				"\"default\": \"" SCALE_FACTOR "\"} }"
using namespace std;

/**
 * The Filter plugin interface
 */
extern "C" {

/**
 * The plugin information structure
 */
static PLUGIN_INFORMATION info = {
        FILTER_NAME,              // Name
        "1.0.0",                  // Version
        0,                        // Flags
        PLUGIN_TYPE_FILTER,       // Type
        "1.0.0",                  // Interface version
	DEFAULT_CONFIG	          // Default plugin configuration
};

/**
 * Return the information about this plugin
 */
PLUGIN_INFORMATION *plugin_info()
{
	return &info;
}

/**
 * Initialise the plugin, called to get the plugin handle and setup the
 * output handle that will be passed to the output stream. The output stream
 * is merely a function pointer that is called with the output handle and
 * the new set of readings generated by the plugin.
 *     (*output)(outHandle, readings);
 * Note that the plugin may not call the output stream if the result of
 * the filtering is that no readings are to be sent onwards in the chain.
 * This allows the plugin to discard data or to buffer it for aggregation
 * with data that follows in subsequent calls
 *
 * @param config	The configuration category for the filter
 * @param outHandle	A handle that will be passed to the output stream
 * @param output	The output stream (function pointer) to which data is passed
 * @return		An opaque handle that is used in all subsequent calls to the plugin
 */
PLUGIN_HANDLE plugin_init(ConfigCategory* config,
			  OUTPUT_HANDLE *outHandle,
			  OUTPUT_STREAM output)
{
	FogLampFilter* handle = new FogLampFilter(FILTER_NAME,
						  *config,
						  outHandle,
						  output);

	return (PLUGIN_HANDLE)handle;
}

/**
 * Ingest a set of readings into the plugin for processing
 *
 * @param handle	The plugin handle returned from plugin_init
 * @param readingSet	The readings to process
 */
void plugin_ingest(PLUGIN_HANDLE *handle,
		   READINGSET *readingSet)
{
	FogLampFilter* filter = (FogLampFilter *)handle;
	if (!filter->isEnabled())
	{
		// Current filter is not active: just pass the readings set
		filter->m_func(filter->m_data, readingSet);
		return;
	}

	// Get filter configuration
	double scaleFactor;
	if (filter->getConfig().itemExists("factor"))
	{
		scaleFactor = strtod(filter->getConfig().getValue("factor").c_str(), NULL);
	}
	else
	{
		scaleFactor = strtod(SCALE_FACTOR, NULL);
	}

	Logger::getLogger()->info("filter %s is using configuration value 'factor' = %f",
				  FILTER_NAME,
				  scaleFactor);

	// 1- We might need to transform the inout readings set: example
	// ReadingSet* newReadings = scale_readings(scaleFactor, readingSet);

	// Just get all the readings in the readingset
	const vector<Reading *>& readings = ((ReadingSet *)readingSet)->getAllReadings();
	// Iterate the readings
	for (vector<Reading *>::const_iterator elem = readings.begin();
						      elem != readings.end();
						      ++elem)
	{
		// Get a reading DataPoint
		const vector<Datapoint *>& dataPoints = (*elem)->getReadingData();
		// Iterate the datapoints
		for (vector<Datapoint *>::const_iterator it = dataPoints.begin(); it != dataPoints.end(); ++it)
		{
			// Get the reference to a DataPointValue
			DatapointValue& value = (*it)->getData();

			// If INTEGER or FLOAT do the change
			if (value.getType() == DatapointValue::T_INTEGER)
			{
				value.setValue((int)(atoi(value.toString().c_str()) * scaleFactor));
			}
			else if (value.getType() == DatapointValue::T_FLOAT)
			{
				value.setValue(atof(value.toString().c_str()) * scaleFactor);
			}
			else
			{
				// do nothing
			}
		}
	}

	// 2- optionally free reading set
	// delete (ReadingSet *)readingSet;
	// With the above DataPointValue change we don't need to free input data

	// 3- pass newReadings to filter->m_func instead of readings if needed.
	// With the value change we can pass same input readingset just modified
	filter->m_func(filter->m_data, readingSet);
}

/**
 * Call the shutdown method in the plugin
 */
void plugin_shutdown(PLUGIN_HANDLE *handle)
{
	FogLampFilter* data = (FogLampFilter *)handle;
	delete data;
}

// End of extern "C"
};
<commit_msg>FOGL-1707: use toInt() and toDouble() instead of string to number con… (#1030)<commit_after>/*
 * FogLAMP "scale" filter plugin.
 *
 * Copyright (c) 2018 Dianomic Systems
 *
 * Released under the Apache 2.0 Licence
 *
 * Author: Massimiliano Pinto
 */

#include <plugin_api.h>
#include <config_category.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <string>
#include <iostream>
#include <filter_plugin.h>
#include <filter.h>
#include <reading_set.h>

#define FILTER_NAME "scale"
#define SCALE_FACTOR "100"
#define DEFAULT_CONFIG "{\"plugin\" : { \"description\" : \"Scale filter plugin\", " \
                       		"\"type\" : \"string\", " \
				"\"default\" : \"" FILTER_NAME "\" }, " \
			 "\"enable\": {\"description\": \"A switch that can be used to enable or disable execution of " \
					 "the scale filter.\", " \
				"\"type\": \"boolean\", " \
				"\"default\": \"false\" }, " \
			"\"factor\" : {\"description\" : \"Scale factor for a reading value.\", " \
				"\"type\": \"integer\", " \
				"\"default\": \"" SCALE_FACTOR "\"} }"
using namespace std;

/**
 * The Filter plugin interface
 */
extern "C" {

/**
 * The plugin information structure
 */
static PLUGIN_INFORMATION info = {
        FILTER_NAME,              // Name
        "1.0.0",                  // Version
        0,                        // Flags
        PLUGIN_TYPE_FILTER,       // Type
        "1.0.0",                  // Interface version
	DEFAULT_CONFIG	          // Default plugin configuration
};

/**
 * Return the information about this plugin
 */
PLUGIN_INFORMATION *plugin_info()
{
	return &info;
}

/**
 * Initialise the plugin, called to get the plugin handle and setup the
 * output handle that will be passed to the output stream. The output stream
 * is merely a function pointer that is called with the output handle and
 * the new set of readings generated by the plugin.
 *     (*output)(outHandle, readings);
 * Note that the plugin may not call the output stream if the result of
 * the filtering is that no readings are to be sent onwards in the chain.
 * This allows the plugin to discard data or to buffer it for aggregation
 * with data that follows in subsequent calls
 *
 * @param config	The configuration category for the filter
 * @param outHandle	A handle that will be passed to the output stream
 * @param output	The output stream (function pointer) to which data is passed
 * @return		An opaque handle that is used in all subsequent calls to the plugin
 */
PLUGIN_HANDLE plugin_init(ConfigCategory* config,
			  OUTPUT_HANDLE *outHandle,
			  OUTPUT_STREAM output)
{
	FogLampFilter* handle = new FogLampFilter(FILTER_NAME,
						  *config,
						  outHandle,
						  output);

	return (PLUGIN_HANDLE)handle;
}

/**
 * Ingest a set of readings into the plugin for processing
 *
 * @param handle	The plugin handle returned from plugin_init
 * @param readingSet	The readings to process
 */
void plugin_ingest(PLUGIN_HANDLE *handle,
		   READINGSET *readingSet)
{
	FogLampFilter* filter = (FogLampFilter *)handle;
	if (!filter->isEnabled())
	{
		// Current filter is not active: just pass the readings set
		filter->m_func(filter->m_data, readingSet);
		return;
	}

	// Get filter configuration
	double scaleFactor;
	if (filter->getConfig().itemExists("factor"))
	{
		scaleFactor = strtod(filter->getConfig().getValue("factor").c_str(), NULL);
	}
	else
	{
		scaleFactor = strtod(SCALE_FACTOR, NULL);
	}

	// 1- We might need to transform the inout readings set: example
	// ReadingSet* newReadings = scale_readings(scaleFactor, readingSet);

	// Just get all the readings in the readingset
	const vector<Reading *>& readings = ((ReadingSet *)readingSet)->getAllReadings();
	// Iterate the readings
	for (vector<Reading *>::const_iterator elem = readings.begin();
						      elem != readings.end();
						      ++elem)
	{
		// Get a reading DataPoint
		const vector<Datapoint *>& dataPoints = (*elem)->getReadingData();
		// Iterate the datapoints
		for (vector<Datapoint *>::const_iterator it = dataPoints.begin(); it != dataPoints.end(); ++it)
		{
			// Get the reference to a DataPointValue
			DatapointValue& value = (*it)->getData();

			// If INTEGER or FLOAT do the change
			if (value.getType() == DatapointValue::T_INTEGER)
			{
				value.setValue((int)(value.toInt() * scaleFactor));
			}
			else if (value.getType() == DatapointValue::T_FLOAT)
			{
				value.setValue(value.toDouble() * scaleFactor);
			}
			else
			{
				// do nothing
			}
		}
	}

	// 2- optionally free reading set
	// delete (ReadingSet *)readingSet;
	// With the above DataPointValue change we don't need to free input data

	// 3- pass newReadings to filter->m_func instead of readings if needed.
	// With the value change we can pass same input readingset just modified
	filter->m_func(filter->m_data, readingSet);
}

/**
 * Call the shutdown method in the plugin
 */
void plugin_shutdown(PLUGIN_HANDLE *handle)
{
	FogLampFilter* data = (FogLampFilter *)handle;
	delete data;
}

// End of extern "C"
};
<|endoftext|>


<commit_before>/******************************************************************************
** Copyright (c) 2013-2015, Intel Corporation                                **
** All rights reserved.                                                      **
**                                                                           **
** Redistribution and use in source and binary forms, with or without        **
** modification, are permitted provided that the following conditions        **
** are met:                                                                  **
** 1. Redistributions of source code must retain the above copyright         **
**    notice, this list of conditions and the following disclaimer.          **
** 2. Redistributions in binary form must reproduce the above copyright      **
**    notice, this list of conditions and the following disclaimer in the    **
**    documentation and/or other materials provided with the distribution.   **
** 3. Neither the name of the copyright holder nor the names of its          **
**    contributors may be used to endorse or promote products derived        **
**    from this software without specific prior written permission.          **
**                                                                           **
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       **
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT         **
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR     **
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT      **
** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,    **
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED  **
** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR    **
** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF    **
** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING      **
** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS        **
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.              **
******************************************************************************/
/* Hans Pabst (Intel Corp.)
******************************************************************************/
#include <libxsmm.h>

#if defined(LIBXSMM_OFFLOAD)
# pragma offload_attribute(push,target(mic))
#endif

#include <algorithm>
#include <stdexcept>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <cstdio>
#include <cmath>

#if defined(USE_MKL) || defined(MKL_DIRECT_CALL_SEQ) || defined(MKL_DIRECT_CALL)
# include <mkl_service.h>
#endif

#if defined(_OPENMP)
# include <omp.h>
#endif

#if defined(LIBXSMM_OFFLOAD)
# pragma offload_attribute(pop)
#endif

template<int Seed>
struct LIBXSMM_TARGET(mic) init {
  template<typename T> init(T *LIBXSMM_RESTRICT dst, int nrows, int ncols, int n = 0, int ld = 0) {
    const int ldx = 0 == ld ? ncols : ld;
    for (int i = 0; i < nrows; ++i) {
      for (int j = 0; j < ncols; ++j) {
        // initialize similar to CP2K's (libsmm_acc) benchmark driver
        dst[i*ldx+j] = static_cast<T>(i * ldx + j + n + Seed);
      }
    }
  }
};

int main(int argc, char* argv[])
{
  try {
    typedef double T;
    const int m = 1 < argc ? std::atoi(argv[1]) : 23;
    const int n = 2 < argc ? std::atoi(argv[2]) : m;
    const int k = 3 < argc ? std::atoi(argv[3]) : m;

    const int asize = m * k, bsize = k * n, aspace = (LIBXSMM_ALIGNED_MAX) / sizeof(T);
    const int ldc = LIBXSMM_ALIGN_STORES(LIBXSMM_LD(m, n), sizeof(T)), csize = LIBXSMM_LD(n, m) * ldc;
    const int s = (2ULL << 30) / ((asize + bsize) * sizeof(T)); // 2 GByte
#if defined(_OPENMP)
    const size_t bwsize = (asize/*load*/ + bsize/*load*/ + csize * 2/*load and store*/) * sizeof(T); // cached
    const double gflops = 2.0 * s * m * n * k * 1E-9;
#endif

    struct raii { // avoid std::vector (first-touch init. causes NUMA issue)
      T *a, *b;
      raii(int s, int asize, int bsize, int aspace)
        : a(new T[s*asize+aspace-1]), b(new T[s*bsize+aspace-1])
      {}
      ~raii() { delete[] a; delete[] b; }
    } buffer(s, asize, bsize, aspace);
    T *const a = LIBXSMM_ALIGN(buffer.a, LIBXSMM_ALIGNED_MAX);
    T *const b = LIBXSMM_ALIGN(buffer.b, LIBXSMM_ALIGNED_MAX);

#if defined(_OPENMP)
#   pragma omp parallel for
#endif
    for (int i = 0; i < s; ++i) {
      init<42>(a + i * asize, m, k, i);
      init<24>(b + i * bsize, k, n, i);
    }

#if defined(LIBXSMM_OFFLOAD)
#   pragma offload target(mic) in(a: length(s * asize)) in(b: length(s * bsize))
#endif
    {
#if defined(USE_MKL) || defined(MKL_DIRECT_CALL_SEQ) || defined(MKL_DIRECT_CALL)
      mkl_enable_instructions(MKL_ENABLE_AVX512_MIC);
#endif
      fprintf(stdout, "m=%i n=%i k=%i ldc=%i (%s) size=%i memory=%.f MB\n\n",
        m, n, k, ldc, 0 != (LIBXSMM_ROW_MAJOR) ? "row-major" : "column-major",
        s, 1.0 * s * (asize + bsize + csize) * sizeof(T) / (1 << 20));

      { // streaming
        fprintf(stdout, "Streamed...\n");
#if defined(_OPENMP)
        double start = 0;
#       pragma omp parallel
        {
#         pragma omp master
          start = omp_get_wtime();
#         pragma omp for
#endif
          for (int i = 0; i < s; ++i) {
            // make sure that stacksize is covering the problem size; tmp is zero-initialized by lang. rules
            LIBXSMM_ALIGNED(T tmp[LIBXSMM_MAX_SIZE/*max. problemsize*/], LIBXSMM_ALIGNED_MAX);
            libxsmm_imm(m, n, k, a + i * asize, b + i * bsize, tmp);
          }
#if defined(_OPENMP)
        }
        const double duration = omp_get_wtime() - start;
        if (0 < duration) {
          fprintf(stdout, "\tperformance: %.1f GFLOPS/s\n", gflops / duration);
          fprintf(stdout, "\tbandwidth: %.1f GB/s\n", s * bwsize / (duration * (1 << 30)));
        }
        fprintf(stdout, "\tduration: %.1f s\n", duration);
#endif
      }

      { // cached
        fprintf(stdout, "Cached...\n");
#if defined(_OPENMP)
        double start = 0;
#       pragma omp parallel
        {
#         pragma omp master
          start = omp_get_wtime();
# if defined(__MIC__)
#         pragma omp for schedule(dynamic)
# else
#         pragma omp for
# endif
#endif
          for (int i = 0; i < s; ++i) {
            // make sure that stacksize is covering the problem size; tmp is zero-initialized by lang. rules
            LIBXSMM_ALIGNED(T tmp[LIBXSMM_MAX_SIZE/*max. problemsize*/], LIBXSMM_ALIGNED_MAX);
            // do nothing else with tmp; just a benchmark
            libxsmm_imm(m, n, k, a, b, tmp);
          }
#if defined(_OPENMP)
        }
        const double duration = omp_get_wtime() - start;
        if (0 < duration) {
          fprintf(stdout, "\tperformance: %.1f GFLOPS/s\n", gflops / duration);
        }
        fprintf(stdout, "\tduration: %.1f s\n", duration);
#endif
      }

      fprintf(stdout, "Finished\n");
    }
  }
  catch(const std::exception& e) {
    fprintf(stderr, "Error: %s\n", e.what());
    return EXIT_FAILURE;
  }
  catch(...) {
    fprintf(stderr, "Error: unknown exception caught!\n");
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}
<commit_msg>Missed to adjust memory consumption calculation (SMM/inlined).<commit_after>/******************************************************************************
** Copyright (c) 2013-2015, Intel Corporation                                **
** All rights reserved.                                                      **
**                                                                           **
** Redistribution and use in source and binary forms, with or without        **
** modification, are permitted provided that the following conditions        **
** are met:                                                                  **
** 1. Redistributions of source code must retain the above copyright         **
**    notice, this list of conditions and the following disclaimer.          **
** 2. Redistributions in binary form must reproduce the above copyright      **
**    notice, this list of conditions and the following disclaimer in the    **
**    documentation and/or other materials provided with the distribution.   **
** 3. Neither the name of the copyright holder nor the names of its          **
**    contributors may be used to endorse or promote products derived        **
**    from this software without specific prior written permission.          **
**                                                                           **
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       **
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT         **
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR     **
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT      **
** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,    **
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED  **
** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR    **
** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF    **
** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING      **
** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS        **
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.              **
******************************************************************************/
/* Hans Pabst (Intel Corp.)
******************************************************************************/
#include <libxsmm.h>

#if defined(LIBXSMM_OFFLOAD)
# pragma offload_attribute(push,target(mic))
#endif

#include <algorithm>
#include <stdexcept>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <cstdio>
#include <cmath>

#if defined(USE_MKL) || defined(MKL_DIRECT_CALL_SEQ) || defined(MKL_DIRECT_CALL)
# include <mkl_service.h>
#endif

#if defined(_OPENMP)
# include <omp.h>
#endif

#if defined(LIBXSMM_OFFLOAD)
# pragma offload_attribute(pop)
#endif

template<int Seed>
struct LIBXSMM_TARGET(mic) init {
  template<typename T> init(T *LIBXSMM_RESTRICT dst, int nrows, int ncols, int n = 0, int ld = 0) {
    const int ldx = 0 == ld ? ncols : ld;
    for (int i = 0; i < nrows; ++i) {
      for (int j = 0; j < ncols; ++j) {
        // initialize similar to CP2K's (libsmm_acc) benchmark driver
        dst[i*ldx+j] = static_cast<T>(i * ldx + j + n + Seed);
      }
    }
  }
};

int main(int argc, char* argv[])
{
  try {
    typedef double T;
    const int m = 1 < argc ? std::atoi(argv[1]) : 23;
    const int n = 2 < argc ? std::atoi(argv[2]) : m;
    const int k = 3 < argc ? std::atoi(argv[3]) : m;

    const int asize = m * k, bsize = k * n, aspace = (LIBXSMM_ALIGNED_MAX) / sizeof(T);
    const int ldc = LIBXSMM_ALIGN_STORES(LIBXSMM_LD(m, n), sizeof(T)), csize = LIBXSMM_LD(n, m) * ldc;
    const int s = (2ULL << 30) / ((asize + bsize) * sizeof(T)); // 2 GByte
#if defined(_OPENMP)
    const size_t bwsize = (asize/*load*/ + bsize/*load*/ + csize * 2/*load and store*/) * sizeof(T); // cached
    const double gflops = 2.0 * s * m * n * k * 1E-9;
#endif

    struct raii { // avoid std::vector (first-touch init. causes NUMA issue)
      T *a, *b;
      raii(int s, int asize, int bsize, int aspace)
        : a(new T[s*asize+aspace-1]), b(new T[s*bsize+aspace-1])
      {}
      ~raii() { delete[] a; delete[] b; }
    } buffer(s, asize, bsize, aspace);
    T *const a = LIBXSMM_ALIGN(buffer.a, LIBXSMM_ALIGNED_MAX);
    T *const b = LIBXSMM_ALIGN(buffer.b, LIBXSMM_ALIGNED_MAX);

#if defined(_OPENMP)
#   pragma omp parallel for
#endif
    for (int i = 0; i < s; ++i) {
      init<42>(a + i * asize, m, k, i);
      init<24>(b + i * bsize, k, n, i);
    }

#if defined(LIBXSMM_OFFLOAD)
#   pragma offload target(mic) in(a: length(s * asize)) in(b: length(s * bsize))
#endif
    {
#if defined(USE_MKL) || defined(MKL_DIRECT_CALL_SEQ) || defined(MKL_DIRECT_CALL)
      mkl_enable_instructions(MKL_ENABLE_AVX512_MIC);
#endif
      fprintf(stdout, "m=%i n=%i k=%i ldc=%i (%s) size=%i memory=%.f MB\n\n",
        m, n, k, ldc, 0 != (LIBXSMM_ROW_MAJOR) ? "row-major" : "column-major",
        s, 1.0 * s * (asize + bsize) * sizeof(T) / (1 << 20));

      { // streaming
        fprintf(stdout, "Streamed...\n");
#if defined(_OPENMP)
        double start = 0;
#       pragma omp parallel
        {
#         pragma omp master
          start = omp_get_wtime();
#         pragma omp for
#endif
          for (int i = 0; i < s; ++i) {
            // make sure that stacksize is covering the problem size; tmp is zero-initialized by lang. rules
            LIBXSMM_ALIGNED(T tmp[LIBXSMM_MAX_SIZE/*max. problemsize*/], LIBXSMM_ALIGNED_MAX);
            libxsmm_imm(m, n, k, a + i * asize, b + i * bsize, tmp);
          }
#if defined(_OPENMP)
        }
        const double duration = omp_get_wtime() - start;
        if (0 < duration) {
          fprintf(stdout, "\tperformance: %.1f GFLOPS/s\n", gflops / duration);
          fprintf(stdout, "\tbandwidth: %.1f GB/s\n", s * bwsize / (duration * (1 << 30)));
        }
        fprintf(stdout, "\tduration: %.1f s\n", duration);
#endif
      }

      { // cached
        fprintf(stdout, "Cached...\n");
#if defined(_OPENMP)
        double start = 0;
#       pragma omp parallel
        {
#         pragma omp master
          start = omp_get_wtime();
# if defined(__MIC__)
#         pragma omp for schedule(dynamic)
# else
#         pragma omp for
# endif
#endif
          for (int i = 0; i < s; ++i) {
            // make sure that stacksize is covering the problem size; tmp is zero-initialized by lang. rules
            LIBXSMM_ALIGNED(T tmp[LIBXSMM_MAX_SIZE/*max. problemsize*/], LIBXSMM_ALIGNED_MAX);
            // do nothing else with tmp; just a benchmark
            libxsmm_imm(m, n, k, a, b, tmp);
          }
#if defined(_OPENMP)
        }
        const double duration = omp_get_wtime() - start;
        if (0 < duration) {
          fprintf(stdout, "\tperformance: %.1f GFLOPS/s\n", gflops / duration);
        }
        fprintf(stdout, "\tduration: %.1f s\n", duration);
#endif
      }

      fprintf(stdout, "Finished\n");
    }
  }
  catch(const std::exception& e) {
    fprintf(stderr, "Error: %s\n", e.what());
    return EXIT_FAILURE;
  }
  catch(...) {
    fprintf(stderr, "Error: unknown exception caught!\n");
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}
<|endoftext|>