<commit_before>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

// [[CITE]] Tarjan's strongly connected components algorithm
// Tarjan, R. E. (1972), "Depth-first search and linear graph algorithms", SIAM Journal on Computing 1 (2): 146–160, doi:10.1137/0201010
// http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm

#include "kernel/register.h"
#include "kernel/celltypes.h"
#include "kernel/sigtools.h"
#include "kernel/log.h"
#include <stdlib.h>
#include <stdio.h>
#include <set>

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

struct SccWorker
{
	RTLIL::Design *design;
	RTLIL::Module *module;
	SigMap sigmap;
	CellTypes ct;

	std::set<RTLIL::Cell*> workQueue;
	std::map<RTLIL::Cell*, std::set<RTLIL::Cell*>> cellToNextCell;
	std::map<RTLIL::Cell*, RTLIL::SigSpec> cellToPrevSig, cellToNextSig;

	std::map<RTLIL::Cell*, std::pair<int, int>> cellLabels;
	std::map<RTLIL::Cell*, int> cellDepth;
	std::set<RTLIL::Cell*> cellsOnStack;
	std::vector<RTLIL::Cell*> cellStack;
	int labelCounter;

	std::map<RTLIL::Cell*, int> cell2scc;
	std::vector<std::set<RTLIL::Cell*>> sccList;

	void run(RTLIL::Cell *cell, int depth, int maxDepth)
	{
		log_assert(workQueue.count(cell) > 0);

		workQueue.erase(cell);
		cellLabels[cell] = std::pair<int, int>(labelCounter, labelCounter);
		labelCounter++;

		cellsOnStack.insert(cell);
		cellStack.push_back(cell);

		if (maxDepth >= 0)
			cellDepth[cell] = depth;

		for (auto nextCell : cellToNextCell[cell])
			if (cellLabels.count(nextCell) == 0) {
				run(nextCell, depth+1, maxDepth);
				cellLabels[cell].second = std::min(cellLabels[cell].second, cellLabels[nextCell].second);
			} else
			if (cellsOnStack.count(nextCell) > 0 && (maxDepth < 0 || cellDepth[nextCell] + maxDepth > depth)) {
					cellLabels[cell].second = std::min(cellLabels[cell].second, cellLabels[nextCell].second);
			}

		if (cellLabels[cell].first == cellLabels[cell].second)
		{
			if (cellStack.back() == cell)
			{
				cellStack.pop_back();
				cellsOnStack.erase(cell);
			}
			else
			{
				log("Found an SCC:");
				std::set<RTLIL::Cell*> scc;
				while (cellsOnStack.count(cell) > 0) {
					RTLIL::Cell *c = cellStack.back();
					cellStack.pop_back();
					cellsOnStack.erase(c);
					log(" %s", RTLIL::id2cstr(c->name));
					cell2scc[c] = sccList.size();
					scc.insert(c);
				}
				sccList.push_back(scc);
				log("\n");
			}
		}
	}

	SccWorker(RTLIL::Design *design, RTLIL::Module *module, bool allCellTypes, int maxDepth) : design(design), module(module), sigmap(module)
	{
		if (module->processes.size() > 0) {
			log("Skipping module %s as it contains processes (run 'proc' pass first).\n", module->name.c_str());
			return;
		}

		if (allCellTypes) {
			ct.setup(design);
		} else {
			ct.setup_internals();
			ct.setup_stdcells();
		}

		SigPool selectedSignals;
		SigSet<RTLIL::Cell*> sigToNextCells;

		for (auto &it : module->wires_)
			if (design->selected(module, it.second))
				selectedSignals.add(sigmap(RTLIL::SigSpec(it.second)));

		for (auto &it : module->cells_)
		{
			RTLIL::Cell *cell = it.second;

			if (!design->selected(module, cell))
				continue;

			if (!allCellTypes && !ct.cell_known(cell->type))
				continue;

			workQueue.insert(cell);

			RTLIL::SigSpec inputSignals, outputSignals;

			for (auto &conn : cell->connections())
			{
				bool isInput = true, isOutput = true;

				if (ct.cell_known(cell->type)) {
					isInput = ct.cell_input(cell->type, conn.first);
					isOutput = ct.cell_output(cell->type, conn.first);
				}

				RTLIL::SigSpec sig = selectedSignals.extract(sigmap(conn.second));
				sig.sort_and_unify();

				if (isInput)
					inputSignals.append(sig);
				if (isOutput)
					outputSignals.append(sig);
			}

			inputSignals.sort_and_unify();
			outputSignals.sort_and_unify();

			cellToPrevSig[cell] = inputSignals;
			cellToNextSig[cell] = outputSignals;
			sigToNextCells.insert(inputSignals, cell);
		}

		for (auto cell : workQueue)
			cellToNextCell[cell] = sigToNextCells.find(cellToNextSig[cell]);

		labelCounter = 0;
		cellLabels.clear();

		while (workQueue.size() > 0) {
			RTLIL::Cell *cell = *workQueue.begin();
			log_assert(cellStack.size() == 0);
			cellDepth.clear();
			run(cell, 0, maxDepth);
		}

		log("Found %d SCCs in module %s.\n", int(sccList.size()), RTLIL::id2cstr(module->name));
	}

	void select(RTLIL::Selection &sel)
	{
		for (int i = 0; i < int(sccList.size()); i++)
		{
			std::set<RTLIL::Cell*> &cells = sccList[i];
			RTLIL::SigSpec prevsig, nextsig, sig;

			for (auto cell : cells) {
				sel.selected_members[module->name].insert(cell->name);
				prevsig.append(cellToPrevSig[cell]);
				nextsig.append(cellToNextSig[cell]);
			}

			prevsig.sort_and_unify();
			nextsig.sort_and_unify();
			sig = prevsig.extract(nextsig);

			for (auto &chunk : sig.chunks())
				if (chunk.wire != NULL)
					sel.selected_members[module->name].insert(chunk.wire->name);
		}
	}
};

struct SccPass : public Pass {
	SccPass() : Pass("scc", "detect strongly connected components (logic loops)") { }
	virtual void help()
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    scc [options] [selection]\n");
		log("\n");
		log("This command identifies strongly connected components (aka logic loops) in the\n");
		log("design.\n");
		log("\n");
		log("    -max_depth <num>\n");
		log("        limit to loops not longer than the specified number of cells. This can\n");
		log("        e.g. be useful in identifying local loops in a module that turns out\n");
		log("        to be one gigantic SCC.\n");
		log("\n");
		log("    -all_cell_types\n");
		log("        Usually this command only considers internal non-memory cells. With\n");
		log("        this option set, all cells are considered. For unknown cells all ports\n");
		log("        are assumed to be bidirectional 'inout' ports.\n");
		log("\n");
		log("    -set_attr <name> <value>\n");
		log("    -set_cell_attr <name> <value>\n");
		log("    -set_wire_attr <name> <value>\n");
		log("        set the specified attribute on all cells and/or wires that are part of\n");
		log("        a logic loop. the special token {} in the value is replaced with a\n");
		log("        unique identifier for the logic loop.\n");
		log("\n");
		log("    -select\n");
		log("        replace the current selection with a selection of all cells and wires\n");
		log("        that are part of a found logic loop\n");
		log("\n");
	}
	virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
	{
		std::map<std::string, std::string> setCellAttr, setWireAttr;
		bool allCellTypes = false;
		bool selectMode = false;
		int maxDepth = -1;

		log_header("Executing SCC pass (detecting logic loops).\n");

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++) {
			if (args[argidx] == "-max_depth" && argidx+1 < args.size()) {
				maxDepth = atoi(args[++argidx].c_str());
				continue;
			}
			if (args[argidx] == "-all_cell_types") {
				allCellTypes = true;
				continue;
			}
			if (args[argidx] == "-set_attr" && argidx+2 < args.size()) {
				setCellAttr[args[argidx+1]] = args[argidx+2];
				setWireAttr[args[argidx+1]] = args[argidx+2];
				argidx += 2;
				continue;
			}
			if (args[argidx] == "-set_cell_attr" && argidx+2 < args.size()) {
				setCellAttr[args[argidx+1]] = args[argidx+2];
				argidx += 2;
				continue;
			}
			if (args[argidx] == "-set_wire_attr" && argidx+2 < args.size()) {
				setWireAttr[args[argidx+1]] = args[argidx+2];
				argidx += 2;
				continue;
			}
			if (args[argidx] == "-select") {
				selectMode = true;
				continue;
			}
			break;
		}
		int origSelectPos = design->selection_stack.size() - 1;
		extra_args(args, argidx, design);

		if (setCellAttr.size() > 0 || setWireAttr.size() > 0)
			log_cmd_error("The -set*_attr options are not implemented at the moment!\n");

		RTLIL::Selection newSelection(false);

		for (auto &mod_it : design->modules_)
			if (design->selected(mod_it.second))
			{
				SccWorker worker(design, mod_it.second, allCellTypes, maxDepth);

				if (selectMode)
					worker.select(newSelection);
			}

		if (selectMode) {
			log_assert(origSelectPos >= 0);
			design->selection_stack[origSelectPos] = newSelection;
			design->selection_stack[origSelectPos].optimize(design);
		}
	}
} SccPass;

PRIVATE_NAMESPACE_END
<commit_msg>Added "scc -expect <N> -nofeedback"<commit_after>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

// [[CITE]] Tarjan's strongly connected components algorithm
// Tarjan, R. E. (1972), "Depth-first search and linear graph algorithms", SIAM Journal on Computing 1 (2): 146–160, doi:10.1137/0201010
// http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm

#include "kernel/register.h"
#include "kernel/celltypes.h"
#include "kernel/sigtools.h"
#include "kernel/log.h"
#include <stdlib.h>
#include <stdio.h>
#include <set>

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

struct SccWorker
{
	RTLIL::Design *design;
	RTLIL::Module *module;
	SigMap sigmap;
	CellTypes ct;

	std::set<RTLIL::Cell*> workQueue;
	std::map<RTLIL::Cell*, std::set<RTLIL::Cell*>> cellToNextCell;
	std::map<RTLIL::Cell*, RTLIL::SigSpec> cellToPrevSig, cellToNextSig;

	std::map<RTLIL::Cell*, std::pair<int, int>> cellLabels;
	std::map<RTLIL::Cell*, int> cellDepth;
	std::set<RTLIL::Cell*> cellsOnStack;
	std::vector<RTLIL::Cell*> cellStack;
	int labelCounter;

	std::map<RTLIL::Cell*, int> cell2scc;
	std::vector<std::set<RTLIL::Cell*>> sccList;

	void run(RTLIL::Cell *cell, int depth, int maxDepth)
	{
		log_assert(workQueue.count(cell) > 0);

		workQueue.erase(cell);
		cellLabels[cell] = std::pair<int, int>(labelCounter, labelCounter);
		labelCounter++;

		cellsOnStack.insert(cell);
		cellStack.push_back(cell);

		if (maxDepth >= 0)
			cellDepth[cell] = depth;

		for (auto nextCell : cellToNextCell[cell])
			if (cellLabels.count(nextCell) == 0) {
				run(nextCell, depth+1, maxDepth);
				cellLabels[cell].second = std::min(cellLabels[cell].second, cellLabels[nextCell].second);
			} else
			if (cellsOnStack.count(nextCell) > 0 && (maxDepth < 0 || cellDepth[nextCell] + maxDepth > depth)) {
					cellLabels[cell].second = std::min(cellLabels[cell].second, cellLabels[nextCell].second);
			}

		if (cellLabels[cell].first == cellLabels[cell].second)
		{
			if (cellStack.back() == cell)
			{
				cellStack.pop_back();
				cellsOnStack.erase(cell);
			}
			else
			{
				log("Found an SCC:");
				std::set<RTLIL::Cell*> scc;
				while (cellsOnStack.count(cell) > 0) {
					RTLIL::Cell *c = cellStack.back();
					cellStack.pop_back();
					cellsOnStack.erase(c);
					log(" %s", RTLIL::id2cstr(c->name));
					cell2scc[c] = sccList.size();
					scc.insert(c);
				}
				sccList.push_back(scc);
				log("\n");
			}
		}
	}

	SccWorker(RTLIL::Design *design, RTLIL::Module *module, bool nofeedbackMode, bool allCellTypes, int maxDepth) :
			design(design), module(module), sigmap(module)
	{
		if (module->processes.size() > 0) {
			log("Skipping module %s as it contains processes (run 'proc' pass first).\n", module->name.c_str());
			return;
		}

		if (allCellTypes) {
			ct.setup(design);
		} else {
			ct.setup_internals();
			ct.setup_stdcells();
		}

		SigPool selectedSignals;
		SigSet<RTLIL::Cell*> sigToNextCells;

		for (auto &it : module->wires_)
			if (design->selected(module, it.second))
				selectedSignals.add(sigmap(RTLIL::SigSpec(it.second)));

		for (auto &it : module->cells_)
		{
			RTLIL::Cell *cell = it.second;

			if (!design->selected(module, cell))
				continue;

			if (!allCellTypes && !ct.cell_known(cell->type))
				continue;

			workQueue.insert(cell);

			RTLIL::SigSpec inputSignals, outputSignals;

			for (auto &conn : cell->connections())
			{
				bool isInput = true, isOutput = true;

				if (ct.cell_known(cell->type)) {
					isInput = ct.cell_input(cell->type, conn.first);
					isOutput = ct.cell_output(cell->type, conn.first);
				}

				RTLIL::SigSpec sig = selectedSignals.extract(sigmap(conn.second));
				sig.sort_and_unify();

				if (isInput)
					inputSignals.append(sig);
				if (isOutput)
					outputSignals.append(sig);
			}

			inputSignals.sort_and_unify();
			outputSignals.sort_and_unify();

			cellToPrevSig[cell] = inputSignals;
			cellToNextSig[cell] = outputSignals;
			sigToNextCells.insert(inputSignals, cell);
		}

		for (auto cell : workQueue)
			cellToNextCell[cell] = sigToNextCells.find(cellToNextSig[cell]);

		labelCounter = 0;
		cellLabels.clear();

		while (workQueue.size() > 0)
		{
			RTLIL::Cell *cell = *workQueue.begin();
			log_assert(cellStack.size() == 0);
			cellDepth.clear();

			if (!nofeedbackMode && cellToNextCell[cell].count(cell)) {
				log("Found an SCC:");
				std::set<RTLIL::Cell*> scc;
				log(" %s", RTLIL::id2cstr(cell->name));
				cell2scc[cell] = sccList.size();
				scc.insert(cell);
				sccList.push_back(scc);
				workQueue.erase(cell);
				log("\n");
			} else
				run(cell, 0, maxDepth);
		}

		log("Found %d SCCs in module %s.\n", int(sccList.size()), RTLIL::id2cstr(module->name));
	}

	void select(RTLIL::Selection &sel)
	{
		for (int i = 0; i < int(sccList.size()); i++)
		{
			std::set<RTLIL::Cell*> &cells = sccList[i];
			RTLIL::SigSpec prevsig, nextsig, sig;

			for (auto cell : cells) {
				sel.selected_members[module->name].insert(cell->name);
				prevsig.append(cellToPrevSig[cell]);
				nextsig.append(cellToNextSig[cell]);
			}

			prevsig.sort_and_unify();
			nextsig.sort_and_unify();
			sig = prevsig.extract(nextsig);

			for (auto &chunk : sig.chunks())
				if (chunk.wire != NULL)
					sel.selected_members[module->name].insert(chunk.wire->name);
		}
	}
};

struct SccPass : public Pass {
	SccPass() : Pass("scc", "detect strongly connected components (logic loops)") { }
	virtual void help()
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    scc [options] [selection]\n");
		log("\n");
		log("This command identifies strongly connected components (aka logic loops) in the\n");
		log("design.\n");
		log("\n");
		log("    -expect <num>\n");
		log("        expect to find exactly <num> SSCs. A different number of SSCs will\n");
		log("        produce an error.\n");
		log("\n");
		log("    -max_depth <num>\n");
		log("        limit to loops not longer than the specified number of cells. This\n");
		log("        can e.g. be useful in identifying small local loops in a module that\n");
		log("        implements one large SCC.\n");
		log("\n");
		log("    -nofeedback\n");
		log("        do not count cells that have their output fed back into one of their\n");
		log("        inputs as single-cell scc.\n");
		log("\n");
		log("    -all_cell_types\n");
		log("        Usually this command only considers internal non-memory cells. With\n");
		log("        this option set, all cells are considered. For unknown cells all ports\n");
		log("        are assumed to be bidirectional 'inout' ports.\n");
		log("\n");
		log("    -set_attr <name> <value>\n");
		log("    -set_cell_attr <name> <value>\n");
		log("    -set_wire_attr <name> <value>\n");
		log("        set the specified attribute on all cells and/or wires that are part of\n");
		log("        a logic loop. the special token {} in the value is replaced with a\n");
		log("        unique identifier for the logic loop.\n");
		log("\n");
		log("    -select\n");
		log("        replace the current selection with a selection of all cells and wires\n");
		log("        that are part of a found logic loop\n");
		log("\n");
	}
	virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
	{
		std::map<std::string, std::string> setCellAttr, setWireAttr;
		bool allCellTypes = false;
		bool selectMode = false;
		bool nofeedbackMode = false;
		int maxDepth = -1;
		int expect = -1;

		log_header("Executing SCC pass (detecting logic loops).\n");

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++) {
			if (args[argidx] == "-max_depth" && argidx+1 < args.size()) {
				maxDepth = atoi(args[++argidx].c_str());
				continue;
			}
			if (args[argidx] == "-expect" && argidx+1 < args.size()) {
				expect = atoi(args[++argidx].c_str());
				continue;
			}
			if (args[argidx] == "-nofeedback") {
				nofeedbackMode = true;
				continue;
			}
			if (args[argidx] == "-all_cell_types") {
				allCellTypes = true;
				continue;
			}
			if (args[argidx] == "-set_attr" && argidx+2 < args.size()) {
				setCellAttr[args[argidx+1]] = args[argidx+2];
				setWireAttr[args[argidx+1]] = args[argidx+2];
				argidx += 2;
				continue;
			}
			if (args[argidx] == "-set_cell_attr" && argidx+2 < args.size()) {
				setCellAttr[args[argidx+1]] = args[argidx+2];
				argidx += 2;
				continue;
			}
			if (args[argidx] == "-set_wire_attr" && argidx+2 < args.size()) {
				setWireAttr[args[argidx+1]] = args[argidx+2];
				argidx += 2;
				continue;
			}
			if (args[argidx] == "-select") {
				selectMode = true;
				continue;
			}
			break;
		}
		int origSelectPos = design->selection_stack.size() - 1;
		extra_args(args, argidx, design);

		if (setCellAttr.size() > 0 || setWireAttr.size() > 0)
			log_cmd_error("The -set*_attr options are not implemented at the moment!\n");

		RTLIL::Selection newSelection(false);
		int scc_counter = 0;

		for (auto &mod_it : design->modules_)
			if (design->selected(mod_it.second))
			{
				SccWorker worker(design, mod_it.second, nofeedbackMode, allCellTypes, maxDepth);
				scc_counter += GetSize(worker.sccList);

				if (selectMode)
					worker.select(newSelection);
			}

		if (expect >= 0) {
			if (scc_counter == expect)
				log("Found and expected %d SCCs.\n", scc_counter);
			else
				log_error("Found %d SCCs but expected %d.\n", scc_counter, expect);
		} else
			log("Found %d SCCs.\n", scc_counter);

		if (selectMode) {
			log_assert(origSelectPos >= 0);
			design->selection_stack[origSelectPos] = newSelection;
			design->selection_stack[origSelectPos].optimize(design);
		}
	}
} SccPass;

PRIVATE_NAMESPACE_END
<|endoftext|>


<commit_before>#include "string_utils.h"

#include <iostream>
#include <ctime>
#include <time.h>

namespace Cthun {
namespace Common {
namespace StringUtils {

std::string plural(int num_of_things) {
    return num_of_things > 1 ? "s" : "";
}

template<>
std::string plural<std::string>(std::vector<std::string> things) {
    return plural(things.size());
}

std::string getExpiryDatetime(int expiry_minutes) {
    struct tm expiry_time_info;
    char expiry_time_buffer[80];

    // Get current time and add the specified minutes
    time_t expiry_time { time(nullptr) };
    expiry_time += 60 * expiry_minutes;

    // Get local time structure
    localtime_r(&expiry_time, &expiry_time_info);

    // Return the formatted string
    if (strftime(expiry_time_buffer, 80, "%FT%TZ", &expiry_time_info) == 0) {
        // invalid buffer
        return "";
    }

    return std::string { expiry_time_buffer };
}

// TODO(ale): test on Linux
void displayProgress(double percent, int len, std::string status) {
    printf("%c[2K", 27);
    printf("\r");

    if (percent > 0) {
        std::string progress {};
        for (int idx = 0; idx < len; ++idx) {
            if (idx < static_cast<int>(len * percent)) {
                progress += "=";
            } else {
                progress += " ";
            }
        }
        std::cout << status << " [" << progress << "] "
                  << static_cast<int>(100 * percent) << "%";
        std::flush(std::cout);
    }
}

}  // namespace StringUtils
}  // namespace Common
}  // namespace Cthun
<commit_msg>(maint) - improving progress message<commit_after>#include "string_utils.h"

#include <iostream>
#include <ctime>
#include <time.h>

namespace Cthun {
namespace Common {
namespace StringUtils {

std::string plural(int num_of_things) {
    return num_of_things > 1 ? "s" : "";
}

template<>
std::string plural<std::string>(std::vector<std::string> things) {
    return plural(things.size());
}

std::string getExpiryDatetime(int expiry_minutes) {
    struct tm expiry_time_info;
    char expiry_time_buffer[80];

    // Get current time and add the specified minutes
    time_t expiry_time { time(nullptr) };
    expiry_time += 60 * expiry_minutes;

    // Get local time structure
    localtime_r(&expiry_time, &expiry_time_info);

    // Return the formatted string
    if (strftime(expiry_time_buffer, 80, "%FT%TZ", &expiry_time_info) == 0) {
        // invalid buffer
        return "";
    }

    return std::string { expiry_time_buffer };
}

// TODO(ale): test on Linux
void displayProgress(double percent, int len, std::string status) {
    printf("%c[2K", 27);
    printf("\r");

    if (percent > 0) {
        std::string progress {};
        for (int idx = 0; idx < len; ++idx) {
            if (idx < static_cast<int>(len * percent)) {
                progress += "=";
            } else {
                progress += " ";
            }
        }
        std::cout << status << "   [" << progress << "]   "
                  << static_cast<int>(100 * percent) << "% completed";
        std::flush(std::cout);
    }
}

}  // namespace StringUtils
}  // namespace Common
}  // namespace Cthun
<|endoftext|>


<commit_before>#include "Ray.h"

Ray::Ray(Side side)
	:m_side(side)
{

}

Ray::~Ray()
{
}

bool Ray::Contains(sf::FloatRect & floatRect)
{
	return false;
}

void Ray::SetTexture(sf::Texture & texture)
{
	m_texture = &texture;
	m_sprite.setTexture(*m_texture);
	m_sprite.setOrigin(m_sprite.getGlobalBounds().width / 2.f, m_sprite.getGlobalBounds().height / 2.f);
}

int Ray::GetSide()
{
	return m_side;
}

void Ray::SetSize(unsigned short size)
{
	m_size = size;
	switch (m_side)
	{
	case Ray::Up:
		m_sprite.setPosition(m_sprite.getPosition().x,m_sprite.getPosition().y - TILE_SIZE);
		m_sprite.setTextureRect(sf::IntRect(TILE_SIZE, m_size*TILE_SIZE,-TILE_SIZE, -m_size*TILE_SIZE));
		break;
	case Ray::Down:
		m_sprite.setPosition(m_sprite.getPosition().x, m_sprite.getPosition().y + TILE_SIZE);
		m_sprite.setTextureRect(sf::IntRect(0, 0, TILE_SIZE, m_size*TILE_SIZE));
		break;
	case Ray::Left:
		m_sprite.setPosition(m_sprite.getPosition().x - TILE_SIZE, m_sprite.getPosition().y );
		m_sprite.setTextureRect(sf::IntRect(m_size* TILE_SIZE, TILE_SIZE, -m_size* TILE_SIZE, TILE_SIZE));
		break;
	case Ray::Right:
		m_sprite.setPosition(m_sprite.getPosition().x + TILE_SIZE, m_sprite.getPosition().y);
		m_sprite.setTextureRect(sf::IntRect(0, 0, m_size*TILE_SIZE, TILE_SIZE));
		break;
	default:
		break;
	}

}

void Ray::SetPosition(float x, float y)
{
	m_sprite.setPosition(x,y);
}

sf::Drawable & Ray::GetSprite()
{
	return m_sprite;
}

<commit_msg>View layer of bombing system finished (Does not include animations)<commit_after>#include "Ray.h"

Ray::Ray(Side side)
	:m_side(side)
{

}

Ray::~Ray()
{
}

bool Ray::Contains(sf::FloatRect & floatRect)
{
	return false;
}

void Ray::SetTexture(sf::Texture & texture)
{
	m_texture = &texture;
	m_sprite.setTexture(*m_texture);

}

int Ray::GetSide()
{
	return m_side;
}

void Ray::SetSize(unsigned short size)
{
	m_size = size;
	m_sprite.setTextureRect(sf::IntRect(0, 0, m_size*TILE_SIZE,TILE_SIZE));
	m_sprite.setOrigin(0, m_sprite.getGlobalBounds().height / 2.f);
	switch (m_side)
	{
	case Ray::Up:
		m_sprite.setPosition(m_sprite.getPosition().x,m_sprite.getPosition().y - TILE_SIZE/2);
		m_sprite.setRotation(270);
		break;
	case Ray::Down:
		m_sprite.setPosition(m_sprite.getPosition().x, m_sprite.getPosition().y + TILE_SIZE/2);
		m_sprite.setRotation(90);
		break;
	case Ray::Left:
		m_sprite.setPosition(m_sprite.getPosition().x - TILE_SIZE/2, m_sprite.getPosition().y );
		m_sprite.setRotation(180);
		break;
	case Ray::Right:
		m_sprite.setPosition(m_sprite.getPosition().x + TILE_SIZE/2, m_sprite.getPosition().y);

		break;
	default:
		break;
	}

}

void Ray::SetPosition(float x, float y)
{
	m_sprite.setPosition(x,y);
}

sf::Drawable & Ray::GetSprite()
{
	return m_sprite;
}

<|endoftext|>


<commit_before>// Time:  O(1), per operation
// Space: O(c), k is capacity of cache

#include <list>

class LRUCache {
public:
    LRUCache(int capacity) : capa_(capacity) {
    }

    int get(int key) {
        auto it = map_.find(key);
        if (it != map_.end()) {
            // It key exists, update it.
            auto l_it = it->second;
            int value = l_it->second;
            update(it, value);
            return value;
        } else {
            return -1;
        }
    }

    void set(int key, int value) {
        auto it = map_.find(key);
        // It key exists, update it.
        if (it != map_.end()) {
            update(it, value);
        } else {
            // If cache is full, remove the last one.
            if (list_.size() == capa_) {
                auto del = list_.back(); list_.pop_back();
                map_.erase(del.first);
            }
            list_.emplace_front(key, value);
            map_[key]=list_.begin();
        }
    }

private:
    list<pair<int, int>> list_; // key, value
    unordered_map<int, list< pair<int, int>>::iterator> map_; // key, list iterator
    int capa_;

    // Update (key, iterator of (key, value)) pair
    void update(unordered_map<int, list<pair<int, int>>::iterator>::iterator it, int value) {
        auto l_it = it->second;
        int key = l_it->first;
        list_.erase(l_it);
        list_.emplace_front(key, value);
        it->second = list_.begin();
    }
};
<commit_msg>Update lru-cache.cpp<commit_after>// Time:  O(1), per operation
// Space: O(k), k is capacity of cache

#include <list>

class LRUCache {
public:
    LRUCache(int capacity) : capa_(capacity) {
    }

    int get(int key) {
        auto it = map_.find(key);
        if (it != map_.end()) {
            // It key exists, update it.
            auto l_it = it->second;
            int value = l_it->second;
            update(it, value);
            return value;
        } else {
            return -1;
        }
    }

    void set(int key, int value) {
        auto it = map_.find(key);
        // It key exists, update it.
        if (it != map_.end()) {
            update(it, value);
        } else {
            // If cache is full, remove the last one.
            if (list_.size() == capa_) {
                auto del = list_.back(); list_.pop_back();
                map_.erase(del.first);
            }
            list_.emplace_front(key, value);
            map_[key]=list_.begin();
        }
    }

private:
    list<pair<int, int>> list_; // key, value
    unordered_map<int, list< pair<int, int>>::iterator> map_; // key, list iterator
    int capa_;

    // Update (key, iterator of (key, value)) pair
    void update(unordered_map<int, list<pair<int, int>>::iterator>::iterator it, int value) {
        auto l_it = it->second;
        int key = l_it->first;
        list_.erase(l_it);
        list_.emplace_front(key, value);
        it->second = list_.begin();
    }
};
<|endoftext|>


<commit_before>#include <librealsense/rs.hpp>
#include "example.h"

#define _USE_MATH_DEFINES
#include <math.h>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <thread>

font font;

float compute_fov(int image_size, float focal_length, float principal_point)
{
    return (atan2f(principal_point + 0.5f, focal_length) + atan2f(image_size - principal_point - 0.5f, focal_length)) * 180.0f / (float)M_PI;
}

void draw_stream(rs::device & dev, rs::stream stream, int x, int y)
{
    if(!dev.is_stream_enabled(stream)) return;

    const rs::intrinsics intrin = dev.get_stream_intrinsics(stream);
    const rs::format format = dev.get_stream_format(stream);
    const int width = intrin.image_size.x, height = intrin.image_size.y, fps = dev.get_stream_framerate(stream);
    const void * pixels = dev.get_frame_data(stream);

    glRasterPos2i(x + (640 - intrin.image_size.x)/2, y + (480 - intrin.image_size.y)/2);
    glPixelZoom(1, -1);
    switch(format)
    {
    case rs::format::z16:
        draw_depth_histogram(reinterpret_cast<const uint16_t *>(pixels), width, height);
        break;
    case rs::format::yuyv:
        glDrawPixels(width, height, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, pixels); // Display YUYV by showing the luminance channel and packing chrominance into ignored alpha channel
        break;
    case rs::format::rgb8: case rs::format::bgr8: // Display both RGB and BGR by interpreting them RGB, to show the flipped byte ordering. Obviously, GL_BGR could be used on OpenGL 1.2+
        glDrawPixels(width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels);
        break;
    case rs::format::rgba8: case rs::format::bgra8: // Display both RGBA and BGRA by interpreting them RGBA, to show the flipped byte ordering. Obviously, GL_BGRA could be used on OpenGL 1.2+
        glDrawPixels(width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
        break;
    case rs::format::y8:
        glDrawPixels(width, height, GL_LUMINANCE, GL_UNSIGNED_BYTE, pixels);
        break;
    case rs::format::y16:
        glDrawPixels(width, height, GL_LUMINANCE, GL_UNSIGNED_SHORT, pixels);
        break;
    }

    std::ostringstream ss; ss << stream << ": " << intrin.image_size.x << " x " << intrin.image_size.y << " " << format;
    ttf_print(&font, x+8, y+16, ss.str().c_str());
}

int main(int argc, char * argv[]) try
{
    // Obtain a RealSense device
    rs::context ctx;
    if(ctx.get_device_count() < 1) throw std::runtime_error("No device detected. Is it plugged in?");
    rs::device device = ctx.get_device(0);

    // Open a GLFW window
    glfwInit();
    std::ostringstream ss; ss << "CPP Restart Example (" << device.get_name() << ")";
    GLFWwindow * win = glfwCreateWindow(1280, 960, ss.str().c_str(), 0, 0);
    glfwMakeContextCurrent(win);

    // Load our truetype font
    if (auto f = find_file("examples/assets/Roboto-Bold.ttf", 3))
    {
        font = ttf_create(f);
        fclose(f);
    }
    else throw std::runtime_error("Unable to open examples/assets/Roboto-Bold.ttf");

    for(int i=0; i<8; ++i)
    {
        switch(i)
        {
        case 0:
            device.enable_stream(rs::stream::depth, rs::preset::best_quality);
            device.enable_stream(rs::stream::color, rs::preset::best_quality);
            break;
        case 1:
            device.enable_stream(rs::stream::depth, rs::preset::largest_image);
            device.enable_stream(rs::stream::color, rs::preset::best_quality);
            break;
        case 2:
            device.enable_stream(rs::stream::depth, rs::preset::best_quality);
            device.enable_stream(rs::stream::color, rs::preset::best_quality);
            device.enable_stream(rs::stream::infrared, rs::preset::best_quality);
            break;
        case 3:
            device.enable_stream(rs::stream::depth, rs::preset::largest_image);
            device.enable_stream(rs::stream::color, rs::preset::best_quality);
            device.enable_stream(rs::stream::infrared, rs::preset::largest_image);
            break;
        case 4:
            device.enable_stream(rs::stream::depth, rs::preset::best_quality);
            device.enable_stream(rs::stream::color, rs::preset::best_quality);
            device.enable_stream(rs::stream::infrared, rs::preset::best_quality);
            device.enable_stream(rs::stream::infrared2, rs::preset::best_quality);
            break;
        case 5:
            device.enable_stream(rs::stream::depth, rs::preset::largest_image);
            device.enable_stream(rs::stream::color, rs::preset::best_quality);
            device.enable_stream(rs::stream::infrared, rs::preset::largest_image);
            device.enable_stream(rs::stream::infrared2, rs::preset::largest_image);
            break;
        case 6:
            device.enable_stream(rs::stream::depth, rs::preset::best_quality);
            device.disable_stream(rs::stream::color);
            device.disable_stream(rs::stream::infrared);
            device.disable_stream(rs::stream::infrared2);
            break;
        case 7:
            device.disable_stream(rs::stream::depth);
            device.enable_stream(rs::stream::color, rs::preset::best_quality);
            break;
        }

        device.start();
        for(int j=0; j<120; ++j)
        {
            // Wait for new images
            glfwPollEvents();
            if(glfwWindowShouldClose(win)) goto done;
            device.wait_for_frames();

            // Draw the images
            glClear(GL_COLOR_BUFFER_BIT);
            glPushMatrix();
            glOrtho(0, 1280, 960, 0, -1, +1);
            draw_stream(device, rs::stream::color, 0, 0);
            draw_stream(device, rs::stream::depth, 640, 0);
            draw_stream(device, rs::stream::infrared, 0, 480);
            draw_stream(device, rs::stream::infrared2, 640, 480);
            glPopMatrix();
            glfwSwapBuffers(win);
        }
        device.stop();
    }
done:
    glfwDestroyWindow(win);
    glfwTerminate();
    return EXIT_SUCCESS;
}
catch(const rs::error & e)
{
    std::cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n    " << e.what() << std::endl;
    return EXIT_FAILURE;
}
catch(const std::exception & e)
{
    std::cerr << e.what() << std::endl;
    return EXIT_FAILURE;
}<commit_msg>Some mode transitions don't seem to work just yet. Requires further analysis.<commit_after>#include <librealsense/rs.hpp>
#include "example.h"

#define _USE_MATH_DEFINES
#include <math.h>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <thread>

font font;

float compute_fov(int image_size, float focal_length, float principal_point)
{
    return (atan2f(principal_point + 0.5f, focal_length) + atan2f(image_size - principal_point - 0.5f, focal_length)) * 180.0f / (float)M_PI;
}

void draw_stream(rs::device & dev, rs::stream stream, int x, int y)
{
    if(!dev.is_stream_enabled(stream)) return;

    const rs::intrinsics intrin = dev.get_stream_intrinsics(stream);
    const rs::format format = dev.get_stream_format(stream);
    const int width = intrin.image_size.x, height = intrin.image_size.y, fps = dev.get_stream_framerate(stream);
    const void * pixels = dev.get_frame_data(stream);

    glRasterPos2i(x + (640 - intrin.image_size.x)/2, y + (480 - intrin.image_size.y)/2);
    glPixelZoom(1, -1);
    switch(format)
    {
    case rs::format::z16:
        draw_depth_histogram(reinterpret_cast<const uint16_t *>(pixels), width, height);
        break;
    case rs::format::yuyv:
        glDrawPixels(width, height, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, pixels); // Display YUYV by showing the luminance channel and packing chrominance into ignored alpha channel
        break;
    case rs::format::rgb8: case rs::format::bgr8: // Display both RGB and BGR by interpreting them RGB, to show the flipped byte ordering. Obviously, GL_BGR could be used on OpenGL 1.2+
        glDrawPixels(width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels);
        break;
    case rs::format::rgba8: case rs::format::bgra8: // Display both RGBA and BGRA by interpreting them RGBA, to show the flipped byte ordering. Obviously, GL_BGRA could be used on OpenGL 1.2+
        glDrawPixels(width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
        break;
    case rs::format::y8:
        glDrawPixels(width, height, GL_LUMINANCE, GL_UNSIGNED_BYTE, pixels);
        break;
    case rs::format::y16:
        glDrawPixels(width, height, GL_LUMINANCE, GL_UNSIGNED_SHORT, pixels);
        break;
    }

    std::ostringstream ss; ss << stream << ": " << intrin.image_size.x << " x " << intrin.image_size.y << " " << format;
    ttf_print(&font, x+8, y+16, ss.str().c_str());
}

int main(int argc, char * argv[]) try
{
    // Obtain a RealSense device
    rs::context ctx;
    if(ctx.get_device_count() < 1) throw std::runtime_error("No device detected. Is it plugged in?");
    rs::device device = ctx.get_device(0);

    // Open a GLFW window
    glfwInit();
    std::ostringstream ss; ss << "CPP Restart Example (" << device.get_name() << ")";
    GLFWwindow * win = glfwCreateWindow(1280, 960, ss.str().c_str(), 0, 0);
    glfwMakeContextCurrent(win);

    // Load our truetype font
    if (auto f = find_file("examples/assets/Roboto-Bold.ttf", 3))
    {
        font = ttf_create(f);
        fclose(f);
    }
    else throw std::runtime_error("Unable to open examples/assets/Roboto-Bold.ttf");

    for(int i=0; i<7; ++i)
    {
        switch(i)
        {
        case 0:
            device.enable_stream(rs::stream::depth, rs::preset::best_quality);
            device.enable_stream(rs::stream::color, rs::preset::best_quality);
            break;
        case 1:
            device.enable_stream(rs::stream::depth, rs::preset::largest_image);
            device.enable_stream(rs::stream::color, rs::preset::best_quality);
            break;
        case 2:
            device.enable_stream(rs::stream::depth, rs::preset::best_quality);
            device.enable_stream(rs::stream::color, rs::preset::best_quality);
            device.enable_stream(rs::stream::infrared, rs::preset::best_quality);
            break;
        case 3:
            device.enable_stream(rs::stream::depth, rs::preset::largest_image);
            device.enable_stream(rs::stream::color, rs::preset::best_quality);
            device.enable_stream(rs::stream::infrared, rs::preset::largest_image);
            break;
        case 4:
            device.enable_stream(rs::stream::depth, rs::preset::best_quality);
            device.enable_stream(rs::stream::color, rs::preset::best_quality);
            device.enable_stream(rs::stream::infrared, rs::preset::best_quality);
            device.enable_stream(rs::stream::infrared2, rs::preset::best_quality);
            break;
        case 5:
            device.enable_stream(rs::stream::depth, rs::preset::largest_image);
            device.enable_stream(rs::stream::color, rs::preset::best_quality);
            device.enable_stream(rs::stream::infrared, rs::preset::largest_image);
            device.enable_stream(rs::stream::infrared2, rs::preset::largest_image);
            break;
        case 6:
            device.disable_stream(rs::stream::depth);
            device.disable_stream(rs::stream::color);
            device.enable_stream(rs::stream::infrared, rs::preset::best_quality);
            device.enable_stream(rs::stream::infrared2, rs::preset::best_quality);
            break;
        }

        device.start();
        for(int j=0; j<120; ++j)
        {
            // Wait for new images
            glfwPollEvents();
            if(glfwWindowShouldClose(win)) goto done;
            device.wait_for_frames();

            // Draw the images
            glClear(GL_COLOR_BUFFER_BIT);
            glPushMatrix();
            glOrtho(0, 1280, 960, 0, -1, +1);
            draw_stream(device, rs::stream::color, 0, 0);
            draw_stream(device, rs::stream::depth, 640, 0);
            draw_stream(device, rs::stream::infrared, 0, 480);
            draw_stream(device, rs::stream::infrared2, 640, 480);
            glPopMatrix();
            glfwSwapBuffers(win);
        }
        device.stop();
    }
done:
    glfwDestroyWindow(win);
    glfwTerminate();
    return EXIT_SUCCESS;
}
catch(const rs::error & e)
{
    std::cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n    " << e.what() << std::endl;
    return EXIT_FAILURE;
}
catch(const std::exception & e)
{
    std::cerr << e.what() << std::endl;
    return EXIT_FAILURE;
}<|endoftext|>


<commit_before><commit_msg>This looks wrong for sure, too.<commit_after><|endoftext|>


<commit_before>//===--- ParseInit.cpp - Initializer Parsing ------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements initializer parsing as specified by C99 6.7.8.
//
//===----------------------------------------------------------------------===//

#include "clang/Parse/Designator.h"
#include "clang/Parse/Parser.h"
#include "clang/Basic/Diagnostic.h"
#include "llvm/ADT/SmallString.h"
using namespace clang;

/// MayBeDesignationStart - Return true if this token might be the start of a
/// designator.  If we can tell it is impossible that it is a designator, return
/// false.
static bool MayBeDesignationStart(tok::TokenKind K, Preprocessor &PP) {
  switch (K) {
  default: return false;
  case tok::period:      // designator: '.' identifier
  case tok::l_square:    // designator: array-designator
      return true;
  case tok::identifier:  // designation: identifier ':'
    return PP.LookAhead(0).is(tok::colon);
  }
}

/// ParseInitializerWithPotentialDesignator - Parse the 'initializer' production
/// checking to see if the token stream starts with a designator.
///
///       designation:
///         designator-list '='
/// [GNU]   array-designator
/// [GNU]   identifier ':'
///
///       designator-list:
///         designator
///         designator-list designator
///
///       designator:
///         array-designator
///         '.' identifier
///
///       array-designator:
///         '[' constant-expression ']'
/// [GNU]   '[' constant-expression '...' constant-expression ']'
///
/// NOTE: [OBC] allows '[ objc-receiver objc-message-args ]' as an
/// initializer (because it is an expression).  We need to consider this case
/// when parsing array designators.
///
Parser::ExprResult Parser::
ParseInitializerWithPotentialDesignator(InitListDesignations &Designations,
                                        unsigned InitNum) {

  // If this is the old-style GNU extension:
  //   designation ::= identifier ':'
  // Handle it as a field designator.  Otherwise, this must be the start of a
  // normal expression.
  if (Tok.is(tok::identifier)) {
    Diag(Tok, diag::ext_gnu_old_style_field_designator);

    Designation &D = Designations.CreateDesignation(InitNum);
    D.AddDesignator(Designator::getField(Tok.getIdentifierInfo()));
    ConsumeToken(); // Eat the identifier.

    assert(Tok.is(tok::colon) && "MayBeDesignationStart not working properly!");
    ConsumeToken();
    return ParseInitializer();
  }

  // Desig - This is initialized when we see our first designator.  We may have
  // an objc message send with no designator, so we don't want to create this
  // eagerly.
  Designation *Desig = 0;

  // Parse each designator in the designator list until we find an initializer.
  while (Tok.is(tok::period) || Tok.is(tok::l_square)) {
    if (Tok.is(tok::period)) {
      // designator: '.' identifier
      ConsumeToken();

      // Create designation if we haven't already.
      if (Desig == 0)
        Desig = &Designations.CreateDesignation(InitNum);

      if (Tok.isNot(tok::identifier)) {
        Diag(Tok.getLocation(), diag::err_expected_field_designator);
        return ExprResult(true);
      }

      Desig->AddDesignator(Designator::getField(Tok.getIdentifierInfo()));
      ConsumeToken(); // Eat the identifier.
      continue;
    }

    // We must have either an array designator now or an objc message send.
    assert(Tok.is(tok::l_square) && "Unexpected token!");

    // array-designator: '[' constant-expression ']'
    // array-designator: '[' constant-expression '...' constant-expression ']'
    // When designation is empty, this can be '[' objc-message-expr ']'.  Note
    // that we also have the case of [4][foo bar], which is the gnu designator
    // extension + objc message send.
    SourceLocation StartLoc = ConsumeBracket();

    // If Objective-C is enabled and this is a typename or other identifier
    // receiver, parse this as a message send expression.
    if (getLang().ObjC1 && isTokObjCMessageIdentifierReceiver()) {
      // FIXME: Emit ext_gnu_missing_equal_designator for inits like
      // [4][foo bar].
      IdentifierInfo *Name = Tok.getIdentifierInfo();
      ConsumeToken();
      return ParseAssignmentExprWithObjCMessageExprStart(StartLoc, Name, 0);
    }

    // Note that we parse this as an assignment expression, not a constant
    // expression (allowing *=, =, etc) to handle the objc case.  Sema needs
    // to validate that the expression is a constant.
    ExprResult Idx = ParseAssignmentExpression();
    if (Idx.isInvalid) {
      SkipUntil(tok::r_square);
      return Idx;
    }

    // Given an expression, we could either have a designator (if the next
    // tokens are '...' or ']' or an objc message send.  If this is an objc
    // message send, handle it now.  An objc-message send is the start of
    // an assignment-expression production.
    if (getLang().ObjC1 && Tok.isNot(tok::ellipsis) &&
        Tok.isNot(tok::r_square)) {
      // FIXME: Emit ext_gnu_missing_equal_designator for inits like
      // [4][foo bar].
      return ParseAssignmentExprWithObjCMessageExprStart(StartLoc, 0,Idx.Val);
    }

    // Handle the gnu array range extension.
    if (Tok.is(tok::ellipsis)) {
      Diag(Tok, diag::ext_gnu_array_range);
      ConsumeToken();

      ExprResult RHS = ParseConstantExpression();
      if (RHS.isInvalid) {
        SkipUntil(tok::r_square);
        return RHS;
      }
    }

    MatchRHSPunctuation(tok::r_square, StartLoc);
  }

  // Okay, we're done with the designator sequence.  We know that there must be
  // at least one designator, because the only case we can get into this method
  // without a designator is when we have an objc message send.  That case is
  // handled and returned from above.

  // Handle a normal designator sequence end, which is an equal.
  if (Tok.is(tok::equal)) {
    ConsumeToken();
    return ParseInitializer();
  }

  // We read some number of designators and found something that isn't an = or
  // an initializer.  If we have exactly one array designator [TODO CHECK], this
  // is the GNU 'designation: array-designator' extension.  Otherwise, it is a
  // parse error.
  SourceLocation Loc = Tok.getLocation();
  ExprResult Init = ParseInitializer();
  if (Init.isInvalid) return Init;

  Diag(Tok, diag::ext_gnu_missing_equal_designator);
  return Init;
}

/// ParseBraceInitializer - Called when parsing an initializer that has a
/// leading open brace.
///
///       initializer: [C99 6.7.8]
///         '{' initializer-list '}'
///         '{' initializer-list ',' '}'
/// [GNU]   '{' '}'
///
///       initializer-list:
///         designation[opt] initializer
///         initializer-list ',' designation[opt] initializer
///
Parser::ExprResult Parser::ParseBraceInitializer() {
  SourceLocation LBraceLoc = ConsumeBrace();

  // We support empty initializers, but tell the user that they aren't using
  // C99-clean code.
  if (Tok.is(tok::r_brace)) {
    Diag(LBraceLoc, diag::ext_gnu_empty_initializer);
    // Match the '}'.
    return Actions.ActOnInitList(LBraceLoc, 0, 0, ConsumeBrace());
  }

  /// InitExprs - This is the actual list of expressions contained in the
  /// initializer.
  llvm::SmallVector<ExprTy*, 8> InitExprs;

  /// ExprDesignators - For each initializer, keep track of the designator that
  /// was specified for it, if any.
  InitListDesignations InitExprDesignations(Actions);

  bool InitExprsOk = true;

  while (1) {
    // Parse: designation[opt] initializer

    // If we know that this cannot be a designation, just parse the nested
    // initializer directly.
    ExprResult SubElt;
    if (!MayBeDesignationStart(Tok.getKind(), PP))
      SubElt = ParseInitializer();
    else
      SubElt = ParseInitializerWithPotentialDesignator(InitExprDesignations,
                                                       InitExprs.size());

    // If we couldn't parse the subelement, bail out.
    if (!SubElt.isInvalid) {
      InitExprs.push_back(SubElt.Val);
    } else {
      InitExprsOk = false;

      // We have two ways to try to recover from this error: if the code looks
      // gramatically ok (i.e. we have a comma coming up) try to continue
      // parsing the rest of the initializer.  This allows us to emit
      // diagnostics for later elements that we find.  If we don't see a comma,
      // assume there is a parse error, and just skip to recover.
      if (Tok.isNot(tok::comma)) {
        SkipUntil(tok::r_brace, false, true);
        break;
      }
    }

    // If we don't have a comma continued list, we're done.
    if (Tok.isNot(tok::comma)) break;

    // TODO: save comma locations if some client cares.
    ConsumeToken();

    // Handle trailing comma.
    if (Tok.is(tok::r_brace)) break;
  }
  if (InitExprsOk && Tok.is(tok::r_brace))
    return Actions.ActOnInitList(LBraceLoc, &InitExprs[0], InitExprs.size(),
                                 ConsumeBrace());

  // On error, delete any parsed subexpressions.
  for (unsigned i = 0, e = InitExprs.size(); i != e; ++i)
    Actions.DeleteExpr(InitExprs[i]);

  // Match the '}'.
  MatchRHSPunctuation(tok::r_brace, LBraceLoc);
  return ExprResult(true); // an error occurred.
}

<commit_msg>improve comments, build array and array range designator nodes,  fix an obscure memory leak.<commit_after>//===--- ParseInit.cpp - Initializer Parsing ------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements initializer parsing as specified by C99 6.7.8.
//
//===----------------------------------------------------------------------===//

#include "clang/Parse/Designator.h"
#include "clang/Parse/Parser.h"
#include "clang/Basic/Diagnostic.h"
#include "llvm/ADT/SmallString.h"
using namespace clang;

/// MayBeDesignationStart - Return true if this token might be the start of a
/// designator.  If we can tell it is impossible that it is a designator, return
/// false.
static bool MayBeDesignationStart(tok::TokenKind K, Preprocessor &PP) {
  switch (K) {
  default: return false;
  case tok::period:      // designator: '.' identifier
  case tok::l_square:    // designator: array-designator
      return true;
  case tok::identifier:  // designation: identifier ':'
    return PP.LookAhead(0).is(tok::colon);
  }
}

/// ParseInitializerWithPotentialDesignator - Parse the 'initializer' production
/// checking to see if the token stream starts with a designator.
///
///       designation:
///         designator-list '='
/// [GNU]   array-designator
/// [GNU]   identifier ':'
///
///       designator-list:
///         designator
///         designator-list designator
///
///       designator:
///         array-designator
///         '.' identifier
///
///       array-designator:
///         '[' constant-expression ']'
/// [GNU]   '[' constant-expression '...' constant-expression ']'
///
/// NOTE: [OBC] allows '[ objc-receiver objc-message-args ]' as an
/// initializer (because it is an expression).  We need to consider this case
/// when parsing array designators.
///
Parser::ExprResult Parser::
ParseInitializerWithPotentialDesignator(InitListDesignations &Designations,
                                        unsigned InitNum) {

  // If this is the old-style GNU extension:
  //   designation ::= identifier ':'
  // Handle it as a field designator.  Otherwise, this must be the start of a
  // normal expression.
  if (Tok.is(tok::identifier)) {
    Diag(Tok, diag::ext_gnu_old_style_field_designator);

    Designation &D = Designations.CreateDesignation(InitNum);
    D.AddDesignator(Designator::getField(Tok.getIdentifierInfo()));
    ConsumeToken(); // Eat the identifier.

    assert(Tok.is(tok::colon) && "MayBeDesignationStart not working properly!");
    ConsumeToken();
    return ParseInitializer();
  }

  // Desig - This is initialized when we see our first designator.  We may have
  // an objc message send with no designator, so we don't want to create this
  // eagerly.
  Designation *Desig = 0;

  // Parse each designator in the designator list until we find an initializer.
  while (Tok.is(tok::period) || Tok.is(tok::l_square)) {
    if (Tok.is(tok::period)) {
      // designator: '.' identifier
      ConsumeToken();

      // Create designation if we haven't already.
      if (Desig == 0)
        Desig = &Designations.CreateDesignation(InitNum);

      if (Tok.isNot(tok::identifier)) {
        Diag(Tok.getLocation(), diag::err_expected_field_designator);
        return ExprResult(true);
      }

      Desig->AddDesignator(Designator::getField(Tok.getIdentifierInfo()));
      ConsumeToken(); // Eat the identifier.
      continue;
    }

    // We must have either an array designator now or an objc message send.
    assert(Tok.is(tok::l_square) && "Unexpected token!");

    // Handle the two forms of array designator:
    //   array-designator: '[' constant-expression ']'
    //   array-designator: '[' constant-expression '...' constant-expression ']'
    //
    // Also, we have to handle the case where the expression after the
    // designator an an objc message send: '[' objc-message-expr ']'.
    // Interesting cases are:
    //   [foo bar]         -> objc message send
    //   [foo]             -> array designator
    //   [foo ... bar]     -> array designator
    //   [4][foo bar]      -> obsolete GNU designation with objc message send.
    //
    SourceLocation StartLoc = ConsumeBracket();

    // If Objective-C is enabled and this is a typename or other identifier
    // receiver, parse this as a message send expression.
    if (getLang().ObjC1 && isTokObjCMessageIdentifierReceiver()) {
      // FIXME: Emit ext_gnu_missing_equal_designator for inits like
      // [4][foo bar].
      IdentifierInfo *Name = Tok.getIdentifierInfo();
      ConsumeToken();
      return ParseAssignmentExprWithObjCMessageExprStart(StartLoc, Name, 0);
    }

    // Note that we parse this as an assignment expression, not a constant
    // expression (allowing *=, =, etc) to handle the objc case.  Sema needs
    // to validate that the expression is a constant.
    ExprResult Idx = ParseAssignmentExpression();
    if (Idx.isInvalid) {
      SkipUntil(tok::r_square);
      return Idx;
    }

    // Given an expression, we could either have a designator (if the next
    // tokens are '...' or ']' or an objc message send.  If this is an objc
    // message send, handle it now.  An objc-message send is the start of
    // an assignment-expression production.
    if (getLang().ObjC1 && Tok.isNot(tok::ellipsis) &&
        Tok.isNot(tok::r_square)) {
      // FIXME: Emit ext_gnu_missing_equal_designator for inits like
      // [4][foo bar].
      return ParseAssignmentExprWithObjCMessageExprStart(StartLoc, 0,Idx.Val);
    }

    // Create designation if we haven't already.
    if (Desig == 0)
      Desig = &Designations.CreateDesignation(InitNum);

    // If this is a normal array designator, remember it.
    if (Tok.isNot(tok::ellipsis)) {
      Desig->AddDesignator(Designator::getArray(Idx.Val));
    } else {
      // Handle the gnu array range extension.
      Diag(Tok, diag::ext_gnu_array_range);
      ConsumeToken();

      ExprResult RHS = ParseConstantExpression();
      if (RHS.isInvalid) {
        Actions.DeleteExpr(Idx.Val);
        SkipUntil(tok::r_square);
        return RHS;
      }
      Desig->AddDesignator(Designator::getArrayRange(Idx.Val, RHS.Val));
    }

    MatchRHSPunctuation(tok::r_square, StartLoc);
  }

  // Okay, we're done with the designator sequence.  We know that there must be
  // at least one designator, because the only case we can get into this method
  // without a designator is when we have an objc message send.  That case is
  // handled and returned from above.

  // Handle a normal designator sequence end, which is an equal.
  if (Tok.is(tok::equal)) {
    ConsumeToken();
    return ParseInitializer();
  }

  // We read some number of designators and found something that isn't an = or
  // an initializer.  If we have exactly one array designator [TODO CHECK], this
  // is the GNU 'designation: array-designator' extension.  Otherwise, it is a
  // parse error.
  SourceLocation Loc = Tok.getLocation();
  ExprResult Init = ParseInitializer();
  if (Init.isInvalid) return Init;

  Diag(Tok, diag::ext_gnu_missing_equal_designator);
  return Init;
}

/// ParseBraceInitializer - Called when parsing an initializer that has a
/// leading open brace.
///
///       initializer: [C99 6.7.8]
///         '{' initializer-list '}'
///         '{' initializer-list ',' '}'
/// [GNU]   '{' '}'
///
///       initializer-list:
///         designation[opt] initializer
///         initializer-list ',' designation[opt] initializer
///
Parser::ExprResult Parser::ParseBraceInitializer() {
  SourceLocation LBraceLoc = ConsumeBrace();

  // We support empty initializers, but tell the user that they aren't using
  // C99-clean code.
  if (Tok.is(tok::r_brace)) {
    Diag(LBraceLoc, diag::ext_gnu_empty_initializer);
    // Match the '}'.
    return Actions.ActOnInitList(LBraceLoc, 0, 0, ConsumeBrace());
  }

  /// InitExprs - This is the actual list of expressions contained in the
  /// initializer.
  llvm::SmallVector<ExprTy*, 8> InitExprs;

  /// ExprDesignators - For each initializer, keep track of the designator that
  /// was specified for it, if any.
  InitListDesignations InitExprDesignations(Actions);

  bool InitExprsOk = true;

  while (1) {
    // Parse: designation[opt] initializer

    // If we know that this cannot be a designation, just parse the nested
    // initializer directly.
    ExprResult SubElt;
    if (!MayBeDesignationStart(Tok.getKind(), PP))
      SubElt = ParseInitializer();
    else
      SubElt = ParseInitializerWithPotentialDesignator(InitExprDesignations,
                                                       InitExprs.size());

    // If we couldn't parse the subelement, bail out.
    if (!SubElt.isInvalid) {
      InitExprs.push_back(SubElt.Val);
    } else {
      InitExprsOk = false;

      // We have two ways to try to recover from this error: if the code looks
      // gramatically ok (i.e. we have a comma coming up) try to continue
      // parsing the rest of the initializer.  This allows us to emit
      // diagnostics for later elements that we find.  If we don't see a comma,
      // assume there is a parse error, and just skip to recover.
      if (Tok.isNot(tok::comma)) {
        SkipUntil(tok::r_brace, false, true);
        break;
      }
    }

    // If we don't have a comma continued list, we're done.
    if (Tok.isNot(tok::comma)) break;

    // TODO: save comma locations if some client cares.
    ConsumeToken();

    // Handle trailing comma.
    if (Tok.is(tok::r_brace)) break;
  }
  if (InitExprsOk && Tok.is(tok::r_brace))
    return Actions.ActOnInitList(LBraceLoc, &InitExprs[0], InitExprs.size(),
                                 ConsumeBrace());

  // On error, delete any parsed subexpressions.
  for (unsigned i = 0, e = InitExprs.size(); i != e; ++i)
    Actions.DeleteExpr(InitExprs[i]);

  // Match the '}'.
  MatchRHSPunctuation(tok::r_brace, LBraceLoc);
  return ExprResult(true); // an error occurred.
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: sychconv.hxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: hr $ $Date: 2000-09-18 16:58:53 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SYCHCONV_HXX
#define _SYCHCONV_HXX

#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _SV_FONT_HXX
#include <vcl/font.hxx>
#endif

// ----------------------
// - CharacterConverter -
// ----------------------

class OutputDevice;

class SymCharConverter
{
public:

    static const BOOL   Convert( Font& rFont, UniString& rString, OutputDevice* pDev = NULL );
};

#endif // _CHARCONV_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.1110); FILE MERGED 2005/09/05 14:51:11 rt 1.1.1.1.1110.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: sychconv.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 14:05:49 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SYCHCONV_HXX
#define _SYCHCONV_HXX

#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _SV_FONT_HXX
#include <vcl/font.hxx>
#endif

// ----------------------
// - CharacterConverter -
// ----------------------

class OutputDevice;

class SymCharConverter
{
public:

    static const BOOL   Convert( Font& rFont, UniString& rString, OutputDevice* pDev = NULL );
};

#endif // _CHARCONV_HXX
<|endoftext|>


<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2013 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#include "nearest_neighbor.hpp"

#include <string>
#include <utility>
#include <vector>
#include "../table/column/row_deleter.hpp"
#include "../fv_converter/weight_manager.hpp"
#include "../fv_converter/mixable_weight_manager.hpp"

namespace jubatus {
namespace core {
namespace driver {

using jubatus::util::lang::shared_ptr;
using fv_converter::mixable_weight_manager;
using fv_converter::weight_manager;

nearest_neighbor::nearest_neighbor(
    shared_ptr<core::nearest_neighbor::nearest_neighbor_base> nn,
    shared_ptr<fv_converter::datum_to_fv_converter> converter)
    : converter_(converter),
      nn_(nn),
      wm_(mixable_weight_manager::model_ptr(new weight_manager)) {
  register_mixable(nn_->get_mixable());
  register_mixable(&wm_);

  converter_->set_weight_manager(wm_.get_model());
}

nearest_neighbor::nearest_neighbor(
    shared_ptr<core::nearest_neighbor::nearest_neighbor_base> nn,
    shared_ptr<fv_converter::datum_to_fv_converter> converter,
    shared_ptr<unlearner::unlearner_base> unlearner)
    : converter_(converter),
      nn_(nn),
      unlearner_(unlearner),
      wm_(mixable_weight_manager::model_ptr(new weight_manager)) {
  register_mixable(nn_->get_mixable());
  register_mixable(&wm_);

  converter_->set_weight_manager(wm_.get_model());
  unlearner->set_callback(table::row_deleter(nn_->get_table()));
}

void nearest_neighbor::set_row(
    const std::string& id,
    const fv_converter::datum& datum) {
  if (unlearner_) {
    unlearner_->touch(id);
  }
  common::sfv_t v;
  converter_->convert(datum, v);
  nn_->set_row(id, v);
}

std::vector<std::pair<std::string, float> >
nearest_neighbor::neighbor_row_from_id(const std::string& id, size_t size) {
  std::vector<std::pair<std::string, float> > ret;
  nn_->neighbor_row(id, ret, size);
  return ret;
}

std::vector<std::pair<std::string, float> >
nearest_neighbor::neighbor_row_from_datum(
    const fv_converter::datum& datum,
    size_t size) {
  common::sfv_t v;
  converter_->convert(datum, v);
  std::vector<std::pair<std::string, float> > ret;
  nn_->neighbor_row(v, ret, size);
  return ret;
}

std::vector<std::pair<std::string, float> >
nearest_neighbor::similar_row(const std::string& id, size_t ret_num) {
  std::vector<std::pair<std::string, float> > ret;
  nn_->similar_row(id, ret, ret_num);
  return ret;
}

std::vector<std::pair<std::string, float> >
nearest_neighbor::similar_row(
    const core::fv_converter::datum& datum,
    size_t ret_num) {
  common::sfv_t v;
  converter_->convert(datum, v);
  std::vector<std::pair<std::string, float> > ret;
  nn_->similar_row(v, ret, ret_num);
  return ret;
}

void nearest_neighbor::clear() {
  converter_->clear_weights();
  nn_->clear();
  if (unlearner_) {
    unlearner_->clear();
  }
}

void nearest_neighbor::pack(framework::packer& pk) const {
  pk.pack_array(2);
  nn_->pack(pk);
  wm_.get_model()->pack(pk);
}

void nearest_neighbor::unpack(msgpack::object o) {
  if (o.type != msgpack::type::ARRAY || o.via.array.size != 2) {
    throw msgpack::type_error();
  }

  // clear
  nn_->clear();
  converter_->clear_weights();

  // load
  nn_->unpack(o.via.array.ptr[0]);
  wm_.get_model()->unpack(o.via.array.ptr[1]);
}

}  // namespace driver
}  // namespace core
}  // namespace jubatus
<commit_msg>fix nearest_neighbor to update weights on set_row (fix #99)<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2013 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#include "nearest_neighbor.hpp"

#include <string>
#include <utility>
#include <vector>
#include "../table/column/row_deleter.hpp"
#include "../fv_converter/weight_manager.hpp"
#include "../fv_converter/mixable_weight_manager.hpp"

namespace jubatus {
namespace core {
namespace driver {

using jubatus::util::lang::shared_ptr;
using fv_converter::mixable_weight_manager;
using fv_converter::weight_manager;

nearest_neighbor::nearest_neighbor(
    shared_ptr<core::nearest_neighbor::nearest_neighbor_base> nn,
    shared_ptr<fv_converter::datum_to_fv_converter> converter)
    : converter_(converter),
      nn_(nn),
      wm_(mixable_weight_manager::model_ptr(new weight_manager)) {
  register_mixable(nn_->get_mixable());
  register_mixable(&wm_);

  converter_->set_weight_manager(wm_.get_model());
}

nearest_neighbor::nearest_neighbor(
    shared_ptr<core::nearest_neighbor::nearest_neighbor_base> nn,
    shared_ptr<fv_converter::datum_to_fv_converter> converter,
    shared_ptr<unlearner::unlearner_base> unlearner)
    : converter_(converter),
      nn_(nn),
      unlearner_(unlearner),
      wm_(mixable_weight_manager::model_ptr(new weight_manager)) {
  register_mixable(nn_->get_mixable());
  register_mixable(&wm_);

  converter_->set_weight_manager(wm_.get_model());
  unlearner->set_callback(table::row_deleter(nn_->get_table()));
}

void nearest_neighbor::set_row(
    const std::string& id,
    const fv_converter::datum& datum) {
  if (unlearner_) {
    unlearner_->touch(id);
  }
  common::sfv_t v;
  converter_->convert_and_update_weight(datum, v);
  nn_->set_row(id, v);
}

std::vector<std::pair<std::string, float> >
nearest_neighbor::neighbor_row_from_id(const std::string& id, size_t size) {
  std::vector<std::pair<std::string, float> > ret;
  nn_->neighbor_row(id, ret, size);
  return ret;
}

std::vector<std::pair<std::string, float> >
nearest_neighbor::neighbor_row_from_datum(
    const fv_converter::datum& datum,
    size_t size) {
  common::sfv_t v;
  converter_->convert(datum, v);
  std::vector<std::pair<std::string, float> > ret;
  nn_->neighbor_row(v, ret, size);
  return ret;
}

std::vector<std::pair<std::string, float> >
nearest_neighbor::similar_row(const std::string& id, size_t ret_num) {
  std::vector<std::pair<std::string, float> > ret;
  nn_->similar_row(id, ret, ret_num);
  return ret;
}

std::vector<std::pair<std::string, float> >
nearest_neighbor::similar_row(
    const core::fv_converter::datum& datum,
    size_t ret_num) {
  common::sfv_t v;
  converter_->convert(datum, v);
  std::vector<std::pair<std::string, float> > ret;
  nn_->similar_row(v, ret, ret_num);
  return ret;
}

void nearest_neighbor::clear() {
  converter_->clear_weights();
  nn_->clear();
  if (unlearner_) {
    unlearner_->clear();
  }
}

void nearest_neighbor::pack(framework::packer& pk) const {
  pk.pack_array(2);
  nn_->pack(pk);
  wm_.get_model()->pack(pk);
}

void nearest_neighbor::unpack(msgpack::object o) {
  if (o.type != msgpack::type::ARRAY || o.via.array.size != 2) {
    throw msgpack::type_error();
  }

  // clear
  nn_->clear();
  converter_->clear_weights();

  // load
  nn_->unpack(o.via.array.ptr[0]);
  wm_.get_model()->unpack(o.via.array.ptr[1]);
}

}  // namespace driver
}  // namespace core
}  // namespace jubatus
<|endoftext|>


<commit_before>/*
 Copyright (c) 2015, The Cinder Project, All rights reserved.

 This code is intended for use with the Cinder C++ library: http://libcinder.org

 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.

 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 "cinder/gl/ShaderPreprocessor.h"
#include "cinder/app/App.h"
#include "cinder/Utilities.h"
#include "cinder/Log.h"

#include <regex>

using namespace std;

namespace cinder { namespace gl {

namespace {
	const regex sIncludeRegex = regex( "^[ ]*#[ ]*include[ ]+[\"<](.*)[\">].*" );
} // anonymous namespace

ShaderPreprocessor::ShaderPreprocessor()
	: mCachingEnabled( true )
{
	// TODO: we discussed keeping this ci assets agnostic, instead adding getAssetPath() from the outside
	// - also, we don't want GlslProg to rely on App at all.
	//    - can it do what it needs to with Platform?
	mSearchDirectories.push_back( app::getAssetPath( "" ) );
}

string ShaderPreprocessor::parse( const fs::path &path )
{
	set<fs::path> includeTree;

	return parseRecursive( path, fs::path(), includeTree );
}

string ShaderPreprocessor::parse( const std::string &source, const fs::path &sourceDirectory )
{
	return parseTopLevel( source, sourceDirectory );
}

string ShaderPreprocessor::parseTopLevel( const string &source, const fs::path &currentDirectory )
{
	set<fs::path> includeTree;

	stringstream output;
	istringstream input( source );

	// go through each line and process includes
	string line;
	smatch matches;

	size_t lineNumber = 1;

	while( getline( input, line ) ) {
		if( regex_search( line, matches, sIncludeRegex ) ) {
			output << parseRecursive( matches[1].str(), currentDirectory, includeTree );
			output << "#line " << lineNumber << endl;
		}
		else
			output << line;

		output << endl;
		lineNumber++;
	}

	return output.str();
}

string ShaderPreprocessor::parseRecursive( const fs::path &path, const fs::path &currentDirectory, set<fs::path> &includeTree )
{
	const fs::path fullPath = findFullPath( path, currentDirectory );

	if( includeTree.count( fullPath ) )
		throw ShaderPreprocessorExc( "circular include found, path: " + fullPath.string() );

	includeTree.insert( fullPath );

	time_t timeLastWrite = 0;
	if( mCachingEnabled ) {
		timeLastWrite = fs::last_write_time( fullPath );

		auto cachedIt = mCachedSources.find( fullPath );
		if( cachedIt != mCachedSources.end() ) {
			if( cachedIt->second.mTimeLastWrite >= timeLastWrite ) {
				return cachedIt->second.mString;
			}
		}
	}

	stringstream output;

	ifstream input( fullPath.c_str() );
	if( ! input.is_open() )
		throw ShaderPreprocessorExc( "Failed to open file at path: " + fullPath.string() );

	// go through each line and process includes
	string line;
	smatch matches;

	size_t lineNumber = 1;

	while( getline( input, line ) ) {
		if( regex_search( line, matches, sIncludeRegex ) ) {
			output << parseRecursive( matches[1].str(), fullPath.parent_path(), includeTree );
			output << "#line " << lineNumber << endl;
		}
		else
			output << line;

		output << endl;
		lineNumber++;
	}

	input.close();

	if( mCachingEnabled ) {
		Source &source = mCachedSources[fullPath];
		source.mTimeLastWrite = timeLastWrite;
		source.mString = output.str();

		return source.mString;
	}
	else
		return output.str();
}

void ShaderPreprocessor::addSearchDirectory( const fs::path &directory )
{
	if( ! fs::is_directory( directory ) ) {
		CI_LOG_E( "Not a directory: " << directory );
		return;
	}

	fs::path dirCanonical = fs::canonical( directory );
	auto it = find( mSearchDirectories.begin(), mSearchDirectories.end(), dirCanonical );
	if( it == mSearchDirectories.end() )
		mSearchDirectories.push_back( dirCanonical );
}

void ShaderPreprocessor::removeSearchDirectory( const fs::path &directory )
{
	fs::path dirCanonical = fs::canonical( directory );
	mSearchDirectories.erase( remove( mSearchDirectories.begin(), mSearchDirectories.end(), dirCanonical ), mSearchDirectories.end() );
}

void ShaderPreprocessor::clearCache()
{
	mCachedSources.clear();
}

fs::path ShaderPreprocessor::findFullPath( const fs::path &includePath, const fs::path &currentDirectory )
{
	auto fullPath = currentDirectory / includePath;
	if( fs::exists( fullPath ) )
		return fs::canonical( fullPath );

	for( auto dirIt = mSearchDirectories.rbegin(); dirIt != mSearchDirectories.rend(); ++dirIt ) {
		fullPath = *dirIt / includePath;
		if( fs::exists( fullPath ) )
			return fs::canonical( fullPath );
	}

	throw ShaderPreprocessorExc( "could not find shader with include path: " + includePath.string() );
}

} } // namespace cinder::gl
<commit_msg>ShaderPreprocessor sets the default lookup path with app::Platform instead of app inlined method<commit_after>/*
 Copyright (c) 2015, The Cinder Project, All rights reserved.

 This code is intended for use with the Cinder C++ library: http://libcinder.org

 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.

 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 "cinder/gl/ShaderPreprocessor.h"
#include "cinder/app/Platform.h"
#include "cinder/Utilities.h"
#include "cinder/Log.h"

#include <regex>

using namespace std;

namespace cinder { namespace gl {

namespace {
	const regex sIncludeRegex = regex( "^[ ]*#[ ]*include[ ]+[\"<](.*)[\">].*" );
} // anonymous namespace

ShaderPreprocessor::ShaderPreprocessor()
	: mCachingEnabled( true )
{
	mSearchDirectories.push_back( app::Platform::get()->getAssetPath( "" ) );
}

string ShaderPreprocessor::parse( const fs::path &path )
{
	set<fs::path> includeTree;

	return parseRecursive( path, fs::path(), includeTree );
}

string ShaderPreprocessor::parse( const std::string &source, const fs::path &sourceDirectory )
{
	return parseTopLevel( source, sourceDirectory );
}

string ShaderPreprocessor::parseTopLevel( const string &source, const fs::path &currentDirectory )
{
	set<fs::path> includeTree;

	stringstream output;
	istringstream input( source );

	// go through each line and process includes
	string line;
	smatch matches;

	size_t lineNumber = 1;

	while( getline( input, line ) ) {
		if( regex_search( line, matches, sIncludeRegex ) ) {
			output << parseRecursive( matches[1].str(), currentDirectory, includeTree );
			output << "#line " << lineNumber << endl;
		}
		else
			output << line;

		output << endl;
		lineNumber++;
	}

	return output.str();
}

string ShaderPreprocessor::parseRecursive( const fs::path &path, const fs::path &currentDirectory, set<fs::path> &includeTree )
{
	const fs::path fullPath = findFullPath( path, currentDirectory );

	if( includeTree.count( fullPath ) )
		throw ShaderPreprocessorExc( "circular include found, path: " + fullPath.string() );

	includeTree.insert( fullPath );

	time_t timeLastWrite = 0;
	if( mCachingEnabled ) {
		timeLastWrite = fs::last_write_time( fullPath );

		auto cachedIt = mCachedSources.find( fullPath );
		if( cachedIt != mCachedSources.end() ) {
			if( cachedIt->second.mTimeLastWrite >= timeLastWrite ) {
				return cachedIt->second.mString;
			}
		}
	}

	stringstream output;

	ifstream input( fullPath.c_str() );
	if( ! input.is_open() )
		throw ShaderPreprocessorExc( "Failed to open file at path: " + fullPath.string() );

	// go through each line and process includes
	string line;
	smatch matches;

	size_t lineNumber = 1;

	while( getline( input, line ) ) {
		if( regex_search( line, matches, sIncludeRegex ) ) {
			output << parseRecursive( matches[1].str(), fullPath.parent_path(), includeTree );
			output << "#line " << lineNumber << endl;
		}
		else
			output << line;

		output << endl;
		lineNumber++;
	}

	input.close();

	if( mCachingEnabled ) {
		Source &source = mCachedSources[fullPath];
		source.mTimeLastWrite = timeLastWrite;
		source.mString = output.str();

		return source.mString;
	}
	else
		return output.str();
}

void ShaderPreprocessor::addSearchDirectory( const fs::path &directory )
{
	if( ! fs::is_directory( directory ) ) {
		CI_LOG_E( "Not a directory: " << directory );
		return;
	}

	fs::path dirCanonical = fs::canonical( directory );
	auto it = find( mSearchDirectories.begin(), mSearchDirectories.end(), dirCanonical );
	if( it == mSearchDirectories.end() )
		mSearchDirectories.push_back( dirCanonical );
}

void ShaderPreprocessor::removeSearchDirectory( const fs::path &directory )
{
	fs::path dirCanonical = fs::canonical( directory );
	mSearchDirectories.erase( remove( mSearchDirectories.begin(), mSearchDirectories.end(), dirCanonical ), mSearchDirectories.end() );
}

void ShaderPreprocessor::clearCache()
{
	mCachedSources.clear();
}

fs::path ShaderPreprocessor::findFullPath( const fs::path &includePath, const fs::path &currentDirectory )
{
	auto fullPath = currentDirectory / includePath;
	if( fs::exists( fullPath ) )
		return fs::canonical( fullPath );

	for( auto dirIt = mSearchDirectories.rbegin(); dirIt != mSearchDirectories.rend(); ++dirIt ) {
		fullPath = *dirIt / includePath;
		if( fs::exists( fullPath ) )
			return fs::canonical( fullPath );
	}

	throw ShaderPreprocessorExc( "could not find shader with include path: " + includePath.string() );
}

} } // namespace cinder::gl
<|endoftext|>


<commit_before>//----------------------------------*-C++-*----------------------------------//
/*!
 * \file   spn/Solver_Base.hh
 * \author Thomas M. Evans
 * \date   Mon Feb 17 20:36:54 2014
 * \brief  Solver_Base class definition.
 * \note   Copyright (C) 2014 Oak Ridge National Laboratory, UT-Battelle, LLC.
 */
//---------------------------------------------------------------------------//

#ifndef spn_Solver_Base_hh
#define spn_Solver_Base_hh

#include "Teuchos_RCP.hpp"

#include "State.hh"
#include "Linear_System.hh"
#include "VectorTraits.hh"
#include "Isotropic_Source.hh"
#include "solvers/LinAlgTypedefs.hh"

namespace profugus
{

//===========================================================================//
/*!
 * \class Solver_Base
 * \brief Base class for SPN solvers (fixed-source and eigenvalue).
 */
/*!
 * \example spn/test/tstSolver_Base.cc
 *
 * Test of Solver_Base.
 */
//===========================================================================//

class Solver_Base
{
  public:
    //@{
    //! Typedefs.
    typedef Teuchos::RCP<Dimensions>           RCP_Dimensions;
    typedef Teuchos::RCP<Mat_DB>               RCP_Mat_DB;
    typedef Teuchos::RCP<Mesh>                 RCP_Mesh;
    typedef Teuchos::RCP<LG_Indexer>           RCP_Indexer;
    typedef Teuchos::RCP<Global_Mesh_Data>     RCP_Global_Data;
    typedef Isotropic_Source                   External_Source;
    typedef State::View_Field                  View_Field;
    //@}

  public:
    // Constructor.
    Solver_Base(){};

    // Virtual destructor.
    virtual ~Solver_Base(){};

    // Set up the solver.
    virtual void setup(RCP_Dimensions dim, RCP_Mat_DB mat, RCP_Mesh mesh,
                       RCP_Indexer indexer, RCP_Global_Data data) = 0;

    // Solve problem
    virtual void solve(Teuchos::RCP<const External_Source> q) = 0;

    //! Write results of solve into state.
    virtual void write_state(State &state) = 0;

    //! Write problem matrix (or matrices to file)
    virtual void write_problem_to_file() const = 0;

};

//===========================================================================//
/*!
 * \class Solver_Base_Tmpl
 * \brief Templated base class for SPN solvers (fixed-source and eigenvalue).
 */
//===========================================================================//
template <class T>
class Solver_Base_Tmpl : public Solver_Base
{
  protected:

    using Solver_Base::RCP_Dimensions;
    using Solver_Base::RCP_Mat_DB;
    using Solver_Base::RCP_Mesh;
    using Solver_Base::RCP_Indexer;
    using Solver_Base::RCP_Global_Data;
    using Solver_Base::View_Field;

    typedef typename T::VECTOR            Vector_t;
    typedef Teuchos::ParameterList        ParameterList;
    typedef Teuchos::RCP<ParameterList>   RCP_ParameterList;
    typedef Linear_System<T>              Linear_System_t;
    typedef Teuchos::RCP<Linear_System_t> RCP_Linear_System;

    // Linear system.
    RCP_Linear_System b_system;

    // Problem database.
    RCP_ParameterList b_db;

  public:

    Solver_Base_Tmpl(RCP_ParameterList db)
    {
        b_db = db;
    }

    virtual ~Solver_Base_Tmpl(){};

    const Linear_System_t &get_linear_system(){return *b_system;}

    // >>> INHERITED METHODS

    // Write u-vector into the state.
    void write_u_into_state(Teuchos::RCP<const Vector_t>, State &state);

};

//===========================================================================//
/*!
 * \brief Write a u-vector into the state.
 */
template <class T>
void Solver_Base_Tmpl<T>::write_u_into_state(Teuchos::RCP<const Vector_t>  u,
                                             State                  &state)
{
    REQUIRE(state.num_cells() * b_system->get_dims()->num_equations()
             * state.num_groups() <=
             VectorTraits<T>::local_length(u));
    REQUIRE(state.num_cells() == state.mesh().num_cells());

    // SPN moments
    double u_m[4] = {0.0, 0.0, 0.0, 0.0};

    // number of equations (moments) in the SPN solution
    int N = b_system->get_dims()->num_equations();

    // number of groups
    int Ng = state.num_groups();

    // number of local cells
    int Nc = state.num_cells();

    // the state field is ordered group->cell whereas the u vector is
    // ordered cell->moments->group

    Teuchos::ArrayView<const double> data = VectorTraits<T>::get_data(u);

    // loop over groups
    for (int g = 0; g < Ng; ++g)
    {
        // get all the fluxes for this group
        View_Field flux = state.flux(g, g);
        CHECK(flux.size() == Nc);

        // loop over cells on this domain
        for (int cell = 0; cell < Nc; ++cell)
        {
            // loop over moments
            for (int n = 0; n < N; ++n)
            {
                CHECK(b_system->index(g, n, cell) <
                      VectorTraits<T>::local_length(u) );

                // get the moment from the solution vector
                u_m[n] = data[b_system->index(g, n, cell)];
            }

            // assign the scalar flux (SPN Phi_0 moment) to the state ->
            // CURRENTLY WE ONLY SUPPORT 1 UNKNOWN PER CELL
            flux[cell] =  Moment_Coefficients::u_to_phi(
                u_m[0], u_m[1], u_m[2], u_m[3]);
        }
    }
}

} // end namespace profugus

#endif // spn_Solver_Base_hh

//---------------------------------------------------------------------------//
//                 end of Solver_Base.hh
//---------------------------------------------------------------------------//
<commit_msg>Fixing some const-correctness issues.<commit_after>//----------------------------------*-C++-*----------------------------------//
/*!
 * \file   spn/Solver_Base.hh
 * \author Thomas M. Evans
 * \date   Mon Feb 17 20:36:54 2014
 * \brief  Solver_Base class definition.
 * \note   Copyright (C) 2014 Oak Ridge National Laboratory, UT-Battelle, LLC.
 */
//---------------------------------------------------------------------------//

#ifndef spn_Solver_Base_hh
#define spn_Solver_Base_hh

#include "Teuchos_RCP.hpp"

#include "State.hh"
#include "Linear_System.hh"
#include "VectorTraits.hh"
#include "Isotropic_Source.hh"
#include "solvers/LinAlgTypedefs.hh"

namespace profugus
{

//===========================================================================//
/*!
 * \class Solver_Base
 * \brief Base class for SPN solvers (fixed-source and eigenvalue).
 */
/*!
 * \example spn/test/tstSolver_Base.cc
 *
 * Test of Solver_Base.
 */
//===========================================================================//

class Solver_Base
{
  public:
    //@{
    //! Typedefs.
    typedef Teuchos::RCP<Dimensions>           RCP_Dimensions;
    typedef Teuchos::RCP<Mat_DB>               RCP_Mat_DB;
    typedef Teuchos::RCP<Mesh>                 RCP_Mesh;
    typedef Teuchos::RCP<LG_Indexer>           RCP_Indexer;
    typedef Teuchos::RCP<Global_Mesh_Data>     RCP_Global_Data;
    typedef Isotropic_Source                   External_Source;
    typedef State::View_Field                  View_Field;
    //@}

  public:
    // Constructor.
    Solver_Base(){};

    // Virtual destructor.
    virtual ~Solver_Base(){};

    // Set up the solver.
    virtual void setup(RCP_Dimensions dim, RCP_Mat_DB mat, RCP_Mesh mesh,
                       RCP_Indexer indexer, RCP_Global_Data data) = 0;

    // Solve problem
    virtual void solve(Teuchos::RCP<const External_Source> q) = 0;

    //! Write results of solve into state.
    virtual void write_state(State &state) = 0;

    //! Write problem matrix (or matrices to file)
    virtual void write_problem_to_file() const = 0;

};

//===========================================================================//
/*!
 * \class Solver_Base_Tmpl
 * \brief Templated base class for SPN solvers (fixed-source and eigenvalue).
 */
//===========================================================================//
template <class T>
class Solver_Base_Tmpl : public Solver_Base
{
  protected:

    using Solver_Base::RCP_Dimensions;
    using Solver_Base::RCP_Mat_DB;
    using Solver_Base::RCP_Mesh;
    using Solver_Base::RCP_Indexer;
    using Solver_Base::RCP_Global_Data;
    using Solver_Base::View_Field;

    typedef typename T::VECTOR            Vector_t;
    typedef Teuchos::ParameterList        ParameterList;
    typedef Teuchos::RCP<ParameterList>   RCP_ParameterList;
    typedef Linear_System<T>              Linear_System_t;
    typedef Teuchos::RCP<Linear_System_t> RCP_Linear_System;

    // Linear system.
    RCP_Linear_System b_system;

    // Problem database.
    RCP_ParameterList b_db;

  public:

    Solver_Base_Tmpl(RCP_ParameterList db)
    {
        b_db = db;
    }

    virtual ~Solver_Base_Tmpl(){};

    const Linear_System_t &get_linear_system() const {return *b_system;}

    // >>> INHERITED METHODS

    // Write u-vector into the state.
    void write_u_into_state(Teuchos::RCP<const Vector_t>, State &state) const;

};

//===========================================================================//
/*!
 * \brief Write a u-vector into the state.
 */
template <class T>
void Solver_Base_Tmpl<T>::write_u_into_state(Teuchos::RCP<const Vector_t>  u,
                                             State &state) const
{
    REQUIRE(state.num_cells() * b_system->get_dims()->num_equations()
             * state.num_groups() <=
             VectorTraits<T>::local_length(u));
    REQUIRE(state.num_cells() == state.mesh().num_cells());

    // SPN moments
    double u_m[4] = {0.0, 0.0, 0.0, 0.0};

    // number of equations (moments) in the SPN solution
    int N = b_system->get_dims()->num_equations();

    // number of groups
    int Ng = state.num_groups();

    // number of local cells
    int Nc = state.num_cells();

    // the state field is ordered group->cell whereas the u vector is
    // ordered cell->moments->group

    Teuchos::ArrayView<const double> data = VectorTraits<T>::get_data(u);

    // loop over groups
    for (int g = 0; g < Ng; ++g)
    {
        // get all the fluxes for this group
        View_Field flux = state.flux(g, g);
        CHECK(flux.size() == Nc);

        // loop over cells on this domain
        for (int cell = 0; cell < Nc; ++cell)
        {
            // loop over moments
            for (int n = 0; n < N; ++n)
            {
                CHECK(b_system->index(g, n, cell) <
                      VectorTraits<T>::local_length(u) );

                // get the moment from the solution vector
                u_m[n] = data[b_system->index(g, n, cell)];
            }

            // assign the scalar flux (SPN Phi_0 moment) to the state ->
            // CURRENTLY WE ONLY SUPPORT 1 UNKNOWN PER CELL
            flux[cell] =  Moment_Coefficients::u_to_phi(
                u_m[0], u_m[1], u_m[2], u_m[3]);
        }
    }
}

} // end namespace profugus

#endif // spn_Solver_Base_hh

//---------------------------------------------------------------------------//
//                 end of Solver_Base.hh
//---------------------------------------------------------------------------//
<|endoftext|>


<commit_before>#include <QTranslator>

#include <QApplication>
#include <QDebug>
#include <QFile>

#include "mainUI.h"
#include "mainWindow.h"
#include <LuminaOS.h>
#include <LuminaUtils.h>
#include <LuminaThemes.h>
#include <LuminaSingleApplication.h>

int main(int argc, char ** argv)
{
    LTHEME::LoadCustomEnvSettings();
    LSingleApplication a(argc, argv, "lumina-config"); //loads translations inside constructor
    if(!a.isPrimaryProcess()){ return 0; }

    LuminaThemeEngine theme(&a);

    //MainUI w;
    mainWindow w;
    QObject::connect(&a, SIGNAL(InputsAvailable(QStringList)), &w, SLOT(slotSingleInstance()) );
    QObject::connect(&theme, SIGNAL(updateIcons()), &w, SLOT(setupIcons()) );
    w.show();

    int retCode = a.exec();
    return retCode;
}
<commit_msg>Re-enable the old UI - only 2 more pages left to convert before switching to the new interface completely.<commit_after>#include <QTranslator>

#include <QApplication>
#include <QDebug>
#include <QFile>

#include "mainUI.h"
#include "mainWindow.h"
#include <LuminaOS.h>
#include <LuminaUtils.h>
#include <LuminaThemes.h>
#include <LuminaSingleApplication.h>

int main(int argc, char ** argv)
{
    LTHEME::LoadCustomEnvSettings();
    LSingleApplication a(argc, argv, "lumina-config"); //loads translations inside constructor
    if(!a.isPrimaryProcess()){ return 0; }

    LuminaThemeEngine theme(&a);

    MainUI w;
    //mainWindow w;
    QObject::connect(&a, SIGNAL(InputsAvailable(QStringList)), &w, SLOT(slotSingleInstance()) );
    QObject::connect(&theme, SIGNAL(updateIcons()), &w, SLOT(setupIcons()) );
    w.show();

    int retCode = a.exec();
    return retCode;
}
<|endoftext|>