text:
package org.apache.ctakes.ytex.weka;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.SortedMap;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ctakes.ytex.kernel.FileUtil;
import org.apache.ctakes.ytex.kernel.KernelContextHolder;
import org.apache.ctakes.ytex.kernel.KernelUtil;
import org.apache.ctakes.ytex.kernel.SparseData;
import org.apache.ctakes.ytex.kernel.SparseDataExporter;
import org.apache.ctakes.ytex.kernel.SparseDataFormatter;
import org.apache.ctakes.ytex.kernel.dao.ClassifierEvaluationDao;
import org.apache.ctakes.ytex.kernel.model.ClassifierEvaluation;
import org.apache.ctakes.ytex.kernel.model.CrossValidationFold;
import org.apache.ctakes.ytex.kernel.model.FeatureEvaluation;
import org.apache.ctakes.ytex.kernel.model.FeatureRank;
import org.apache.ctakes.ytex.weka.WekaFormatterFactory.WekaFormatter;

import weka.attributeSelection.ASEvaluation;
import weka.attributeSelection.AttributeSelection;
import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;

public class WekaAttributeEvaluatorImpl implements WekaAttributeEvaluator {
	public class WekaAttributeEvaluatorFormatter extends WekaFormatter {
		String corpusName;

		String featureSetName;

		String splitName;

		public WekaAttributeEvaluatorFormatter(String corpusName,
				String featureSetName, String splitName) {
			super(getKernelUtil());
			this.featureSetName = featureSetName;
			this.corpusName = corpusName;
			this.splitName = splitName;
		}

		@Override
		public void exportFold(SparseData sparseData,
				SortedMap<Long, String> instanceClasses, boolean train,
				String label, Integer run, Integer fold) throws IOException {
			if (train) {
				Instances inst = this.initializeInstances(sparseData,
						instanceClasses, train, label, run, fold);
				try {
					evaluateAttributes(corpusName, featureSetName, splitName,
							inst, label, run, fold);
				} catch (Exception e) {
					throw new IOException(e);
				}
			}
		}

	}

	private static final Log log = LogFactory
			.getLog(WekaAttributeEvaluatorImpl.class);

	/**
	 * @param args
	 * @throws Exception
	 */
	@SuppressWarnings("static-access")
	public static void main(String[] args) throws Exception {
		Options options = new Options();
		options.addOption(OptionBuilder
				.withArgName("property file")
				.hasArg()
				.withDescription(
						"load parameters from property file.  If queries defiend as for SparseDataExporter, use them to load the instances")
				.create("prop"));
		options.addOption(OptionBuilder
				.withArgName("train_data.arff")
				.hasArg()
				.withDescription(
						"use specified weka arff file to load instances for evaluation.")
				.create("arff"));
		try {
			CommandLineParser parser = new GnuParser();
			CommandLine line = parser.parse(options, args);
			Properties props = FileUtil.loadProperties(
					line.getOptionValue("prop"), true);
			String corpusName = props.getProperty("org.apache.ctakes.ytex.corpusName");
			String splitName = props.getProperty("org.apache.ctakes.ytex.splitName");
			String featureSetName = props.getProperty("org.apache.ctakes.ytex.featureSetName");
			WekaAttributeEvaluator wekaEval = KernelContextHolder
					.getApplicationContext().getBean(
							WekaAttributeEvaluator.class);
			if (line.hasOption("arff")) {
				wekaEval.evaluateAttributesFromFile(corpusName, splitName,
						featureSetName, line.getOptionValue("arff"));
			} else {
				wekaEval.evaluateAttributesFromProps(corpusName, splitName,
						featureSetName, props);
			}
		} catch (ParseException pe) {
			printHelp(options);
		}
	}

	private static void printHelp(Options options) {
		HelpFormatter formatter = new HelpFormatter();
		formatter
				.printHelp(
						"java "
								+ WekaAttributeEvaluatorImpl.class.getName()
								+ " evaluate attributes using a weka AttributeEvaluator",
						options);
	}

	private ASEvaluation asEvaluation;
	private AttributeSelection attributeSelection;

	private ClassifierEvaluationDao classifierEvaluationDao;

	private KernelUtil kernelUtil;

	private SparseDataExporter sparseDataExporter;

	/**
	 * evaluate attributes, store in db
	 *
	 * @param inst
	 *            instances
	 * @param label
	 *            {@link FeatureEvaluation#getLabel()}
	 * @param run
	 *            {@link ClassifierEvaluation#getRun()} to map to fold
	 * @param fold
	 *            {@link ClassifierEvaluation#getFold()} to map to fold
	 * @throws Exception
	 */
	public void evaluateAttributes(String corpusName, String featureSetName,
			String splitName, Instances inst, String label, Integer run,
			Integer fold) throws Exception {
		AttributeSelection ae = this.getAttributeSelection();
		ae.SelectAttributes(inst);
		double rankedAttributes[][] = ae.rankedAttributes();
		FeatureEvaluation fe = initializeFeatureEvaluation(corpusName,
				featureSetName, splitName, label, run, fold);
		List<FeatureRank> featureRanks = new ArrayList<FeatureRank>(
				rankedAttributes.length);
		for (int i = 0; i < rankedAttributes.length; i++) {
			int index = (int) rankedAttributes[i][0];
			double eval = rankedAttributes[i][1];
			FeatureRank r = new FeatureRank();
			r.setFeatureEval(fe);
			r.setFeatureName(inst.attribute(index).name());
			r.setRank(i + 1);
			r.setEvaluation(eval);
			featureRanks.add(r);
		}
		// delete this feature evaluation if it exists
		classifierEvaluationDao.deleteFeatureEvaluation(corpusName,
				featureSetName, label, fe.getEvaluationType(),
				fe.getCrossValidationFoldId(), fe.getParam1(), fe.getParam2());
		classifierEvaluationDao.saveFeatureEvaluation(fe, featureRanks);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.apache.ctakes.ytex.weka.WekaAttributeEvaluator#evaluateAttributesFromFile(java.lang
	 * .String, java.lang.String)
	 */
	@Override
	public void evaluateAttributesFromFile(String corpusName,
			String featureSetName, String splitName, String file)
			throws Exception {
		DataSource ds = new DataSource(file);
		Instances inst = ds.getDataSet();
		String label = FileUtil.parseLabelFromFileName(inst.relationName());
		Integer run = FileUtil.parseRunFromFileName(inst.relationName());
		Integer fold = FileUtil.parseFoldFromFileName(inst.relationName());
		evaluateAttributes(corpusName, featureSetName, splitName, inst, label,
				run, fold);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.apache.ctakes.ytex.weka.WekaAttributeEvaluator#evaluateAttributesFromProps(java.lang
	 * .String, java.lang.String)
	 */
	@Override
	public void evaluateAttributesFromProps(String corpusName,
			String splitName, String featureSetName, Properties props)
			throws Exception {
		sparseDataExporter.exportData(props,
				new WekaAttributeEvaluatorFormatter(corpusName, featureSetName,
						splitName), null);
	}

	public ASEvaluation getAsEvaluation() {
		return asEvaluation;
	}

	public AttributeSelection getAttributeSelection() {
		return attributeSelection;
	}

	public ClassifierEvaluationDao getClassifierEvaluationDao() {
		return classifierEvaluationDao;
	}

	public KernelUtil getKernelUtil() {
		return kernelUtil;
	}

	public SparseDataExporter getSparseDataExporter() {
		return sparseDataExporter;
	}

	public FeatureEvaluation initializeFeatureEvaluation(String corpusName,
			String featureSetName, String splitName, String label, Integer run,
			Integer fold) {
		FeatureEvaluation fe = new FeatureEvaluation();
		fe.setCorpusName(corpusName);
		fe.setFeatureSetName(featureSetName);
		fe.setEvaluationType(this.getAsEvaluation().getClass().getSimpleName());
		fe.setLabel(label);
		if (run != null && fold != null) {
			CrossValidationFold cvFold = this.classifierEvaluationDao
					.getCrossValidationFold(corpusName, splitName, label, run,
							fold);
			if (cvFold != null)
				fe.setCrossValidationFoldId(cvFold.getCrossValidationFoldId());
			else {
				log.warn("could not obtain cv_fold_id. label=" + label
						+ ", run=" + run + ", fold=" + fold);
			}
		}
		return fe;
	}

	public void setAsEvaluation(ASEvaluation asEvaluation) {
		this.asEvaluation = asEvaluation;
	}

	public void setAttributeSelection(AttributeSelection attributeSelection) {
		this.attributeSelection = attributeSelection;
	}

	public void setClassifierEvaluationDao(
			ClassifierEvaluationDao classifierEvaluationDao) {
		this.classifierEvaluationDao = classifierEvaluationDao;
	}

	public void setKernelUtil(KernelUtil kernelUtil) {
		this.kernelUtil = kernelUtil;
	}

	public void setSparseDataExporter(SparseDataExporter sparseDataExporter) {
		this.sparseDataExporter = sparseDataExporter;
	}

}


text:
let fs = require('fs');

const trim_chars = (str, chars) => str.split(chars).filter(Boolean).join(chars);

function friendlyName(name)
{
    let friendly_name;

    let splits = name.split(/(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])/g);
    splits = splits.reduce((ret, word) =>
    {
        if (!word) return ret;
        return [...ret, trim_chars(word.toLowerCase(), '_')]
    }, []);

    splits[0] = splits[0].substring(0, 1).toUpperCase() + splits[0].substring(1);

    return splits.join(' ');
}

// Find components
let dir = fs.readdirSync('../common');
let components = dir.reduce((components, file) =>
{
    if (file.endsWith('.h') && file != "Component.h")
    {
        let filename = `../common/${file}`;
        let file_content = fs.readFileSync(filename).toString();
        let found = file_content.match(/COMPONENT_DECLARATION\(\s*(\w+)\s*,\s*(\w+)\s*\)/);
        if (found)
        {
            let component = {
                className: found[1],
                name: found[2],
                filename: filename,
                source: file_content,
                properties: []
            }
            components.push(component);
        }
    }
    return components;
}, []);

// Find components' properties
components.forEach(component =>
{
    // Find those with flags
    {
        let regex = /COMPONENT_PROPERTY\(\s*([\w\:]+)\s*,\s*(\w+)\s*,\s*(.+)\s*,\s*([\w|\s]+)\s*\)/g;
        let output = [];
        let matches;
        while (matches = regex.exec(component.source))
        {
            let flags = [];
            if (matches[4]) flags = matches[4].split('|');
            flags = flags.map(flag => flag.trim());

            let property = {
                type: matches[1].replace('::', '_'),
                name: matches[2],
                default_value: matches[3],
                flags: flags
            };

            component.properties.push(property);
        }
    }

    // Find those without flags
    {
        let regex = /COMPONENT_PROPERTY\(\s*([\w\:]+)\s*,\s*(\w+)\s*,\s*(.+)\s*\)/g;
        let output = [];
        let matches;
        while (matches = regex.exec(component.source))
        {
            let name = matches[2];
            if (!component.properties.find(property => property.name == name))
            {
                let property = {
                    type: matches[1].replace('::', '_'),
                    name: name,
                    default_value: matches[3],
                    flags: []
                };

                component.properties.push(property);
            }
        }
    }
});

// Erase old generated code in the sources
components.forEach(component =>
{
    let end_tag = `// [GENERATED COMPONENT DECLARATION END]`;
    let start_index = component.source.search(/\/\/ \[GENERATED COMPONENT DECLARATION BEGIN\]/, '');
    let end_index = component.source.search(/\/\/ \[GENERATED COMPONENT DECLARATION END\]/, '');
    if (start_index != -1 && end_index != -1)
    {
        component.start_code = component.source.substring(0, start_index).trimEnd();
        component.end_code = component.source.substring(end_index + end_tag.length).trimStart();
    }
});

// Add derialize/deserialize to the header files
components.forEach(component =>
{
    let insert_block = `\n    // [GENERATED COMPONENT DECLARATION BEGIN]
public:
#if BARK_EDITOR
    Json::Value serialize() override
    {
        auto json = Component::serialize();

`;

    component.properties.forEach(property =>
    {
        insert_block += `        setJson_${property.type}(json, "${property.name}", ${property.name});\n`;
    });

    insert_block += `
        return std::move(json);
    }
#endif

    void deserialize(const Json::Value& json) override
    {
        Component::deserialize(json);

`;

    component.properties.forEach(property =>
    {
        insert_block += `        ${property.name} = getJson_${property.type}(json, "${property.name}", ${property.default_value});\n`;
    });

    insert_block += `    }

#if !BARK_EDITOR
    static void* js_prototype;
    void* getJSPrototype() override { return js_prototype; };
#endif

#if BARK_EDITOR
    void drawProperties(GUIContext* ctx) override
    {
`
    component.properties.forEach(property =>
    {
        insert_block += `        ctx->${property.type}_prop(&${property.name}, "${friendlyName(property.name)}");\n`;
    });

    insert_block += `    }
#endif
    // [GENERATED COMPONENT DECLARATION END]\n`;

    component.source = `${component.start_code}${insert_block}${component.end_code}`;
    delete component.start_code
    delete component.end_code

    component.source = component.source.replace(/\r?\n/g, "\r\n");
    fs.writeFileSync(component.filename, component.source);
    console.log(`=> ${component.filename}`);
});

let ComponentBindings_cpp = `// DO NOT EDIT - THIS FILE IS GENERATED

#include <JSBindings_Macros.h>
#include "ComponentBindings.h"
#include "Component.h"
#include "JSTypeHelper.h"

namespace onut
{
    namespace js
    {
        extern duk_context* pContext;
    }
}

using namespace onut::js;
`;

components.forEach(component =>
{
    let code = `
// ${component.className}
#include "${component.className}.h"

void* ${component.className}::js_prototype = nullptr;

void create${component.className}Bindings()
{
    auto ctx = pContext;

    // Constructor
    duk_push_c_function(ctx, [](duk_context *ctx)->duk_ret_t
    {
        return DUK_RET_TYPE_ERROR; // No constructor allowed
    }, 1);
    duk_push_object(ctx);

    // Destructor
    duk_push_c_function(ctx, [](duk_context *ctx)->duk_ret_t
    {
        duk_push_pointer(ctx, nullptr);
        duk_put_prop_string(ctx, 0, "\\xff""\\xff""data");
        return 0;
    }, 1);
    duk_set_finalizer(ctx, -2);
`
    component.properties.forEach(property =>
    {
        let is_read_only = property.flags.indexOf("PROP_READ_ONLY") != -1;
        let has_cpp_getter = property.flags.indexOf("PROP_CPP_GETTER") != -1;
        let has_cpp_setter = property.flags.indexOf("PROP_CPP_SETTER") != -1;

        code += `
    // ${property.type} ${property.name}
    duk_push_string(ctx, "${property.name}");
    duk_push_c_function(ctx, [](duk_context *ctx)->duk_ret_t
    {
        duk_push_this(ctx);
        duk_get_prop_string(ctx, -1, "\\xff""\\xff""data");
        auto pComponent = (${component.className}*)duk_to_pointer(ctx, -1);
        if (pComponent)
        {
            pushJs_${property.type}(ctx, ${has_cpp_getter ? `pComponent->get_${property.name}()` : `pComponent->${property.name}`});
            return 1;
        }
        return 0;
    }, 0);
`
    if (!is_read_only) code +=
`    duk_push_c_function(ctx, [](duk_context *ctx)->duk_ret_t
    {
        duk_push_this(ctx);
        duk_get_prop_string(ctx, -1, "\\xff""\\xff""data");
        auto pComponent = (${component.className}*)duk_to_pointer(ctx, -1);
        if (pComponent)
        {
            ${has_cpp_setter ? `pComponent->set_${property.name}(getJs_${property.type}(ctx, ${property.default_value}))` : `pComponent->${property.name} = getJs_${property.type}(ctx, ${property.default_value})`};
        }
        return 0;
    }, 1);
    duk_def_prop(ctx, -4, DUK_DEFPROP_HAVE_GETTER | DUK_DEFPROP_HAVE_SETTER);
`
        else code +=
`    duk_def_prop(ctx, -3, DUK_DEFPROP_HAVE_GETTER);
`
    });

    // Finalize
    code += `
    ${component.className}::js_prototype = duk_get_heapptr(ctx, -1);
    duk_put_prop_string(ctx, -2, "prototype");

    duk_put_global_string(ctx, "${component.name}");
}
`
    ComponentBindings_cpp += code;
});

ComponentBindings_cpp += `
// Main function
void createComponentBindings()
{
`
components.forEach(component =>
{
    ComponentBindings_cpp += `    create${component.className}Bindings();
`
});
    ComponentBindings_cpp += `}
`;

fs.writeFileSync('../src/ComponentBindings.cpp', ComponentBindings_cpp.replace(/\r?\n/g, "\r\n"));
console.log(`=> ../src/ComponentBindings.cpp`);

let ComponentFactory_cpp = `// DO NOT EDIT - THIS FILE IS GENERATED

#include "ComponentFactory.h"
#include "Component.h"
#include <map>
#include <functional>
#include <onut/Log.h>

${
    components.reduce((code, component)=>
    {
        code += `#include "${component.className}.h"
`
        return code;
    }, "")
}
#include "ScriptComponent.h"

static std::map<std::string, std::function<ComponentRef()>> factories;

void initComponentFactory()
{
${
    components.reduce((code, component)=>
    {
        code += `    factories["${component.name}"] = []()->ComponentRef {return OMake<${component.className}>();};
`
        return code;
    }, "")
}
    factories["Script"] = []()->ComponentRef {return OMake<ScriptComponent>();};
}

void shutdownComponentFactory()
{
    factories.clear();
}

ComponentRef createComponentByName(const std::string& name)
{
    auto it = factories.find(name);
    if (it == factories.end())
    {
        OLogE("No Component found: " + name);
        return nullptr;
    }
    auto component = it->second();
#if !BARK_EDITOR
    component->initJSObject(component->getJSPrototype());
#endif
    return component;
}
`

fs.writeFileSync('../common/ComponentFactory.cpp', ComponentFactory_cpp.replace(/\r?\n/g, "\r\n"));
console.log(`=> ../common/ComponentFactory.cpp`);

let ComponentGetterBindings_cpp = `#include "Component.h"
#include "Entity.h"
#include <JSBindings_Macros.h>

using namespace onut::js;

void createComponentGetterBindings(duk_context* ctx)
{
#define IMPL_COMPONENT_GETTER(__prop_name__, __comp_name__) \\
    duk_push_string(ctx, #__prop_name__); \\
    duk_push_c_function(ctx, [](duk_context *ctx)->duk_ret_t \\
    { \\
        duk_push_this(ctx); \\
        duk_get_prop_string(ctx, -1, "\\xff""\\xff""data"); \\
        auto pEntity = (Entity*)duk_to_pointer(ctx, -1); \\
        if (pEntity) \\
        { \\
            auto it = pEntity->components.find(#__comp_name__); \\
            if (it == pEntity->components.end()) \\
            { \\
                OLogE("Entity has no component named: " #__comp_name__); \\
                return 0; \\
            } \\
            auto pComponent = it->second.get(); \\
            duk_push_heapptr(ctx, pComponent->js_object); \\
            return 1; \\
        } \\
        return 0; \\
    }, 0); \\
    duk_def_prop(ctx, -3, DUK_DEFPROP_HAVE_GETTER);

${
        components.reduce((output, component) =>
        {
            let nameLowerCase = component.name.charAt(0).toLowerCase() + component.name.slice(1);
            output += `    IMPL_COMPONENT_GETTER(${nameLowerCase}, ${component.name});
`
            return output;
        }, "")
    }}
`;

fs.writeFileSync('../src/ComponentGetterBindings.cpp', ComponentGetterBindings_cpp.replace(/\r?\n/g, "\r\n"));
console.log(`=> ../src/ComponentGetterBindings.cpp`);

let bark_d_ts = `// DO NOT EDIT - THIS FILE IS GENERATED

// Entity
declare class Entity {
    name: string;

    getPosition(): Vector3;
    getWorldPosition(): Vector3;
    setPosition(position: Vector3);

    getTransform(): Matrix;
    getWorldTransform(): Matrix;
    setTransform(transform: Matrix);

    getComponent(name: string): object;
    addComponent(name: string): object;
    removeComponent(name: string);
    disableComponent(name: string);
    enableComponent(name: string);

    add(child: Entity);
    insert(before: Entity, child: Entity);
    remove(child: Entity);
    removeAll();
    getChildCount(): number;
    getChild(index: number): Entity;
    getChild(name: string, deepSearch: boolean = true): UEntityI;
    getParent(): Entity;

    copy(): Entity;

    // Quick access to default components
`
components.forEach(component =>
{
    let nameLowerCase = component.name.charAt(0).toLowerCase() + component.name.slice(1);
    bark_d_ts += `    ${nameLowerCase}: ${component.name};
`
});

bark_d_ts += `}
declare function findEntity(name: string): Entity;
declare function destroyEntity(entity: Entity);

// Scene
declare function loadScene(name: string);

// Components
`

function typeToJS(type)
{
    switch (type)
    {
        case "bool": return "boolean";
        case "int": return "int";
        case "float": return "number";
        case "std_string": return "string";
        case "OTextureRef": return "Texture";
        case "OTiledMapRef": return "TiledMap";
        case "OSoundRef": return "Sound";
        case "OSpriteAnimRef": return "SpriteAnim";
        case "OModelRef": return "Model";
        case "OShaderRef": return "Shader";
        default: return type;
    }
}

components.forEach(component =>
{
    bark_d_ts += `declare class ${component.name}
{
`
    component.properties.forEach(property =>
    {
        bark_d_ts += `    ${property.name}: ${typeToJS(property.type)};
`
    });

    bark_d_ts += `}

`
})

fs.writeFileSync('../typings/bark.d.ts', bark_d_ts.replace(/\r?\n/g, "\r\n"));
console.log(`=> ../typings/bark.d.ts`);

redpajama_set_name: RedPajamaGithub


text:
#ifndef CXXBLAS_LEVEL2EXTENSIONS_SYMV_H
#define CXXBLAS_LEVEL2EXTENSIONS_SYMV_H 1

#include <cxxblas/drivers/drivers.h>
#include <cxxblas/typedefs.h>

#define HAVE_CXXBLAS_SYMV 1

namespace cxxblas {

#ifdef HAVE_CBLAS

template <typename IndexType>
    typename If<IndexType>::isBlasCompatibleInteger
    symv(StorageOrder order, StorageUpLo upLo,
         IndexType n, float alpha,
         const float *A, IndexType ldA,
         const float *x, IndexType incX,
         float beta,
         Complex<float> *y, IndexType incY);

template <typename IndexType>
    typename If<IndexType>::isBlasCompatibleInteger
    symv(StorageOrder order, StorageUpLo upLo,
         IndexType n, float alpha,
         const float *A, IndexType ldA,
         const float *x, IndexType incX,
         Complex<float> beta,
         Complex<float> *y, IndexType incY);

template <typename IndexType>
    typename If<IndexType>::isBlasCompatibleInteger
    symv(StorageOrder order, StorageUpLo upLo,
         IndexType n, float alpha,
         const float *A, IndexType ldA,
         const Complex<float> *x, IndexType incX,
         float beta,
         Complex<float> *y, IndexType incY);

template <typename IndexType>
    typename If<IndexType>::isBlasCompatibleInteger
    symv(StorageOrder order, StorageUpLo upLo,
         IndexType n, float alpha,
         const float *A, IndexType ldA,
         const Complex<float> *x, IndexType incX,
         Complex<float> beta,
         Complex<float> *y, IndexType incY);

template <typename IndexType>
    typename If<IndexType>::isBlasCompatibleInteger
    symv(StorageOrder order, StorageUpLo upLo,
         IndexType n, double alpha,
         const double *A, IndexType ldA,
         const double *x, IndexType incX,
         double beta,
         Complex<double> *y, IndexType incY);

template <typename IndexType>
    typename If<IndexType>::isBlasCompatibleInteger
    symv(StorageOrder order, StorageUpLo upLo,
         IndexType n, double alpha,
         const double *A, IndexType ldA,
         const double *x, IndexType incX,
         Complex<double> beta,
         Complex<double> *y, IndexType incY);

template <typename IndexType>
    typename If<IndexType>::isBlasCompatibleInteger
    symv(StorageOrder order, StorageUpLo upLo,
         IndexType n, double alpha,
         const double *A, IndexType ldA,
         const Complex<double> *x, IndexType incX,
         double beta,
         Complex<double> *y, IndexType incY);

template <typename IndexType>
    typename If<IndexType>::isBlasCompatibleInteger
    symv(StorageOrder order, StorageUpLo upLo,
         IndexType n, double alpha,
         const double *A, IndexType ldA,
         const Complex<double> *x, IndexType incX,
         Complex<double> beta,
         Complex<double> *y, IndexType incY);

#endif // HAVE_CBLAS

} // namespace cxxblas

#endif // CXXBLAS_LEVEL2EXTENSIONS_SYMV_H


text:
package com.jimandreas.aarch.popm.vo;

/**
 * Status of a resource that is provided to the UI.
 * <p>
 * These are usually created by the Repository classes where they return
 * {@code LiveData<Resource<T>>} to pass back the latest data to the UI with its fetch status.
 */
public enum Status {
    SUCCESS,
    ERROR,
    LOADING
}


text:
class Mockserver < Formula
  desc "Mock HTTP server and proxy"
  homepage "https://www.mock-server.com/"
  url "https://search.maven.org/remotecontent?filepath=org/mock-server/mockserver-netty/5.14.0/mockserver-netty-5.14.0-brew-tar.tar"
  sha256 "235ebe34e9317de685693bcffe57df7144cc102952a4267e6dfa9548063a1268"
  license "Apache-2.0"

  livecheck do
    url "https://search.maven.org/remotecontent?filepath=org/mock-server/mockserver-netty/maven-metadata.xml"
    regex(%r{<version>v?(\d+(?:\.\d+)+)</version>}i)
  end

  bottle do
    sha256 cellar: :any_skip_relocation, all: "b1ac4dd7b832de2a5afdb8536eaf6ec503a3a16b5c0f73dddb07b30d2febeb75"
  end

  depends_on "openjdk"

  def install
    inreplace "bin/run_mockserver.sh", "/usr/local", HOMEBREW_PREFIX
    libexec.install Dir["*"]
    (bin/"mockserver").write_env_script libexec/"bin/run_mockserver.sh", JAVA_HOME: Formula["openjdk"].opt_prefix

    lib.install_symlink "#{libexec}/lib" => "mockserver"

    mockserver_log = var/"log/mockserver"
    mockserver_log.mkpath

    libexec.install_symlink mockserver_log => "log"
  end

  test do
    port = free_port

    mockserver = fork do
      exec "#{bin}/mockserver", "-serverPort", port.to_s
    end

    loop do
      Utils.popen_read("curl", "-s", "http://localhost:#{port}/status", "-X", "PUT")
      break if $CHILD_STATUS.exitstatus.zero?
    end

    system "curl", "-s", "http://localhost:#{port}/stop", "-X", "PUT"

    Process.wait(mockserver)
  end
end


text:
<?php

namespace Tests\Unit\Meetup\Domain\Model\Util;

use Meetup\Model\Description;
use Meetup\Model\Meetup;
use Meetup\Model\MeetupId;
use Meetup\Model\Name;

class MeetupFactory
{
    public static function pastMeetup()
    {
        return Meetup::schedule(
            MeetupId::fromString('some id'),
            Name::fromString('Name'),
            Description::fromString('Description'),
            new \DateTimeImmutable('-5 days')
        );
    }

    public static function upcomingMeetup(MeetupId $meetupId = null)
    {
        return Meetup::schedule(
            $meetupId ?: MeetupId::fromString('some id'),
            Name::fromString('Name'),
            Description::fromString('Description'),
            new \DateTimeImmutable('+5 days')
        );
    }

    public static function someMeetup(MeetupId $meetupId = null)
    {
        return self::upcomingMeetup($meetupId);
    }

    public static function someMeetupWithId(MeetupId $meetupId)
    {
        return self::someMeetup($meetupId);
    }
}


text:
package fisica;

import processing.core.*;

import java.util.ArrayList;

import org.jbox2d.common.*;
import org.jbox2d.collision.*;
import org.jbox2d.collision.shapes.*;
import org.jbox2d.dynamics.*;
import org.jbox2d.dynamics.joints.*;

/**
 * Represents constant volume joint that tries to keep the volume enclosed by a group of bodies constant.  This joint is similar to connecting multiple springs between the bodies in order to maintain the volume inside their position constant. This is the joint used to create the {@link FBlob} body.
 *
 */
public class FConstantVolumeJoint extends FJoint {
  protected ArrayList m_bodies;
  protected float m_damping = 0.0f;
  protected float m_frequency = 0.0f;

  protected JointDef getJointDef(FWorld world) {
    ConstantVolumeJointDef md = new ConstantVolumeJointDef();
    md.frequencyHz = m_frequency;
    md.dampingRatio = m_damping;

    for (int i=0; i<m_bodies.size(); i++) {
      Body b = ((FBody)m_bodies.get(i)).m_body;
      if (b != null) {
        md.addBody(b);
      }
    }

    return md;
  }

  /**
   * Constructs an constant volume joint.  It creates an empty joint, before adding the joint to the world use {@link #addBody(FBody) addBody} to add bodies to the joint and to define the initial and target volume of the joint.
   */
  public FConstantVolumeJoint() {
    super();

    m_bodies = new ArrayList();
  }

  /**
   * Adds a body to the joint.  This method must be called before adding the joint to the world.
   *
   * @param b  body to be added
   */
  public void addBody(FBody b) {
    m_bodies.add(b);
  }

  /**
   * Return the group of bodies that are connected by this joint.
   *
   * @return   list of bodies (ArrayList of FBody) connected by the joint
   *
   */
  public ArrayList getBodies() {
    return m_bodies;
  }

  /**
   * Sets the damping of the springs used to maintain the volume defined by the vertices constant.  This method must be called before adding the joint to the world.
   *
   * @param damping  the damping of the springs of the constant volume joint
   */
  public void setDamping(float damping) {
    m_damping = damping;
  }

  /**
   * Sets the frequency of the springs used to maintain the volume defined by the vertices constant.  This method must be called before adding the joint to the world.
   *
   * @param frequency  the frequency of the springs of the constant volume joint
   */
  public void setFrequency(float frequency) {
    m_frequency = frequency;
  }

  public PVector getCentroid() {
    PVector centroid = new PVector(0, 0);
    float signedArea = 0.0f;
    float x0 = 0.0f; // Current vertex X
    float y0 = 0.0f; // Current vertex Y
    float x1 = 0.0f; // Next vertex X
    float y1 = 0.0f; // Next vertex Y
    float a = 0.0f;  // Partial signed area

    // For all vertices except last
    int i;
    for (i=0; i<m_bodies.size()-1; ++i)
    {
        x0 = ((FBody)m_bodies.get(i)).getX();
        y0 = ((FBody)m_bodies.get(i)).getY();
        x1 = ((FBody)m_bodies.get(i+1)).getX();
        y1 = ((FBody)m_bodies.get(i+1)).getY();
        a = x0*y1 - x1*y0;
        signedArea += a;
        centroid.x += (x0 + x1)*a;
        centroid.y += (y0 + y1)*a;
    }

    // Do last vertex
    x0 = ((FBody)m_bodies.get(i)).getX();
    y0 = ((FBody)m_bodies.get(i)).getY();
    x1 = ((FBody)m_bodies.get(0)).getX();
    y1 = ((FBody)m_bodies.get(0)).getY();
    a = x0*y1 - x1*y0;
    signedArea += a;
    centroid.x += (x0 + x1)*a;
    centroid.y += (y0 + y1)*a;

    signedArea *= 0.5;
    centroid.x /= (6.0*signedArea);
    centroid.y /= (6.0*signedArea);

    return centroid;
  }

  public void draw(PGraphics applet){
    preDraw(applet);

    if (m_image != null ) {
      applet.pushMatrix();
      PVector c = getCentroid();
      applet.translate(c.x, c.y);
      drawImage(applet);
      applet.popMatrix();
    } else {
      if (m_bodies.size()>0) {
        applet.beginShape();
        for (int i=0; i<m_bodies.size(); i++) {
          applet.vertex(((FBody)m_bodies.get(i)).getX(), ((FBody)m_bodies.get(i)).getY());
        }
        applet.endShape(applet.CLOSE);
      }
    }

    postDraw(applet);
  }

  public void drawDebug(PGraphics applet){
    preDrawDebug(applet);

    if (m_bodies.size()>0) {
      applet.beginShape();
      for (int i=0; i<m_bodies.size(); i++) {
        applet.vertex(((FBody)m_bodies.get(i)).getX(), ((FBody)m_bodies.get(i)).getY());
      }
      applet.endShape(applet.CLOSE);

      for (int i=0; i<m_bodies.size(); i++) {
        applet.ellipse(((FBody)m_bodies.get(i)).getX(), ((FBody)m_bodies.get(i)).getY(), 5, 5);
      }
    }

    postDrawDebug(applet);
  }
}


text:
<?xml version="1.0"?>
<project
   xmlns="http://maven.apache.org/POM/4.0.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>org.picketlink.certmgmt</groupId>
      <artifactId>picketlink-certmgmt-parent</artifactId>
      <version>1.0.0-SNAPSHOT</version>
      <relativePath>../pom.xml</relativePath>
   </parent>
   <artifactId>picketlink-cert-mgmt-ear</artifactId>
   <packaging>ear</packaging>
   <name>picketlink-cert-mgmt EAR</name>
   <description>picketlink-cert-mgmt EAR includes: picketlink-certmgmt-www and picketlink-certmgmt-server - EAR</description>
   <licenses>
      <license>
         <name>Apache License, Version 2.0</name>
         <distribution>repo</distribution>
         <url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
      </license>
   </licenses>
   <properties>
       <!-- JBoss dependency versions -->
       <version.jboss.maven.plugin>7.4.Final</version.jboss.maven.plugin>
   </properties>
   <dependencies>
      <dependency>
         <groupId>org.picketlink.certmgmt</groupId>
         <artifactId>picketlink-certmgmt-server</artifactId>
         <version>1.0.0-SNAPSHOT</version>
         <type>war</type>
         <scope>provided</scope>
      </dependency>
      <dependency>
         <groupId>org.picketlink.certmgmt</groupId>
         <artifactId>picketlink-certmgmt-www</artifactId>
         <version>1.0.0-SNAPSHOT</version>
         <type>war</type>
         <scope>provided</scope>
      </dependency>
   </dependencies>
   <build>
      <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-ear-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
               <finalName>picketlink-cert-mgmt</finalName>
               <defaultJavaBundleDir>lib/</defaultJavaBundleDir>
               <modules>
                  <webModule>
                     <groupId>org.picketlink.certmgmt</groupId>
                     <artifactId>picketlink-certmgmt-server</artifactId>
                  </webModule>
                  <webModule>
                     <groupId>org.picketlink.certmgmt</groupId>
                     <artifactId>picketlink-certmgmt-www</artifactId>
                     <contextRoot>/picketlink-certmgmt</contextRoot>
                  </webModule>
               </modules>
            </configuration>
         </plugin>
         <plugin>
            <groupId>org.jboss.as.plugins</groupId>
            <artifactId>jboss-as-maven-plugin</artifactId>
            <version>${version.jboss.maven.plugin}</version>
            <configuration>
               <filename>picketlink-cert-mgmt.ear</filename>
               <skip>false</skip>
            </configuration>
            <executions>
               <execution>
                  <phase>install</phase>
                  <goals>
                     <goal>deploy</goal>
                  </goals>
               </execution>
            </executions>
         </plugin>
         <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.1</version>
            <configuration>
               <source>1.6</source>
               <target>1.6</target>
            </configuration>
         </plugin>
      </plugins>
   </build>
</project>


text:
package apolo.data.repository;

import apolo.data.enums.UserStatus;
import apolo.data.model.Tenant;
import apolo.data.model.User;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface UserRepository extends JpaRepository<User, Long> {

	User findUserByEmail(String email);

	User findUserByTenantAndEmail(Tenant tenant, String email);

	Page<User> findByTenantAndStatusNotOrderByNameAsc(
			@Param("tenant") Tenant tenant,
			@Param("status") UserStatus status,
			Pageable page
	);

	@Query("select u from User u where u.tenant = ?1 and (u.name like ?2 or u.email like ?3) order by name asc)")
	Page<User> findByTenantAndNameLikeOrEmailLikeOrderByNameAsc(
			Tenant tenant,
			String name,
			String email,
			Pageable page
	);

	Page<User> findByTenantAndNameLikeOrEmailLikeAndStatusOrderByNameAsc(
			@Param("tenant") Tenant tenant,
			@Param("name") String name,
			@Param("email") String email,
			@Param("status") UserStatus status,
			Pageable page
	);

	Page<User> findByTenantAndNameLikeOrEmailLikeAndStatusNotOrderByNameAsc(
			@Param("tenant") Tenant tenant,
			@Param("name") String name,
			@Param("email") String email,
			@Param("status") UserStatus status,
			Pageable page
	);

	Page<User> findByTenantAndStatus(
			Tenant tenant,
			UserStatus status,
			Pageable page
	);

	Page<User> findByStatusNot(
			UserStatus status,
			Pageable page
	);

	Page<User> findAll(
			Pageable page
	);

	List<User> findByStatus(UserStatus status);

	User findByEmailAndPassword(String email, String password);

	List<User> findByEmail(String email);

	User findByResetPasswordToken(String token);

	User findByTokenAndSessionId(String token, String sessionId);

	User findByTenantAndId(Tenant tenant, Long id);

	long count();

	long countByTenant(Tenant tenant);

}


text:
There are four main _operations_ in `libelektra-kdb`: `open`, `get`, `set` and `close`.
For each of these there is a `kdb*` function the user calls to trigger the operation and plugins export a function for each of the operations they support (at least `get`).

Additionally, plugins may implement `commit` and `error`.
These are part of the `set` operation and there is no corresponding `kdbCommit` or `kdbError` function available in `libelektra-kdb`.

The operations `get` and `set` also have different _phases_:

- The `get` operation has: `init`, `resolver`, `cachecheck`, `prestorage`, `storage` and `poststorage`.
- The `set` operation has: `resolver`, `prestorage`, `storage` and `poststorage` followed by `precommit`, `commit` and `postcommit` if the previous phases where successful or by `prerollback`, `rollback` and `postrollback` if the previous phases failed.

These phases are implemented by a backend plugin.
Read the [Documentation on Backend Plugins](./backend-plugins.md) for more information on what backend plugins do.

> **Note** The steps of the operations described below, are referenced in the source code with `// Step X` comments.

## `open` Operation

The `open` operation implemented in `kdbOpen` is the first thing that happens to all `KDB` instances.

The basic flow of this operation is:

1. Create empty `KDB` instance
2. Configure `KDB` instance for bootstrap
3. Run bootstrap `get` operation:
   This loads the contents of `system:/elektra/mountpoints` so that the mountpoints can be configured.
4. Process contract and set up plugins for hooks (see [Hooks](hooks.md))
5. Parse mountpoints:
   This transforms the contents of `system:/elektra/mountpoints` into the internal state stored in a `KDB` instance.
6. Reconfigure `KDB` with real mountpoints:
   This switches the `KDB` instance from bootstrap mode to use the real mountpoint state created above.
7. Add hard coded mountpoints to `KDB` instance:
   There are a few hard coded mountpoints (root mountpoints, `system:/elektra/modules`, `system:/elektra/version`, etc.) that are always present.
   They are added in this step.

Namespaces in mountpoint configs:

- `dir:/`, `user:/` and `system:/` mountpoints can be created without restrictions, except for the reserved sections listed below.
- `spec:/` mountpoints can be created with the same restrictions, but they are also treated specially during `get` and `set`.
- `proc:/` mountpoints are always read-only and receive special treatment during `get`
- `default:/` mountpoints are read-only and receive special treatment during `get`, specifically they only go through the `poststorage` phase
- mountpoints in all other namespaces are entirely illegal

> **Note** The special treatments of the various namespaces are explained below in the sections for the `get` and `set` operation.

Reserved sections:

- Creating a mountpoint for `/elektra` or below in _any namespace_ is forbidden.
  This section of the KDB is reserved for Elektra's own config.
- `system:/elektra/mountpoints`, `user:/elektra/mountpoints` and `dir:/elektra/mountpoints` are all required for the bootstrap process and use a hard coded backend.
  The backends are implemented by a standard file-based backend plugin that is defined at compile-time of `libelektra-kdb`.
- `system:/elektra/version` and `system:/elektra/modules` will always use hard coded read-only backends containing information about this Elektra installation.
  The backends are implemented by special purpose backend plugins.

## `get` Operation

The purpose of the `get` operation is to read data stored in backends into a `KDB` instance.

> **Note:** Some details of a `get` operation are defined in the [contract with backend plugins](./backend-plugins.md).

Properties of `kdbGet()`:

- After calling `kdbGet (kdb, ks, parentKey)`, the KeySet `ks` will contain _all keys_ (including their values) that are stored in _any backend_ with a mountpoint that is _below `parentKey`_.
- After calling `kdbGet (kdb, ks, parentKey)`, below `parentKey` the KeySet `ks` will _mostly_ contain keys that are stored in a backend.
  The exception here are `proc:/` and `spec:/` keys.
  For other namespaces, all keys below `parentKey` will be removed from `ks`.
  For `proc:/` and `spec:/` only keys that overlap with a backend that was loaded will be removed from `ks`.
- The KeySet `ks` _may_ contain other keys not below `parentKey`:
  1. Keys that are not below `parentKey`, but are stored in a backend that contains other keys which are below `parentKey`.
     These keys are returned, because backends are treated as one atomic unit.
     Either all keys within a backend are read, or none of them are.
  2. Keys that were already present in `ks` when `kdbGet()` was called and do not conflict with the goal of representing the current state of the KDB below `parentKey`.
- After calling `kdbGet (kdb, ks, parentKey)`, the Key `parentKey` will only have the `meta:/error/*` or `meta:/warnings/#/*` metakeys, if the errors/warnings originate from this `kdbGet()` call.
  In other words, `kdbGet ()` first clears any existing errors/warnings and only then starts doing the actual work.
- It is an error to use a `parentKey` with a namespace other than: `default:/`, `proc:/`, `spec:`, `dir:/`, `user:/`, `system:/` or cascading

To the caller it looks as if `kdbGet()` had removed all keys below `parentKey`, as well as some others, from `ks` and then loaded the data from the backends.
Which backends are actually read is an implementation detail.
Which keys are removed from `ks` depends on the backends that are read.

`kdbGet()` will always try to be efficient in achieving its goal of reading the keys below `parentKey`.
It is only guaranteed that below `parentKey` the KeySet `ks` correctly represents the state of the KDB.
For the rest of `ks` there are no such guarantees.

> **Note:** In the list below "phase" always refers to a phase of the `get` operation as described in [the backend plugin contract](backend-plugins.md).

The flow of this operation is:

1. Determine the backends needed to read all keys below `parentKey`
2. Run the `open` operation for all required backends that haven't been opened
3. Run the `init` phase on all the backends that haven't been initialized
4. Run the `resolver` phase on all backends
5. From now on ignore all backends, which indicated that there is no update.
6. If all backends are now ignored, **return**.
7. If a global cache plugin is enabled:
   Ask the global cache plugin for the cache handles (normally modification times) for all backends.
8. If all backends have an existing cache entry:
   Run the `cachecheck` phase on all backends
9. If all backends indicated the cache is still valid:
   Ask the global cache plugin for the cached data and **return**.
10. Run the `prestorage` and `storage` phase on all backends.
11. Run the `poststorage` phase of all `spec:/` backends.
12. Merge the data from all backends
13. If enabled, run the `gopts/get` hook.
14. Run the `spec/copy` hook.
15. Split data back into individual backends.
16. Run the `poststorage` phase for all non-`spec:/` backends.
17. Remove all keys which are below the parent key of any backend that has been read from `ks`.
18. Merge the data from all backends into `ks`.
19. If a global cache plugin is enabled, update cache.
20. Run the `notification/send` hook.
    Then **return**.

> **Note:** In case of error, we abort immediately, restore `ks` to its original state and return.

Influence of namespaces:

- `spec:/` backends go through `init`, `resolver`, `cache`, `presetstorage` and `storage` phases as normal, but their `poststorage` phase is called earlier.
  This is required, because any validation and post-processing of `spec:/` keys needs to happen, before they are used as the specification for other keys in the actual `poststorage` phase.
- `dir:/`, `user:/` and `system:/` go through all phases as described above.
- `proc:/` mountpoints go through all the phases as described above, but they are not stored in the cache.
- `default:/` backends only go through the `poststorage` phase.
  This is because `default:/` keys are generated from the specification (stored as `spec:/` keys).
  Therefore, no `default:/` keys can exist before the specification is processed by the `spec/copy` hook.
- keys with other namespaces are always illegal in `ks`

## `set` Operation

The purpose of the `set` operation is to write data from a `KDB` instance into backends.

> **Note:** Some details of a `set` operation are defined in the [contract with backend plugins](./backend-plugins.md).

Properties of `kdbSet()`:

- When calling `kdbSet (kdb, ks, parentKey)` the contents (key names, values and metadata) of `ks` will _mostly_ not be modified.
  The only modifications that are made to `ks` are those that originate from the `spec/copy` hook.
- _All keys_ in `ks` that are below `parentKey` will be persisted in the KDB, when a `kdbSet (kdb, ks, parentKey)` call returns successfully.
  Additionally, any key in `ks` that shares a backend with another key which is below `parentKey` will also be persisted.
- Calling `kdbSet` may result in an error, if `kdbGet` wasn't called on this `KDB` instance with the same `parentKey` at least once.
- After calling `kdbSet (kdb, ks, parentKey)`, the Key `parentKey` will only have the `meta:/error/*` or `meta:/warnings/#/*` metakeys, if the errors/warnings originate from this `kdbSet()` call.
  In other words, `kdbSet ()` first clears any existing errors/warnings and only then starts doing the actual work.
- It is an error to use a `parentKey` with a namespace other than: `default:/`, `proc:/`, `spec:`, `dir:/`, `user:/`, `system:/` or cascading

The flow of this operation is:

1. Determine the backends needed to write all keys below `parentKey`.
2. Check that all backends are opened and initialized (i.e. `kdbGet()` was called).
3. Run the `spec/copy` hook on `ks` (to add metakeys to newly created keys).
4. Deep-Copy `ks` (below `parentKey`) into a new KeySet `set_ks`
5. Split `set_ks` into individual backends
6. Determine which backends contain changed data.
   Any backend that contains a key that needs sync (via `KEY_FLAG_SYNC`) could contain changed data.
   From now on ignore all backends that have not changed.
   From now on also ignore all backends that were initialized as read-only.
   Issue a warning, if a change was detected (via `KEY_FLAG_SYNC`) in a read-only backend.
   > **Note**: Steps 4-6 might be combined into a single procedure that deep-copies only keys from changed backends into separate KeySets per backend
7. Run the `resolver` and `prestorage` on all backends (abort immediately on error and go to e).
8. Merge the results into a new version of `set_ks`.
9. Run the `spec/remove` hook on `set_ks` (to remove copied metakeys).
10. Split `set_ks` into individual backends again.
11. Run the `storage` and `poststorage` phases on all backends (abort immediately on error and go to e).
12. If everything was successful:
    Run the `precommit` and `commit` phases on all backends (abort immediately on error and go to e), then run the `postcommit` phase on all backends (record all errors as warnings and ignore them) and **return**.

 If there was an error:
    Run the prerollback, rollback and postrollback phases on all backends and return.

Influence of namespaces:

- `default:/` and `proc:/` keys are completely ignored by `kdbSet()`
- `spec:/`, `dir:/`, `user:/` and `system:/` go through all phases as described above.
- keys with other namespaces are always illegal in `ks`

## `close` Operation

The `close` operation is very simple.
It simply frees up all resources used by a `KDB` instance.


text:
package org.apache.maven.lifecycle.internal;

import java.util.List;

import org.apache.maven.lifecycle.MavenExecutionPlan;
import org.apache.maven.lifecycle.internal.stub.LifecycleExecutionPlanCalculatorStub;
import org.apache.maven.lifecycle.internal.stub.ProjectDependencyGraphStub;
import org.apache.maven.plugin.MojoExecution;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
 * @author Kristian Rosenvold
 */
public class PhaseRecorderTest
{
    @Test
    public void testObserveExecution() throws Exception {
        PhaseRecorder phaseRecorder = new PhaseRecorder( ProjectDependencyGraphStub.A);
        MavenExecutionPlan plan = LifecycleExecutionPlanCalculatorStub.getProjectAExecutionPlan();
        final List<MojoExecution> executions = plan.getMojoExecutions();

        final MojoExecution mojoExecution1 = executions.get( 0 );
        final MojoExecution mojoExecution2 = executions.get( 1 );
        phaseRecorder.observeExecution( mojoExecution1 );

        assertTrue( ProjectDependencyGraphStub.A.hasLifecyclePhase( mojoExecution1.getLifecyclePhase() ));
        assertFalse( ProjectDependencyGraphStub.A.hasLifecyclePhase( mojoExecution2.getLifecyclePhase() ));

        assertFalse( phaseRecorder.isDifferentPhase( mojoExecution1));
        assertTrue( phaseRecorder.isDifferentPhase( mojoExecution2));

    }

}


text:
package org.jbpm.formModeler.core.xml.util;

import java.io.IOException;
import java.io.Serializable;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.xerces.util.XMLChar;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 */
public class XMLNode implements Serializable {

    private String objectName;

    private Properties attributes = new Properties();
    private List<XMLNode> children = new ArrayList<XMLNode>();
    private byte[] content;
    private List warnings = new ArrayList();
    private List warningArguments = new ArrayList();
    private XMLNode parent;

    private static final String INDENT_STR = "    ";

    public XMLNode(String objectName, XMLNode parent) {
        this.parent = parent;
        this.objectName = objectName;
    }

    public String getObjectName() {
        return objectName;
    }

    public Properties getAttributes() {
        return attributes;
    }

    public List<XMLNode> getChildren() {
        return children;
    }

    public List getWarnings() {
        return warnings;
    }

    public List getWarningArguments() {
        return warningArguments;
    }

    public XMLNode getParent() {
        return parent;
    }

    public Object addAttribute(String name, String value) {
        if (name != null) {
            if (value == null) {
                return attributes.remove(name);
            }
            return attributes.setProperty(name, value);
        }
        return null;
    }

    public void addChild(XMLNode node) {
        children.add(node);
    }

    public void addWarning(String warning, Object[] arguments) {
        warnings.add(warning);
        warningArguments.add(arguments);
    }

    public void addWarning(String warning, Object arguments) {
        warnings.add(warning);
        warningArguments.add(new Object[]{arguments});
    }

    public byte[] getContent() {
        return content;
    }

    public void setContent(byte[] content) {
        this.content = content;
    }

    public void writeXML(Writer writer, boolean blanks) throws IOException {
        writeXML(writer, blanks, false);
    }

    public void writeXML(Writer writer, boolean blanks, boolean indent) throws IOException {

        String indentStr = null;
        if (blanks) {
            writer.write("\n");
            if (indent) {
                indentStr = indentStr(indent());
                writer.write(indentStr);
            }
        }
        writer.write("<");
        writer.write(objectName);
        for (Iterator it = attributes.keySet().iterator(); it.hasNext();) {
            String attributeName = (String) it.next();
            String attributeValue = attributes.getProperty(attributeName, "");
            writer.write(" " + attributeName + "=\"" + escapeXml(attributeValue) + "\"");
        }
        if (children.isEmpty() && content == null) {
            writer.write("/>");
        } else {
            writer.write(">");
            for (int i = 0; i < children.size(); i++) {
                XMLNode child = children.get(i);
                child.writeXML(writer, blanks, indent);
            }
            if (content != null) {
                writer.write(Base64.encode(content));
            } else {
                if (blanks) {
                    writer.write("\n");
                    if (indent) writer.write(indentStr);
                }
            }
            writer.write("</");
            writer.write(objectName);
            writer.write(">");
        }
        writer.flush();
    }

    public void loadFromXMLNode(Node node) {
        objectName = node.getNodeName();
        NamedNodeMap attributesMap = node.getAttributes();
        if (attributesMap != null)
            for (int i = 0; i < attributesMap.getLength(); i++) {
                Node attribute = attributesMap.item(i);
                addAttribute(attribute.getNodeName(), StringEscapeUtils.unescapeXml(attribute.getNodeValue()));
            }
        NodeList children = node.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if (child.getNodeName().equals("#text")) {
                String content = child.getNodeValue();
                if (content != null && content.trim().length() > 0)
                    setContent(Base64.decode(child.getNodeValue().trim()));
            } else {
                XMLNode childNode = new XMLNode("?", this);
                childNode.loadFromXMLNode(child);
                addChild(childNode);
            }
        }
    }

    public int indent() {
        if (getParent() != null) {
            return 1 + getParent().indent();
        }
        return 0;
    }

    public static String escapeXml(String s) {
        s = StringEscapeUtils.escapeXml(s);
        StringBuffer dest = new StringBuffer();
        char c;
        for (int i = 0; i < s.length(); i++) {
            c = s.charAt(i);
            if (XMLChar.isValid(c)) {
                dest.append(c);
            }
        }
        return dest.toString();
    }

    public String indentStr(int indent) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("");
        for (int i = 0; i < indent ; i++) {
            stringBuffer.append(INDENT_STR);
        }
        return stringBuffer.toString();
    }

}


text:
#include <fstream>
#include <thread>
#include <mutex>
#include <iomanip>
#include <ncurses.h>

#include "util/accelergy_interface.hpp"

#include "applications/mapper/mapper.hpp"

//--------------------------------------------//
//                Application                 //
//--------------------------------------------//

template <class Archive>
void Application::serialize(Archive& ar, const unsigned int version)
{
  if(version == 0)
  {
    ar& BOOST_SERIALIZATION_NVP(workload_);
  }
}

Application::Application(config::CompoundConfig* config,
                         std::string output_dir,
                         std::string name) :
    name_(name)
{
  auto rootNode = config->getRoot();

  // Problem configuration.
  auto problem = rootNode.lookup("problem");
  problem::ParseWorkload(problem, workload_);
  std::cout << "Problem configuration complete." << std::endl;

  // Mapper (this application) configuration.
  auto mapper = rootNode.lookup("mapper");
  std::string semi_qualified_prefix = name;
  mapper.lookupValue("out_prefix", semi_qualified_prefix);
  out_prefix_ = output_dir + "/" + semi_qualified_prefix;

  // Architecture configuration.
  config::CompoundConfigNode arch;
  if (rootNode.exists("arch"))
  {
    arch = rootNode.lookup("arch");
  }
  else if (rootNode.exists("architecture"))
  {
    arch = rootNode.lookup("architecture");
  }

  bool is_sparse_topology = rootNode.exists("sparse_optimizations");
  arch_specs_ = model::Engine::ParseSpecs(arch, is_sparse_topology);

  if (rootNode.exists("ERT"))
  {
    auto ert = rootNode.lookup("ERT");
    std::cout << "Found Accelergy ERT (energy reference table), replacing internal energy model." << std::endl;
    arch_specs_.topology.ParseAccelergyERT(ert);
    if (rootNode.exists("ART")){ // Nellie: well, if the users have the version of Accelergy that generates ART
      auto art = rootNode.lookup("ART");
      std::cout << "Found Accelergy ART (area reference table), replacing internal area model." << std::endl;
      arch_specs_.topology.ParseAccelergyART(art);
    }
  }
  else
  {
#ifdef USE_ACCELERGY
    // Call accelergy ERT with all input files
    if (arch.exists("subtree") || arch.exists("local"))
    {
      accelergy::invokeAccelergy(config->inFiles, semi_qualified_prefix, output_dir);
      std::string ertPath = out_prefix_ + ".ERT.yaml";
      auto ertConfig = new config::CompoundConfig(ertPath.c_str());
      auto ert = ertConfig->getRoot().lookup("ERT");
      std::cout << "Generate Accelergy ERT (energy reference table) to replace internal energy model." << std::endl;
      arch_specs_.topology.ParseAccelergyERT(ert);

      std::string artPath = out_prefix_ + ".ART.yaml";
      auto artConfig = new config::CompoundConfig(artPath.c_str());
      auto art = artConfig->getRoot().lookup("ART");
      std::cout << "Generate Accelergy ART (area reference table) to replace internal area model." << std::endl;
      arch_specs_.topology.ParseAccelergyART(art);
    }
#endif
  }

  std::cout << "Architecture configuration complete." << std::endl;

  // Sparse optimizations
  config::CompoundConfigNode sparse_optimizations;
  if (is_sparse_topology)
    sparse_optimizations = rootNode.lookup("sparse_optimizations");

  sparse_optimizations_ = new sparse::SparseOptimizationInfo(sparse::ParseAndConstruct(sparse_optimizations, arch_specs_));
  // characterize workload on whether it has metadata
  workload_.SetDefaultDenseTensorFlag(sparse_optimizations_->compression_info.all_ranks_default_dense);

  std::cout << "Sparse optimization configuration complete." << std::endl;

  // Mapper (this application) configuration. (the rest)

  num_threads_ = std::thread::hardware_concurrency();
  if (mapper.lookupValue("num-threads", num_threads_))
  {
    std::cout << "Using threads = " << num_threads_ << std::endl;
  }
  else
  {
    std::cout << "Using all available hardware threads = " << num_threads_ << std::endl;
  }

  std::string metric;
  std::vector<std::string> raw_metrics;
  if (mapper.lookupValue("optimization-metric", metric))
  {
    raw_metrics = { metric };
  }
  else if (mapper.exists("optimization-metrics"))
  {
    mapper.lookupArrayValue("optimization-metrics", raw_metrics);
  }
  else
  {
    std::cerr << "WARNING: no optimization metric(s) specified, using edp as default." << std::endl;
    raw_metrics = { "edp" };
  }

  for (auto& metric: raw_metrics)
  {
    // Special-case: if any metric is "ordered-accesses" expand it into a list
    // of "access-X" strings.
    if (metric == "ordered-accesses")
    {
      auto num_levels = arch_specs_.topology.NumStorageLevels();
      for (unsigned i = num_levels-1; i < num_levels; i--)
      {
        optimization_metrics_.push_back(std::string("accesses-") + std::to_string(i));
      }
    }
    else
    {
      optimization_metrics_.push_back(metric);
    }
  }

  // Search size (divide between threads).
  std::uint32_t search_size = 0;
  mapper.lookupValue("search-size", search_size);
  mapper.lookupValue("search_size", search_size); // backwards compatibility.
  if (search_size > 0)
    search_size = 1 + (search_size - 1) / num_threads_;
  search_size_ = static_cast<uint128_t>(search_size);

  // Number of consecutive invalid mappings to trigger termination.
  timeout_ = 1000;
  mapper.lookupValue("timeout", timeout_);
  mapper.lookupValue("heartbeat", timeout_); // backwards compatibility.

  // Number of suboptimal valid mappings to trigger victory
  // (do NOT divide between threads).
  victory_condition_ = 500;
  mapper.lookupValue("victory-condition", victory_condition_);

  // Inter-thread sync interval.
  std::uint32_t sync_interval = 0;
  mapper.lookupValue("sync-interval", sync_interval);
  sync_interval_ = static_cast<uint128_t>(sync_interval);

  // Misc.
  log_stats_ = false;
  mapper.lookupValue("log-stats", log_stats_);

  log_suboptimal_ = false;
  mapper.lookupValue("log-suboptimal", log_suboptimal_);
  mapper.lookupValue("log-all", log_suboptimal_); // backwards compatibility.

  live_status_ = false;
  mapper.lookupValue("live-status", live_status_);

  diagnostics_on_ = false;
  mapper.lookupValue("diagnostics", diagnostics_on_);

  penalize_consecutive_bypass_fails_ = false;
  mapper.lookupValue("penalize-consecutive-bypass-fails", penalize_consecutive_bypass_fails_);

  emit_whoop_nest_ = false;
  mapper.lookupValue("emit-whoop-nest", emit_whoop_nest_);

  std::cout << "Mapper configuration complete." << std::endl;

  // MapSpace configuration.
  config::CompoundConfigNode arch_constraints;
  config::CompoundConfigNode mapspace;

  // Architecture constraints.
  if (arch.exists("constraints"))
    arch_constraints = arch.lookup("constraints");
  else if (rootNode.exists("arch_constraints"))
    arch_constraints = rootNode.lookup("arch_constraints");
  else if (rootNode.exists("architecture_constraints"))
    arch_constraints = rootNode.lookup("architecture_constraints");

  // Mapspace constraints.
  if (rootNode.exists("mapspace"))
    mapspace = rootNode.lookup("mapspace");
  else if (rootNode.exists("mapspace_constraints"))
    mapspace = rootNode.lookup("mapspace_constraints");
  // else
  // {
  //   std::cerr << "ERROR: found neither \"mapspace\" nor \"mapspace_constraints\" "
  //             << "directive. To run the mapper without any constraints set "
  //             << "mapspace_constraints as an empty list []." << std::endl;
  //   exit(1);
  // }

  bool filter_spatial_fanout = sparse_optimizations_->action_spatial_skipping_info.size() == 0;
  mapspace_ = mapspace::ParseAndConstruct(mapspace, arch_constraints, arch_specs_, workload_, filter_spatial_fanout);
  split_mapspaces_ = mapspace_->Split(num_threads_);

  std::cout << "Mapspace construction complete." << std::endl;

  // Search configuration.
  auto search = rootNode.lookup("mapper");
  for (unsigned t = 0; t < num_threads_; t++)
  {
    search_.push_back(search::ParseAndConstruct(search, split_mapspaces_.at(t), t));
  }
  std::cout << "Search configuration complete." << std::endl;
  // Store the complete configuration in a string.
  if (config->hasLConfig())
  {
    std::size_t len;
    FILE* cfg_stream = open_memstream(&cfg_string_, &len);
    auto& lconfig = config->getLConfig();
    lconfig.write(cfg_stream);
    fclose(cfg_stream);
  }
  else
  {
    cfg_string_ = nullptr;
  }

}

Application::~Application()
{
  if (mapspace_)
  {
    delete mapspace_;
  }

  if (sparse_optimizations_)
  {
    delete sparse_optimizations_;
  }

  for (auto& search: search_)
  {
    if (search)
    {
      delete search;
    }
  }
}

EvaluationResult Application::GetGlobalBest()
{
  return global_best_;
}

// ---------------
// Run the mapper.
// ---------------
void Application::Run()
{
  // Output file names.
  std::string log_file_name = out_prefix_ + ".log";
  std::string stats_file_name = out_prefix_ + ".stats.txt";
  std::string xml_file_name = out_prefix_ + ".map+stats.xml";
  std::string map_txt_file_name = out_prefix_ + ".map.txt";
  std::string map_yaml_file_name = out_prefix_ + ".map.yaml";
  std::string map_cfg_file_name = out_prefix_ + ".map.cfg";
  std::string map_cpp_file_name = out_prefix_ + ".map.cpp";

  // Prepare live status/log stream.
  std::ofstream log_file;

  // std::streambuf* streambuf_cout = std::cout.rdbuf();
  std::streambuf* streambuf_cerr = std::cerr.rdbuf();

  if (live_status_)
  {
    log_file.open(log_file_name);
    // std::cout.rdbuf(log_file.rdbuf());
    std::cerr.rdbuf(log_file.rdbuf());

    initscr();
    cbreak();
    noecho();
    clear();

    std::stringstream line0, line1, line2, line3, line4, line5;
    line0 << "================================================================================";
    line1 << "                                TIMELOOP MAPPER";
    line2 << "================================================================================";
    line3 << std::setw(3) << "TID" << std::setw(11) << "Total" << std::setw(11) << "Invalid"
          << std::setw(11) << "Valid" <<  std::setw(11) << "Consec." << std::setw(11) << "Last"
          << std::setw(11) << "Opt.util" << std::setw(11) << "Opt.energy";
    line4 << std::setw(3) << " " << std::setw(11) << " " << std::setw(11) << " "
          << std::setw(11) << " " <<  std::setw(11) << "invalid" << std::setw(11) << "update";
    line5 << "--------------------------------------------------------------------------------";
    mvaddstr(0, 0, line0.str().c_str());
    mvaddstr(1, 0, line1.str().c_str());
    mvaddstr(2, 0, line2.str().c_str());
    mvaddstr(3, 0, line3.str().c_str());
    mvaddstr(4, 0, line4.str().c_str());
    mvaddstr(5, 0, line5.str().c_str());
    refresh();
  }

  // Prepare the threads.
  std::mutex mutex;
  std::vector<MapperThread*> threads_;
  for (unsigned t = 0; t < num_threads_; t++)
  {
    threads_.push_back(new MapperThread(t, search_.at(t),
                                        split_mapspaces_.at(t),
                                        &mutex,
                                        search_size_,
                                        timeout_,
                                        victory_condition_,
                                        sync_interval_,
                                        log_stats_,
                                        log_suboptimal_,
                                        live_status_ ? log_file : std::cerr,
                                        live_status_,
                                        diagnostics_on_,
                                        penalize_consecutive_bypass_fails_,
                                        optimization_metrics_,
                                        arch_specs_,
                                        workload_,
                                        sparse_optimizations_,
                                        &best_));
  }

  // Launch the threads.
  for (unsigned t = 0; t < num_threads_; t++)
  {
    threads_.at(t)->Start();
  }

  // Wait for the threads to join.
  for (unsigned t = 0; t < num_threads_; t++)
  {
    threads_.at(t)->Join();
  }

  // Close log and end curses.
  if (live_status_)
  {
    // std::cout.rdbuf(streambuf_cout);
    std::cerr.rdbuf(streambuf_cerr);
    log_file.close();

    mvaddstr(LINES-1, 0, "Press any key to exit.");
    getch();
    endwin();
  }

  // Diagnostics.
  if (diagnostics_on_)
  {
    // Aggregate diagnostic data from all threads.
    std::map<FailClass, std::map<unsigned, FailInfo>> fail_stats;

    for (unsigned t = 0; t < num_threads_; t++)
    {
      for (auto& i: threads_.at(t)->GetStats().fail_stats)
      {
        auto& thread_fail_class = i.first;
        auto& thread_fail_bucket = i.second;

        auto fail_bucket_it = fail_stats.find(thread_fail_class);
        if (fail_bucket_it == fail_stats.end())
        {
          // We've never seen this fail class before.
          fail_stats[thread_fail_class] = thread_fail_bucket;
        }
        else
        {
          auto& fail_bucket = fail_bucket_it->second;

          // We've seen this fail class. Walk through each level in this fail bucket.
          for (auto& j: thread_fail_bucket)
          {
            auto& thread_fail_level_id = j.first;
            auto& thread_fail_info = j.second;

            auto fail_info_it = fail_bucket.find(thread_fail_level_id);
            if (fail_info_it == fail_bucket.end())
            {
              // We haven't seen this level within this fail bucket.
              fail_bucket[thread_fail_level_id] = thread_fail_info;
            }
            else
            {
              // We've seen this level within this fail bucket.
              fail_info_it->second.count += thread_fail_info.count;
            }
          }
        }
      }
    }

    // Print.
    std::cout << std::endl;
    std::cout << "===============================================" << std::endl;
    std::cout << "               BEGIN DIAGNOSTICS               " << std::endl;
    std::cout << "-----------------------------------------------" << std::endl;

    for (auto& i: fail_stats)
    {
      auto& fail_class = i.first;
      auto& fail_bucket = i.second;

      std::cout << "Fail class: " << fail_class << std::endl;
      for (auto& j: fail_bucket)
      {
        std::cout << std::endl;
        std::cout << "  Level: " << arch_specs_.topology.GetLevel(j.first)->level_name << std::endl;
        std::cout << "    Fail count: " << j.second.count << std::endl;
        std::cout << "    Sample mapping that experienced this fail class:" << std::endl;

        auto& mapping = j.second.mapping;

        model::Engine engine;
        engine.Spec(arch_specs_);
        engine.Evaluate(mapping, workload_, sparse_optimizations_, false);
        mapping.PrettyPrint(std::cout, arch_specs_.topology.StorageLevelNames(),
                            engine.GetTopology().GetStats().utilized_capacities,
                            engine.GetTopology().GetStats().tile_sizes, "      ");

        std::cout << "    Fail reason: " << j.second.reason << std::endl;
        std::cout << std::endl;
      }
    }

    std::cout << "-----------------------------------------------" << std::endl;
    std::cout << "                 END DIAGNOSTICS               " << std::endl;
    std::cout << "===============================================" << std::endl;
  }

  // Select the best mapping from each thread.
  for (unsigned t = 0; t < num_threads_; t++)
  {
    auto& thread_best = threads_.at(t)->GetStats().thread_best;
    global_best_.UpdateIfBetter(thread_best, optimization_metrics_);
  }

  std::cout << std::endl;

  for (unsigned t = 0; t < num_threads_; t++)
  {
    delete threads_.at(t);
    threads_.at(t) = nullptr;
  }

  if (global_best_.valid)
  {
    std::ofstream map_txt_file(map_txt_file_name);
    global_best_.mapping.PrettyPrint(map_txt_file, arch_specs_.topology.StorageLevelNames(),
                                     global_best_.stats.utilized_capacities,
                                     global_best_.stats.tile_sizes);
    map_txt_file.close();

    // std::ofstream map_yaml_file(map_yaml_file_name);
    // global_best_.mapping.PrintAsConstraints(map_yaml_file_name);
    // map_yaml_file.close();

    // Re-evaluate the mapping so that we get a live engine with complete specs and stats
    // that can be printed out hierarchically.
    model::Engine engine;
    engine.Spec(arch_specs_);
    engine.Evaluate(global_best_.mapping, workload_, sparse_optimizations_);

    std::ofstream stats_file(stats_file_name);
    stats_file << engine << std::endl;
    stats_file.close();

    if (emit_whoop_nest_)
    {
      std::ofstream map_cpp_file(map_cpp_file_name);
      global_best_.mapping.PrintWhoopNest(map_cpp_file, arch_specs_.topology.StorageLevelNames(),
                                          global_best_.stats.tile_sizes,
                                          global_best_.stats.utilized_instances);
      map_cpp_file.close();
    }

    std::cout << std::endl;
    if (!sparse_optimizations_->no_optimization_applied)
    {
      std::cout << "Summary stats for best mapping found by mapper:" << std::endl;
      std::cout << "  Utilization = " << std::setw(4) << OUT_FLOAT_FORMAT << std::setprecision(2)
                << global_best_.stats.utilization << " | pJ/Algorithmic-Compute = " << std::setw(8)
                << OUT_FLOAT_FORMAT << PRINTFLOAT_PRECISION << global_best_.stats.energy /
        global_best_.stats.algorithmic_computes
                << " | pJ/Compute = " << std::setw(8)
                << OUT_FLOAT_FORMAT << PRINTFLOAT_PRECISION << global_best_.stats.energy /
        global_best_.stats.actual_computes << std::endl;
    }
    else
    {
      std::cout << "Summary stats for best mapping found by mapper:" << std::endl;
      std::cout << "  Utilization = " << std::setw(4) << OUT_FLOAT_FORMAT << std::setprecision(2)
                << global_best_.stats.utilization
                << " | pJ/Compute = " << std::setw(8)
                << OUT_FLOAT_FORMAT << PRINTFLOAT_PRECISION << global_best_.stats.energy /
        global_best_.stats.actual_computes << std::endl;
    }

    // Print the engine stats and mapping to an XML file
    std::ofstream ofs(xml_file_name);
    boost::archive::xml_oarchive ar(ofs);
    ar << boost::serialization::make_nvp("engine", engine);
    ar << boost::serialization::make_nvp("mapping", global_best_.mapping);
    const Application* a = this;
    ar << BOOST_SERIALIZATION_NVP(a);
  }
  else
  {
    std::cout << "MESSAGE: no valid mappings found within search criteria. Some suggestions:" << std::endl;
    std::cout << "(1) Observe each mapper thread's termination message. If it terminated due to" << std::endl
              << "    consecutive failed mappings, it will tell you the number of mappings that" << std::endl
              << "    failed because of a spatial fanout violation and the number that failed" << std::endl
              << "    because of a buffer capacity violation." << std::endl;
    std::cout << "(2) Check your architecture configuration (especially mapspace constraints)." << std::endl
              << "    Try to find the offending constraints that are likely to have caused the" << std::endl
              << "    above violations, and disable those constraints." << std::endl;
    std::cout << "(3) Try other search algorithms, and relax the termination criteria:" << std::endl
              << "    victory-condition, timeout and/or search-size." << std::endl;
    if (!diagnostics_on_)
    {
      std::cout << "(4) Enable mapper's diagnostics (mapper.diagnostics = True) to track and emit " << std::endl
                << "    more information about failed mappings." << std::endl;
    }
  }

  // Create an output cfg starting with the original cfg contents.
  // Create an output yaml that contains the best mapping,
  libconfig::Config config;
  YAML::Emitter yaml_out;

  if (cfg_string_) {
    config.readString(cfg_string_);
    free(cfg_string_);
  }
  libconfig::Setting& root = config.getRoot();

#ifdef EMIT_OPT_AS_CONSTRAINTS
  // Update the mapper constraints.
  libconfig::Setting& mapper = root.lookup("mapper");

  if (mapper.exists("algorithm"))
    mapper["algorithm"] = "exhaustive";
  else
    mapper.add("algorithm", libconfig::Setting::TypeString) = "exhaustive";

  if (mapper.exists("num-threads"))
    mapper["num-threads"] = 1;
  else
    mapper.add("num-threads", libconfig::Setting::TypeInt) = 1;

  if (mapper.exists("search_size"))
    mapper.remove("search_size");

  if (mapper.exists("search-size"))
    mapper["search-size"] = 1;
  else
    mapper.add("search-size", libconfig::Setting::TypeInt) = 1;

  // Delete the mapspace constraint.
  if (root.exists("mapspace"))
    root.remove("mapspace");

  if (global_best_.valid)
  {
    // Create a new mapspace constraint.
    libconfig::Setting& mapspace = root.add("mapspace", libconfig::Setting::TypeGroup);

    // Format the best mapping as libconfig constraints.
    global_best_.mapping.FormatAsConstraints(mapspace);
  }
#else
  // We used to create a set of mapper constraints to fit exactly one mapping,
  // which could then be provided to timeloop-mapper.
  // We now create a single mapping which can be fed to timeloop-model.
  if (root.exists("mapper"))
    root.remove("mapper");

  if (root.exists("mapspace"))
    root.remove("mapspace");

  if (global_best_.valid)
  {
    // Create a new mapping.
    libconfig::Setting& mapping = root.add("mapping", libconfig::Setting::TypeList);

    // Format the best mapping as a libconfig spec.
    global_best_.mapping.FormatAsLibConfig(mapping, arch_specs_.topology.StorageLevelNames());

    yaml_out << YAML::BeginMap;
    yaml_out << YAML::Key << "mapping";
    yaml_out << YAML::Value;
    yaml_out << YAML::BeginSeq;
    global_best_.mapping.FormatAsYaml(yaml_out, arch_specs_.topology.StorageLevelNames());
    yaml_out << YAML::EndSeq;
    yaml_out << YAML::EndMap;
  }
#endif
  if (!cfg_string_) {
    std::ofstream mapping_output_file;
    mapping_output_file.open(map_yaml_file_name.c_str());
    mapping_output_file << yaml_out.c_str();
    mapping_output_file.close();
  } else {
    config.writeFile(map_cfg_file_name.c_str());
  }
}