text:
/*
 * This file is part of the CitizenFX project - http://citizen.re/
 *
 * See LICENSE and MENTIONS in the root of the source tree for information
 * regarding licensing.
 */

#include "StdInc.h"
#include "EpisodeManager.h"
#include "InitializerFactory.h"

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>

class EpisodeSourceNorthNY : public EpisodeSource
{
private:
	fwRefContainer<Episode> CreateNorthEpisode(const std::wstring& path);

public:
	virtual std::vector<fwRefContainer<Episode>> GetEpisodes() override;
};

std::vector<fwRefContainer<Episode>> EpisodeSourceNorthNY::GetEpisodes()
{
	std::vector<fwRefContainer<Episode>> retval;

	// obtain the EFLC InstallPath value from the registry.
	// this value *should* always exist _for EFLC_, as without it EFLC.exe will not start.
	wchar_t installPath[MAX_PATH];
	DWORD installPathSize = sizeof(installPath); // we don't reallocate as Win32 doesn't support larger paths using typical DosDevices syntax anyway

	DWORD result = RegGetValue(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Rockstar Games\\EFLC", L"InstallFolder", RRF_RT_REG_SZ, nullptr, reinterpret_cast<LPBYTE>(installPath), &installPathSize);

	if (result == ERROR_SUCCESS)
	{
		DWORD folderAttributes = GetFileAttributes(installPath);

		if (folderAttributes != INVALID_FILE_ATTRIBUTES && (folderAttributes & FILE_ATTRIBUTE_DIRECTORY))
		{
			// add episodes based on, well, these
			auto addEpisode = [&] (const wchar_t* namePart)
			{
				std::wstring epPath = va(L"%s\\%s\\setup2.xml", installPath, namePart);
				fwRefContainer<Episode> episode = CreateNorthEpisode(epPath);

				if (episode.GetRef())
				{
					retval.push_back(episode);
				}
			};

			addEpisode(L"TLaD");
			addEpisode(L"TBoGT");
		}
	}

	return retval;
}

fwRefContainer<Episode> EpisodeSourceNorthNY::CreateNorthEpisode(const std::wstring& path)
{
	std::ifstream stream;
	stream.open(path);

	fwRefContainer<Episode> retval;

	try
	{
		boost::property_tree::ptree pt;
		boost::property_tree::read_xml(stream, pt);

		// iterate through all ini.content nodes
		for (auto& child : pt.get_child("ini"))
		{
			// try to get the 'episode' identifier
			auto& episodeIdRef = child.second.get_optional<int>("episode");

			// if this is actually an episode...
			if (episodeIdRef.is_initialized())
			{
				// get the episode ID and name
				int episodeId = episodeIdRef.value();
				std::string episodeName = child.second.get<std::string>("name");

				// convert the path to non-wide string as the game uses ANSI functions anyway
				char outPath[256];
				wcstombs(outPath, path.c_str(), sizeof(outPath));

				retval = new Episode();
				retval->SetIdentifier(std::string(va("gta-ny-dlc-%d@rockstarnorth.com", child.second.get<int>("id"))));
				retval->SetName(episodeName);
				retval->SetEpisodeInitializer(InitializerFactory::GetSinglePlayerInitializer(episodeId, outPath));
			}
		}
	}
	catch (...)
	{
		trace("parsing of an episode file failed.\n");
	}

	return retval;
}

static InitFunction initFunction([] ()
{
	Instance<EpisodeManager>::Get()->AddEpisodeSource(new EpisodeSourceNorthNY());
});

max_issues_repo_name: Zuiron/FiveM

max_forks_repo_name: Zuiron/FiveM


text:
/*****************************************************************************
 * Licensed to Qualys, Inc. (QUALYS) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * QUALYS licenses this file to You under the Apache License, Version 2.0
 * (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ****************************************************************************/

/**
 * @file
 * @brief IronBee --- CLIPP Protobuf Consumer Implementation
 *
 * @author Christopher Alfeld <calfeld@qualys.com>
 */

#include "ironbee_config_auto.h"

#include "pb_consumer.hpp"

#include <clipp/clipp.pb.h>

#ifdef __clang__
#pragma clang diagnostic push
#if __has_warning("-Wunused-local-typedef")
#pragma clang diagnostic ignored "-Wunused-local-typedef"
#endif
#endif
#include <boost/foreach.hpp>
#include <boost/make_shared.hpp>
#include <boost/scoped_ptr.hpp>
#ifdef __clang__
#pragma clang diagnostic pop
#endif

#include <google/protobuf/io/gzip_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>

#include <fstream>
#include <stdexcept>

#if defined(HAVE_ARPA_INET_H)
#include <arpa/inet.h>
#elif defined(HAVE_NETINET_IN_H)
#include <netinet/in.h>
#endif

using namespace std;

namespace IronBee {
namespace CLIPP {

namespace  {

void fill_event(PB::Event& pb_event, const Input::Event& event)
{
    if (event.pre_delay > 0) {
        pb_event.set_pre_delay(event.pre_delay);
    }
    if (event.post_delay > 0) {
        pb_event.set_post_delay(event.post_delay);
    }
    pb_event.set_which(event.which);
}

class PBConsumerDelegate :
    public Input::Delegate
{
public:
    explicit
    PBConsumerDelegate(PB::Event& pb_event) :
        m_pb_event(pb_event)
    {
        // nop
    }

    void connection_opened(const Input::ConnectionEvent& event)
    {
        PB::ConnectionEvent& pb_ce = *m_pb_event.mutable_connection_event();
        if (event.local_ip.length > 0) {
            pb_ce.set_local_ip(event.local_ip.data, event.local_ip.length);
        }
        if (event.remote_ip.length > 0) {
            pb_ce.set_remote_ip(event.remote_ip.data, event.remote_ip.length);
        }
        if (event.local_port > 0) {
            pb_ce.set_local_port(event.local_port);
        }
        if (event.remote_port > 0) {
            pb_ce.set_remote_port(event.remote_port);
        }
    }

    void connection_closed(const Input::NullEvent& event)
    {
        // nop
    }

    void connection_data_in(const Input::DataEvent& event)
    {
        PB::DataEvent& pb = *m_pb_event.mutable_data_event();
        if (event.data.length > 0) {
            pb.set_data(event.data.data, event.data.length);
        }
    }

    void connection_data_out(const Input::DataEvent& event)
    {
        // Forward to connection_data_in
        connection_data_in(event);
    }

    void request_started(const Input::RequestEvent& event)
    {
        PB::RequestEvent& pb =
            *m_pb_event.mutable_request_event();
        if (event.raw.length > 0) {
            pb.set_raw(event.raw.data, event.raw.length);
        }
        if (event.method.length > 0) {
            pb.set_method(event.method.data, event.method.length);
        }
        if (event.uri.length > 0) {
            pb.set_uri(event.uri.data, event.uri.length);
        }
        if (event.protocol.length > 0) {
            pb.set_protocol(event.protocol.data, event.protocol.length);
        }
    }

    void request_header(const Input::HeaderEvent& event)
    {
        PB::HeaderEvent& pb = *m_pb_event.mutable_header_event();
        BOOST_FOREACH(const Input::header_t& header, event.headers)
        {
            PB::Header& h = *pb.add_header();
            h.set_name(header.first.data, header.first.length);
            h.set_value(header.second.data, header.second.length);
        }
    }

    void request_header_finished(const Input::NullEvent& event)
    {
        // nop
    }

    void request_body(const Input::DataEvent& event)
    {
        // Forward to connection_data_in
        connection_data_in(event);
    }

    void request_finished(const Input::NullEvent& event)
    {
        // nop
    }

    void response_started(const Input::ResponseEvent& event)
    {
        PB::ResponseEvent& pb =
            *m_pb_event.mutable_response_event();
        if (event.raw.length > 0) {
            pb.set_raw(event.raw.data, event.raw.length);
        }
        if (event.protocol.length > 0) {
            pb.set_protocol(event.protocol.data, event.protocol.length);
        }
        if (event.status.length > 0) {
            pb.set_status(event.status.data, event.status.length);
        }
        if (event.message.length > 0) {
            pb.set_message(event.message.data, event.message.length);
        }
    }

    void response_header(const Input::HeaderEvent& event)
    {
        // Forward to request_header
        request_header(event);
    }

    void response_header_finished(const Input::NullEvent& event)
    {
        // nop
    }

    void response_body(const Input::DataEvent& event)
    {
        // Forward to connection_data_in
        connection_data_in(event);
    }

    void response_finished(const Input::NullEvent& event)
    {
        // nop
    }

private:
    PB::Event& m_pb_event;
};

}

struct PBConsumer::State
{
    explicit
    State(const std::string& path) :
        file(new ofstream(path.c_str(), ios::binary | ios::app)),
        output(file.get())
    {
        if (! output) {
            throw runtime_error("Could not open " + path + " for writing.");
        }
    }

    explicit
    State(ostream* out) :
        output(out)
    {
        // nop
    }

    boost::scoped_ptr<ofstream> file;
    ostream* output;
};

PBConsumer::PBConsumer()
{
    // nop
}

PBConsumer::PBConsumer(const std::string& output_path) :
    m_state(boost::make_shared<State>(output_path))
{
    GOOGLE_PROTOBUF_VERIFY_VERSION;
}

PBConsumer::PBConsumer(ostream& out) :
    m_state(boost::make_shared<State>(&out))
{
    GOOGLE_PROTOBUF_VERIFY_VERSION;
}

bool PBConsumer::operator()(const Input::input_p& input)
{
    if (! m_state || ! *m_state->output) {
        return false;
    }

    PB::Input pb_input;

    if (! input->id.empty()) {
        pb_input.set_id(input->id);
    }

    PB::Connection& pb_connection = *pb_input.mutable_connection();

    BOOST_FOREACH(
        const Input::event_p event,
        input->connection.pre_transaction_events
    )
    {
        PB::Event& pb_event = *pb_connection.add_pre_transaction_event();
        fill_event(pb_event, *event);
        PBConsumerDelegate delegate(pb_event);
        event->dispatch(delegate);
    }

    BOOST_FOREACH(
        const Input::Transaction& tx,
        input->connection.transactions
    )
    {
        PB::Transaction& pb_tx = *pb_connection.add_transaction();
        BOOST_FOREACH(const Input::event_p event, tx.events) {
            PB::Event& pb_event = *pb_tx.add_event();
            fill_event(pb_event, *event);
            PBConsumerDelegate delegate(pb_event);
            event->dispatch(delegate);
        }
    }

    BOOST_FOREACH(
        const Input::event_p event,
        input->connection.post_transaction_events
    )
    {
        PB::Event& pb_event = *pb_connection.add_post_transaction_event();
        fill_event(pb_event, *event);
        PBConsumerDelegate delegate(pb_event);
        event->dispatch(delegate);
    }

    string buffer;
    google::protobuf::io::StringOutputStream output(&buffer);
    google::protobuf::io::GzipOutputStream zipped_output(&output);

    pb_input.SerializeToZeroCopyStream(&zipped_output);
    zipped_output.Close();

    uint32_t size = buffer.length();
    uint32_t nsize = htonl(size);
    m_state->output->write(
        reinterpret_cast<const char*>(&nsize), sizeof(uint32_t)
    );
    m_state->output->write(buffer.data(), size);

    return true;
}

} // CLIPP
} // IronBee

ext: cpp

max_issues_repo_name: ErikHendriks/ironbee

max_forks_repo_name: ErikHendriks/ironbee


text:
//
// Copyright (c) 2018 Sergey Panov.
// Copyright (c) 2018 Second Star Algonumerix LLC
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#include <complex>
#include <iostream>

#include <vector>
#include <iterator>
#include <numeric>
#include <fstream>
#include <cmath>

#include <boost/lexical_cast.hpp>

#include "octio.hpp"

using boost::lexical_cast;
using namespace ssan::octio;

template<typename T>
void print_matrix(const std::vector<std::vector<T>> &matrix,
        const std::string & name) {
    if (!matrix.empty()) {
        std::cout << name << "["
                  << matrix.size() << ","
                  << matrix[0].size() << "]: [" << std::endl;
        for (const auto & row : matrix) {
            for (auto element : row) {
                std::cout << " " << lexical_cast<std::string>(element);
            }
            std::cout << std::endl;
        }
        std::cout << "]" << std::endl;
    }
}

template<typename T>
void print_vector(const std::vector<T> &vector, const std::string & name) {
    if (!vector.empty()) {
        std::cout << name << "["
                  << vector.size() << "]: [";
        for (auto element : vector) {
                std::cout << " " << lexical_cast<std::string>(element);
        }
        std::cout << "]" << std::endl;
    }
}

int main() {
    int int_var = -1;
    float float_var(nanf(""));
    double double_var(nan(""));
    long double ldouble_var(nanl(""));
    std::complex<float> cfloat_var(nanf(""), nanf(""));
    std::complex<double> cdouble_var(nan(""), nan(""));
    std::complex<long double> cldouble_var(nanl(""), nanl(""));
    std::vector<int8_t> int8_vect;
    std::vector<int16_t> int16_vect;
    std::vector<int32_t> int32_vect;
    std::vector<int64_t> int64_vect;
    std::vector<uint8_t> uint8_vect;
    std::vector<uint16_t> uint16_vect;
    std::vector<uint32_t> uint32_vect;
    std::vector<uint64_t> uint64_vect;
    std::vector<float> float_vect;
    std::vector<double> double_vect;
    std::vector<long double> ldouble_vect;
    std::vector<int> int_covect;
    std::vector<float> float_covect;
    std::vector<double> double_covect;
    std::vector<long double> ldouble_covect;
    std::vector<std::complex<int>> cint_vect;
    std::vector<std::complex<float>> cfloat_vect;
    std::vector<std::complex<double>> cdouble_vect;
    std::vector<std::complex<long double>> cldouble_vect;
    std::vector<std::complex<float>> cfloat_covect;
    std::vector<std::complex<double>> cdouble_covect;
    std::vector<std::complex<long double>> cldouble_covect;
    std::vector<std::vector<int>> int_mat;
    std::vector<std::vector<float>> float_mat;
    std::vector<std::vector<double>> double_mat;
    std::vector<std::vector<long double>> ldouble_mat;
    std::vector<std::vector<std::complex<float>>> cfloat_mat;
    std::vector<std::vector<std::complex<double>>> cdouble_mat;
    std::vector<std::vector<std::complex<long double>>> cldouble_mat;

    const std::string file_name = "test_octio.mat";
    const std::string file_name_out = "test_octio_out.mat";

    std::ifstream file(file_name);
    reader input(&file);
    std::ofstream ofile(file_name_out);
    writer output(&ofile, "Test file");

    std::cout << input.title() << std::endl;
    do {
        bool consumed = false;
        // std::cout << input.next_name() << std::endl;
        // std::cout << input.next_type() << std::endl;
        if (input.next_type() == SCALAR) {
            if (input.next_name() == "int_var") {
                consumed = input.read(int_var);
                output.write(int_var, "int_var");
            } else if (input.next_name() == "float_var") {
                consumed = input.read(float_var);
                output.write(float_var, "float_var");
            } else if (input.next_name() == "double_var") {
                consumed = input.read(double_var);
                output.write(double_var, "double_var");
            } else if (input.next_name() == "ldouble_var") {
                consumed = input.read(ldouble_var);
                output.write(ldouble_var, "ldouble_var");
            }
        } else if (input.next_type() == COMPLEX_SCALAR) {
            if (input.next_name() == "cfloat_var") {
                consumed = input.read(cfloat_var);
                output.write(cfloat_var, "cfloat_var");
            } else if (input.next_name() == "cdouble_var") {
                consumed = input.read(cdouble_var);
                output.write(cdouble_var, "cdouble_var");
            } else if (input.next_name() == "cldouble_var") {
                consumed = input.read(cldouble_var);
                output.write(cldouble_var, "cldouble_var");
            }
        } else if (input.next_type() == VECTOR
                   || input.next_type() == COVECTOR) {
            if (input.next_name() == "int8_vect") {
                consumed = input.read(int8_vect);
                output.write(int8_vect, "int8_vect");
            } else if (input.next_name() == "int16_vect") {
                consumed = input.read(int16_vect);
                output.write(int16_vect, "int16_vect");
            } else if (input.next_name() == "int32_vect") {
                consumed = input.read(int32_vect);
                output.write(int32_vect, "int32_vect");
            } else if (input.next_name() == "int64_vect") {
                consumed = input.read(int64_vect);
                output.write(int64_vect, "int64_vect");
            } else if (input.next_name() == "uint8_vect") {
                consumed = input.read(uint8_vect);
                output.write(uint8_vect, "uint8_vect");
            } else if (input.next_name() == "uint16_vect") {
                consumed = input.read(uint16_vect);
                output.write(uint16_vect, "uint16_vect");
            } else if (input.next_name() == "uint32_vect") {
                consumed = input.read(int32_vect);
                output.write(uint32_vect, "uint32_vect");
            } else if (input.next_name() == "uint64_vect") {
                consumed = input.read(uint64_vect);
                output.write(uint64_vect, "uint64_vect");
            } else if (input.next_name() == "float_vect") {
                consumed = input.read(float_vect);
                output.write(float_vect, "float_vect");
            } else if (input.next_name() == "double_vect") {
                consumed = input.read(double_vect);
            } else if (input.next_name() == "ldouble_vect") {
                consumed = input.read(ldouble_vect);
            } else if (input.next_name() == "int_covect") {
                consumed = input.read(int_covect);
            } else if (input.next_name() == "float_covect") {
                consumed = input.read(float_covect);
                output.write_covec(float_covect, "float_covect");
            } else if (input.next_name() == "double_covect") {
                consumed = input.read(double_covect);
            } else if (input.next_name() == "ldouble_covect") {
                consumed = input.read(ldouble_covect);
            }
        } else if (input.next_type() == COMPLEX_VECTOR
                   || input.next_type() == COMPLEX_COVECTOR) {
            if (input.next_name() == "cint_vect") {
                consumed = input.read(cint_vect);
                output.write(cint_vect, "cint_vect");
            } else if (input.next_name() == "cfloat_vect") {
                consumed = input.read(cfloat_vect);
                output.write(cfloat_vect, "cfloat_vect");
            } else if (input.next_name() == "cdouble_vect") {
                consumed = input.read(cdouble_vect);
            } else if (input.next_name() == "cldouble_vect") {
                consumed = input.read(cldouble_vect);
            } else if (input.next_name() == "cfloat_covect") {
                consumed = input.read(cfloat_covect);
                output.write_covec(cfloat_covect, "cfloat_covect");
            } else if (input.next_name() == "cdouble_covect") {
                consumed = input.read(cdouble_covect);
            } else if (input.next_name() == "cldouble_covect") {
                consumed = input.read(cldouble_covect);
            }
        } else if (input.next_type() == MATRIX) {
            if (input.next_name() == "int_mat") {
                consumed = input.read(int_mat);
            } else if (input.next_name() == "float_mat") {
                consumed = input.read(float_mat);
                output.write(float_mat, "float_mat");
            } else if (input.next_name() == "double_mat") {
                consumed = input.read(double_var);
            } else if (input.next_name() == "ldouble_mat") {
                consumed = input.read(ldouble_var);
            }
        } else if (input.next_type() == COMPLEX_MATRIX) {
            if (input.next_name() == "cfloat_mat") {
                consumed = input.read(cfloat_mat);
                output.write(cfloat_mat, "cfloat_mat");
            } else if (input.next_name() == "cdouble_mat") {
                consumed = input.read(cdouble_mat);
            } else if (input.next_name() == "cldouble_mat") {
                consumed = input.read(cldouble_mat);
            }
        }

        if (!consumed) {
            input.skip_one();
        }

    } while (input.next_type() != INVALID);

    std::cout << "int_var: " << int_var << std::endl;
    std::cout << "float_var: " << lexical_cast<std::string>(float_var)
              << std::endl;
    std::cout << "double_var: " << lexical_cast<std::string>(double_var)
              << std::endl;
    std::cout << "ldouble_var: " << lexical_cast<std::string>(ldouble_var)
              << std::endl;
    std::cout << "cfloat_var: ("
              << lexical_cast<std::string>(cfloat_var.real()) << ","
              << lexical_cast<std::string>(cfloat_var.imag()) << ")"
              << std::endl;
    std::cout << "cdouble_var: ("
              << lexical_cast<std::string>(cdouble_var.real()) << ","
              << lexical_cast<std::string>(cdouble_var.imag()) << ")"
              << std::endl;
    std::cout << "cldouble_var: ("
              << lexical_cast<std::string>(cldouble_var.real()) << ","
              << lexical_cast<std::string>(cldouble_var.imag()) << ")"
              << std::endl;
    print_vector(float_vect, "float_vect");
    print_vector(float_covect, "float_covect");
    print_vector(cint_vect, "cint_vect");
    print_vector(cfloat_vect, "cfloat_vect");
    print_vector(cfloat_covect, "cfloat_covect");
    print_matrix(float_mat, "float_mat");
    print_matrix(cfloat_mat, "cfloat_mat");

    return 0;
}

max_stars_repo_name: sipanov/lightio

max_issues_repo_name: sipanov/lightio

max_forks_repo_name: sipanov/lightio


text:
// generate by pypp <https://github.com/mugwort-rc/pypp>
// original source code: SPK_Vortex.h

#include <Extensions/Modifiers/SPK_Vortex.h>
#include <boost/python.hpp>

class VortexWrapper :
    public SPK::Vortex,
    public boost::python::wrapper<SPK::Vortex>
{
public:
    using SPK::Vortex::Vortex;
    std::string getClassName () const {
        if ( auto getClassName = this->get_override("getClassName") ) {
            return getClassName();
        } else {
            return Vortex::getClassName();
        }
    }
    void innerUpdateTransform () {
        if ( auto innerUpdateTransform = this->get_override("_innerUpdateTransform") ) {
            innerUpdateTransform();
        } else {
            Vortex::innerUpdateTransform();
        }
    }
};

BOOST_PYTHON_FUNCTION_OVERLOADS(create_overload, SPK::Vortex::create, 0, 4)

void init_SPK_Vortex_h() {
    boost::python::class_<VortexWrapper, boost::python::bases<SPK::Modifier>, std::shared_ptr<SPK::Vortex>>("Vortex",
		boost::python::init<boost::python::optional<const SPK::Vector3D &, const SPK::Vector3D &, float, float>>(
			":brief: Constructor of vortex\n"
			":param position: the position of the eye\n"
			":param direction: the direction of the eye\n"
			":param rotationSpeed: the speed of rotation\n"
			":param attractionSpeed: the speed of attraction\n"))
        .def("getClassName", &SPK::Vortex::getClassName)
        .def("create", &SPK::Vortex::create, create_overload(
			":brief: Creates and registers a new Vortex\n"
			":param position: the position of the eye\n"
			":param direction: the direction of the eye\n"
			":param rotationSpeed: the speed of rotation\n"
			":param attractionSpeed: the speed of attraction\n"
			":return: a new registered vortex\n")
			[boost::python::return_value_policy<boost::python::reference_existing_object>()])
        .def("setPosition", &SPK::Vortex::setPosition,
			":brief: Sets the position of the eye of the vortex\n"
			"\n"
			"The eye of the vortex is an infinite line defined by a position and a direction.\n"
			"\n"
			":param position: the position of the eye of the vortex\n")
        .def("setDirection", &SPK::Vortex::setDirection,
			":brief: Sets the direction of the eye of the vortex\n"
			"\n"
			"The eye of the vortex is an infinite line defined by a position and a direction.\n"
			"Note that the direction is normalized internally.\n"
			"\n"
			":param direction: the direction of the eye of the vortex\n")
        .def("setRotationSpeed", &SPK::Vortex::setRotationSpeed,
			":brief: Sets the rotation speed of the vortex\n"
			"\n"
			"The rotation speed can either be in units per second or in radians per second (angular).\n"
			"In the case the rotation speed is angular, all particles are rotated around the eye at the same speed.\n"
			"In the other case, the more particles are close to the eye, the faster they rotate.\n"
			"\n"
			"The sens of rotation is defined by the sens of the speed (and depends also on whether we are in a right or left handed system).\n"
			"A speed of 0 means no rotation.\n"
			"\n"
			":param rotationSpeed: the speed of rotation (either in units per unit of time or in radians per unit of time dependent on the second parameter)\n"
			":param angular:  True to have the rotation in radians per unit of time, False to have it in unit per unit of time.\n")
        .def("setAttractionSpeed", &SPK::Vortex::setAttractionSpeed,
			":brief: Sets the attraction speed of the vortex\n"
			"\n"
			"The attraction speed is the speed that move particles towards the eye of the vortex.\n"
			"It can either be constant or linear (function of the distance of the particle from the eye).\n"
			"\n"
			"A constant attraction speed is defined in units per unit of time,\n"
			"a linear attraction speed is also defined in units per unit of time and the value is the speed at a distance of 1.0 from the eye.\n"
			"\n"
			"A negative speed means particles are repelled by the eye.\n"
			"A speed of 0.0 means particles are neither attracted nor repelled by the eye of the vortex.\n"
			"\n"
			":param attractionSpeed: the attraction speed of the vortex in units per unit of time\n"
			":param linear: True to set the speed function of the distance from the eye, False to set it constant\n")
        .def("setEyeRadius", &SPK::Vortex::setEyeRadius,
			":brief: Sets the eye radius\n"
			"\n"
			"Note that an negative radius is inverted internally\n"
			"\n"
			":param eyeRadius: the eye radius\n")
        .def("enableParticleKilling", &SPK::Vortex::enableParticleKilling,
			":brief: Tells whether particles is the eye must be killed or not\n"
			":param kill: True to kill particles in the eye, False not to\n")
        .def("getPosition", &SPK::Vortex::getPosition,
			":brief: Gets the position of the eye\n"
			":return: the position of the eye\n",
			boost::python::return_value_policy<boost::python::copy_const_reference>())
        .def("getDirection", &SPK::Vortex::getDirection,
			":brief: Gets the direction of the eye\n"
			":return: the direction of the eye (normalized)\n",
			boost::python::return_value_policy<boost::python::copy_const_reference>())
        .def("getTransformedPosition", &SPK::Vortex::getTransformedPosition,
			":brief: Gets the transformed position of the eye\n"
			":return: the transformed position of the eye\n",
			boost::python::return_value_policy<boost::python::copy_const_reference>())
        .def("getTransformedDirection", &SPK::Vortex::getTransformedDirection,
			":brief: Gets the transformed direction of the eye\n"
			":return: the transformed direction of the eye (normalized)\n",
			boost::python::return_value_policy<boost::python::copy_const_reference>())
        .def("getRotationSpeed", &SPK::Vortex::getRotationSpeed,
			":brief: Gets the rotation speed\n"
			":return: the rotation speed\n")
        .def("getAttractionSpeed", &SPK::Vortex::getAttractionSpeed,
			":brief: Gets the attraction speed\n"
			":return: the attraction speed\n")
        .def("isRotationSpeedAngular", &SPK::Vortex::isRotationSpeedAngular,
			":brief: Tells whether rotation speed is angular\n"
			":return: True if rotation speed is angular, False if not\n")
        .def("isAttractionSpeedLinear", &SPK::Vortex::isAttractionSpeedLinear,
			":brief: Tells whether attraction speed is function of the distance from the eye\n"
			":return: True if attraction speed is linear, False if it is constant\n")
        .def("getEyeRadius", &SPK::Vortex::getEyeRadius,
			":brief: Returns the eye radius\n"
			":return: the eye radius\n")
        .def("isParticleKillingEnabled", &SPK::Vortex::isParticleKillingEnabled,
			":brief: Tells whether particles are killed when in the eye\n"
			":return: True if particles are killed in the eye, False if not\n")
        .staticmethod("create")
        ;
}

max_stars_repo_name: chromia/pyspk

max_issues_repo_name: chromia/pyspk

max_forks_repo_name: chromia/pyspk


text:
/*
	Copyright (C) 2003-2013 by David White <davewx7@gmail.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef HEX_MAP_HPP_INCLUDED
#define HEX_MAP_HPP_INCLUDED

#include <boost/intrusive_ptr.hpp>
#include <vector>

namespace hex {
	enum direction {NORTH, NORTH_EAST, SOUTH_EAST, SOUTH, SOUTH_WEST, NORTH_WEST};
}

#include "graphics.hpp"
#include "hex_object_fwd.hpp"
#include "hex_object.hpp"
#include "formula_callable.hpp"
#include "variant.hpp"

namespace hex {

class hex_map : public game_logic::formula_callable
{
public:
	hex_map() : zorder_(-1000), width_(0), height_(0), x_(0), y_(0)
	{}
	virtual ~hex_map()
	{}
	explicit hex_map(variant node);
	int zorder() const { return zorder_; }
	void set_zorder(int zorder) { zorder_ = zorder; }

	int x() const { return x_; }
	int y() const { return y_; }

	size_t width() const { return width_; }
	size_t height() const { return height_; }
	size_t size() const { return width_ * height_; }
	void build();
	virtual void draw() const;
	variant write() const;

	game_logic::formula_ptr create_formula(const variant& v);
	bool execute_command(const variant& var);

	bool set_tile(int x, int y, const std::string& tile);

	hex_object_ptr get_hex_tile(direction d, int x, int y) const;
	hex_object_ptr get_tile_at(int x, int y) const;
	hex_object_ptr get_tile_from_pixel_pos(int x, int y) const;
	static point get_tile_pos_from_pixel_pos(int x, int y);
	static point get_pixel_pos_from_tile_pos(int x, int y);

	static point loc_in_dir(int x, int y, direction d);
	static point loc_in_dir(int x, int y, const std::string& s);
protected:
	virtual variant get_value(const std::string&) const;
	virtual void set_value(const std::string& key, const variant& value);

private:
	std::vector<hex_object_ptr> tiles_;
	size_t width_;
	size_t height_;
	int x_;
	int y_;
	int zorder_;
#ifdef USE_SHADERS
	gles2::shader_program_ptr shader_;
#endif
};

typedef boost::intrusive_ptr<hex_map> hex_map_ptr;
typedef boost::intrusive_ptr<const hex_map> const_hex_map_ptr;

}

#endif

ext: hpp

max_stars_repo_name: sweetkristas/anura

max_issues_repo_name: sweetkristas/anura

max_forks_repo_name: sweetkristas/anura


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

#include <boost/test/unit_test.hpp>

#include <graphene/chain/database.hpp>

#include <graphene/chain/account_object.hpp>

#include <fc/crypto/digest.hpp>

#include "../common/database_fixture.hpp"

using namespace graphene::chain;

BOOST_FIXTURE_TEST_SUITE( database_tests, database_fixture )

BOOST_AUTO_TEST_CASE( undo_test )
{
   try {
      database db;
      auto ses = db._undo_db.start_undo_session();
      const auto& bal_obj1 = db.create<account_balance_object>( [&]( account_balance_object& obj ){
               /* no balances right now */
      });
      auto id1 = bal_obj1.id;
      // abandon changes
      ses.undo();
      // start a new session
      ses = db._undo_db.start_undo_session();

      const auto& bal_obj2 = db.create<account_balance_object>( [&]( account_balance_object& obj ){
               /* no balances right now */
      });
      auto id2 = bal_obj2.id;
      BOOST_CHECK( id1 == id2 );
   } catch ( const fc::exception& e )
   {
      edump( (e.to_detail_string()) );
      throw;
   }
}

BOOST_AUTO_TEST_CASE( merge_test )
{
   try {
      database db;
      auto ses = db._undo_db.start_undo_session();
      const auto& bal_obj1 = db.create<account_balance_object>( [&]( account_balance_object& obj ){
          obj.balance = 42;
      });
      ses.merge();

      auto balance = db.get_balance( account_id_type(), asset_id_type() );
      BOOST_CHECK_EQUAL( 42, balance.amount.value );
   } catch ( const fc::exception& e )
   {
      edump( (e.to_detail_string()) );
      throw;
   }
}

BOOST_AUTO_TEST_CASE( flat_index_test )
{
   ACTORS((sam));
   const auto& bitusd = create_bitasset("USDBIT", sam.id);
   update_feed_producers(bitusd, {sam.id});
   price_feed current_feed;
   current_feed.settlement_price = bitusd.amount(100) / asset(100);
   publish_feed(bitusd, sam, current_feed);
   FC_ASSERT( bitusd.bitasset_data_id->instance.value == 0 );
   FC_ASSERT( !(*bitusd.bitasset_data_id)(db).current_feed.settlement_price.is_null() );
   try {
      auto ses = db._undo_db.start_undo_session();
      const auto& obj1 = db.create<asset_bitasset_data_object>( [&]( asset_bitasset_data_object& obj ){
          obj.settlement_fund = 17;
      });
      FC_ASSERT( obj1.settlement_fund == 17 );
      throw std::string("Expected");
      // With flat_index, obj1 will not really be removed from the index
   } catch ( const std::string& e )
   { // ignore
   }

   // force maintenance
   const auto& dynamic_global_props = db.get<dynamic_global_property_object>(dynamic_global_property_id_type());
   generate_blocks(dynamic_global_props.next_maintenance_time, true);

   FC_ASSERT( !(*bitusd.bitasset_data_id)(db).current_feed.settlement_price.is_null() );
}

BOOST_AUTO_TEST_CASE( direct_index_test )
{ try {
   try {
      const graphene::db::primary_index< account_index, 6 > small_chunkbits( db );
      BOOST_FAIL( "Expected assertion failure!" );
   } catch( const fc::assert_exception& expected ) {}

   graphene::db::primary_index< account_index, 8 > my_accounts( db );
   const auto& direct = my_accounts.get_secondary_index<graphene::db::direct_index< account_object, 8 >>();
   BOOST_CHECK_EQUAL( 0, my_accounts.indices().size() );
   BOOST_CHECK( nullptr == direct.find( account_id_type( 1 ) ) );
   // BOOST_CHECK_THROW( direct.find( asset_id_type( 1 ) ), fc::assert_exception ); // compile-time error
   BOOST_CHECK_THROW( direct.find( object_id_type( asset_id_type( 1 ) ) ), fc::assert_exception );
   BOOST_CHECK_THROW( direct.get( account_id_type( 1 ) ), fc::assert_exception );

   account_object test_account;
   test_account.id = account_id_type(1);
   test_account.name = "account1";

   my_accounts.load( fc::raw::pack( test_account ) );

   BOOST_CHECK_EQUAL( 1, my_accounts.indices().size() );
   BOOST_CHECK( nullptr == direct.find( account_id_type( 0 ) ) );
   BOOST_CHECK( nullptr == direct.find( account_id_type( 2 ) ) );
   BOOST_CHECK( nullptr != direct.find( account_id_type( 1 ) ) );
   BOOST_CHECK_EQUAL( test_account.name, direct.get( test_account.id ).name );

   // The following assumes that MAX_HOLE = 100
   test_account.id = account_id_type(102);
   test_account.name = "account102";
   // highest insert was 1, direct.next is 2 => 102 is highest allowed instance
   my_accounts.load( fc::raw::pack( test_account ) );
   BOOST_CHECK_EQUAL( test_account.name, direct.get( test_account.id ).name );

   // direct.next is now 103, but index sequence counter is 0
   my_accounts.create( [] ( object& o ) {
       account_object& acct = dynamic_cast< account_object& >( o );
       BOOST_CHECK_EQUAL( 0, acct.id.instance() );
       acct.name = "account0";
   } );

   test_account.id = account_id_type(50);
   test_account.name = "account50";
   my_accounts.load( fc::raw::pack( test_account ) );

   // can handle nested modification
   my_accounts.modify( direct.get( account_id_type(0) ), [&direct,&my_accounts] ( object& outer ) {
      account_object& _outer = dynamic_cast< account_object& >( outer );
      my_accounts.modify( direct.get( account_id_type(50) ), [] ( object& inner ) {
         account_object& _inner = dynamic_cast< account_object& >( inner );
         _inner.referrer = account_id_type(102);
      });
      _outer.options.voting_account = GRAPHENE_PROXY_TO_SELF_ACCOUNT;
   });

   // direct.next is still 103, so 204 is not allowed
   test_account.id = account_id_type(204);
   test_account.name = "account204";
   GRAPHENE_REQUIRE_THROW( my_accounts.load( fc::raw::pack( test_account ) ), fc::assert_exception );
   // This is actually undefined behaviour. The object has been inserted into
   // the primary index, but the secondary has refused to insert it!
   BOOST_CHECK_EQUAL( 5, my_accounts.indices().size() );

   uint32_t count = 0;
   for( uint32_t i = 0; i < 250; i++ )
   {
      const account_object* aptr = dynamic_cast< const account_object* >( my_accounts.find( account_id_type( i ) ) );
      if( aptr )
      {
         count++;
         BOOST_CHECK( aptr->id.instance() == 0 || aptr->id.instance() == 1
                      || aptr->id.instance() == 50 || aptr->id.instance() == 102 );
         BOOST_CHECK_EQUAL( i, aptr->id.instance() );
         BOOST_CHECK_EQUAL( "account" + std::to_string( i ), aptr->name );
      }
   }
   BOOST_CHECK_EQUAL( count, my_accounts.indices().size() - 1 );

   GRAPHENE_REQUIRE_THROW( my_accounts.modify( direct.get( account_id_type( 1 ) ), [] ( object& acct ) {
      acct.id = account_id_type(2);
   }), fc::assert_exception );
   // This is actually undefined behaviour. The object has been modified, but
   // but the secondary has not updated its representation
} FC_LOG_AND_RETHROW() }

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: nathanhourt/peerplays

max_issues_repo_name: nathanhourt/peerplays

max_forks_repo_name: nathanhourt/peerplays


text:
#include <iostream>
#include <armadillo>
#include <cmath>

double calculate_anisotropy(const arma::mat &m) {

    const double iso = arma::mean(arma::eig_sym(m));
    double aniso = arma::accu(m % m);
    aniso = std::sqrt(std::abs(1.5*(aniso - (3.0*iso*iso))));

    return aniso;
}

int main() {

    arma::mat tensor(3, 3);
    tensor(0, 0) = 71.96979730;
    tensor(0, 1) = -7.19617988;
    tensor(0, 2) = 1.01470321;
    tensor(1, 0) = -7.19617833;
    tensor(1, 1) = 65.74361807;
    tensor(1, 2) = -5.62003645;
    tensor(2, 0) = 1.01469269;
    tensor(2, 1) = -5.62002592;
    tensor(2, 2) = 65.05385723;

    // arma::cx_vec principal_components_cx;
    // arma::cx_mat orientation_cx;

    // arma::eig_gen(principal_components_cx, orientation_cx, tensor);
    // principal_components_cx.print("principal components (complex)");
    // orientation_cx.print("orientation (complex)");

    arma::vec principal_components;
    arma::mat orientation;

    arma::eig_sym(principal_components, orientation, tensor);

    principal_components.print("principal components (real)");
    orientation.print("orientation (real)");

    double isotropic = arma::mean(principal_components);
    std::cout << "isotropic  : " << isotropic << std::endl;
    double anisotropic = calculate_anisotropy(tensor);
    std::cout << "anisotropic: " << anisotropic << std::endl;

    return 0;
}

max_stars_repo_name: berquist/eg

max_issues_repo_name: berquist/eg

max_forks_repo_name: berquist/eg


text:
#ifndef _planeseg_Types_hpp_
#define _planeseg_Types_hpp_

//#define PCL_NO_PRECOMPILE
#include <Eigen/Dense>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>

namespace planeseg {

  /*
struct Point {
  PCL_ADD_POINT4D;
  float delta;
  int label;
  EIGEN_MAKE_ALIGNED_OPERATOR_NEW
} EIGEN_ALIGN16;

POINT_CLOUD_REGISTER_POINT_STRUCT(Point,
                                  (float, x, x)
                                  (float, y, y)
                                  (float, z, z)
                                  (float, delta, delta)
                                  (int, label, label)
)
  */
typedef pcl::PointXYZL Point;

typedef pcl::PointCloud<pcl::Normal> NormalCloud;
typedef pcl::PointCloud<Point> LabeledCloud;
typedef Eigen::Matrix<float,Eigen::Dynamic,3> MatrixX3f;

}

#endif


text:
#include <intercept.hpp>

#include <boost/algorithm/algorithm.hpp>
#include <boost/algorithm/string.hpp>

#include <string>
#include <sstream>

#include "../addons/main/script_version.hpp"

using namespace intercept;
using SQFPar = game_value_parameter;

namespace ba = boost::algorithm;

void prettyDiagLog(std::string msg) {
    intercept::sqf::diag_log(sqf::text(msg));
}

void prettyDiagLogInfo(std::string info) {
    prettyDiagLog("[TF47] (intercept_template) INFO: " + info);
}

int intercept::api_version() {
    return INTERCEPT_SDK_API_VERSION;
}

void intercept::register_interfaces() {}

void intercept::pre_init() {
    std::stringstream strVersion;
    strVersion << "Running (" << MAJOR << "." << MINOR << "." << PATCHLVL << "." << BUILD << ")";
    prettyDiagLogInfo(strVersion.str());
}

game_value testCommand(game_state& gs, SQFPar right_arg) {
    if (right_arg.type_enum() == game_data_type::STRING) {
        prettyDiagLogInfo(ba::to_upper_copy(static_cast<std::string>(right_arg)));
        return true;
    }
    else {
        gs.set_script_error(game_state::game_evaluator::evaluator_error_type::type, "string expected"sv);
        return false;
    }
}

void intercept::pre_start() {

    static auto grad_intercept_template_test_command =
        client::host::register_sqf_command("tf47test", "Test Command", testCommand, game_data_type::BOOL, game_data_type::STRING);

}

void intercept::post_init() {

}


text:
#pragma once
#include "Command.hpp"

#include <boost/spirit/include/support_utree.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/mpl/map/map20.hpp>
#include <boost/mpl/string.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/optional.hpp>
#include <boost/variant.hpp>

#include <map>

namespace metaSMT {
  namespace evaluator {
    namespace mpl = boost::mpl;
    namespace spirit = boost::spirit;

    template < typename Context >
    struct SMT_Command_Map {
      typedef mpl::map11<
        mpl::pair<
          string_concat<mpl::string<'d','e','c','l','a','r','e','-'>, mpl::string<'f','u','n'> >::type
        , cmd::DeclareFun<Context>
        >
      , mpl::pair<
          string_concat<mpl::string<'g','e','t','-'>, mpl::string<'v','a','l','u','e'> >::type
        , cmd::GetValue<Context>
        >
      , mpl::pair<
          string_concat<mpl::string<'s','e','t','-'>, mpl::string<'l','o','g','i','c'> >::type
        , cmd::SetLogic<Context>
        >
      , mpl::pair<
          string_concat<mpl::string<'s','e','t','-'>, mpl::string<'i','n','f','o'> >::type
        , cmd::SetInfo<Context>
        >
      , mpl::pair<
          string_concat<mpl::string<'s','e','t','-'>, mpl::string<'o','p','t','i','o','n'> >::type
        , cmd::SetOption<Context>
        >
      , mpl::pair<
          string_concat<mpl::string<'g','e','t','-'>, mpl::string<'o','p','t','i','o','n'> >::type
        , cmd::GetOption<Context>
        >
      , mpl::pair<
          string_concat<mpl::string<'c','h','e','c','k','-'>, mpl::string<'s','a','t'> >::type
        , cmd::CheckSat<Context>
        >
      , mpl::pair<mpl::string<'p','u','s','h'>, cmd::Push<Context> >
      , mpl::pair<mpl::string<'p','o','p'>, cmd::Pop<Context> >
      , mpl::pair<mpl::string<'e','x','i','t'>, cmd::Exit<Context> >
      , mpl::pair<mpl::string<'a','s','s','e','r','t'>, cmd::Assert<Context> >
      > TheMapping;

      typedef boost::variant<
        cmd::DefaultConstructableDummyCommand
      , cmd::DeclareFun<Context>
      , cmd::GetValue<Context>
      , cmd::SetLogic<Context>
      , cmd::SetInfo<Context>
      , cmd::SetOption<Context>
      , cmd::GetOption<Context>
      , cmd::CheckSat<Context>
      , cmd::Push<Context>
      , cmd::Pop<Context>
      , cmd::Exit<Context>
      , cmd::Assert<Context>
      > Command;

      typedef type::TypedSymbol<Context> TypedSymbol;
      typedef boost::shared_ptr<TypedSymbol> TypedSymbolPtr;
      typedef std::map<std::string, TypedSymbolPtr> VarMap;
      typedef spirit::utree utree;

      class RunCommandVisitor
        : public boost::static_visitor< boost::optional<boost::any> > {
      public:
        RunCommandVisitor(utree const &ast)
          : ast(ast)
        {}

        template < typename Command >
        typename boost::enable_if<
          typename boost::is_same<typename Command::result_type, void>::type
          , boost::optional<boost::any>
        >::type
        operator()(Command command) const {
          command(boost::optional<utree>(ast));
          return boost::optional<boost::any>();
        }

        template < typename Command >
        typename boost::disable_if<
          typename boost::is_same<typename Command::result_type, void>::type
        , boost::optional<boost::any>
        >::type
        operator()(Command command) const {
          return  boost::optional<boost::any>(command(boost::optional<utree>(ast)));
        }

        utree const ast;
      }; // RunCommandVisitor

      struct GetCommandVisitor {
      public:
        GetCommandVisitor(bool &found,
                          Command &command,
                          std::string const &name,
                          Context &ctx,
                          VarMap &var_map,
                          support::simple_symbol_table &table)
          : found(found)
          , command(command)
          , name(name)
          , ctx(ctx)
          , var_map(var_map)
          , table(table)
        {}

        template < typename Pair >
        void operator()( Pair const & ) {
          typedef typename Pair::first String;
          typedef typename Pair::second Cmd;

          if ( !found &&
               mpl::c_str<String>::value == name ) {
            found = true;
            command = Cmd(&ctx, &var_map, &table);
          }
        }

        bool &found;
        Command &command;
        std::string name;
        Context &ctx;
        VarMap &var_map;
        support::simple_symbol_table &table;
      }; // GetCommandVisitor

      static boost::optional<boost::any>
      execute_command(Command const &command, utree const &ast) {
        return boost::apply_visitor(RunCommandVisitor(ast), command);
      }

      static boost::optional<Command>
      get_command(std::string const &name, Context &ctx, VarMap &var_map,
                  support::simple_symbol_table &table) {
        bool found = false;
        Command command;
        GetCommandVisitor vis(found, command, name, ctx, var_map, table);
        mpl::for_each<TheMapping>(vis);
        if (found) {
          return boost::optional<Command>(command);
        }
        else {
          return boost::optional<Command>();
        }
      }
    }; // SMT_Command_Map
  } // evaluator
} // metaSMT

max_stars_repo_name: finnhaedicke/metaSMT

max_issues_repo_name: finnhaedicke/metaSMT

max_forks_repo_name: finnhaedicke/metaSMT


text:
//==================================================================
// Author       : Pointner Sebastian
// Company      : Johannes Kepler University
// Name         : SMT Macro Placer
// Workfile     : supplement.hpp
//
// Date         : 09. January 2019
// Compiler     : gcc version 9.2.0 (GCC)
// Copyright    : Johannes Kepler University
// Description  : LEF/DEF Supplement File
//==================================================================
#ifndef SUPPLEMENT_HPP
#define SUPPLEMENT_HPP

#include <object.hpp>
#include <logger.hpp>
#include <exception.hpp>
#include <supplementmacro.hpp>
#include <supplementlayout.hpp>
#include <supplementterminal.hpp>

#include <json/json.h>
#include <unordered_map>
#include <iostream>

#include <boost/filesystem.hpp>

namespace Placer {

/**
 * @class Supplement
 * @brief Add Additional Information not Supported by LEF/DEF Standard
 */
class Supplement: public virtual Object{
public:

    Supplement();

    ~Supplement();

    void read_supplement_file();

    void write_supplement_file();

    bool has_supplement();

    bool has_macro(std::string const & id);

    bool has_terminal(std::string const & id);

    bool has_layout();

    SupplementMacro* get_macro(std::string const & id);
    void add_macro(SupplementMacro const * macro);

    SupplementLayout* get_layout();
    void set_layout(SupplementLayout * layout);

    SupplementTerminal* get_terminal(std::string const & id);
    void add_terminal(SupplementTerminal const * terminal);

private:
    Utils::Logger* m_logger;
    std::unordered_map<std::string, SupplementMacro*> m_macros;
    std::unordered_map<std::string, SupplementTerminal*> m_terminals;
    SupplementLayout* m_layout;
};

} /* namespace Placer */

#endif /* SUPPLEMENT_HPP */


text:
///////////////////////////////////////////////////////////////////////////////
// lambda.hpp
//
//  Copyright 2008 Eric Niebler. Distributed under the Boost
//  Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <sstream>
#include <boost/mpl/int.hpp>
#include <boost/mpl/min_max.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/mpl/next_prior.hpp>
#include <boost/fusion/tuple.hpp>
#include <boost/typeof/typeof.hpp>
#include <boost/typeof/std/sstream.hpp>
#include <boost/typeof/std/ostream.hpp>
#include <boost/typeof/std/iostream.hpp>
#include <boost/type_traits/add_const.hpp>
#include <boost/type_traits/add_reference.hpp>
#include <boost/proto/core.hpp>
#include <boost/proto/context.hpp>
#include <boost/proto/transform.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/test/floating_point_comparison.hpp>

using namespace boost;

// Forward declaration of the lambda expression wrapper
template<typename T>
struct lambda;

struct lambda_domain
  : proto::domain<proto::pod_generator<lambda> >
{};

template<typename I>
struct placeholder
{
    typedef I arity;
};

template<typename T>
struct placeholder_arity
{
    typedef typename T::arity type;
};

namespace grammar
{
    using namespace proto;

    // The lambda grammar, with the transforms for calculating the max arity
    struct Lambda
      : or_<
            when< terminal< placeholder<_> >,  mpl::next<placeholder_arity<_value> >() >
          , when< terminal<_>,                 mpl::int_<0>() >
          , when< nary_expr<_, vararg<_> >,    fold<_, mpl::int_<0>(), mpl::max<Lambda,_state>()> >
        >
    {};
}

// simple wrapper for calculating a lambda expression's arity.
template<typename Expr>
struct lambda_arity
  : boost::result_of<grammar::Lambda(Expr, mpl::void_, mpl::void_)>
{};

// The lambda context is the same as the default context
// with the addition of special handling for lambda placeholders
template<typename Tuple>
struct lambda_context
  : proto::callable_context<lambda_context<Tuple> const>
{
    lambda_context(Tuple const &args)
      : args_(args)
    {}

    template<typename Sig>
    struct result;

    template<typename This, typename I>
    struct result<This(proto::tag::terminal, placeholder<I> const &)>
      : fusion::result_of::at<Tuple, I>
    {};

    template<typename I>
    typename fusion::result_of::at<Tuple, I>::type
    operator ()(proto::tag::terminal, placeholder<I> const &) const
    {
        return fusion::at<I>(this->args_);
    }

    Tuple args_;
};

// The lambda<> expression wrapper makes expressions polymorphic
// function objects
template<typename T>
struct lambda
{
    BOOST_PROTO_BASIC_EXTENDS(T, lambda<T>, lambda_domain)
    BOOST_PROTO_EXTENDS_ASSIGN()
    BOOST_PROTO_EXTENDS_SUBSCRIPT()

    // Careful not to evaluate the return type of the nullary function
    // unless we have a nullary lambda!
    typedef typename mpl::eval_if<
        typename lambda_arity<T>::type
      , mpl::identity<void>
      , proto::result_of::eval<T const, lambda_context<fusion::tuple<> > >
    >::type nullary_type;

    // Define our operator () that evaluates the lambda expression.
    nullary_type operator ()() const
    {
        fusion::tuple<> args;
        lambda_context<fusion::tuple<> > ctx(args);
        return proto::eval(*this, ctx);
    }

    #define M0(N, typename_A, A_const_ref, A_const_ref_a, ref_a)                                    \
    template<typename_A(N)>                                                                         \
    typename proto::result_of::eval<T const, lambda_context<fusion::tuple<A_const_ref(N)> > >::type \
    operator ()(A_const_ref_a(N)) const                                                             \
    {                                                                                \
        fusion::tuple<A_const_ref(N)> args(ref_a(N));                                               \
        lambda_context<fusion::tuple<A_const_ref(N)> > ctx(args);                                   \
        return proto::eval(*this, ctx);                                                             \
    }                                                                                \
    /**/
    BOOST_PROTO_REPEAT_FROM_TO(1, 4, M0)
    #undef M0
};

// Define some lambda placeholders
lambda<proto::terminal<placeholder<mpl::int_<0> > >::type> const _1 = {{}};
lambda<proto::terminal<placeholder<mpl::int_<1> > >::type> const _2 = {{}};
lambda<proto::terminal<placeholder<mpl::int_<3> > >::type> const _3 = {{}};

template<typename T>
lambda<typename proto::terminal<T>::type> const val(T const &t)
{
    lambda<typename proto::terminal<T>::type> that = {{t}};
    return that;
}

template<typename T>
lambda<typename proto::terminal<T &>::type> const var(T &t)
{
    lambda<typename proto::terminal<T &>::type> that = {{t}};
    return that;
}

void test_lambda()
{
    BOOST_CHECK_EQUAL(11, ( (_1 + 2) / 4 )(42));
    BOOST_CHECK_EQUAL(-11, ( (-(_1 + 2)) / 4 )(42));
    BOOST_CHECK_CLOSE(2.58, ( (4 - _2) * 3 )(42, 3.14), 0.1);

    // check non-const ref terminals
    std::stringstream sout;
    (sout << _1 << " -- " << _2)(42, "Life, the Universe and Everything!");
    BOOST_CHECK_EQUAL("42 -- Life, the Universe and Everything!", sout.str());

    // check nullary lambdas
    BOOST_CHECK_EQUAL(3, (val(1) + val(2))());

    // check array indexing for kicks
    int integers[5] = {0};
    (var(integers)[2] = 2)();
    (var(integers)[_1] = _1)(3);
    BOOST_CHECK_EQUAL(2, integers[2]);
    BOOST_CHECK_EQUAL(3, integers[3]);
}

using namespace unit_test;
///////////////////////////////////////////////////////////////////////////////
// init_unit_test_suite
//
test_suite* init_unit_test_suite( int argc, char* argv[] )
{
    test_suite *test = BOOST_TEST_SUITE("test expression template domains");

    test->add(BOOST_TEST_CASE(&test_lambda));

    return test;
}

max_stars_repo_name: zyiacas/boost-doc-zh

max_issues_repo_name: sdfict/boost-doc-zh

max_forks_repo_name: sdfict/boost-doc-zh


text:
// This source file is part of the polarphp.org open source project
//
// Copyright (c) 2017 - 2018 polarphp software foundation
// Copyright (c) 2017 - 2018 zzu_softboy <zzu_softboy@163.com>
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://polarphp.org/LICENSE.txt for license information
// See https://polarphp.org/CONTRIBUTORS.txt for the list of polarphp project authors
//
// Created by polarboy on 2018/10/25.

#include "Global.h"
#include "CheckFuncs.h"
#include "CheckPattern.h"
#include "CheckString.h"
#include "polarphp/utils/MemoryBuffer.h"
#include "polarphp/basic/adt/StringSet.h"
#include "polarphp/basic/adt/Twine.h"
#include "polarphp/utils/Debug.h"
#include "CLI/CLI.hpp"
#include <boost/regex.hpp>

namespace polar {
namespace filechecker {

using polar::basic::Twine;
using polar::basic::StringSet;
using polar::basic::SmallString;
using polar::basic::SmallVector;
using polar::utils::MemoryBuffer;

/// Canonicalize whitespaces in the file. Line endings are replaced with
/// UNIX-style '\n'.
StringRef canonicalize_file(MemoryBuffer &memorybuffer,
                            SmallVectorImpl<char> &outputbuffer)
{
   CLI::App &parser = retrieve_command_parser();
   bool noCanonicalizeWhiteSpace = parser.get_option("--strict-whitespace")->count() > 0 ? true : false;
   outputbuffer.reserve(memorybuffer.getBufferSize());
   for (const char *ptr = memorybuffer.getBufferStart(), *end = memorybuffer.getBufferEnd();
        ptr != end; ++ptr) {
      // Eliminate trailing dosish \r.
      if (ptr <= end - 2 && ptr[0] == '\r' && ptr[1] == '\n') {
         continue;
      }
      // If current char is not a horizontal whitespace or if horizontal
      // whitespace canonicalization is disabled, dump it to output as is.
      if (noCanonicalizeWhiteSpace || (*ptr != ' ' && *ptr != '\t')) {
         outputbuffer.push_back(*ptr);
         continue;
      }
      // Otherwise, add one space and advance over neighboring space.
      outputbuffer.push_back(' ');
      while (ptr + 1 != end && (ptr[1] == ' ' || ptr[1] == '\t')) {
         ++ptr;
      }
   }
   // Add a null byte and then return all but that byte.
   outputbuffer.push_back('\0');
   return StringRef(outputbuffer.getData(), outputbuffer.size() - 1);
}

bool is_part_of_word(char c)
{
   return (isalnum(c) || c == '-' || c == '_');
}

// Get the size of the prefix extension.
size_t check_type_size(CheckType checkType)
{
   switch (checkType) {
   case CheckType::CheckNone:
   case CheckType::CheckBadNot:
      return 0;

   case CheckType::CheckPlain:
      return sizeof(":") - 1;

   case CheckType::CheckNext:
      return sizeof("-NEXT:") - 1;

   case CheckType::CheckSame:
      return sizeof("-SAME:") - 1;

   case CheckType::CheckNot:
      return sizeof("-NOT:") - 1;

   case CheckType::CheckDAG:
      return sizeof("-DAG:") - 1;

   case CheckType::CheckLabel:
      return sizeof("-LABEL:") - 1;

   case CheckType::CheckEmpty:
      return sizeof("-EMPTY:") - 1;

   case CheckType::CheckEOF:
      polar_unreachable("Should not be using EOF size");
   }
   polar_unreachable("Bad check type");
}

// Get a description of the type.
std::string check_type_name(StringRef prefix, CheckType checkType)
{
   switch (checkType) {
   case CheckType::CheckNone:
      return "invalid";
   case CheckType::CheckPlain:
      return prefix;
   case CheckType::CheckNext:
      return prefix.getStr() + "-NEXT";
   case CheckType::CheckSame:
      return prefix.getStr() + "-SAME";
   case CheckType::CheckNot:
      return prefix.getStr() + "-NOT";
   case CheckType::CheckDAG:
      return prefix.getStr() + "-DAG";
   case CheckType::CheckLabel:
      return prefix.getStr() + "-LABEL";
   case CheckType::CheckEmpty:
      return prefix.getStr() + "-EMPTY";
   case CheckType::CheckEOF:
      return "implicit EOF";
   case CheckType::CheckBadNot:
      return "bad NOT";
   }
   polar_unreachable("unknown CheckType");
}

CheckType find_check_type(StringRef buffer, StringRef prefix)
{
   if (buffer.size() <= prefix.size()) {
      return CheckType::CheckNone;
   }
   char nextChar = buffer[prefix.size()];
   // Verify that the : is present after the prefix.
   if (nextChar == ':') {
      return CheckType::CheckPlain;
   }
   if (nextChar != '-') {
      return CheckType::CheckNone;
   }
   StringRef rest = buffer.dropFront(prefix.size() + 1);
   if (rest.startsWith("NEXT:")) {
      return CheckType::CheckNext;
   }
   if (rest.startsWith("SAME:")) {
      return CheckType::CheckSame;
   }
   if (rest.startsWith("NOT:")) {
      return CheckType::CheckNot;
   }
   if (rest.startsWith("DAG:")) {
      return CheckType::CheckDAG;
   }
   if (rest.startsWith("LABEL:")) {
      return CheckType::CheckLabel;
   }
   if (rest.startsWith("EMPTY:")) {
      return CheckType::CheckEmpty;
   }
   // You can't combine -NOT with another suffix.
   if (rest.startsWith("DAG-NOT:") || rest.startsWith("NOT-DAG:") ||
       rest.startsWith("NEXT-NOT:") || rest.startsWith("NOT-NEXT:") ||
       rest.startsWith("SAME-NOT:") || rest.startsWith("NOT-SAME:") ||
       rest.startsWith("EMPTY-NOT:") || rest.startsWith("NOT-EMPTY:")) {
      return CheckType::CheckBadNot;
   }
   return CheckType::CheckNone;
}

// From the given position, find the next character after the word.
size_t skip_word(StringRef str)
{
   size_t i = 0;
   for (;i < str.size() && is_part_of_word(str[i]); ++i);
   return i;
}

/// Search the buffer for the first prefix in the prefix regular expression.
///
/// This searches the buffer using the provided regular expression, however it
/// enforces constraints beyond that:
/// 1) The found prefix must not be a suffix of something that looks like
///    a valid prefix.
/// 2) The found prefix must be followed by a valid check type suffix using \c
///    FindCheckTypepe above.
///
/// The first match of the regular expression to satisfy these two is returned,
/// otherwise an empty StringRef is returned to indicate failure.
///
/// If this routine returns a valid prefix, it will also shrink \p buffer to
/// start at the beginning of the returned prefix, increment \p lineNumber for
/// each new line consumed from \p buffer, and set \p CheckType to the type of
/// check found by examining the suffix.
///
/// If no valid prefix is found, the state of buffer, lineNumber, and CheckType
/// is unspecified.
StringRef find_first_matching_prefix(boost::regex &prefixRegex, StringRef &buffer,
                                     unsigned &lineNumber,
                                     CheckType &checkType)
{
   while (!buffer.empty()) {
      boost::cmatch matches;
      // Find the first (longest) match using the RE.
      if (!boost::regex_search(buffer.begin(), buffer.end(), matches, prefixRegex,
                               boost::match_posix)) {
         // No match at all, bail.
         return StringRef();
      }
      StringRef prefix(buffer.getData() + matches.position(), matches[0].length());
      assert(prefix.getData() >= buffer.getData() &&
             prefix.getData() < buffer.getData() + buffer.size() &&
             "Prefix doesn't start inside of buffer!");

      size_t loc = matches.position();
      StringRef skipped = buffer.substr(0, loc);
      buffer = buffer.dropFront(loc);
      lineNumber += skipped.count('\n');

      // Check that the matched prefix isn't a suffix of some other check-like
      // word.
      // FIXME: This is a very ad-hoc check. it would be better handled in some
      // other way. Among other things it seems hard to distinguish between
      // intentional and unintentional uses of this feature.
      if (skipped.empty() || !is_part_of_word(skipped.back())) {
         // Now extract the type.
         checkType = find_check_type(buffer, prefix);
         // If we've found a valid check type for this prefix, we're done.
         if (checkType != CheckType::CheckNone) {
            return prefix;
         }
      }

      // If we didn't successfully find a prefix, we need to skip this invalid
      // prefix and continue scanning. We directly skip the prefix that was
      // matched and any additional parts of that check-like word.
      buffer = buffer.dropFront(skip_word(buffer));
   }

   // We ran out of buffer while skipping partial matches so give up.
   return StringRef();
}

/// Read the check file, which specifies the sequence of expected strings.
///
/// The strings are added to the checkStrings vector. Returns true in case of
/// an error, false otherwise.
bool read_check_file(SourceMgr &sourceMgr, StringRef buffer, boost::regex &prefixRegex,
                     std::vector<CheckString> &checkStrings)
{
   CLI::App &parser = retrieve_command_parser();
   std::string cmdName = "--implicit-check-not";
   bool noCanonicalizeWhiteSpace = parser.get_option("--strict-whitespace")->count() > 0 ? true : false;
   bool matchFullLines = parser.get_option("--match-full-lines")->count() > 0 ? true : false;
   std::vector<Pattern> implicitNegativeChecks;
   for (const auto &patternstring : sg_implicitCheckNot) {
      // Create a buffer with fake command line content in order to display the
      // command line option responsible for the specific implicit CHECK-NOT.
      std::string prefix = Twine(cmdName, " '").getStr();
      std::string suffix = "'";
      std::unique_ptr<MemoryBuffer> cmdLine = MemoryBuffer::getMemBufferCopy(
               prefix + patternstring + suffix, "command line");

      StringRef patternInbuffer =
            cmdLine->getBuffer().substr(prefix.size(), patternstring.size());
      sourceMgr.addNewSourceBuffer(std::move(cmdLine), SMLocation());

      implicitNegativeChecks.push_back(Pattern(CheckType::CheckNot));
      implicitNegativeChecks.back().parsePattern(patternInbuffer,
                                                 "IMPLICIT-CHECK", sourceMgr, 0);
   }

   std::vector<Pattern> dagNotMatches = implicitNegativeChecks;

   // lineNumber keeps track of the line on which Checkprefix instances are
   // found.
   unsigned lineNumber = 1;
   while (true) {
      CheckType checkType;
      // See if a prefix occurs in the memory buffer.
      StringRef usedPrefix = find_first_matching_prefix(prefixRegex, buffer, lineNumber,
                                                        checkType);
      if (usedPrefix.empty()) {
         break;
      }
      assert(usedPrefix.getData() == buffer.getData() &&
             "Failed to move buffer's start forward, or pointed prefix outside "
             "of the buffer!");

      // location to use for error messages.
      const char *usedprefixStart = usedPrefix.getData();

      // Skip the buffer to the end.
      buffer = buffer.dropFront(usedPrefix.size() + check_type_size(checkType));

      // Complain about useful-looking but unsupported suffixes.
      if (checkType == CheckType::CheckBadNot) {
         sourceMgr.printMessage(SMLocation::getFromPointer(buffer.getData()), SourceMgr::DK_Error,
                                "unsupported -NOT combo on prefix '" + usedPrefix + "'");
         return true;
      }

      // Okay, we found the prefix, yay. Remember the rest of the line, but ignore
      // leading whitespace.
      if (!(noCanonicalizeWhiteSpace && matchFullLines)) {
         buffer = buffer.substr(buffer.findFirstNotOf(" \t"));
      }
      // Scan ahead to the end of line.
      size_t eol = buffer.findFirstOf("\n\r");

      // Remember the location of the start of the pattern, for diagnostics.
      SMLocation patternloc = SMLocation::getFromPointer(buffer.getData());

      // Parse the pattern.
      Pattern pattern(checkType);
      if (pattern.parsePattern(buffer.substr(0, eol), usedPrefix, sourceMgr, lineNumber)) {
         return true;
      }
      // Verify that CHECK-LABEL lines do not define or use variables
      if ((checkType == CheckType::CheckLabel) && pattern.hasVariable()) {
         sourceMgr.printMessage(
                  SMLocation::getFromPointer(usedprefixStart), SourceMgr::DK_Error,
                  "found '" + usedPrefix + "-LABEL:'"
                                           " with variable definition or use");
         return true;
      }

      buffer = buffer.substr(eol);

      // Verify that CHECK-NEXT/SAME/EMPTY lines have at least one CHECK line before them.
      if ((checkType == CheckType::CheckNext || checkType == CheckType::CheckSame ||
           checkType == CheckType::CheckEmpty) &&
          checkStrings.empty()) {
         StringRef type = checkType == CheckType::CheckNext
               ? "NEXT"
               : checkType == CheckType::CheckEmpty ? "EMPTY" : "SAME";
         sourceMgr.printMessage(SMLocation::getFromPointer(usedprefixStart),
                                SourceMgr::DK_Error,
                                "found '" + usedPrefix + "-" + type +
                                "' without previous '" + usedPrefix + ": line");
         return true;
      }

      // Handle CHECK-DAG/-NOT.
      if (checkType == CheckType::CheckDAG || checkType == CheckType::CheckNot) {
         dagNotMatches.push_back(pattern);
         continue;
      }

      // Okay, add the string we captured to the output vector and move on.
      checkStrings.emplace_back(pattern, usedPrefix, patternloc);
      std::swap(dagNotMatches, checkStrings.back().m_dagNotStrings);
      dagNotMatches = implicitNegativeChecks;
   }

   // Add an EOF pattern for any trailing CHECK-DAG/-NOTs, and use the first
   // prefix as a filler for the error message.
   if (!dagNotMatches.empty()) {
      checkStrings.emplace_back(Pattern(CheckType::CheckEOF), *sg_checkPrefixes.begin(),
                                SMLocation::getFromPointer(buffer.getData()));
      std::swap(dagNotMatches, checkStrings.back().m_dagNotStrings);
   }
   if (checkStrings.empty()) {
      polar::utils::error_stream() << "error: no check strings found with prefix"
                                   << (sg_checkPrefixes.size() > 1 ? "es " : " ");
      auto iter = sg_checkPrefixes.begin();
      auto endMark = sg_checkPrefixes.end();
      if (iter != endMark) {
         polar::utils::error_stream() << "\'" << *iter << ":'";
         ++iter;
      }
      for (; iter != endMark; ++iter) {
         polar::utils::error_stream() << ", \'" << *iter << ":'";
      }

      polar::utils::error_stream() << '\n';
      return true;
   }

   return false;
}

void print_match(bool expectedMatch, const SourceMgr &sourceMgr,
                 StringRef prefix, SMLocation loc, const Pattern &pattern,
                 StringRef buffer, StringMap<std::string> &variableTable,
                 size_t matchPos, size_t matchLen)
{
   CLI::App &parser = retrieve_command_parser();
   bool verbose = parser.get_option("-v")->count() >= 1 ? true : false;
   bool verboseVerbose = parser.get_option("-v")->count() > 1 ? true : false;
   if (expectedMatch) {
      if (!verbose) {
         return;
      }
      if (!verboseVerbose && pattern.getCheckType() == CheckType::CheckEOF) {
         return;
      }
   }
   SMLocation matchStart = SMLocation::getFromPointer(buffer.getData() + matchPos);
   SMLocation matchEnd = SMLocation::getFromPointer(buffer.getData() + matchPos + matchLen);
   SMRange matchRange(matchStart, matchEnd);
   sourceMgr.printMessage(
            loc, expectedMatch ? SourceMgr::DK_Remark : SourceMgr::DK_Error,
            check_type_name(prefix, pattern.getCheckType()) + ": " +
            (expectedMatch ? "expected" : "excluded") +
            " string found in input");
   sourceMgr.printMessage(matchStart, SourceMgr::DK_Note, "found here", {matchRange});
   pattern.printVariableUses(sourceMgr, buffer, variableTable, matchRange);
}

void print_match(bool expectedMatch, const SourceMgr &sourceMgr,
                 const CheckString &Checkstr, StringRef buffer,
                 StringMap<std::string> &variableTable, size_t matchPos,
                 size_t matchLen)
{
   print_match(expectedMatch, sourceMgr, Checkstr.m_prefix, Checkstr.m_location, Checkstr.m_pattern,
               buffer, variableTable, matchPos, matchLen);
}

void print_no_match(bool expectedMatch, const SourceMgr &sourceMgr,
                    StringRef prefix, SMLocation loc, const Pattern &pattern,
                    StringRef buffer,
                    StringMap<std::string> &variableTable)
{
   CLI::App &parser = retrieve_command_parser();
   bool verboseVerbose = parser.get_option("-v")->count() > 1 ? true : false;
   if (!expectedMatch && !verboseVerbose) {
      return;
   }

   // Otherwise, we have an error, emit an error message.
   sourceMgr.printMessage(loc,
                          expectedMatch ? SourceMgr::DK_Error : SourceMgr::DK_Remark,
                          check_type_name(prefix, pattern.getCheckType()) + ": " +
                          (expectedMatch ? "expected" : "excluded") +
                          " string not found in input");

   // Print the "scanning from here" line.  If the current position is at the
   // end of a line, advance to the start of the next line.
   buffer = buffer.substr(buffer.findFirstNotOf(" \t\n\r"));

   sourceMgr.printMessage(SMLocation::getFromPointer(buffer.getData()), SourceMgr::DK_Note,
                          "scanning from here");

   // Allow the pattern to print additional information if desired.
   pattern.printVariableUses(sourceMgr, buffer, variableTable);
   if (expectedMatch) {
      pattern.printFuzzyMatch(sourceMgr, buffer, variableTable);
   }
}

void print_no_match(bool expectedMatch, const SourceMgr &sourceMgr,
                    const CheckString &Checkstr, StringRef buffer,
                    StringMap<std::string> &variableTable)
{
   print_no_match(expectedMatch, sourceMgr, Checkstr.m_prefix, Checkstr.m_location, Checkstr.m_pattern,
                  buffer, variableTable);
}

/// Count the number of newlines in the specified range.
unsigned count_num_newlines_between(StringRef range,
                                    const char *&firstNewLine)
{
   unsigned numNewLines = 0;
   while (true) {
      // Scan for newline.
      range = range.substr(range.findFirstOf("\n\r"));
      if (range.empty()) {
         return numNewLines;
      }
      ++numNewLines;

      // Handle \n\r and \r\n as a single newline.
      if (range.size() > 1 && (range[1] == '\n' || range[1] == '\r') &&
          (range[0] != range[1])) {
         range = range.substr(1);
      }
      range = range.substr(1);
      if (numNewLines == 1) {
         firstNewLine = range.begin();
      }
   }
}

// A check prefix must contain only alphanumeric, hyphens and underscores.
bool validate_check_prefix(StringRef checkPrefix)
{
   return boost::regex_match(checkPrefix.getStr(), boost::regex("^[a-zA-Z0-9_-]*$"));
}

bool validate_check_prefixes()
{
   StringSet<> prefixSet;

   for (StringRef prefix : sg_checkPrefixes) {
      // Reject empty prefixes.
      if (prefix.trim() == "") {
         return false;
      }
      if (!prefixSet.insert(prefix).second) {
         return false;
      }
      if (!validate_check_prefix(prefix)) {
         return false;
      }
   }
   return true;
}

// Combines the check prefixes into a single regex so that we can efficiently
// scan for any of the set.
//
// The semantics are that the longest-match wins which matches our regex
// library.
bool build_check_prefix_regex(boost::regex &regex, std::string &errorMsg)
{
   // I don't think there's a way to specify an initial value for cl::list,
   // so if nothing was specified, add the default
   if (sg_checkPrefixes.empty()) {
      sg_checkPrefixes.push_back("CHECK");
   }
   // We already validated the contents of checkPrefixes so just concatenate
   // them as alternatives.
   SmallString<32> prefixRegexStr;
   for (StringRef prefix : sg_checkPrefixes) {
      if (prefix != sg_checkPrefixes.front()) {
         prefixRegexStr.push_back('|');
      }
      prefixRegexStr.append(prefix);
   }
   try {
      regex = boost::regex(prefixRegexStr.getStr().getStr());
      return true;
   } catch (std::exception &e) {
      errorMsg = e.what();
      return false;
   }
}

void dump_command_line(int argc, char **argv)
{
   polar::utils::error_stream() << "filechecker command line: ";
   for (int index = 0; index < argc; index++) {
      polar::utils::error_stream() << " " << argv[index];
   }
   polar::utils::error_stream() << "\n";
}

// Remove local variables from \p variableTable. Global variables
// (start with '$') are preserved.
void clear_local_vars(StringMap<std::string> &variableTable)
{
   SmallVector<StringRef, 16> localVars;
   for (const auto &var : variableTable) {
      if (var.getFirst()[0] != '$') {
         localVars.push_back(var.getFirst());
      }
   }
   for (const auto &var : localVars) {
      variableTable.erase(var);
   }
}

/// Check the input to filechecker provided in the \p buffer against the \p
/// checkStrings read from the check file.
///
/// Returns false if the input fails to satisfy the checks.
bool check_input(SourceMgr &sourceMgr, StringRef buffer,
                 ArrayRef<CheckString> checkStrings)
{
   CLI::App &parser = retrieve_command_parser();
   bool enableVarScope = parser.get_option("--enable-var-scope")->count() > 0 ? true : false;
   bool checksFailed = false;
   /// variableTable - This holds all the current filecheck variables.
   StringMap<std::string> variableTable;
   for (const auto& def : sg_defines) {
      variableTable.insert(StringRef(def).split('='));
   }
   unsigned i = 0, j = 0, e = checkStrings.getSize();
   while (true) {
      StringRef checkRegion;
      if (j == e) {
         checkRegion = buffer;
      } else {
         const CheckString &checkLabelStr = checkStrings[j];
         if (checkLabelStr.m_pattern.getCheckType() != CheckType::CheckLabel) {
            ++j;
            continue;
         }

         // Scan to next CHECK-LABEL match, ignoring CHECK-NOT and CHECK-DAG
         size_t matchLabelLen = 0;
         size_t matchLabelPos =
               checkLabelStr.check(sourceMgr, buffer, true, matchLabelLen, variableTable);
         if (matchLabelPos == StringRef::npos) {
            // Immediately bail of CHECK-LABEL fails, nothing else we can do.
            return false;
         }
         checkRegion = buffer.substr(0, matchLabelPos + matchLabelLen);
         buffer = buffer.substr(matchLabelPos + matchLabelLen);
         ++j;
      }
      if (enableVarScope) {
         clear_local_vars(variableTable);
      }
      for (; i != j; ++i) {
         const CheckString &checkStr = checkStrings[i];
         // Check each string within the scanned region, including a second check
         // of any final CHECK-LABEL (to verify CHECK-NOT and CHECK-DAG)
         size_t matchLen = 0;
         size_t matchPos =
               checkStr.check(sourceMgr, checkRegion, false, matchLen, variableTable);

         if (matchPos == StringRef::npos) {
            checksFailed = true;
            i = j;
            break;
         }

         checkRegion = checkRegion.substr(matchPos + matchLen);
      }

      if (j == e) {
         break;
      }
   }
   // Success if no checks failed.
   return !checksFailed;
}

} // filechecker
} // polar

max_stars_repo_name: normal-coder/polarphp

max_issues_repo_name: normal-coder/polarphp

max_forks_repo_name: normal-coder/polarphp


text:
// Copyright (c) 2012 Christopher Lux <christopherlux@gmail.com>
// Distributed under the Modified BSD License, see license.txt.

#include "display_impl_win32.h"

#if SCM_PLATFORM == SCM_PLATFORM_WINDOWS

#include <exception>
#include <stdexcept>
#include <sstream>
#include <string>

#include <boost/lexical_cast.hpp>
#include <boost/unordered_map.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>

#include <scm/log.h>
#include <scm/core/memory.h>

#include <scm/gl_core/window_management/wm_win32/util/classic_context_win32.h>
#include <scm/gl_core/window_management/wm_win32/util/error_win32.h>
#include <scm/gl_core/window_management/wm_win32/util/wgl_extensions.h>

namespace scm {
namespace gl {
namespace wm {

namespace detail {

typedef boost::unordered_map<std::string, shared_ptr<display_info> > display_info_map;

bool
enum_display_infos(display_info_map& display_infos, std::ostream& os)
{
    display_infos.clear();

    int num_output_devices = ::GetSystemMetrics(SM_CMONITORS);

    if (num_output_devices < 1) {
        os << "display::display_impl::enum_display_infos() <win32>: "
           << "unable to determine number of monitor output devices in system";
        return (false);
    }

    for (int i = 0; i < num_output_devices; ++i) {
        DISPLAY_DEVICE  disp_device;
        DEVMODE         disp_mode;

        ::ZeroMemory(&disp_device, sizeof(disp_device));
        disp_device.cb = sizeof(DISPLAY_DEVICE);

        if (0 == ::EnumDisplayDevices(NULL, i, &disp_device, 0)) {
            os << "display::display_impl::enum_display_infos() <win32>: "
               << "EnumDisplayDevices failed for device num " + boost::lexical_cast<std::string>(i);
            return (false);
        }

        if (0 == ::EnumDisplaySettings(disp_device.DeviceName, ENUM_CURRENT_SETTINGS, &disp_mode)) {
            os << "display::display_impl::enum_display_infos() <win32>: "
               << "EnumDisplaySettings failed for device num " + boost::lexical_cast<std::string>(i);
            //return (false);

        }
        else {
        //std::cout << "dev_name = " << dev_mode.dmDeviceName << ",\tdev_mode._width = " << dev_mode.dmPelsWidth << ",\t dev_mode._height = " << dev_mode.dmPelsHeight
        //          << ",\t dev_mode._refresh_rate = " << dev_mode.dmDisplayFrequency << ",\t dev_mode._bpp = " << dev_mode.dmBitsPerPel << ",\t dev_pos.x = " << dev_mode.dmPosition.x
        //          << ",\t dev_pos.y = " << dev_mode.dmPosition.y << std::endl;

            shared_ptr<display_info>    di(new display_info());

            di->_dev_name               = disp_device.DeviceName;
            di->_dev_string             = disp_device.DeviceString;
            di->_screen_origin          = math::vec2i(disp_mode.dmPosition.x, disp_mode.dmPosition.y);
            di->_screen_size            = math::vec2i(disp_mode.dmPelsWidth, disp_mode.dmPelsHeight);
            di->_screen_refresh_rate    = disp_mode.dmDisplayFrequency;
            di->_screen_bpp             = disp_mode.dmBitsPerPel;

            display_infos.insert(std::make_pair(di->_dev_name, di));
        }
    }

    return !display_infos.empty();
}

std::string
default_display_name()
{
    DISPLAY_DEVICE  disp_device;

    ::ZeroMemory(&disp_device, sizeof(disp_device));
    disp_device.cb = sizeof(DISPLAY_DEVICE);

    if (0 == ::EnumDisplayDevices(NULL, 0, &disp_device, 0)) {
        err() << log::error
              << "display::display_impl::default_display_name() <win32>: "
              << "EnumDisplayDevices failed for device num " + boost::lexical_cast<std::string>(0) << log::end;
        return ("");
    }
    else {
        return (std::string(disp_device.DeviceName));
    }
}

} // namespace detail

display::display_impl::display_impl(const std::string& name)
  : _hinstance(0),
    _device_handle(0),
    _wgl_extensions(new util::wgl_extensions())
{
    try {
        _hinstance = ::GetModuleHandle(0);

        if (!_hinstance) {
            std::ostringstream s;
            s << "display::display_impl::display_impl() <win32>: "
              << "unable to get module handle "
              << "(system message: " << util::win32_error_message() << ")" << log::end;
            //err() << log::fatal << s.str() << log::end;
            throw(std::runtime_error(s.str()));

        }

        std::string class_name(name + boost::lexical_cast<std::string>(boost::uuids::random_generator()()));

        WNDCLASSEX wnd_class;
        ZeroMemory(&wnd_class, sizeof(WNDCLASSEX));
        wnd_class.cbSize        = sizeof(WNDCLASSEX);
        wnd_class.lpfnWndProc   = &DefWindowProc;
        wnd_class.style         = CS_OWNDC | CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS;
        wnd_class.hInstance     = _hinstance;
        wnd_class.hbrBackground = 0;//(HBRUSH)::GetStockObject(DKGRAY_BRUSH);
        wnd_class.lpszClassName = class_name.c_str();

        _window_class = ::RegisterClassEx(&wnd_class);

        if (0 == _window_class) {
            std::ostringstream s;
            s << "display::display_impl::display_impl() <win32>: "
              << "unable to register window class (" << class_name << ") "
              << "(system message: " << util::win32_error_message() << ")";
            //err() << log::fatal << s.str() << log::end;
            throw(std::runtime_error(s.str()));
        }
        //else {
        //    std::cout << class_name << " registered" << std::endl;
        //}

        detail::display_info_map display_infos;

        std::stringstream dsp_enum_err;
        if (!detail::enum_display_infos(display_infos, dsp_enum_err)) {
            std::ostringstream s;
            s << "display::display_impl::display_impl() <win32>: "
              << "unable to enumerate displays: " << dsp_enum_err.str() << std::endl;
            //err() << log::fatal << s.str() << log::end;
            throw(std::runtime_error(s.str()));
        }

        std::string disp_name;
        if (name.empty()) {// == std::string("")) {
            disp_name = detail::default_display_name();
        }
        else {
            disp_name = name;
        }

        detail::display_info_map::const_iterator dsp = display_infos.find(disp_name);

        if (dsp == display_infos.end()) {
            std::ostringstream s;
            s << "display::display_impl::display_impl() <win32>: "
              << "unable find display (" << disp_name << ")" << std::endl
              << "available displays:" << std::endl;
            for (detail::display_info_map::const_iterator i = display_infos.begin();
                 i != display_infos.end(); ++i) {
                s << i->first << std::endl;
            }
            //err() << log::fatal << s.str() << log::end;
            throw(std::runtime_error(s.str()));
        }

        _info           = dsp->second;
        _device_handle  = ::CreateDC(TEXT("DISPLAY"), _info->_dev_name.c_str(), 0, NULL);

        if (0 == _device_handle) {
            std::ostringstream s;
            s << "display::display_impl::display_impl() <win32>: "
              << "unable to create device context "
              << "(system message: " << util::win32_error_message() << ")";
            //err() << log::fatal << s.str() << log::end;
            throw(std::runtime_error(s.str()));
        }

        // setup a dummy gl context to initialize the wgl extensions
        scm::scoped_ptr<util::classic_gl_window>    dummy_window;
        scm::scoped_ptr<util::classic_gl_context>   dummy_context;

        dummy_window.reset(new util::classic_gl_window(_info->_screen_origin, math::vec2ui(10, 10)));
        if (!dummy_window->valid()) {
             std::ostringstream s;
            s << "display::display_impl::display_impl() <win32>: "
              << "unable to create dummy window for WGL initialization.";
            //err() << log::fatal << s.str() << log::end;
            throw(std::runtime_error(s.str()));
       }
        dummy_context.reset(new util::classic_gl_context(*dummy_window));
        if (!dummy_context->valid()) {
            std::ostringstream s;
            s << "display::display_impl::display_impl() <win32>: "
              << "unable to create dummy window context for WGL initialization.";
            //err() << log::fatal << s.str() << log::end;
            throw(std::runtime_error(s.str()));
        }

        std::stringstream init_err;
        if (!_wgl_extensions->initialize(init_err)) {
            std::ostringstream s;
            s << "display::display_impl::display_impl() <win32>: "
              << "unable to initialize WGL ARB extensions, WGL init failed: "
              << init_err.str();
            //err() << log::fatal << s.str() << log::end;
            throw(std::runtime_error(s.str()));
        }

        dummy_context.reset();
        dummy_window.reset();
    }
    catch(...) {
        cleanup();
        throw;
    }
}

display::display_impl::~display_impl()
{
    cleanup();
}

void
display::display_impl::cleanup()
{
    if (_device_handle) {
        if (0 == ::DeleteDC(_device_handle)) {
            err() << log::error
                  << "display::display_impl::~display_impl() <win32>: "
                  << "unable to delete device context "
                  << "(system message: " << util::win32_error_message() << ")" << log::end;
        }
    }
    if (_window_class) {
        if (0 == ::UnregisterClass(reinterpret_cast<LPCSTR>(_window_class), _hinstance)) {
            err() << log::error
                  << "display::display_impl::~display_impl() <win32>: "
                  << "unable to unregister window class "
                  << "(system message: " << util::win32_error_message() << ")" << log::end;
        }
    }
    _info.reset();
}

} // namespace wm
} // namepspace gl
} // namepspace scm

#endif // SCM_PLATFORM == SCM_PLATFORM_WINDOWS

max_stars_repo_name: Nyran/schism

max_issues_repo_name: Nyran/schism

max_forks_repo_name: Nyran/schism


text:
//
// Created by 王耀 on 2017/9/16.
//

#include "config.h"
#include "mmu.h"
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <iostream>

Config* Config::instance = nullptr;
bool Config::mShowErrorLog = true;

Config* Config::getInstance() {
    if (!instance)
        init();
    return instance;
}

bool Config::init(const std::string &path, const bool showErrorLog) {
    Config::mShowErrorLog = showErrorLog;
    delete instance;
    try {
        instance = new Config(path);
    } catch (std::bad_alloc& e) {
        if (Config::mShowErrorLog)
            std::cerr << "Alloc Error: " << e.what() << std::endl;
        return false;
    }
    return instance != nullptr && instance->check();
}

bool Config::check() {
    mValid = MMU::check();
    return mValid;
}

Config::Config(const std::string &path) {
    mConfigPath = path;
    if (!reload()) {
        if (Config::mShowErrorLog)
            std::cerr << "Using default config." << std::endl;
        loadDefault();
    }
}

/*
 * This method needs change when add/delete configurations items.
 */

bool Config::reload() {
    std::ifstream configFileStream(mConfigPath.c_str(), std::ifstream::in | std::ifstream::binary);
    if (configFileStream.fail()) {
        if (Config::mShowErrorLog)
            std::cerr << "Loading Config File Error: '" << mConfigPath << "'." << std::endl;
        return false;
    }
    boost::property_tree::ptree pt;
    try {
        boost::property_tree::read_json(configFileStream, pt);
    } catch (boost::property_tree::ptree_error &e) {
        if (Config::mShowErrorLog)
            std::cerr << "Building JSON Tree Error: " << std::endl;
        return false;
    }
    try {
        boost::property_tree::ptree cpu = pt.get_child("CPU");
        boost::property_tree::ptree disk = pt.get_child("DISK");
        boost::property_tree::ptree mem = pt.get_child("MEM");
        boost::property_tree::ptree os = pt.get_child("OS");

        /* CPU configuration */
        CPU.CORE_NUM = cpu.get<unsigned int>("CORE_NUM");
        CPU.CPU_RATE = cpu.get<unsigned long>("CPU_RATE");

        /* DISK configuration */
        DISK.ROOT_PATH = disk.get<std::string>("ROOT_PATH");
        DISK.BLOCK_SIZE = disk.get<unsigned int>("BLOCK_SIZE");
        DISK.BLOCK_COUNT = disk.get<unsigned long>("BLOCK_COUNT");
        boost::property_tree::ptree disk_buffer = disk.get_child("BUFFER");
        DISK.BUFFER.DEFAULT_BLOCK = disk_buffer.get<unsigned int>("DEFAULT_BLOCK");
        DISK.BUFFER.MAX_BLOCK = disk_buffer.get<unsigned int>("MAX_BLOCK");
        DISK.BUFFER.MIN_BLOCK = disk_buffer.get<unsigned int>("MIN_BLOCK");
        DISK.DEFAULT_BLOCKS_PER_FILE = disk.get<unsigned int>("DEFAULT_BLOCKS_PER_FILE");

        /* MEM configuration */
        MEM.DEFAULT_CAPACITY = mem.get<unsigned long>("DEFAULT_CAPACITY");
        MEM.DEFAULT_PROCESS_PAGE = mem.get<unsigned long>("DEFAULT_PROCESS_PAGE");
        MEM.DEFAULT_STACK_PAGE = mem.get<unsigned long>("DEFAULT_STACK_PAGE");
        MEM.DEFAULT_PAGE_BIT = mem.get<unsigned char>("DEFAULT_PAGE_BIT");
        MEM.DEFAULT_PAGE_SIZE = (unsigned int)(1 << MEM.DEFAULT_PAGE_BIT);

        /* OS configuration */
        boost::property_tree::ptree os_mem = os.get_child("MEM");
        OS.MEM.DEFAULT_OS_USED_PAGE = os_mem.get<unsigned int>("DEFAULT_OS_USED_PAGE");
        OS.MEM.SWAP_PAGE = os_mem.get<unsigned long>("SWAP_PAGE");
        OS.MEM.SWAP_BLOCK = OS.MEM.SWAP_PAGE * (MEM.DEFAULT_PAGE_SIZE / DISK.BLOCK_SIZE);
        OS.MEM.SWAP_SIZE = OS.MEM.SWAP_PAGE << MEM.DEFAULT_PAGE_BIT;
        OS.BOOT_MEMORY_KB = os.get<unsigned int>("BOOT_MEMORY_KB");
        OS.MAXIMUM_TASKS = os.get<unsigned int>("MAXIMUM_TASKS");
        OS.MAXIMUM_TASK_PAGE = os.get<unsigned long>("MAXIMUM_TASK_PAGE");
        OS.EXEC_FILE_EXT = os.get<std::string>("EXEC_FILE_EXT");
        OS.TICKS_PER_SEC = os.get<unsigned long>("TICKS_PER_SEC");
        OS.TICKS_PER_SCHED = os.get<unsigned long>("TICKS_PER_SCHED");
        OS.MAX_SEM = os.get<unsigned long>("MAX_SEM");

    } catch (boost::property_tree::ptree_error &e) {
        if (Config::mShowErrorLog)
            std::cerr << "Parsing JSON Tree Error: " << e.what() << "." << std::endl;
        return false;
    }
    return true;
}

/*
 * This method needs change when add/modify/remove configuration items, or
 * you wanna adjust the default values for some configuration items.
 */

void Config::loadDefault() {
    CPU.CORE_NUM = _CPU_CORE_NUM;
    CPU.CPU_RATE = _CPU_CPU_RATE;
    DISK.ROOT_PATH = _DISK_ROOT_PATH;
    DISK.BLOCK_SIZE = _DISK_BLOCK_SIZE;
    DISK.BLOCK_COUNT = _DISK_BLOCK_COUNT;
    DISK.BUFFER.DEFAULT_BLOCK = _DISK_BUFFER_DEFAULT_BLOCK;
    DISK.BUFFER.MAX_BLOCK = _DISK_BUFFER_MAX_BLOCK;
    DISK.BUFFER.MIN_BLOCK = _DISK_BUFFER_MIN_BLOCK;
    DISK.DEFAULT_BLOCKS_PER_FILE = _DISK_DEFAULT_BLOCKS_PER_FILE;
    MEM.DEFAULT_CAPACITY = _MEM_DEFAULT_CAPACITY;
    MEM.DEFAULT_PROCESS_PAGE = _MEM_DEFAULT_PROCESS_PAGE;
    MEM.DEFAULT_STACK_PAGE = _MEM_DEFAULT_STACK_PAGE;
    MEM.DEFAULT_PAGE_BIT = _MEM_DEFAULT_PAGE_BIT;
    MEM.DEFAULT_PAGE_SIZE = _MEM_DEFAULT_PAGE_SIZE;
    OS.MEM.DEFAULT_OS_USED_PAGE = _OS_MEM_DEFAULT_OS_USED_PAGE;
    OS.MEM.SWAP_PAGE = _OS_MEM_SWAP_PAGE;
    OS.MEM.SWAP_BLOCK = _OS_MEM_SWAP_BLOCK;
    OS.MEM.SWAP_SIZE = _OS_MEM_SWAP_SIZE;
    OS.BOOT_MEMORY_KB = _OS_BOOT_MEMORY_KB;
    OS.MAXIMUM_TASKS = _OS_MAXIMUM_TASKS;
    OS.MAXIMUM_TASK_PAGE = _OS_MAXIMUM_TASK_PAGE;
    OS.EXEC_FILE_EXT = _OS_EXEC_FILE_EXT;
    OS.TICKS_PER_SEC = _OS_TICKS_PER_SEC;
    OS.TICKS_PER_SCHED = _OS_TICKS_PER_SCHED;
    OS.MAX_SEM = _OS_MAX_SEM;
}

max_stars_repo_name: forec-org/os-sumulator

max_issues_repo_name: forec-org/os-sumulator

max_forks_repo_name: forec-org/os-sumulator


text: #include <boost/accumulators/statistics/p_square_cumulative_distribution.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/* Copyright 2022 Zuru Tech HK Limited.
 *
 * Licensed under the Apache License, Version 2.0(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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef SOLVERS_PETSCSOLVER_HPP
#define SOLVERS_PETSCSOLVER_HPP

#include <Eigen/Dense>

#include <petscksp.h>

#include <solvers/Solver.hpp>
#include <solvers/SparseSystem.hpp>

namespace solvers {

enum class PetscMethod {
    CG,
    FlexibleCG,
    GMRES,
    FlexibleGMRES,
    QMR,
    CR,
    MinRes,
    SymmLQ,
    Cholesky,
    LU,
    QR
};

enum class PetscPreconditioner { None, Jacobi, SOR, Eisenstat, ILU, ICC };

/**
 * \brief PetscSolver Solver based on PETSc library.
 */
class PetscSolver : public Solver {
private:
    /**
     * \brief _ksp Resolution algorithm.
     */
    KSP _ksp{};

public:
    explicit PetscSolver(
        PetscMethod method = PetscMethod::CG,
        PetscPreconditioner preconditioner = PetscPreconditioner::None);

    Eigen::VectorXd solve(const SparseSystem& system,
                          double& duration) const override;
};

}    // namespace solvers

#endif    // SOLVERS_PETSCSOLVER_HPP

max_stars_repo_name: zurutech/stand

max_issues_repo_name: zurutech/stand

max_forks_repo_name: zurutech/stand