<commit_before>/*
 * Copyright (c) 2016 Jason White
 *
 * 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 <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <vector>

#include "pefile.h"
#include "pemap.h"
#include "pepatch.h"

namespace {

/**
 * A range of memory to patch. This is used to keep track of what needs to be
 * patched in the PE file.
 *
 * All the patch locations need to be found before finishing parsing. If we
 * patched while parsing, then parsing could fail and we could be left with an
 * incomplete patch. Thus, we keep a list of patches and patch everything all at
 * once to mitigate failure cases.
 */
struct Patch
{
    // Location to patch.
    uint8_t* addr;

    // Length of the data.
    size_t length;

    // Data overwrite the given location with.
    const uint8_t* data;

    Patch(uint8_t* addr, size_t length, const uint8_t* data)
        : addr(addr), length(length), data(data)
    {}

    template<typename T>
    Patch(T* addr, const T* data)
        : addr((uint8_t*)addr),
          length(sizeof(T)),
          data((const uint8_t*)data)
    {
    }

    /**
     * Applies the patch. Note that no bounds checking is done. It is assumed
     * that it has already been done.
     */
    void apply() {
        for (size_t i = 0; i < length; ++i)
            *addr = data[i];
    }
};

class Patches
{
private:
    // List of patches
    std::vector<Patch> _patches;

public:

    Patches() {}
    ~Patches() {}

    void add(Patch patch);

    void applyAll();
};

void Patches::add(Patch patch) {
    _patches.push_back(patch);
}

void Patches::applyAll() {
    for (auto&& patch: _patches)
        patch.apply();
}

}

void patchImage(const char* imagePath, const char* pdbPath) {
    MemMap image(imagePath);

    // Replacement for timestamps
    const uint32_t timestamp = 0;

    uint8_t* pStart = (uint8_t*)image.buf();
    uint8_t* pEnd   = pStart + image.length();
    uint8_t* p      = pStart;

    Patches patches;

    if (image.length() < sizeof(IMAGE_DOS_HEADER))
        throw InvalidImage("missing DOS header");

    IMAGE_DOS_HEADER* dosHeader = (IMAGE_DOS_HEADER*)p;
    if (dosHeader->e_magic != IMAGE_DOS_SIGNATURE)
        throw InvalidImage("invalid DOS signature");

    // Skip to the NT headers. Note that we assume this is a PE32 (not a PE32+)
    // header for now.
    p += dosHeader->e_lfanew;
    if (p + sizeof(IMAGE_NT_HEADERS32) >= pEnd)
        throw InvalidImage("missing IMAGE_NT_HEADERS");

    IMAGE_NT_HEADERS32* ntHeaders = (IMAGE_NT_HEADERS32*)p;

    // Check the signature
    if (ntHeaders->Signature != *(const uint32_t*)"PE\0\0")
        throw InvalidImage("invalid PE signature");

    // Eliminate non-determinism
    patches.add(Patch(&ntHeaders->FileHeader.TimeDateStamp, &timestamp));
    patches.add(Patch(&ntHeaders->OptionalHeader.CheckSum, &timestamp));

    patches.applyAll();
}
<commit_msg>Minor fefactoring<commit_after>/*
 * Copyright (c) 2016 Jason White
 *
 * 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 <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <vector>

#include "pefile.h"
#include "pemap.h"
#include "pepatch.h"

namespace {

/**
 * A range of memory to patch. This is used to keep track of what needs to be
 * patched in the PE file.
 *
 * All the patch locations need to be found before finishing parsing. If we
 * patched while parsing, then parsing could fail and we could be left with an
 * incomplete patch. Thus, we keep a list of patches and patch everything all at
 * once to mitigate failure cases.
 */
struct Patch
{
    // Location to patch.
    uint8_t* addr;

    // Length of the data.
    size_t length;

    // Data overwrite the given location with.
    const uint8_t* data;

    Patch(uint8_t* addr, size_t length, const uint8_t* data)
        : addr(addr), length(length), data(data)
    {}

    template<typename T>
    Patch(T* addr, const T* data)
        : addr((uint8_t*)addr),
          length(sizeof(T)),
          data((const uint8_t*)data)
    {
    }

    /**
     * Applies the patch. Note that no bounds checking is done. It is assumed
     * that it has already been done.
     */
    void apply() {
        for (size_t i = 0; i < length; ++i)
            *addr = data[i];
    }
};

class Patches
{
private:
    // List of patches
    std::vector<Patch> _patches;

public:

    Patches() {}
    ~Patches() {}

    void add(Patch patch) {
        _patches.push_back(patch);
    }

    void applyAll() {
        for (auto&& patch: _patches)
            patch.apply();
    }
};

}

void patchImage(const char* imagePath, const char* pdbPath) {
    MemMap image(imagePath);

    // Replacement for timestamps
    const uint32_t timestamp = 0;

    uint8_t* pStart = (uint8_t*)image.buf();
    uint8_t* pEnd   = pStart + image.length();
    uint8_t* p      = pStart;

    Patches patches;

    if (image.length() < sizeof(IMAGE_DOS_HEADER))
        throw InvalidImage("missing DOS header");

    IMAGE_DOS_HEADER* dosHeader = (IMAGE_DOS_HEADER*)p;
    if (dosHeader->e_magic != IMAGE_DOS_SIGNATURE)
        throw InvalidImage("invalid DOS signature");

    // Skip to the NT headers. Note that we assume this is a PE32 (not a PE32+)
    // header for now.
    p += dosHeader->e_lfanew;
    if (p + sizeof(IMAGE_NT_HEADERS32) >= pEnd)
        throw InvalidImage("missing IMAGE_NT_HEADERS");

    IMAGE_NT_HEADERS32* ntHeaders = (IMAGE_NT_HEADERS32*)p;

    // Check the signature
    if (ntHeaders->Signature != *(const uint32_t*)"PE\0\0")
        throw InvalidImage("invalid PE signature");

    // Eliminate non-determinism
    patches.add(Patch(&ntHeaders->FileHeader.TimeDateStamp, &timestamp));
    patches.add(Patch(&ntHeaders->OptionalHeader.CheckSum, &timestamp));

    patches.applyAll();
}
<|endoftext|>


<commit_before>#include <mettle.hpp>
using namespace mettle;

#include "run_counter.hpp"

template<typename F, typename Tuple, std::size_t ...I>
decltype(auto) apply_impl(F &&f, Tuple &&t, std::index_sequence<I...>) {
  return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
}

template<typename F, typename Tuple>
decltype(auto) apply(F&& f, Tuple &&t) {
  using Indices = std::make_index_sequence<
    std::tuple_size<std::decay_t<Tuple>>::value
  >;
  return apply_impl(std::forward<F>(f), std::forward<Tuple>(t), Indices());
}

template<typename Tuple>
struct run_counter_from_tuple_t;

template<typename ...T>
struct run_counter_from_tuple_t<std::tuple<T...>> {
  using type = run_counter<T &...>;
};

template<typename Tuple>
using run_counter_from_tuple = typename run_counter_from_tuple_t<Tuple>::type;

using namespace mettle::detail;

suite<std::tuple<>, std::tuple<int, int>>
test_test_caller("test_caller", [](auto &_) {
  using Fixture = fixture_type_t<decltype(_)>;

  _.test("test with no fixture", [](auto &tup) {
    run_counter_from_tuple<Fixture> setup, teardown, test;
    test_caller<auto_factory_t, Fixture> t(
      auto_factory, setup, teardown, test
    );
    apply(t, tup);

    expect("setup run count", setup.runs(), equal_to(1));
    expect("test run count", test.runs(), equal_to(1));
    expect("teardown run count", teardown.runs(), equal_to(1));
  });

// XXX: Enable this test on MSVC (it triggers an ICE somewhere).
#if !defined(_MSC_VER) || defined(__clang__)
  _.test("test with auto fixture", [](auto &tup) {
    run_counter_from_tuple<decltype(
      std::tuple_cat(tup, std::tuple<int>())
    )> setup, teardown, test;
    test_caller<auto_factory_t, Fixture, int> t(
      auto_factory, setup, teardown, test
    );
    apply(t, tup);

    expect("setup run count", setup.runs(), equal_to(1));
    expect("test run count", test.runs(), equal_to(1));
    expect("teardown run count", teardown.runs(), equal_to(1));
  });
#endif

  _.test("test with type-only fixture", [](auto &tup) {
    run_counter_from_tuple<Fixture> setup, teardown, test;
    test_caller<type_only_factory_t, Fixture, int> t(
      type_only, setup, teardown, test
    );
    apply(t, tup);

    expect("setup run count", setup.runs(), equal_to(1));
    expect("test run count", test.runs(), equal_to(1));
    expect("teardown run count", teardown.runs(), equal_to(1));
  });
});
<commit_msg>Enable test_caller tests on MSVC<commit_after>#include <mettle.hpp>
using namespace mettle;

#include "run_counter.hpp"

template<typename F, typename Tuple, std::size_t ...I>
decltype(auto) apply_impl(F &&f, Tuple &&t, std::index_sequence<I...>) {
  return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
}

template<typename F, typename Tuple>
decltype(auto) apply(F&& f, Tuple &&t) {
  using Indices = std::make_index_sequence<
    std::tuple_size<std::decay_t<Tuple>>::value
  >;
  return apply_impl(std::forward<F>(f), std::forward<Tuple>(t), Indices());
}

template<typename Tuple>
struct run_counter_from_tuple_t;

template<typename ...T>
struct run_counter_from_tuple_t<std::tuple<T...>> {
  using type = run_counter<T &...>;
};

template<typename Tuple>
using run_counter_from_tuple = typename run_counter_from_tuple_t<Tuple>::type;

using namespace mettle::detail;

suite<std::tuple<>, std::tuple<int, int>>
test_test_caller("test_caller", [](auto &_) {
  using Fixture = fixture_type_t<decltype(_)>;

  _.test("test with no fixture", [](auto &tup) {
    run_counter_from_tuple<Fixture> setup, teardown, test;
    test_caller<auto_factory_t, Fixture> t(
      auto_factory, setup, teardown, test
    );
    apply(t, tup);

    expect("setup run count", setup.runs(), equal_to(1));
    expect("test run count", test.runs(), equal_to(1));
    expect("teardown run count", teardown.runs(), equal_to(1));
  });

  _.test("test with auto fixture", [](auto &tup) {
    run_counter_from_tuple<decltype(
      std::tuple_cat(tup, std::tuple<int>())
    )> setup, teardown, test;
    test_caller<auto_factory_t, Fixture, int> t(
      auto_factory, setup, teardown, test
    );
    apply(t, tup);

    expect("setup run count", setup.runs(), equal_to(1));
    expect("test run count", test.runs(), equal_to(1));
    expect("teardown run count", teardown.runs(), equal_to(1));
  });

  _.test("test with type-only fixture", [](auto &tup) {
    run_counter_from_tuple<Fixture> setup, teardown, test;
    test_caller<type_only_factory_t, Fixture, int> t(
      type_only, setup, teardown, test
    );
    apply(t, tup);

    expect("setup run count", setup.runs(), equal_to(1));
    expect("test run count", test.runs(), equal_to(1));
    expect("teardown run count", teardown.runs(), equal_to(1));
  });
});
<|endoftext|>


<commit_before>#include "bs_mesh_stdafx.h"

#include "py_rs_mesh.h"
#include "bs_mesh_grdecl.h"

#include "export_python_wrapper.h"
#include "py_pair_converter.h"
#include <boost/python/tuple.hpp>

#ifdef BSPY_EXPORTING_PLUGIN
using namespace boost::python;

namespace blue_sky { namespace python {

void init_props1(bs_mesh_grdecl& m, t_long nx, t_long ny, t_long nz,
	spv_float dx, spv_float dy, spv_float dz)
{
	m.init_props(nx, ny, nz, dx, dy, dz);
}

void init_props2(bs_mesh_grdecl& m, t_long nx, t_long ny, spv_float coord, spv_float zcorn) {
	m.init_props(nx, ny, coord, zcorn);
}

PY_EXPORTER (mesh_grdecl_exporter, rs_mesh_iface_exporter)
	.def ("get_ext_to_int", &T::get_ext_to_int, args(""), "Return reference to external-to-internal mesh index")
	.def ("get_int_to_ext", &T::get_int_to_ext, args(""), "Return reference to internal-to-external mesh index")
	.def ("get_volumes", &T::get_volumes, args(""), "Return reference to volumes vector")
	.def ("get_dimensions_range", &T::get_dimensions_range, args("dim1_max, dim1_min, dim2_max, dim2_min, dim3_max, dim3_min"), "Get dimensions ranges")
	.def ("get_element_size", &T::get_element_size, args ("n_elem, dx, dy, dz"), "get elements sizes")
	.def ("get_element_dz", &T::get_element_dim3_size, args ("n_elem"), "get elements dz by internal index")
	.def ("get_element_dz_ext", &T::get_element_dim3_size_ext, args ("i, j, k"), "get elements dz by external index")
	.def ("get_element_ijk_to_int", &T::get_element_ijk_to_int, args ("i, j, k"), "get elements sizes")
	.def ("get_n_active_elements", &T::get_n_active_elements, args (""), "Get elements sizes")
	.def ("calc_element_tops", &T::calc_element_tops, args (""), "Calc element tops")
	.def ("calc_element_center", &T::calc_element_center, args (""), "Calc element center")
	.def ("calc_cells_vertices", &T::calc_cells_vertices)
	.def ("init_props", &init_props1)
	.def ("init_props", &init_props2)
	.def ("get_element_sizes", &T::get_element_sizes)
	;
PY_EXPORTER_END;

}}  // eof blue_sky::python

namespace {
using namespace blue_sky;
using namespace blue_sky::python;

// same as grdecl exporter, but also export gen_coord_zcorn
template <typename T>
struct mesh_grdecl_exporter_plus {
	typedef t_long int_t;
	typedef t_double fp_t;
	typedef spv_float spfp_storarr_t;
	typedef spv_long spi_arr_t;
	typedef typename spi_arr_t::pure_pointed_t int_arr_t;
	typedef std::pair< spv_float, spv_float > coord_zcorn_pair;

	// gen_coord_zcorn overloads
	static coord_zcorn_pair gen_coord_zcorn1(int_t nx, int_t ny, int_t nz, spfp_storarr_t dx, spfp_storarr_t dy, spfp_storarr_t dz,
			fp_t x0, fp_t y0)
	{
		return T::gen_coord_zcorn(nx, ny, nz, dx, dy, dz, x0, y0);
	}
	static coord_zcorn_pair gen_coord_zcorn2(int_t nx, int_t ny, int_t nz, spfp_storarr_t dx, spfp_storarr_t dy, spfp_storarr_t dz,
			fp_t x0)
	{
		return T::gen_coord_zcorn(nx, ny, nz, dx, dy, dz, x0);
	}
	static coord_zcorn_pair gen_coord_zcorn3(int_t nx, int_t ny, int_t nz, spfp_storarr_t dx, spfp_storarr_t dy, spfp_storarr_t dz)
	{
		return T::gen_coord_zcorn(nx, ny, nz, dx, dy, dz);
	}

	// refine_mesh_deltas with overloads
	static tuple refine_mesh_deltas(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t points,
			fp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD)
	{
		spi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type());
		std::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh_deltas(nx, ny, coord, points, hit_idx, m_thresh, b_thresh);
		return make_tuple(r.first, r.second, nx, ny, hit_idx);
	}

	static tuple refine_mesh_deltas1(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t points) {
		return refine_mesh_deltas(nx, ny, coord, points);
	}
	static tuple refine_mesh_deltas2(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t points, fp_t m_thresh) {
		return refine_mesh_deltas(nx, ny, coord, points, m_thresh);
	}

	// refine_mesh with overloads
	static tuple refine_mesh(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points,
			fp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD)
	{
		spi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type());
		std::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh(nx, ny, coord, zcorn, points, hit_idx, m_thresh, b_thresh);
		return make_tuple(r.first, r.second, nx, ny, hit_idx);
	}

	static tuple refine_mesh1(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points) {
		return refine_mesh(nx, ny, coord, zcorn, points);
	}
	static tuple refine_mesh2(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points, fp_t m_thresh) {
		return refine_mesh(nx, ny, coord, zcorn, points, m_thresh);
	}

	// refine_mesh_deltas with overloads
	// (i,j) points format
	static tuple refine_mesh_deltas_ij(int_t nx, int_t ny, spfp_storarr_t coord,
			spi_arr_t points_pos, spfp_storarr_t points_param,
			fp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD)
	{
		spi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type());
		std::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh_deltas(nx, ny, coord, points_pos, points_param,
				hit_idx, m_thresh, b_thresh);
		return make_tuple(r.first, r.second, nx, ny, hit_idx);
	}

	static tuple refine_mesh_deltas_ij1(int_t nx, int_t ny, spfp_storarr_t coord,
			spi_arr_t points_pos, spfp_storarr_t points_param)
	{
		return refine_mesh_deltas_ij(nx, ny, coord, points_pos, points_param);
	}

	static tuple refine_mesh_deltas_ij2(int_t nx, int_t ny, spfp_storarr_t coord,
			spi_arr_t points_pos, spfp_storarr_t points_param, fp_t m_thresh)
	{
		return refine_mesh_deltas_ij(nx, ny, coord, points_pos, points_param, m_thresh);
	}

	// refine_mesh with overloads
	// (i, j) points format
	static tuple refine_mesh_ij(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn,
			spi_arr_t points_pos, spfp_storarr_t points_param,
			fp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD)
	{
		spi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type());
		std::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh(nx, ny, coord, zcorn, points_pos, points_param,
				hit_idx, m_thresh, b_thresh);
		return make_tuple(r.first, r.second, nx, ny, hit_idx);
	}

	static tuple refine_mesh_ij1(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn,
			spi_arr_t points_pos, spfp_storarr_t points_param)
	{
		return refine_mesh_ij(nx, ny, coord, zcorn, points_pos, points_param);
	}

	static tuple refine_mesh_ij2(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn,
			spi_arr_t points_pos, spfp_storarr_t points_param, fp_t m_thresh)
	{
		return refine_mesh_ij(nx, ny, coord, zcorn, points_pos, points_param, m_thresh);
	}

	template <typename class_t>
	static class_t &
	export_class (class_t &class__) {
		using namespace boost::python;

		mesh_grdecl_exporter<T>::export_class (class__)
			.def("gen_coord_zcorn", &T::gen_coord_zcorn, "Generate COORD & ZCORN from given dimensions")
			.def("gen_coord_zcorn", &gen_coord_zcorn1, "Generate COORD & ZCORN from given dimensions")
			.def("gen_coord_zcorn", &gen_coord_zcorn2, "Generate COORD & ZCORN from given dimensions")
			.def("gen_coord_zcorn", &gen_coord_zcorn3, "Generate COORD & ZCORN from given dimensions")
			.staticmethod("gen_coord_zcorn")
			.def("refine_mesh_deltas", &refine_mesh_deltas, "Calc dx and dy arrays for refined mesh in given points")
			.def("refine_mesh_deltas", &refine_mesh_deltas1, "Calc dx and dy arrays for refined mesh in given points")
			.def("refine_mesh_deltas", &refine_mesh_deltas2, "Calc dx and dy arrays for refined mesh in given points")
			.def("refine_mesh_deltas", &refine_mesh_deltas_ij, "Calc dx and dy arrays for refined mesh in given points")
			.def("refine_mesh_deltas", &refine_mesh_deltas_ij1, "Calc dx and dy arrays for refined mesh in given points")
			.def("refine_mesh_deltas", &refine_mesh_deltas_ij2, "Calc dx and dy arrays for refined mesh in given points")
			.staticmethod("refine_mesh_deltas")
			.def("refine_mesh", &refine_mesh, "Refine existing mesh in given points")
			.def("refine_mesh", &refine_mesh1, "Refine existing mesh in given points")
			.def("refine_mesh", &refine_mesh2, "Refine existing mesh in given points")
			.def("refine_mesh", &refine_mesh_ij, "Refine existing mesh in given points")
			.def("refine_mesh", &refine_mesh_ij1, "Refine existing mesh in given points")
			.def("refine_mesh", &refine_mesh_ij2, "Refine existing mesh in given points")
			.staticmethod("refine_mesh")
			;
		return class__;
	}
};

template< class fp_type >
void reg_sparray_pair() {
	// register converter from pair of returned arrayes to python list
	typedef std::pair< spv_float, spv_float > array_pair;
	typedef bspy_converter< pair_traits< array_pair > > array_pair_converter;
	array_pair_converter::register_to_py();
	array_pair_converter::register_from_py();
}

} // eof hidden namespace

namespace blue_sky { namespace python {

void py_export_mesh_grdecl () {
	class_exporter< bs_mesh_grdecl, rs_mesh_iface, mesh_grdecl_exporter_plus >::export_class ("mesh_grdecl");
	//reg_sparray_pair< float >();
	reg_sparray_pair< double >();
}

}} // namespace blue_sky::python
#endif
<commit_msg>added vertices_xyz py-export<commit_after>#include "bs_mesh_stdafx.h"

#include "py_rs_mesh.h"
#include "bs_mesh_grdecl.h"

#include "export_python_wrapper.h"
#include "py_pair_converter.h"
#include <boost/python/tuple.hpp>

#ifdef BSPY_EXPORTING_PLUGIN
using namespace boost::python;

namespace blue_sky { namespace python {

void init_props1(bs_mesh_grdecl& m, t_long nx, t_long ny, t_long nz,
	spv_float dx, spv_float dy, spv_float dz)
{
	m.init_props(nx, ny, nz, dx, dy, dz);
}

void init_props2(bs_mesh_grdecl& m, t_long nx, t_long ny, spv_float coord, spv_float zcorn) {
	m.init_props(nx, ny, coord, zcorn);
}

PY_EXPORTER (mesh_grdecl_exporter, rs_mesh_iface_exporter)
	.def ("get_ext_to_int", &T::get_ext_to_int, args(""), "Return reference to external-to-internal mesh index")
	.def ("get_int_to_ext", &T::get_int_to_ext, args(""), "Return reference to internal-to-external mesh index")
	.def ("get_volumes", &T::get_volumes, args(""), "Return reference to volumes vector")
	.def ("get_dimensions_range", &T::get_dimensions_range, args("dim1_max, dim1_min, dim2_max, dim2_min, dim3_max, dim3_min"), "Get dimensions ranges")
	.def ("get_element_size", &T::get_element_size, args ("n_elem, dx, dy, dz"), "get elements sizes")
	.def ("get_element_dz", &T::get_element_dim3_size, args ("n_elem"), "get elements dz by internal index")
	.def ("get_element_dz_ext", &T::get_element_dim3_size_ext, args ("i, j, k"), "get elements dz by external index")
	.def ("get_element_ijk_to_int", &T::get_element_ijk_to_int, args ("i, j, k"), "get elements sizes")
	.def ("get_n_active_elements", &T::get_n_active_elements, args (""), "Get elements sizes")
	.def ("calc_element_tops", &T::calc_element_tops, args (""), "Calc element tops")
	.def ("calc_element_center", &T::calc_element_center, args (""), "Calc element center")
	.def ("calc_cells_vertices", &T::calc_cells_vertices)
	.def ("calc_cells_vertices_xyz", &T::calc_cells_vertices_xyz)
	.def ("init_props", &init_props1)
	.def ("init_props", &init_props2)
	.def ("get_element_sizes", &T::get_element_sizes)
	;
PY_EXPORTER_END;

}}  // eof blue_sky::python

namespace {
using namespace blue_sky;
using namespace blue_sky::python;

// same as grdecl exporter, but also export gen_coord_zcorn
template <typename T>
struct mesh_grdecl_exporter_plus {
	typedef t_long int_t;
	typedef t_double fp_t;
	typedef spv_float spfp_storarr_t;
	typedef spv_long spi_arr_t;
	typedef typename spi_arr_t::pure_pointed_t int_arr_t;
	typedef std::pair< spv_float, spv_float > coord_zcorn_pair;

	// gen_coord_zcorn overloads
	static coord_zcorn_pair gen_coord_zcorn1(int_t nx, int_t ny, int_t nz, spfp_storarr_t dx, spfp_storarr_t dy, spfp_storarr_t dz,
			fp_t x0, fp_t y0)
	{
		return T::gen_coord_zcorn(nx, ny, nz, dx, dy, dz, x0, y0);
	}
	static coord_zcorn_pair gen_coord_zcorn2(int_t nx, int_t ny, int_t nz, spfp_storarr_t dx, spfp_storarr_t dy, spfp_storarr_t dz,
			fp_t x0)
	{
		return T::gen_coord_zcorn(nx, ny, nz, dx, dy, dz, x0);
	}
	static coord_zcorn_pair gen_coord_zcorn3(int_t nx, int_t ny, int_t nz, spfp_storarr_t dx, spfp_storarr_t dy, spfp_storarr_t dz)
	{
		return T::gen_coord_zcorn(nx, ny, nz, dx, dy, dz);
	}

	// refine_mesh_deltas with overloads
	static tuple refine_mesh_deltas(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t points,
			fp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD)
	{
		spi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type());
		std::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh_deltas(nx, ny, coord, points, hit_idx, m_thresh, b_thresh);
		return make_tuple(r.first, r.second, nx, ny, hit_idx);
	}

	static tuple refine_mesh_deltas1(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t points) {
		return refine_mesh_deltas(nx, ny, coord, points);
	}
	static tuple refine_mesh_deltas2(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t points, fp_t m_thresh) {
		return refine_mesh_deltas(nx, ny, coord, points, m_thresh);
	}

	// refine_mesh with overloads
	static tuple refine_mesh(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points,
			fp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD)
	{
		spi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type());
		std::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh(nx, ny, coord, zcorn, points, hit_idx, m_thresh, b_thresh);
		return make_tuple(r.first, r.second, nx, ny, hit_idx);
	}

	static tuple refine_mesh1(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points) {
		return refine_mesh(nx, ny, coord, zcorn, points);
	}
	static tuple refine_mesh2(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points, fp_t m_thresh) {
		return refine_mesh(nx, ny, coord, zcorn, points, m_thresh);
	}

	// refine_mesh_deltas with overloads
	// (i,j) points format
	static tuple refine_mesh_deltas_ij(int_t nx, int_t ny, spfp_storarr_t coord,
			spi_arr_t points_pos, spfp_storarr_t points_param,
			fp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD)
	{
		spi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type());
		std::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh_deltas(nx, ny, coord, points_pos, points_param,
				hit_idx, m_thresh, b_thresh);
		return make_tuple(r.first, r.second, nx, ny, hit_idx);
	}

	static tuple refine_mesh_deltas_ij1(int_t nx, int_t ny, spfp_storarr_t coord,
			spi_arr_t points_pos, spfp_storarr_t points_param)
	{
		return refine_mesh_deltas_ij(nx, ny, coord, points_pos, points_param);
	}

	static tuple refine_mesh_deltas_ij2(int_t nx, int_t ny, spfp_storarr_t coord,
			spi_arr_t points_pos, spfp_storarr_t points_param, fp_t m_thresh)
	{
		return refine_mesh_deltas_ij(nx, ny, coord, points_pos, points_param, m_thresh);
	}

	// refine_mesh with overloads
	// (i, j) points format
	static tuple refine_mesh_ij(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn,
			spi_arr_t points_pos, spfp_storarr_t points_param,
			fp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD)
	{
		spi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type());
		std::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh(nx, ny, coord, zcorn, points_pos, points_param,
				hit_idx, m_thresh, b_thresh);
		return make_tuple(r.first, r.second, nx, ny, hit_idx);
	}

	static tuple refine_mesh_ij1(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn,
			spi_arr_t points_pos, spfp_storarr_t points_param)
	{
		return refine_mesh_ij(nx, ny, coord, zcorn, points_pos, points_param);
	}

	static tuple refine_mesh_ij2(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn,
			spi_arr_t points_pos, spfp_storarr_t points_param, fp_t m_thresh)
	{
		return refine_mesh_ij(nx, ny, coord, zcorn, points_pos, points_param, m_thresh);
	}

	template <typename class_t>
	static class_t &
	export_class (class_t &class__) {
		using namespace boost::python;

		mesh_grdecl_exporter<T>::export_class (class__)
			.def("gen_coord_zcorn", &T::gen_coord_zcorn, "Generate COORD & ZCORN from given dimensions")
			.def("gen_coord_zcorn", &gen_coord_zcorn1, "Generate COORD & ZCORN from given dimensions")
			.def("gen_coord_zcorn", &gen_coord_zcorn2, "Generate COORD & ZCORN from given dimensions")
			.def("gen_coord_zcorn", &gen_coord_zcorn3, "Generate COORD & ZCORN from given dimensions")
			.staticmethod("gen_coord_zcorn")
			.def("refine_mesh_deltas", &refine_mesh_deltas, "Calc dx and dy arrays for refined mesh in given points")
			.def("refine_mesh_deltas", &refine_mesh_deltas1, "Calc dx and dy arrays for refined mesh in given points")
			.def("refine_mesh_deltas", &refine_mesh_deltas2, "Calc dx and dy arrays for refined mesh in given points")
			.def("refine_mesh_deltas", &refine_mesh_deltas_ij, "Calc dx and dy arrays for refined mesh in given points")
			.def("refine_mesh_deltas", &refine_mesh_deltas_ij1, "Calc dx and dy arrays for refined mesh in given points")
			.def("refine_mesh_deltas", &refine_mesh_deltas_ij2, "Calc dx and dy arrays for refined mesh in given points")
			.staticmethod("refine_mesh_deltas")
			.def("refine_mesh", &refine_mesh, "Refine existing mesh in given points")
			.def("refine_mesh", &refine_mesh1, "Refine existing mesh in given points")
			.def("refine_mesh", &refine_mesh2, "Refine existing mesh in given points")
			.def("refine_mesh", &refine_mesh_ij, "Refine existing mesh in given points")
			.def("refine_mesh", &refine_mesh_ij1, "Refine existing mesh in given points")
			.def("refine_mesh", &refine_mesh_ij2, "Refine existing mesh in given points")
			.staticmethod("refine_mesh")
			;
		return class__;
	}
};

template< class fp_type >
void reg_sparray_pair() {
	// register converter from pair of returned arrayes to python list
	typedef std::pair< spv_float, spv_float > array_pair;
	typedef bspy_converter< pair_traits< array_pair > > array_pair_converter;
	array_pair_converter::register_to_py();
	array_pair_converter::register_from_py();
}

} // eof hidden namespace

namespace blue_sky { namespace python {

void py_export_mesh_grdecl () {
	class_exporter< bs_mesh_grdecl, rs_mesh_iface, mesh_grdecl_exporter_plus >::export_class ("mesh_grdecl");
	//reg_sparray_pair< float >();
	reg_sparray_pair< double >();
}

}} // namespace blue_sky::python
#endif
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkDummyImageToListAdaptorTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include <time.h>

#include "itkFixedArray.h"
#include "itkImage.h"
#include "itkImageAdaptor.h"
#include "itkImageRegionIterator.h"
#include "itkPixelTraits.h"

#include "itkListSampleBase.h"
#include "itkImageToListAdaptor.h"
#include "itkScalarToArrayCastImageFilter.h"

#include "itkImage.h"
#include "itkObject.h"
#include "itkMacro.h"
#include "itkPixelTraits.h"

template<class TPixelType>
struct MeasurementVectorTraits
{
  typedef TPixelType VectorType;
};

/** Specialization of MeasurementVectorTraitss for scalar images. */
template <>
struct MeasurementVectorTraits<bool>
{
  typedef itk::FixedArray< bool, 1 > VectorType;
};

template <>
struct MeasurementVectorTraits<char>
{
  typedef itk::FixedArray< char, 1 > VectorType;
};

template <>
struct MeasurementVectorTraits<unsigned char>
{
  typedef itk::FixedArray< unsigned char, 1 > VectorType;
};

template <>
struct MeasurementVectorTraits<short>
{
  typedef itk::FixedArray< short, 1 > VectorType;
};

template <>
struct MeasurementVectorTraits<unsigned short>
{
  typedef itk::FixedArray< unsigned short, 1 > VectorType;
};

template <>
struct MeasurementVectorTraits<int>
{
  typedef itk::FixedArray< int, 1 > VectorType;
};

template <>
struct MeasurementVectorTraits<unsigned int>
{
  typedef itk::FixedArray< unsigned int, 1 > VectorType;
};

template <>
struct MeasurementVectorTraits<long>
{
  typedef itk::FixedArray< long, 1 > VectorType;
};

template <>
struct MeasurementVectorTraits<unsigned long>
{
  typedef itk::FixedArray< unsigned long, 1 > VectorType;
};

template <>
struct MeasurementVectorTraits<float>
{
  typedef itk::FixedArray< float, 1 > VectorType;
};

template <>
struct MeasurementVectorTraits<double>
{
  typedef itk::FixedArray< double, 1 > VectorType;
};

template < class TImage, class TMeasurementVector = ITK_TYPENAME TImage::PixelType >
class ITK_EXPORT DummyImageToListAdaptor :
  public itk::Statistics::ListSampleBase< TMeasurementVector >
{
public:
  typedef DummyImageToListAdaptor Self ;
  typedef itk::Statistics::ListSampleBase< TMeasurementVector > Superclass ;

  typedef itk::SmartPointer< Self > Pointer ;
  typedef itk::SmartPointer< const Self > ConstPointer ;

  itkTypeMacro( DummyImageToListAdaptor, Object ) ;
  itkNewMacro( Self ) ;

  typedef typename TImage::PixelType PixelType ;
  typedef typename itk::PixelTraits< PixelType >::ValueType MeasurementType ;
  itkStaticConstMacro( MeasurementVectorSize, unsigned int,
                       itk::PixelTraits< PixelType >::Dimension ) ;

  typedef TMeasurementVector MeasurementVectorType ;

  unsigned int Size() const
  { return 1 ;}

  float GetTotalFrequency() const
  { return 1 ;}

  float GetFrequency(const unsigned long& id) const
  { return 1.0f ; }

  virtual MeasurementVectorType GetMeasurementVector(const unsigned long& id)
  {
    if( m_UseBuffer )
      {
      return *(reinterpret_cast< MeasurementVectorType* >
               (&(*m_ImageBuffer)[id]))  ;
      }
    else
      {
      return *(reinterpret_cast< MeasurementVectorType* >
               (&(m_Image->GetPixel( m_Image->ComputeIndex( id ))) ) )   ;
      }
  }

  void SetImage( TImage* image )
  {
    m_Image = image ;
    m_ImageBuffer = m_Image->GetPixelContainer() ;
    if ( strcmp( m_Image->GetNameOfClass(), "Image" ) != 0 )
      {
      m_UseBuffer = false ;
      }
    else
      {
      m_UseBuffer = true ;
      }
  }

protected:
  DummyImageToListAdaptor()
  { m_Image = 0 ; }

  virtual ~DummyImageToListAdaptor() {}

  typename TImage::Pointer m_Image ;
  typename TImage::PixelContainer* m_ImageBuffer ;
  MeasurementVectorType m_TempVector ;
  bool m_UseBuffer ;

private:
  DummyImageToListAdaptor(const Self&) ;
  void operator=(const Self&) ;

} ;

template < class TImage >
class ITK_EXPORT DummyScalarImageToListAdaptor :
  public DummyImageToListAdaptor< TImage, itk::FixedArray< typename TImage::PixelType, 1> >
{
public:
  typedef DummyScalarImageToListAdaptor Self ;
  typedef DummyImageToListAdaptor<
    TImage, itk::FixedArray< typename TImage::PixelType, 1> > Superclass ;

  typedef itk::SmartPointer< Self > Pointer ;
  typedef itk::SmartPointer< const Self > ConstPointer ;

  itkTypeMacro( DummyScalarImageToListAdaptor, DummyImageToListAdaptor ) ;
  itkNewMacro( Self ) ;

  typedef typename Superclass::MeasurementVectorType MeasurementVectorType ;

  MeasurementVectorType GetMeasurementVector(const unsigned long& id)
  {
    if( m_UseBuffer )
      {
      m_TempVector[0] = (*m_ImageBuffer)[id] ;
      }
    else
      {
      m_TempVector[0] = m_Image->GetPixel( m_Image->ComputeIndex( id ) )  ;
      }
      return m_TempVector  ;
  }
protected:
  DummyScalarImageToListAdaptor() {}
  virtual ~DummyScalarImageToListAdaptor() {}
} ; // end of class

template< class TImage, class TCoordRep >
struct ImageJointDomainTraits
{
  typedef itk::PixelTraits< typename TImage::PixelType > PixelTraitsType ;
  itkStaticConstMacro(Size,
                      unsigned int,
                      TImage::ImageDimension +
                      PixelTraitsType::Dimension ) ;
  typedef itk::JoinTraits<
    TCoordRep,
    PixelTraitsType::ValueType > JoinTraitsType ;

  typedef JoinTraitsType::ValueType MeasurementType ;

  typedef itk::FixedArray< MeasurementType, itkGetStaticConstMacro(Size) >
  MeasurementVectorType ;
} ; // end of ImageJointDomainTraits

template < class TImage, class TCoordRep >
class ITK_EXPORT DummyJointDomainImageToListAdaptor :
  public DummyImageToListAdaptor< TImage,
                                  ImageJointDomainTraits<
  TImage, TCoordRep >::MeasurementVectorType >
{
public:
  typedef DummyJointDomainImageToListAdaptor Self ;
  typedef DummyImageToListAdaptor< TImage,
    ImageJointDomainTraits< TImage, TCoordRep >::MeasurementVectorType >
  Superclass ;

  typedef itk::SmartPointer< Self > Pointer ;
  typedef itk::SmartPointer< const Self > ConstPointer ;

  itkTypeMacro( DummyJointDomainImageToListAdaptor, DummyImageToListAdaptor ) ;
  itkNewMacro( Self ) ;

  typedef typename Superclass::MeasurementType MeasurementType ;
  typedef typename Superclass::MeasurementVectorType MeasurementVectorType ;

  typedef itk::FixedArray< MeasurementType,
    itk::PixelTraits< typename TImage::PixelType >::Dimension >
  RangeDomainMeasurementVectorType ;

  MeasurementVectorType GetMeasurementVector(const unsigned long& id)
  {
    typename itk::Point<MeasurementType, TImage::ImageDimension> point ;
    typename TImage::IndexType index = m_Image->ComputeIndex( id ) ;
    m_Image->TransformIndexToPhysicalPoint( index, point ) ;

    for ( unsigned int i = 0 ; i < TImage::ImageDimension ; ++i )
      {
      m_TempVector[i] = point[i] ;
      }

    if( m_UseBuffer )
      {
      m_TempVector2 =
        *(reinterpret_cast< RangeDomainMeasurementVectorType* >
          (&(*m_ImageBuffer)[id]))  ;
      }
    else
      {
      m_TempVector2 =
        *(reinterpret_cast< RangeDomainMeasurementVectorType* >
          (&(m_Image->GetPixel( m_Image->ComputeIndex( id ) ) ) ) ) ;
      }

    for ( unsigned int i = TImage::ImageDimension ; i < MeasurementVectorType::Length ; ++i )
      {
      m_TempVector[i]= m_TempVector2[i - TImage::ImageDimension] ;
      }
    return m_TempVector ;
  }
protected:
  DummyJointDomainImageToListAdaptor() {}
  virtual ~DummyJointDomainImageToListAdaptor() {}
  RangeDomainMeasurementVectorType m_TempVector2 ;
} ; // end of class

int itkDummyImageToListAdaptorTest(int, char* [] )
{
  typedef int ScalarPixelType ;
  typedef itk::FixedArray< ScalarPixelType, 1 > ArrayPixelType ;
  typedef itk::Vector< ScalarPixelType, 2 > VectorPixelType ;

  typedef itk::Image< ScalarPixelType, 3 > ScalarImageType ;
  typedef itk::Image< ArrayPixelType, 3 > ArrayImageType ;
  typedef itk::Image< VectorPixelType, 3 > VectorImageType ;

  typedef itk::ImageRegionIterator< ScalarImageType > ScalarImageIteratorType ;
  typedef itk::ImageRegionIterator< ArrayImageType > ArrayImageIteratorType ;
  typedef itk::ImageRegionIterator< VectorImageType > VectorImageIteratorType ;

  itk::Size< 3 > size ;
  size.Fill(10) ;

  ScalarImageType::Pointer scalarImage = ScalarImageType::New() ;
  scalarImage->SetRegions(size) ;
  scalarImage->Allocate() ;

  int count = 0 ;
  ScalarImageIteratorType s_iter =
    ScalarImageIteratorType(scalarImage,
                            scalarImage->GetLargestPossibleRegion() ) ;
  while ( !s_iter.IsAtEnd() )
    {
    s_iter.Set(count) ;
    ++count ;
    ++s_iter ;
    }

  VectorImageType::Pointer vectorImage = VectorImageType::New() ;
  vectorImage->SetRegions(size) ;
  vectorImage->Allocate() ;
  count = 0 ;
  VectorImageType::PixelType vPixel ;
  VectorImageIteratorType v_iter =
    VectorImageIteratorType(vectorImage,
                            vectorImage->GetLargestPossibleRegion()) ;
  while ( !v_iter.IsAtEnd() )
    {
    vPixel[0] = count ;
    vPixel[1] = count ;
    v_iter.Set( vPixel ) ;
    ++count ;
    ++v_iter ;
    }

  typedef DummyScalarImageToListAdaptor< ScalarImageType > ScalarListType ;
  ScalarListType::Pointer sList = ScalarListType::New() ;
  sList->SetImage( scalarImage ) ;

  typedef DummyImageToListAdaptor< VectorImageType > VectorListType ;
  VectorListType::Pointer vList = VectorListType::New() ;
  vList->SetImage( vectorImage ) ;

  typedef itk::ScalarToArrayCastImageFilter< ScalarImageType, ArrayImageType > CasterType ;
  CasterType::Pointer caster = CasterType::New() ;
  caster->SetInput( scalarImage ) ;
  caster->Update() ;

  typedef itk::Statistics::ImageToListAdaptor< ArrayImageType > ImageListType ;
  ImageListType::Pointer imageList = ImageListType::New() ;
  imageList->SetImage( caster->GetOutput() ) ;

  typedef DummyJointDomainImageToListAdaptor< VectorImageType,
    float > JointDomainImageListType ;
  JointDomainImageListType::Pointer jointDomainImageList =
    JointDomainImageListType::New() ;
  jointDomainImageList->SetImage( vectorImage ) ;

  std::cout << "Testing the each measurement values:" << std::endl ;
  for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i )
    {
    if ( sList->GetMeasurementVector( i )[0] !=
         vList->GetMeasurementVector( i )[0]
         || sList->GetMeasurementVector( i )[0] !=
         imageList->GetMeasurementVector( i )[0]
         || sList->GetMeasurementVector( i )[0] !=
         jointDomainImageList->GetMeasurementVector( i )[3]
      )
      {
      std::cout << "ERROR: measurement mismatch!!!" << std::endl ;
      return EXIT_FAILURE ;
      }
    }
  std::cout << std::endl ;

  std::cout << "Scalar image (casted) pixel access performance test:" << std::endl ;
  time_t begin = clock() ;
  for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i )
    {
    imageList->GetMeasurementVector( i )  ;
    }
  time_t end = clock() ;

  std::cout << "time: "
            << (double(end - begin) /CLOCKS_PER_SEC)
            << " seconds" << std::endl ;

  std::cout << "Scalar image pixel access performance test:" << std::endl ;
  begin = clock() ;
  for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i )
    {
    sList->GetMeasurementVector( i )  ;
    }
  end = clock() ;

  std::cout << "time: "
            << (double(end - begin) /CLOCKS_PER_SEC)
            << " seconds" << std::endl ;

  std::cout << "Vector image pixel access performance test:" << std::endl ;
  begin = clock() ;
  for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i )
    {
    vList->GetMeasurementVector( i )  ;
    }
  end = clock() ;

  std::cout << "time: "
            << (double(end - begin) /CLOCKS_PER_SEC)
            << " seconds" << std::endl ;

  std::cout << "Joint Domain Vector image pixel access performance test:" << std::endl ;
  begin = clock() ;
  for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i )
    {
      std::cout << jointDomainImageList->GetMeasurementVector( i )
                << std::endl ;
    }
  end = clock() ;

  std::cout << "time: "
            << (double(end - begin) /CLOCKS_PER_SEC)
            << " seconds" << std::endl ;

  return EXIT_SUCCESS ;
}
<commit_msg>BUG: BCC complains about the Size enum. to use itkGetStaticConstMacro, each class should have Self declared.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkDummyImageToListAdaptorTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include <time.h>

#include "itkFixedArray.h"
#include "itkImage.h"
#include "itkImageAdaptor.h"
#include "itkImageRegionIterator.h"
#include "itkPixelTraits.h"

#include "itkListSampleBase.h"
#include "itkImageToListAdaptor.h"
#include "itkScalarToArrayCastImageFilter.h"

#include "itkImage.h"
#include "itkObject.h"
#include "itkMacro.h"
#include "itkPixelTraits.h"

template < class TImage, class TMeasurementVector = ITK_TYPENAME TImage::PixelType >
class ITK_EXPORT DummyImageToListAdaptor :
  public itk::Statistics::ListSampleBase< TMeasurementVector >
{
public:
  typedef DummyImageToListAdaptor Self ;
  typedef itk::Statistics::ListSampleBase< TMeasurementVector > Superclass ;

  typedef itk::SmartPointer< Self > Pointer ;
  typedef itk::SmartPointer< const Self > ConstPointer ;

  itkTypeMacro( DummyImageToListAdaptor, Object ) ;
  itkNewMacro( Self ) ;

  typedef typename TImage::PixelType PixelType ;
  typedef typename itk::PixelTraits< PixelType >::ValueType MeasurementType ;
  itkStaticConstMacro( MeasurementVectorSize, unsigned int,
                       itk::PixelTraits< PixelType >::Dimension ) ;

  typedef TMeasurementVector MeasurementVectorType ;

  unsigned int Size() const
  { return 1 ;}

  float GetTotalFrequency() const
  { return 1 ;}

  float GetFrequency(const unsigned long& id) const
  { return id ; }

  virtual MeasurementVectorType GetMeasurementVector(const unsigned long& id)
  {
    if( m_UseBuffer )
      {
      return *(reinterpret_cast< MeasurementVectorType* >
               (&(*m_ImageBuffer)[id]))  ;
      }
    else
      {
      return *(reinterpret_cast< MeasurementVectorType* >
               (&(m_Image->GetPixel( m_Image->ComputeIndex( id ))) ) )   ;
      }
  }

  void SetImage( TImage* image )
  {
    m_Image = image ;
    m_ImageBuffer = m_Image->GetPixelContainer() ;
    if ( strcmp( m_Image->GetNameOfClass(), "Image" ) != 0 )
      {
      m_UseBuffer = false ;
      }
    else
      {
      m_UseBuffer = true ;
      }
  }

protected:
  DummyImageToListAdaptor()
  { m_Image = 0 ; }

  virtual ~DummyImageToListAdaptor() {}

  typename TImage::Pointer m_Image ;
  typename TImage::PixelContainer* m_ImageBuffer ;
  MeasurementVectorType m_TempVector ;
  bool m_UseBuffer ;

private:
  DummyImageToListAdaptor(const Self&) ;
  void operator=(const Self&) ;

} ;

template < class TImage >
class ITK_EXPORT DummyScalarImageToListAdaptor :
  public DummyImageToListAdaptor< TImage, itk::FixedArray< typename TImage::PixelType, 1> >
{
public:
  typedef DummyScalarImageToListAdaptor Self ;
  typedef DummyImageToListAdaptor<
    TImage, itk::FixedArray< typename TImage::PixelType, 1> > Superclass ;

  typedef itk::SmartPointer< Self > Pointer ;
  typedef itk::SmartPointer< const Self > ConstPointer ;

  itkTypeMacro( DummyScalarImageToListAdaptor, DummyImageToListAdaptor ) ;
  itkNewMacro( Self ) ;

  typedef typename Superclass::MeasurementVectorType MeasurementVectorType ;

  MeasurementVectorType GetMeasurementVector(const unsigned long& id)
  {
    if( m_UseBuffer )
      {
      m_TempVector[0] = (*m_ImageBuffer)[id] ;
      }
    else
      {
      m_TempVector[0] = m_Image->GetPixel( m_Image->ComputeIndex( id ) )  ;
      }
    return m_TempVector  ;
  }
protected:
  DummyScalarImageToListAdaptor() {}
  virtual ~DummyScalarImageToListAdaptor() {}
} ; // end of class

template< class TImage, class TCoordRep >
struct ImageJointDomainTraits
{
  typedef ImageJointDomainTraits Self ;

  typedef itk::PixelTraits< typename TImage::PixelType > PixelTraitsType ;
  itkStaticConstMacro(Size,
                      unsigned int,
                      TImage::ImageDimension +
                      PixelTraitsType::Dimension ) ;
  typedef itk::JoinTraits<
    TCoordRep,
    PixelTraitsType::ValueType > JoinTraitsType ;

  typedef JoinTraitsType::ValueType MeasurementType ;

  typedef itk::FixedArray< MeasurementType, itkGetStaticConstMacro(Size) >
  MeasurementVectorType ;
} ; // end of ImageJointDomainTraits

template < class TImage, class TCoordRep >
class ITK_EXPORT DummyJointDomainImageToListAdaptor :
  public DummyImageToListAdaptor< TImage,
                                  ImageJointDomainTraits<
  TImage, TCoordRep >::MeasurementVectorType >
{
public:
  typedef DummyJointDomainImageToListAdaptor Self ;
  typedef DummyImageToListAdaptor< TImage,
                                   ImageJointDomainTraits< TImage, TCoordRep >::MeasurementVectorType >
  Superclass ;

  typedef itk::SmartPointer< Self > Pointer ;
  typedef itk::SmartPointer< const Self > ConstPointer ;

  itkTypeMacro( DummyJointDomainImageToListAdaptor, DummyImageToListAdaptor ) ;
  itkNewMacro( Self ) ;

  typedef typename Superclass::MeasurementType MeasurementType ;
  typedef typename Superclass::MeasurementVectorType MeasurementVectorType ;

  itkStaticConstMacro(RangeDomainDimension,
                      unsigned int,
                      itk::PixelTraits<
                      typename TImage::PixelType >::Dimension) ;
  typedef typename itk::FixedArray<
    MeasurementType,
    itkGetStaticConstMacro( RangeDomainDimension ) >
  RangeDomainMeasurementVectorType ;

  MeasurementVectorType GetMeasurementVector(const unsigned long& id)
  {
    typename itk::Point<MeasurementType, TImage::ImageDimension> point ;
    typename TImage::IndexType index = m_Image->ComputeIndex( id ) ;
    m_Image->TransformIndexToPhysicalPoint( index, point ) ;

    for ( unsigned int i = 0 ; i < TImage::ImageDimension ; ++i )
      {
      m_TempVector[i] = point[i] ;
      }

    if( m_UseBuffer )
      {
      m_TempVector2 =
        *(reinterpret_cast< RangeDomainMeasurementVectorType* >
          (&(*m_ImageBuffer)[id]))  ;
      }
    else
      {
      m_TempVector2 =
        *(reinterpret_cast< RangeDomainMeasurementVectorType* >
          (&(m_Image->GetPixel( m_Image->ComputeIndex( id ) ) ) ) ) ;
      }

    for ( unsigned int i = TImage::ImageDimension ; i < MeasurementVectorType::Length ; ++i )
      {
      m_TempVector[i]= m_TempVector2[i - TImage::ImageDimension] ;
      }
    return m_TempVector ;
  }
protected:
  DummyJointDomainImageToListAdaptor() {}
  virtual ~DummyJointDomainImageToListAdaptor() {}
  RangeDomainMeasurementVectorType m_TempVector2 ;
} ; // end of class

int itkDummyImageToListAdaptorTest(int, char* [] )
{
  typedef int ScalarPixelType ;
  typedef itk::FixedArray< ScalarPixelType, 1 > ArrayPixelType ;
  typedef itk::Vector< ScalarPixelType, 2 > VectorPixelType ;

  typedef itk::Image< ScalarPixelType, 3 > ScalarImageType ;
  typedef itk::Image< ArrayPixelType, 3 > ArrayImageType ;
  typedef itk::Image< VectorPixelType, 3 > VectorImageType ;

  typedef itk::ImageRegionIterator< ScalarImageType > ScalarImageIteratorType ;
  typedef itk::ImageRegionIterator< ArrayImageType > ArrayImageIteratorType ;
  typedef itk::ImageRegionIterator< VectorImageType > VectorImageIteratorType ;

  itk::Size< 3 > size ;
  size.Fill(10) ;

  ScalarImageType::Pointer scalarImage = ScalarImageType::New() ;
  scalarImage->SetRegions(size) ;
  scalarImage->Allocate() ;

  int count = 0 ;
  ScalarImageIteratorType s_iter =
    ScalarImageIteratorType(scalarImage,
                            scalarImage->GetLargestPossibleRegion() ) ;
  while ( !s_iter.IsAtEnd() )
    {
    s_iter.Set(count) ;
    ++count ;
    ++s_iter ;
    }

  VectorImageType::Pointer vectorImage = VectorImageType::New() ;
  vectorImage->SetRegions(size) ;
  vectorImage->Allocate() ;
  count = 0 ;
  VectorImageType::PixelType vPixel ;
  VectorImageIteratorType v_iter =
    VectorImageIteratorType(vectorImage,
                            vectorImage->GetLargestPossibleRegion()) ;
  while ( !v_iter.IsAtEnd() )
    {
    vPixel[0] = count ;
    vPixel[1] = count ;
    v_iter.Set( vPixel ) ;
    ++count ;
    ++v_iter ;
    }

  typedef DummyScalarImageToListAdaptor< ScalarImageType > ScalarListType ;
  ScalarListType::Pointer sList = ScalarListType::New() ;
  sList->SetImage( scalarImage ) ;

  typedef DummyImageToListAdaptor< VectorImageType > VectorListType ;
  VectorListType::Pointer vList = VectorListType::New() ;
  vList->SetImage( vectorImage ) ;

  typedef itk::ScalarToArrayCastImageFilter< ScalarImageType, ArrayImageType > CasterType ;
  CasterType::Pointer caster = CasterType::New() ;
  caster->SetInput( scalarImage ) ;
  caster->Update() ;

  typedef itk::Statistics::ImageToListAdaptor< ArrayImageType > ImageListType ;
  ImageListType::Pointer imageList = ImageListType::New() ;
  imageList->SetImage( caster->GetOutput() ) ;

  typedef DummyJointDomainImageToListAdaptor< VectorImageType,
    float > JointDomainImageListType ;
  JointDomainImageListType::Pointer jointDomainImageList =
    JointDomainImageListType::New() ;
  jointDomainImageList->SetImage( vectorImage ) ;

  std::cout << "Testing the each measurement values:" << std::endl ;
  for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i )
    {
    if ( sList->GetMeasurementVector( i )[0] !=
         vList->GetMeasurementVector( i )[0]
         || sList->GetMeasurementVector( i )[0] !=
         imageList->GetMeasurementVector( i )[0]
         || sList->GetMeasurementVector( i )[0] !=
         jointDomainImageList->GetMeasurementVector( i )[3]
      )
      {
      std::cout << "ERROR: measurement mismatch!!!" << std::endl ;
      return EXIT_FAILURE ;
      }
    }
  std::cout << std::endl ;

  std::cout << "Scalar image (casted) pixel access performance test:" << std::endl ;
  time_t begin = clock() ;
  for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i )
    {
    imageList->GetMeasurementVector( i )  ;
    }
  time_t end = clock() ;

  std::cout << "time: "
            << (double(end - begin) /CLOCKS_PER_SEC)
            << " seconds" << std::endl ;

  std::cout << "Scalar image pixel access performance test:" << std::endl ;
  begin = clock() ;
  for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i )
    {
    sList->GetMeasurementVector( i )  ;
    }
  end = clock() ;

  std::cout << "time: "
            << (double(end - begin) /CLOCKS_PER_SEC)
            << " seconds" << std::endl ;

  std::cout << "Vector image pixel access performance test:" << std::endl ;
  begin = clock() ;
  for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i )
    {
    vList->GetMeasurementVector( i )  ;
    }
  end = clock() ;

  std::cout << "time: "
            << (double(end - begin) /CLOCKS_PER_SEC)
            << " seconds" << std::endl ;

  std::cout << "Joint Domain Vector image pixel access performance test:" << std::endl ;
  begin = clock() ;
  for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i )
    {
    std::cout << jointDomainImageList->GetMeasurementVector( i )
              << std::endl ;
    }
  end = clock() ;

  std::cout << "time: "
            << (double(end - begin) /CLOCKS_PER_SEC)
            << " seconds" << std::endl ;

  return EXIT_SUCCESS ;
}
<|endoftext|>


<commit_before>#ifndef _BME280_IMPL_
#define _BME280_IMPL_

#include "SensorInterface.hpp"
#include <Wire.h>
#include <Adafruit_BME280.h>

class BME280_Impl : public SensorInterface {
  public:
    BME280_Impl(uint8_t i2caddr);
    virtual ~BME280_Impl();

    virtual float temperature();
    virtual float humidity();
    virtual float pressure();
    virtual SensorInterface::SensorState state();
  private:
    void readSensor();
    Adafruit_BME280 bme;
    SensorInterface::SensorState ss;
    float h; // humidity in percent
    float t; // temperature as Celsius
    float p; // pressure in hPa
};

inline BME280_Impl::BME280_Impl(uint8_t i2caddr)
  : bme()
  , ss(SensorInterface::state())
  , t(SensorInterface::temperature())
  , h(SensorInterface::humidity())
  , p(SensorInterface::pressure()) {
  if (!bme.begin(i2caddr)) {
    Homie.getLogger() << "Couldn't find BME280" << endl;
    ss = connect_error;
  }
  else
  {
    // weather monitoring
    bme.setSampling(Adafruit_BME280::MODE_FORCED,
                  Adafruit_BME280::SAMPLING_X1, // temperature
                  Adafruit_BME280::SAMPLING_X1, // pressure
                  Adafruit_BME280::SAMPLING_X1, // humidity
                  Adafruit_BME280::FILTER_OFF   );
  }
}

inline BME280_Impl::~BME280_Impl() {

}

inline void BME280_Impl::readSensor() {
  if(ss == connect_error)
    return;

  static unsigned long lastRead = 0;
  if(lastRead == 0 || (millis() - lastRead >= 60000UL)) { // suggested: 1 reading per minute
    // Only needed in forced mode! In normal mode, you can remove the next line.
    bme.takeForcedMeasurement(); // has no effect in normal mode

    float _t = bme.readTemperature();
    float _h = bme.readHumidity();
    float _p = bme.readPressure() / 100.0F;
    // Check if any reads failed and keep old values (to try again).
    if (isnan(_h) || isnan(_t) || isnan(_p)) {
      ss = SensorInterface::read_error;
      Homie.getLogger() << "Failed to read BME280 sensor!" << endl;
    } else {
      ss = SensorInterface::ok;
      t = _t;
      h = _h;
      p = _p;
    }
  }
}

inline float BME280_Impl::temperature() {
  readSensor();
  return t;
}

inline float BME280_Impl::humidity() {
  readSensor();
  return h;
}

inline float BME280_Impl::pressure() {
  readSensor();
  return p;
}

inline SensorInterface::SensorState BME280_Impl::state() {
  readSensor();
  return ss;
}

#endif
<commit_msg>* fixed max reading interval of BME280<commit_after>#ifndef _BME280_IMPL_
#define _BME280_IMPL_

#include "SensorInterface.hpp"
#include <Wire.h>
#include <Adafruit_BME280.h>

class BME280_Impl : public SensorInterface {
  public:
    BME280_Impl(uint8_t i2caddr);
    virtual ~BME280_Impl();

    virtual float temperature();
    virtual float humidity();
    virtual float pressure();
    virtual SensorInterface::SensorState state();
  private:
    void readSensor();
    Adafruit_BME280 bme;
    SensorInterface::SensorState ss;
    float h; // humidity in percent
    float t; // temperature as Celsius
    float p; // pressure in hPa
};

inline BME280_Impl::BME280_Impl(uint8_t i2caddr)
  : bme()
  , ss(SensorInterface::state())
  , t(SensorInterface::temperature())
  , h(SensorInterface::humidity())
  , p(SensorInterface::pressure()) {
  if (!bme.begin(i2caddr)) {
    Homie.getLogger() << "Couldn't find BME280" << endl;
    ss = connect_error;
  }
  else
  {
    // weather monitoring
    bme.setSampling(Adafruit_BME280::MODE_FORCED,
                  Adafruit_BME280::SAMPLING_X1, // temperature
                  Adafruit_BME280::SAMPLING_X1, // pressure
                  Adafruit_BME280::SAMPLING_X1, // humidity
                  Adafruit_BME280::FILTER_OFF   );
  }
}

inline BME280_Impl::~BME280_Impl() {

}

inline void BME280_Impl::readSensor() {
  if(ss == connect_error)
    return;

  if((now - last) > 60000UL || (last == 0)) { // suggested: 1 reading per minute

    // Only needed in forced mode! In normal mode, you can remove the next line.
    bme.takeForcedMeasurement(); // has no effect in normal mode

    float _t = bme.readTemperature();
    float _h = bme.readHumidity();
    float _p = bme.readPressure() / 100.0F;
    // Check if any reads failed and keep old values (to try again).
    if (isnan(_h) || isnan(_t) || isnan(_p)) {
      ss = SensorInterface::read_error;
      Homie.getLogger() << "Failed to read BME280 sensor!" << endl;
    } else {
      ss = SensorInterface::ok;
      t = _t;
      h = _h;
      p = _p;
      last = now;
    }
  }
}

inline float BME280_Impl::temperature() {
  readSensor();
  return t;
}

inline float BME280_Impl::humidity() {
  readSensor();
  return h;
}

inline float BME280_Impl::pressure() {
  readSensor();
  return p;
}

inline SensorInterface::SensorState BME280_Impl::state() {
  readSensor();
  return ss;
}

#endif
<|endoftext|>


<commit_before>#include <iostream>
#include "convexHull.h"
#include "testUtil.h"

using namespace Eigen;

void testConvexHull() {
  Matrix<double, 2, Dynamic> pts(2, 4);
  pts << 1.0, 2.0, 3.0, 2.0,
         2.0, 1.0, 2.0, 3.0;

  valuecheck(inConvexHull(pts, Vector2d(2.0, 2.0)), true);
  valuecheck(inConvexHull(pts, Vector2d(1.0001, 2.0)), true);
  valuecheck(inConvexHull(pts, Vector2d(0.9999, 2.0)), false);
  valuecheck(inConvexHull(pts, Vector2d(2.49, 2.49)), true);
  valuecheck(inConvexHull(pts, Vector2d(2.51, 2.51)), false);
}

void testDistanceFromHull() {
  Matrix<double, 2, Dynamic> pts(2, 5);
  pts << 0, 1, 1, 0, 0.5,
         0, 1, 0, 1, 0.5;

  double d = signedDistanceInsideConvexHull(pts, Vector2d(0, 0));
  valuecheck(d, 0.0, 1e-8);

  d = signedDistanceInsideConvexHull(pts, Vector2d(0.5, 0.5));
  valuecheck(d, 0.5, 1e-8);

  d = signedDistanceInsideConvexHull(pts, Vector2d(-0.5, 0));
  valuecheck(d, -0.5, 1e-8);

  pts << 0, 2, 2, 0, 0.5,
         0, 2, 0, 2, 0.5;

  d = signedDistanceInsideConvexHull(pts, Vector2d(0, 0));
  valuecheck(d, 0.0, 1e-8);

  d = signedDistanceInsideConvexHull(pts, Vector2d(0.5, 0.5));
  valuecheck(d, 0.5, 1e-8);

  d = signedDistanceInsideConvexHull(pts, Vector2d(-0.5, 0));
  valuecheck(d, -0.5, 1e-8);
}

void testRealData() {
  Matrix<double, 2, Dynamic> pts(2, 16);
  pts << 0.237506,    0.330077,    0.297687,    0.390258,    0.177325,    0.269896,    0.357868,    0.450439,  0.00257912,    0.116144,   0.0466612,    0.160226,    -0.03475,   0.0788149,   0.0873669,    0.200932,
        -0.00459488,   -0.093748,   0.0579462,  -0.0312069,   -0.067136,   -0.156289,    0.120487,   0.0313342,    0.102483,   0.0421703,    0.185504,    0.125191,   0.0321808,  -0.0281323,    0.262166,    0.201853;
  Vector2d q(0.196956, 0.0487772);

  double d = signedDistanceInsideConvexHull(pts, q);
  valuecheck(d, 0.136017, 1e-6);
}

void testDuplicates() {
  Matrix<double, 2, Dynamic> pts(2, 8);
  pts << 0.0, 1.0, 1.0, 0.0, 0.5, 0.0, 0.0, 1.0 - 1e-16,
         0.0, 1.0, 0.0, 1.0, 0.5, 0.0, 0.0, 1.0 - 1e-16;
  double d = signedDistanceInsideConvexHull(pts, Vector2d(0, 0));
  valuecheck(d, 0.0, 1e-8);

  d = signedDistanceInsideConvexHull(pts, Vector2d(0.5, 0.5));
  valuecheck(d, 0.5, 1e-8);

  d = signedDistanceInsideConvexHull(pts, Vector2d(-0.5, 0));
  valuecheck(d, -0.5, 1e-8);
}

void testRandomConvexCombinations() {
  for (int i=2; i < 10; ++i) {
    for (int j=0; j < 100; ++j) {
      MatrixXd pts = MatrixXd::Random(2, i);
      VectorXd weights = VectorXd::Random(i);
      if (weights.minCoeff() < 0) {
        weights = weights.array() - weights.minCoeff(); // make sure they're all nonnegative
      }
      weights = weights.array() / weights.sum();
      Vector2d q = pts * weights;
      valuecheck(inConvexHull(pts, q, 1e-8), true);
    }
  }
}

int main() {
  testConvexHull();
  std::cout << "testConvexHull passed" << std::endl;
  testDistanceFromHull();
  std::cout << "testDistanceFromHull passed" << std::endl;
  testRealData();
  std::cout << "testRealData passed" << std::endl;
  testDuplicates();
  std::cout << "testDuplicates passed" << std::endl;
  testRandomConvexCombinations();
  std::cout << "testRandomConvexCombinations passed" << std::endl;
}
<commit_msg>more tests<commit_after>#include <iostream>
#include "convexHull.h"
#include "testUtil.h"

using namespace Eigen;

void testConvexHull() {
  Matrix<double, 2, Dynamic> pts(2, 4);
  pts << 1.0, 2.0, 3.0, 2.0,
         2.0, 1.0, 2.0, 3.0;

  valuecheck(inConvexHull(pts, Vector2d(2.0, 2.0)), true);
  valuecheck(inConvexHull(pts, Vector2d(1.0001, 2.0)), true);
  valuecheck(inConvexHull(pts, Vector2d(0.9999, 2.0)), false);
  valuecheck(inConvexHull(pts, Vector2d(2.49, 2.49)), true);
  valuecheck(inConvexHull(pts, Vector2d(2.51, 2.51)), false);
}

void testDistanceFromHull() {
  Matrix<double, 2, Dynamic> pts(2, 5);
  pts << 0, 1, 1, 0, 0.5,
         0, 1, 0, 1, 0.5;

  double d = signedDistanceInsideConvexHull(pts, Vector2d(0, 0));
  valuecheck(d, 0.0, 1e-8);

  d = signedDistanceInsideConvexHull(pts, Vector2d(0.5, 0.5));
  valuecheck(d, 0.5, 1e-8);

  d = signedDistanceInsideConvexHull(pts, Vector2d(-0.5, 0));
  valuecheck(d, -0.5, 1e-8);

  pts << 0, 2, 2, 0, 0.5,
         0, 2, 0, 2, 0.5;

  d = signedDistanceInsideConvexHull(pts, Vector2d(0, 0));
  valuecheck(d, 0.0, 1e-8);

  d = signedDistanceInsideConvexHull(pts, Vector2d(0.5, 0.5));
  valuecheck(d, 0.5, 1e-8);

  d = signedDistanceInsideConvexHull(pts, Vector2d(-0.5, 0));
  valuecheck(d, -0.5, 1e-8);
}

void testRealData() {
  Matrix<double, 2, Dynamic> pts(2, 16);
  pts << 0.237506,    0.330077,    0.297687,    0.390258,    0.177325,    0.269896,    0.357868,    0.450439,  0.00257912,    0.116144,   0.0466612,    0.160226,    -0.03475,   0.0788149,   0.0873669,    0.200932,
        -0.00459488,   -0.093748,   0.0579462,  -0.0312069,   -0.067136,   -0.156289,    0.120487,   0.0313342,    0.102483,   0.0421703,    0.185504,    0.125191,   0.0321808,  -0.0281323,    0.262166,    0.201853;
  Vector2d q(0.196956, 0.0487772);

  double d = signedDistanceInsideConvexHull(pts, q);
  valuecheck(d, 0.136017, 1e-6);
}

void testDuplicates() {
  Matrix<double, 2, Dynamic> pts(2, 8);
  pts << 0.0, 1.0, 1.0, 0.0, 0.5, 0.0, 0.0, 1.0 - 1e-16,
         0.0, 1.0, 0.0, 1.0, 0.5, 0.0, 0.0, 1.0 - 1e-16;
  double d = signedDistanceInsideConvexHull(pts, Vector2d(0, 0));
  valuecheck(d, 0.0, 1e-8);

  d = signedDistanceInsideConvexHull(pts, Vector2d(0.5, 0.5));
  valuecheck(d, 0.5, 1e-8);

  d = signedDistanceInsideConvexHull(pts, Vector2d(-0.5, 0));
  valuecheck(d, -0.5, 1e-8);
}

void testRandomConvexCombinations() {
  for (int i=2; i < 50; ++i) {
    for (int j=0; j < 500; ++j) {
      MatrixXd pts = MatrixXd::Random(2, i);
      VectorXd weights = VectorXd::Random(i);
      if (weights.minCoeff() < 0) {
        weights = weights.array() - weights.minCoeff(); // make sure they're all nonnegative
      }
      weights = weights.array() / weights.sum();
      Vector2d q = pts * weights;
      valuecheck(inConvexHull(pts, q, 1e-8), true);
    }
  }
}

int main() {
  testConvexHull();
  std::cout << "testConvexHull passed" << std::endl;
  testDistanceFromHull();
  std::cout << "testDistanceFromHull passed" << std::endl;
  testRealData();
  std::cout << "testRealData passed" << std::endl;
  testDuplicates();
  std::cout << "testDuplicates passed" << std::endl;
  testRandomConvexCombinations();
  std::cout << "testRandomConvexCombinations passed" << std::endl;
}
<|endoftext|>


<commit_before>//===========================================
//  Lumina-DE source code
//  Copyright (c) 2016, Ken Moore
//  Available under the 3-clause BSD license
//  See the LICENSE file for full details
//===========================================
#ifdef __linux__
#include <QDebug>
#include "LuminaOS.h"
#include <unistd.h>
#include <stdio.h> // Needed for BUFSIZ

//can't read xbrightness settings - assume invalid until set
static int screenbrightness = -1;

QString LOS::OSName(){ return "Gentoo Linux"; }

//OS-specific prefix(s)
// NOTE: PREFIX, L_ETCDIR, L_SHAREDIR are defined in the OS-detect.pri project file and passed in
QString LOS::LuminaShare(){ return (L_SHAREDIR+"/lumina-desktop/"); } //Install dir for Lumina share files
QString LOS::AppPrefix(){ return "/usr/"; } //Prefix for applications
QString LOS::SysPrefix(){ return "/"; } //Prefix for system

//OS-specific application shortcuts (*.desktop files)
QString LOS::ControlPanelShortcut(){ return ""; } //system control panel
QString LOS::AppStoreShortcut(){ return LOS::AppPrefix() + "/share/applications/porthole.desktop"; } //graphical app/pkg manager
//OS-specific RSS feeds (Format: QStringList[ <name>::::<url> ]; )
QStringList LOS::RSSFeeds(){ return QStringList(); }

// ==== ExternalDevicePaths() ====
QStringList LOS::ExternalDevicePaths(){
  /* Returns: QStringList[<type>::::<filesystem>::::<path>]
     Note: <type> = [USB, HDRIVE, DVD, SDCARD, UNKNOWN]
     df is much better for this than mount, because it skips
     all non-physical devices (like bind-mounts from schroot)
     so they are not listed in lumina-fm */
  QStringList devs = LUtils::getCmdOutput("df --output=source,fstype,target");
  //Now check the output
  for(int i=0; i<devs.length(); i++){
    if(devs[i].startsWith("/dev/")){
      devs[i] = devs[i].simplified();
      QString type = devs[i].section(" on ",0,0);
      type.remove("/dev/");
      //Determine the type of hardware device based on the dev node
      if(type.startsWith("sd") || type.startsWith("nvme")){ type = "HDRIVE"; }
      else if(type.startsWith("sr")){ type="DVD"; }
      else if(type.contains("mapper")){ type="LVM"; }
      else{ type = "UNKNOWN"; }
      //Now put the device in the proper output format
      devs[i] = type + "::::" + devs[i].section(" ",1,1) + "::::" + devs[i].section(" ",2,2);
    }else{
      //invalid device - remove it from the list
      devs.removeAt(i);
      i--;
    }
  }
  return devs;
}

//Read screen brightness information
int LOS::ScreenBrightness(){
   //Returns: Screen Brightness as a percentage (0-100, with -1 for errors)
  if(screenbrightness==-1){
    if(QFile::exists(QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/.currentxbrightness")){
      int val = LUtils::readFile(QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/.currentxbrightness").join("").simplified().toInt();
      screenbrightness = val;
    }
  }
  return screenbrightness;

}

//Set screen brightness
void LOS::setScreenBrightness(int percent){
  //ensure bounds
  if(percent<0){percent=0;}
  else if(percent>100){ percent=100; }
  // float pf = percent/100.0; //convert to a decimel
  //Run the command
  QString cmd = "xbacklight -set %1";
  // cmd = cmd.arg( QString::number( int(65535*pf) ) );
  cmd = cmd.arg( QString::number( percent ) );
  int ret = LUtils::runCmd(cmd);
  //Save the result for later
  if(ret!=0){ screenbrightness = -1; }
  else{ screenbrightness = percent; }
  LUtils::writeFile(QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/.currentxbrightness", QStringList() << QString::number(screenbrightness), true);

}

//Read the current volume
int LOS::audioVolume(){ //Returns: audio volume as a percentage (0-100, with -1 for errors)
QString info = LUtils::getCmdOutput("amixer get Master").join("").simplified();;
  int out = -1;
  int start_position, end_position;
  QString current_volume;
  if(!info.isEmpty()){
     start_position = info.indexOf("[");
     start_position++;
     end_position = info.indexOf("%");
     current_volume = info.mid(start_position, end_position - start_position);
     out = current_volume.toInt();
  }
  return out;

}

//Set the current volume
void LOS::setAudioVolume(int percent){
  if(percent<0){percent=0;}
  else if(percent>100){percent=100;}
  // QString info = "amixer -c 0 sset Master,0 " + QString::number(percent) + "%";
  QString info = "amixer set Master " + QString::number(percent) + "%";
  if(!info.isEmpty()){
    //Run Command
    LUtils::runCmd(info);
  }

}

//Change the current volume a set amount (+ or -)
void LOS::changeAudioVolume(int percentdiff){
  int old_volume = audioVolume();
  int new_volume = old_volume + percentdiff;
  if (new_volume < 0)
      new_volume = 0;
  if (new_volume > 100)
      new_volume = 100;
  qDebug() << "Setting new volume to: " << new_volume;
  setAudioVolume(new_volume);
}

//Check if a graphical audio mixer is installed
bool LOS::hasMixerUtility(){
  return QFile::exists(LOS::AppPrefix() + "bin/pavucontrol");
}

//Launch the graphical audio mixer utility
void LOS::startMixerUtility(){
  QProcess::startDetached(LOS::AppPrefix() + "bin/pavucontrol");
}

//Check for user system permission (shutdown/restart)
bool LOS::userHasShutdownAccess(){
  return QProcess::startDetached("dbus-send --system --print-reply=literal \
  --type=method_call --dest=org.freedesktop.login1 \
  /org/freedesktop/login1 org.freedesktop.login1.Manager.CanPowerOff");
}

//Check for whether the system is safe to power off (no updates being perfomed)
bool LOS::systemPerformingUpdates(){
  return false; //Not implemented yet
}

//Return the details of any updates which are waiting to apply on shutdown
QString LOS::systemPendingUpdates(){
  return "";
}

//System Shutdown
void LOS::systemShutdown(bool){ //start poweroff sequence
  //INPUT: skip updates (true/false)
  QProcess::startDetached("dbus-send --system --print-reply \
  --dest=org.freedesktop.login1 /org/freedesktop/login1 \
  org.freedesktop.login1.Manager.PowerOff boolean:true");
}

//System Restart
void LOS::systemRestart(bool){ //start reboot sequence
  //INPUT: skip updates (true/false)
  QProcess::startDetached("dbus-send --system --print-reply \
  --dest=org.freedesktop.login1 /org/freedesktop/login1 \
  org.freedesktop.login1.Manager.Reboot boolean:true");
}

//Check for suspend support
bool LOS::systemCanSuspend(){
  return QProcess::startDetached("dbus-send --system --print-reply=literal \
  --type=method_call --dest=org.freedesktop.login1 \
  /org/freedesktop/login1 org.freedesktop.login1.Manager.CanSuspend");
}

//Put the system into the suspend state
void LOS::systemSuspend(){
  QProcess::startDetached("dbus-send --system --print-reply \
  --dest=org.freedesktop.login1 /org/freedesktop/login1 \
  org.freedesktop.login1.Manager.Suspend boolean:true");
}

//Battery Availability
bool LOS::hasBattery(){
  QString my_status = LUtils::getCmdOutput("acpi -b").join("");
  bool no_battery = my_status.contains("No support");
  if (no_battery) return false;
  return true;
}

//Battery Charge Level
int LOS::batteryCharge(){ //Returns: percent charge (0-100), anything outside that range is counted as an error
  QString my_status = LUtils::getCmdOutput("acpi -b").join("");
  int my_start = my_status.indexOf("%");
  // get the number right before the % sign
  int my_end = my_start;
  my_start--;
  while ( (my_status[my_start] != ' ') && (my_start > 0) )
      my_start--;
  my_start++;
  int my_charge = my_status.mid(my_start, my_end - my_start).toInt();
  if ( (my_charge < 0) || (my_charge > 100) ) return -1;
  return my_charge;
}

//Battery Charging State
// Many possible values are returned if the laptop is plugged in
// these include "Unknown, Full and No support.
// However, it seems just one status is returned when running
// on battery and that is "Discharging". So if the value we get
// is NOT Discharging then we assume the battery is charging.
bool LOS::batteryIsCharging(){
  QString my_status = LUtils::getCmdOutput("acpi -b").join("");
  bool discharging = my_status.contains("Discharging");
  if (discharging) return false;
  return true;
}

//Battery Time Remaining
int LOS::batterySecondsLeft(){ //Returns: estimated number of seconds remaining
  return 0; //not implemented yet for Linux
}

//File Checksums
QStringList LOS::Checksums(QStringList filepaths){ //Return: checksum of the input file
  QStringList info = LUtils::getCmdOutput("md5sum \""+filepaths.join("\" \"")+"\"");
  for(int i=0; i<info.length(); i++){
    // first: md5sum: = error ; second: there's always one empty entry generated by getCmdOutput
    if( info[i].startsWith("md5sum:") || info[i].isEmpty()){ info.removeAt(i); i--; }
    else{
      //Strip out the extra information
      info[i] = info[i].section(" ",0,0);
    }
  }
 return info;
}

//file system capacity
QString LOS::FileSystemCapacity(QString dir) { //Return: percentage capacity as give by the df command
  QStringList mountInfo = LUtils::getCmdOutput("df -h \"" + dir + "\"");
  QString::SectionFlag skipEmpty = QString::SectionSkipEmpty;
  //output: 200G of 400G available on /mount/point
  QString capacity = mountInfo[1].section(" ",3,3, skipEmpty) + " of " + mountInfo[1].section(" ",1,1, skipEmpty) + " available on " +  mountInfo[1].section(" ",5,5, skipEmpty);
  return capacity;
}

QStringList LOS::CPUTemperatures(){ //Returns: List containing the temperature of any CPU's ("50C" for example)
  QStringList temp = LUtils::getCmdOutput("acpi -t").filter("degrees");
  for(int i=0; i<temp.length(); i++){
    if(temp[i].startsWith("Thermal")){
      temp[i] = temp[i].section(" ", 4, 6);
    }else{
      temp.removeAt(i); i--;
    }
  }
  if(temp.isEmpty()) {
    temp << "Not available";
  }
  return temp;
}

int LOS::CPUUsagePercent(){ //Returns: Overall percentage of the amount of CPU cycles in use (-1 for errors)
  QStringList info = LUtils::getCmdOutput("top -bn1").filter("Cpu(s)");
  if(info.isEmpty()){ return -1; }
  QString idle = info.first().section(" ", 7, 7, QString::SectionSkipEmpty);
  if(idle.isEmpty()){ return -1; }
  else{
    return (100 - idle.toDouble());
  }
}

int LOS::MemoryUsagePercent(){
  QStringList mem = LUtils::getCmdOutput("top -bn1").filter("Mem :");
  if(mem.isEmpty()){ return -1; }
  double fB = 0; //Free Bytes
  double uB = 0; //Used Bytes
  fB = mem.first().section(" ", 5, 5, QString::SectionSkipEmpty).toDouble();
  uB = mem.first().section(" ", 7, 7, QString::SectionSkipEmpty).toDouble();
  double per = (uB/(fB+uB)) * 100.0;
  return qRound(per);
}

QStringList LOS::DiskUsage(){ //Returns: List of current read/write stats for each device
  QStringList info = LUtils::getCmdOutput("iostat -dx -N");
  if(info.length()<3){ return QStringList(); } //nothing from command
  QStringList labs = info[1].split(" ",QString::SkipEmptyParts);
  QStringList out;
  QString fmt = "%1: %2 %3";
  for(int i=2; i<info.length(); i++){ //skip the first two lines, just labels
    info[i].replace("\t"," ");
    if(info[i].startsWith("Device:")){ labs = info[i].split(" ", QString::SkipEmptyParts); }//the labels for each column
    else{
      QStringList data = info[i].split(" ",QString::SkipEmptyParts); //data[0] is always the device
      if(data.length()>2 && labs.length()>2){
        out << fmt.arg(data[0], data[3]+" "+labs[3], data[4]+" "+labs[4]);
      }
    }
  }

  return out;
}
#endif
<commit_msg>Fix dbus-send calls for Gentoo.<commit_after>//===========================================
//  Lumina-DE source code
//  Copyright (c) 2016, Ken Moore
//  Available under the 3-clause BSD license
//  See the LICENSE file for full details
//===========================================
#ifdef __linux__
#include <QDebug>
#include "LuminaOS.h"
#include <unistd.h>
#include <stdio.h> // Needed for BUFSIZ

//can't read xbrightness settings - assume invalid until set
static int screenbrightness = -1;

QString LOS::OSName(){ return "Gentoo Linux"; }

//OS-specific prefix(s)
// NOTE: PREFIX, L_ETCDIR, L_SHAREDIR are defined in the OS-detect.pri project file and passed in
QString LOS::LuminaShare(){ return (L_SHAREDIR+"/lumina-desktop/"); } //Install dir for Lumina share files
QString LOS::AppPrefix(){ return "/usr/"; } //Prefix for applications
QString LOS::SysPrefix(){ return "/"; } //Prefix for system

//OS-specific application shortcuts (*.desktop files)
QString LOS::ControlPanelShortcut(){ return ""; } //system control panel
QString LOS::AppStoreShortcut(){ return LOS::AppPrefix() + "/share/applications/porthole.desktop"; } //graphical app/pkg manager
//OS-specific RSS feeds (Format: QStringList[ <name>::::<url> ]; )
QStringList LOS::RSSFeeds(){ return QStringList(); }

// ==== ExternalDevicePaths() ====
QStringList LOS::ExternalDevicePaths(){
  /* Returns: QStringList[<type>::::<filesystem>::::<path>]
     Note: <type> = [USB, HDRIVE, DVD, SDCARD, UNKNOWN]
     df is much better for this than mount, because it skips
     all non-physical devices (like bind-mounts from schroot)
     so they are not listed in lumina-fm */
  QStringList devs = LUtils::getCmdOutput("df --output=source,fstype,target");
  //Now check the output
  for(int i=0; i<devs.length(); i++){
    if(devs[i].startsWith("/dev/")){
      devs[i] = devs[i].simplified();
      QString type = devs[i].section(" on ",0,0);
      type.remove("/dev/");
      //Determine the type of hardware device based on the dev node
      if(type.startsWith("sd") || type.startsWith("nvme")){ type = "HDRIVE"; }
      else if(type.startsWith("sr")){ type="DVD"; }
      else if(type.contains("mapper")){ type="LVM"; }
      else{ type = "UNKNOWN"; }
      //Now put the device in the proper output format
      devs[i] = type + "::::" + devs[i].section(" ",1,1) + "::::" + devs[i].section(" ",2,2);
    }else{
      //invalid device - remove it from the list
      devs.removeAt(i);
      i--;
    }
  }
  return devs;
}

//Read screen brightness information
int LOS::ScreenBrightness(){
   //Returns: Screen Brightness as a percentage (0-100, with -1 for errors)
  if(screenbrightness==-1){
    if(QFile::exists(QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/.currentxbrightness")){
      int val = LUtils::readFile(QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/.currentxbrightness").join("").simplified().toInt();
      screenbrightness = val;
    }
  }
  return screenbrightness;

}

//Set screen brightness
void LOS::setScreenBrightness(int percent){
  //ensure bounds
  if(percent<0){percent=0;}
  else if(percent>100){ percent=100; }
  // float pf = percent/100.0; //convert to a decimel
  //Run the command
  QString cmd = "xbacklight -set %1";
  // cmd = cmd.arg( QString::number( int(65535*pf) ) );
  cmd = cmd.arg( QString::number( percent ) );
  int ret = LUtils::runCmd(cmd);
  //Save the result for later
  if(ret!=0){ screenbrightness = -1; }
  else{ screenbrightness = percent; }
  LUtils::writeFile(QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/.currentxbrightness", QStringList() << QString::number(screenbrightness), true);

}

//Read the current volume
int LOS::audioVolume(){ //Returns: audio volume as a percentage (0-100, with -1 for errors)
QString info = LUtils::getCmdOutput("amixer get Master").join("").simplified();;
  int out = -1;
  int start_position, end_position;
  QString current_volume;
  if(!info.isEmpty()){
     start_position = info.indexOf("[");
     start_position++;
     end_position = info.indexOf("%");
     current_volume = info.mid(start_position, end_position - start_position);
     out = current_volume.toInt();
  }
  return out;

}

//Set the current volume
void LOS::setAudioVolume(int percent){
  if(percent<0){percent=0;}
  else if(percent>100){percent=100;}
  // QString info = "amixer -c 0 sset Master,0 " + QString::number(percent) + "%";
  QString info = "amixer set Master " + QString::number(percent) + "%";
  if(!info.isEmpty()){
    //Run Command
    LUtils::runCmd(info);
  }

}

//Change the current volume a set amount (+ or -)
void LOS::changeAudioVolume(int percentdiff){
  int old_volume = audioVolume();
  int new_volume = old_volume + percentdiff;
  if (new_volume < 0)
      new_volume = 0;
  if (new_volume > 100)
      new_volume = 100;
  qDebug() << "Setting new volume to: " << new_volume;
  setAudioVolume(new_volume);
}

//Check if a graphical audio mixer is installed
bool LOS::hasMixerUtility(){
  return QFile::exists(LOS::AppPrefix() + "bin/pavucontrol");
}

//Launch the graphical audio mixer utility
void LOS::startMixerUtility(){
  QProcess::startDetached(LOS::AppPrefix() + "bin/pavucontrol");
}

//Check for user system permission (shutdown/restart)
bool LOS::userHasShutdownAccess(){
  return QProcess::startDetached("dbus-send --system --print-reply=literal \
  --type=method_call --dest=org.freedesktop.ConsoleKit \
  /org/freedesktop/ConsoleKit/Manager org.freedesktop.ConsoleKit.Manager.CanPowerOff");
}

//Check for whether the system is safe to power off (no updates being perfomed)
bool LOS::systemPerformingUpdates(){
  return false; //Not implemented yet
}

//Return the details of any updates which are waiting to apply on shutdown
QString LOS::systemPendingUpdates(){
  return "";
}

//System Shutdown
void LOS::systemShutdown(bool){ //start poweroff sequence
  //INPUT: skip updates (true/false)
  QProcess::startDetached("dbus-send --system --print-reply \
  --dest=org.freedesktop.ConsoleKit /org/freedesktop/ConsoleKit/Manager \
  org.freedesktop.ConsoleKit.Manager.PowerOff boolean:true");
}

//System Restart
void LOS::systemRestart(bool){ //start reboot sequence
  //INPUT: skip updates (true/false)
  QProcess::startDetached("dbus-send --system --print-reply \
  --dest=org.freedesktop.ConsoleKit /org/freedesktop/ConsoleKit/Manager \
  org.freedesktop.ConsoleKit.Manager.Reboot boolean:true");
}

//Check for suspend support
bool LOS::systemCanSuspend(){
  return QProcess::startDetached("dbus-send --system --print-reply=literal \
  --type=method_call --dest=org.freedesktop.ConsoleKit \
  /org/freedesktop/ConsoleKit/Manager org.freedesktop.ConsoleKit.Manager.CanSuspend");
}

//Put the system into the suspend state
void LOS::systemSuspend(){
  QProcess::startDetached("dbus-send --system --print-reply \
  --dest=org.freedesktop.ConsoleKit /org/freedesktop/ConsoleKit/Manager \
  org.freedesktop.ConsoleKit.Manager.Suspend boolean:true");
}

//Battery Availability
bool LOS::hasBattery(){
  QString my_status = LUtils::getCmdOutput("acpi -b").join("");
  bool no_battery = my_status.contains("No support");
  if (no_battery) return false;
  return true;
}

//Battery Charge Level
int LOS::batteryCharge(){ //Returns: percent charge (0-100), anything outside that range is counted as an error
  QString my_status = LUtils::getCmdOutput("acpi -b").join("");
  int my_start = my_status.indexOf("%");
  // get the number right before the % sign
  int my_end = my_start;
  my_start--;
  while ( (my_status[my_start] != ' ') && (my_start > 0) )
      my_start--;
  my_start++;
  int my_charge = my_status.mid(my_start, my_end - my_start).toInt();
  if ( (my_charge < 0) || (my_charge > 100) ) return -1;
  return my_charge;
}

//Battery Charging State
// Many possible values are returned if the laptop is plugged in
// these include "Unknown, Full and No support.
// However, it seems just one status is returned when running
// on battery and that is "Discharging". So if the value we get
// is NOT Discharging then we assume the battery is charging.
bool LOS::batteryIsCharging(){
  QString my_status = LUtils::getCmdOutput("acpi -b").join("");
  bool discharging = my_status.contains("Discharging");
  if (discharging) return false;
  return true;
}

//Battery Time Remaining
int LOS::batterySecondsLeft(){ //Returns: estimated number of seconds remaining
  return 0; //not implemented yet for Linux
}

//File Checksums
QStringList LOS::Checksums(QStringList filepaths){ //Return: checksum of the input file
  QStringList info = LUtils::getCmdOutput("md5sum \""+filepaths.join("\" \"")+"\"");
  for(int i=0; i<info.length(); i++){
    // first: md5sum: = error ; second: there's always one empty entry generated by getCmdOutput
    if( info[i].startsWith("md5sum:") || info[i].isEmpty()){ info.removeAt(i); i--; }
    else{
      //Strip out the extra information
      info[i] = info[i].section(" ",0,0);
    }
  }
 return info;
}

//file system capacity
QString LOS::FileSystemCapacity(QString dir) { //Return: percentage capacity as give by the df command
  QStringList mountInfo = LUtils::getCmdOutput("df -h \"" + dir + "\"");
  QString::SectionFlag skipEmpty = QString::SectionSkipEmpty;
  //output: 200G of 400G available on /mount/point
  QString capacity = mountInfo[1].section(" ",3,3, skipEmpty) + " of " + mountInfo[1].section(" ",1,1, skipEmpty) + " available on " +  mountInfo[1].section(" ",5,5, skipEmpty);
  return capacity;
}

QStringList LOS::CPUTemperatures(){ //Returns: List containing the temperature of any CPU's ("50C" for example)
  QStringList temp = LUtils::getCmdOutput("acpi -t").filter("degrees");
  for(int i=0; i<temp.length(); i++){
    if(temp[i].startsWith("Thermal")){
      temp[i] = temp[i].section(" ", 4, 6);
    }else{
      temp.removeAt(i); i--;
    }
  }
  if(temp.isEmpty()) {
    temp << "Not available";
  }
  return temp;
}

int LOS::CPUUsagePercent(){ //Returns: Overall percentage of the amount of CPU cycles in use (-1 for errors)
  QStringList info = LUtils::getCmdOutput("top -bn1").filter("Cpu(s)");
  if(info.isEmpty()){ return -1; }
  QString idle = info.first().section(" ", 7, 7, QString::SectionSkipEmpty);
  if(idle.isEmpty()){ return -1; }
  else{
    return (100 - idle.toDouble());
  }
}

int LOS::MemoryUsagePercent(){
  QStringList mem = LUtils::getCmdOutput("top -bn1").filter("Mem :");
  if(mem.isEmpty()){ return -1; }
  double fB = 0; //Free Bytes
  double uB = 0; //Used Bytes
  fB = mem.first().section(" ", 5, 5, QString::SectionSkipEmpty).toDouble();
  uB = mem.first().section(" ", 7, 7, QString::SectionSkipEmpty).toDouble();
  double per = (uB/(fB+uB)) * 100.0;
  return qRound(per);
}

QStringList LOS::DiskUsage(){ //Returns: List of current read/write stats for each device
  QStringList info = LUtils::getCmdOutput("iostat -dx -N");
  if(info.length()<3){ return QStringList(); } //nothing from command
  QStringList labs = info[1].split(" ",QString::SkipEmptyParts);
  QStringList out;
  QString fmt = "%1: %2 %3";
  for(int i=2; i<info.length(); i++){ //skip the first two lines, just labels
    info[i].replace("\t"," ");
    if(info[i].startsWith("Device:")){ labs = info[i].split(" ", QString::SkipEmptyParts); }//the labels for each column
    else{
      QStringList data = info[i].split(" ",QString::SkipEmptyParts); //data[0] is always the device
      if(data.length()>2 && labs.length()>2){
        out << fmt.arg(data[0], data[3]+" "+labs[3], data[4]+" "+labs[4]);
      }
    }
  }

  return out;
}
#endif
<|endoftext|>