<commit_before>// Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license.

#include "GamepadLinux.hpp"
#include "../InputSystem/GamepadHelper.hpp"
#include "Pomdog/Logging/Log.hpp"
#include "Pomdog/Utility/Assert.hpp"
#include <linux/input.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <algorithm>
#include <tuple>

namespace Pomdog {
namespace Detail {
namespace InputSystem {
namespace Linux {
namespace {

constexpr size_t BitCount(size_t n)
{
    return (n / 8) + 1;
}

template <typename T>
bool HasBit(const T& array, uint32_t bit)
{
    return ((1 << (bit % 8)) & array[bit / 8]) != 0;
}

ButtonState GetTriggerButtonValue(int value)
{
    return (value > 0) ? ButtonState::Pressed : ButtonState::Released;
}

float GetThumbStickValue(int value, const ThumbStickInfo& info)
{
    return (static_cast<float>((value - info.Minimum) * 2 - info.Range) / info.Range);
}

} // unnamed namespace

bool GamepadDevice::Open(int deviceIndex)
{
    POMDOG_ASSERT(fd == -1);

    const auto js = "/dev/input/event" + std::to_string(deviceIndex);
    fd = ::open(js.c_str(), O_RDONLY | O_NONBLOCK);
    if (fd < 0) {
        fd = -1;
        return false;
    }

    POMDOG_ASSERT(fd >= 0);

    struct input_id inputId;
    if (::ioctl(fd, EVIOCGID, &inputId) < 0) {
        Close();
        return false;
    }

    auto& uuid = caps.DeviceUUID;
    uuid.BusType = static_cast<uint16_t>(inputId.bustype);
    uuid.VendorID = static_cast<uint16_t>(inputId.vendor);
    uuid.ProductID = static_cast<uint16_t>(inputId.product);
    uuid.VersionNumber = static_cast<uint16_t>(inputId.version);

    // TODO: Use udev-joystick-blacklist here
    // https://github.com/denilsonsa/udev-joystick-blacklist

    std::array<uint8_t, BitCount(EV_MAX)> evBits;
    std::array<uint8_t, BitCount(KEY_MAX)> keyBits;
    std::array<uint8_t, BitCount(ABS_MAX)> absBits;

    std::fill(std::begin(evBits), std::end(evBits), 0);
    std::fill(std::begin(keyBits), std::end(keyBits), 0);
    std::fill(std::begin(absBits), std::end(absBits), 0);

    if ((ioctl(fd, EVIOCGBIT(0, evBits.size()), evBits.data()) < 0) ||
        (ioctl(fd, EVIOCGBIT(EV_KEY, keyBits.size()), keyBits.data()) < 0) ||
        (ioctl(fd, EVIOCGBIT(EV_ABS, absBits.size()), absBits.data()) < 0)) {
        Close();
        return false;
    }

    if (!HasBit(evBits, EV_KEY) ||
        !HasBit(evBits, EV_ABS) ||
        !HasBit(absBits, ABS_X) ||
        !HasBit(absBits, ABS_Y)) {
        // The device is not a joystick or gamepad.
        Close();
        return false;
    }

    std::tie(this->mappings, this->caps.Name) = GetMappings(uuid);

    int numOfButtons = 0;
    std::fill(std::begin(keyMap), std::end(keyMap), -1);

    for (int i = BTN_JOYSTICK; i < KEY_MAX; ++i) {
        if (HasBit(keyBits, static_cast<uint32_t>(i))) {
            const auto index = i - BTN_GAMEPAD;
            if ((index < 0) || (index >= static_cast<int>(keyMap.size()))) {
                continue;
            }
            keyMap[index] = static_cast<int8_t>(numOfButtons);

            POMDOG_ASSERT(numOfButtons >= 0);
            POMDOG_ASSERT(numOfButtons < static_cast<int>(mappings.buttons.size()));

            if (auto hasButton = HasButton(caps, mappings.buttons, numOfButtons); hasButton != nullptr) {
                (*hasButton) = true;
            }
            ++numOfButtons;
        }
    }

    for (int i = ABS_X; i <= ABS_RZ; ++i) {
        if (HasBit(absBits, i)) {
            struct input_absinfo absInfo;
            if (::ioctl(fd, EVIOCGABS(i), &absInfo) < 0) {
                continue;
            }

            POMDOG_ASSERT(i >= 0);
            POMDOG_ASSERT(i < static_cast<int>(mappings.axes.size()));

            if (auto hasAxis = HasAxis(caps, mappings, i); hasAxis != nullptr) {
                (*hasAxis) = true;
            }

            POMDOG_ASSERT(i >= 0);
            POMDOG_ASSERT(i < static_cast<int>(thumbStickInfos.size()));
            auto& info = thumbStickInfos[i];
            info.Minimum = absInfo.minimum;
            info.Range = std::max(1, absInfo.maximum - absInfo.minimum);
        }
    }

    if (caps.Name.empty()) {
        std::array<char, 256> gamepadName;
        std::fill(std::begin(gamepadName), std::end(gamepadName), 0);
        if (::ioctl(fd, EVIOCGNAME(255), gamepadName.data()) < 0) {
            Close();
            return false;
        }
        caps.Name = gamepadName.data();
    }

    GamepadHelper::ClearState(state);
    state.IsConnected = true;

    this->deviceEventIndex = deviceIndex;

    Log::Internal("Open gamepad: " + caps.Name + " at " + js);
    return true;
}

void GamepadDevice::Close()
{
    if (fd >= 0) {
        ::close(fd);
        fd = -1;
    }

    GamepadHelper::ClearState(state);
    state.IsConnected = false;

    GamepadCapabilities emptyCaps;
    std::swap(caps, emptyCaps);
}

bool GamepadDevice::HasFileDescriptor() const
{
    return fd >= 0;
}

void GamepadDevice::PollEvents()
{
    for (;;) {
        struct input_event event;

        errno = 0;
        if (::read(fd, &event, sizeof(event)) < 0) {
            if (errno == ENODEV) {
                Log::Internal("Disconnect gamepad: " + caps.Name);
                Close();
            }
            break;
        }

        switch (event.type) {
        case EV_KEY: {
            const auto physicalIndex = static_cast<int>(event.code) - BTN_GAMEPAD;
            if (physicalIndex >= static_cast<int>(keyMap.size())) {
                break;
            }
            const auto buttonIndex = keyMap[physicalIndex];
            if (auto button = GetButton(state, mappings.buttons, buttonIndex); button != nullptr) {
                (*button) = (event.value != 0) ? ButtonState::Pressed: ButtonState::Released;
            }
            break;
        }
        case EV_ABS:
            switch (event.code) {
            case ABS_HAT0X:
            case ABS_HAT0Y:
            case ABS_HAT1X:
            case ABS_HAT1Y:
            case ABS_HAT2X:
            case ABS_HAT2Y:
            case ABS_HAT3X:
            case ABS_HAT3Y: {
                const auto code = (event.code - ABS_HAT0X);
                const auto axis = code % 2;
                if (event.value == 0) {
                    if (axis == 0) {
                        state.DPad.Left = ButtonState::Released;
                        state.DPad.Right = ButtonState::Released;
                    }
                    else {
                        state.DPad.Up = ButtonState::Released;
                        state.DPad.Down = ButtonState::Released;
                    }
                }
                else if (event.value > 0) {
                    if (axis == 0) {
                        state.DPad.Right = ButtonState::Pressed;
                    }
                    else {
                        state.DPad.Down = ButtonState::Pressed;
                    }
                }
                else if (event.value < 0) {
                    if (axis == 0) {
                        state.DPad.Left = ButtonState::Pressed;
                    }
                    else {
                        state.DPad.Up = ButtonState::Pressed;
                    }
                }
                break;
            }
            case ABS_X:
            case ABS_Y:
            case ABS_Z:
            case ABS_RX:
            case ABS_RY:
            case ABS_RZ:
                static_assert(ABS_X == 0, "");
                static_assert(ABS_Y == 1, "");
                static_assert(ABS_Z == 2, "");
                static_assert(ABS_RX == 3, "");
                static_assert(ABS_RY == 4, "");
                static_assert(ABS_RZ == 5, "");
                POMDOG_ASSERT(event.code >= 0);
                POMDOG_ASSERT(event.code < static_cast<int>(mappings.axes.size()));
                POMDOG_ASSERT(event.code < static_cast<int>(thumbStickInfos.size()));

                switch (mappings.axes[event.code]) {
                case AxesKind::LeftTrigger:
                    state.Buttons.LeftTrigger = GetTriggerButtonValue(event.value);
                    break;
                case AxesKind::RightTrigger:
                    state.Buttons.RightTrigger = GetTriggerButtonValue(event.value);
                    break;
                case AxesKind::LeftStickX:
                    state.ThumbSticks.Left.X = GetThumbStickValue(event.value, thumbStickInfos[event.code]);
                    break;
                case AxesKind::LeftStickY:
                    state.ThumbSticks.Left.Y = GetThumbStickValue(event.value, thumbStickInfos[event.code]);
                    break;
                case AxesKind::RightStickX:
                    state.ThumbSticks.Right.X = GetThumbStickValue(event.value, thumbStickInfos[event.code]);
                    break;
                case AxesKind::RightStickY:
                    state.ThumbSticks.Right.Y = GetThumbStickValue(event.value, thumbStickInfos[event.code]);
                    break;
                default:
                    break;
                }
                break;
            default:
                break;
            }
            break;
        default:
            break;
        }
    }
}

GamepadLinux::GamepadLinux()
{
}

GamepadLinux::~GamepadLinux()
{
    for (auto& gamepad : gamepads) {
        if (gamepad.HasFileDescriptor()) {
            Log::Internal("Close gamepad: " + gamepad.caps.Name);
            gamepad.Close();
        }
    }
}

GamepadCapabilities GamepadLinux::GetCapabilities(PlayerIndex playerIndex) const
{
    const auto index = GamepadHelper::ToInt(playerIndex);
    POMDOG_ASSERT(index < static_cast<int>(gamepads.size()));
    return gamepads[index].caps;
}

GamepadState GamepadLinux::GetState(PlayerIndex playerIndex) const
{
    const auto index = GamepadHelper::ToInt(playerIndex);
    POMDOG_ASSERT(index < static_cast<int>(gamepads.size()));
    return gamepads[index].state;
}

void GamepadLinux::EnumerateDevices()
{
    auto gamepad = std::begin(gamepads);

    for (int i = 0; i < 32; i++) {
        while ((gamepad != std::end(gamepads)) && gamepad->HasFileDescriptor()) {
            ++gamepad;
        }
        if (gamepad == std::end(gamepads)) {
            break;
        }

        auto iter = std::find_if(std::begin(gamepads), std::end(gamepads), [&](auto& dev) {
            return (dev.HasFileDescriptor() && (dev.deviceEventIndex == i));
        });
        if (iter != std::end(gamepads)) {
            // The device is already opened.
            continue;
        }

        POMDOG_ASSERT(!gamepad->HasFileDescriptor());

        if (!gamepad->Open(i)) {
            gamepad->Close();
            continue;
        }
    }
}

void GamepadLinux::PollEvents()
{
    for (auto& gamepad : gamepads) {
        if (!gamepad.HasFileDescriptor()) {
            continue;
        }

        gamepad.PollEvents();
    }
}

} // namespace Linux
} // namespace InputSystem
} // namespace Detail
} // namespace Pomdog
<commit_msg>Add assertions<commit_after>// Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license.

#include "GamepadLinux.hpp"
#include "../InputSystem/GamepadHelper.hpp"
#include "Pomdog/Logging/Log.hpp"
#include "Pomdog/Utility/Assert.hpp"
#include <linux/input.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <algorithm>
#include <tuple>

namespace Pomdog {
namespace Detail {
namespace InputSystem {
namespace Linux {
namespace {

constexpr size_t BitCount(size_t n)
{
    return (n / 8) + 1;
}

template <typename T>
bool HasBit(const T& array, uint32_t bit)
{
    return ((1 << (bit % 8)) & array[bit / 8]) != 0;
}

ButtonState GetTriggerButtonValue(int value)
{
    return (value > 0) ? ButtonState::Pressed : ButtonState::Released;
}

float GetThumbStickValue(int value, const ThumbStickInfo& info)
{
    return (static_cast<float>((value - info.Minimum) * 2 - info.Range) / info.Range);
}

} // unnamed namespace

bool GamepadDevice::Open(int deviceIndex)
{
    POMDOG_ASSERT(fd == -1);

    const auto js = "/dev/input/event" + std::to_string(deviceIndex);
    fd = ::open(js.c_str(), O_RDONLY | O_NONBLOCK);
    if (fd < 0) {
        fd = -1;
        return false;
    }

    POMDOG_ASSERT(fd >= 0);

    struct input_id inputId;
    if (::ioctl(fd, EVIOCGID, &inputId) < 0) {
        Close();
        return false;
    }

    auto& uuid = caps.DeviceUUID;
    uuid.BusType = static_cast<uint16_t>(inputId.bustype);
    uuid.VendorID = static_cast<uint16_t>(inputId.vendor);
    uuid.ProductID = static_cast<uint16_t>(inputId.product);
    uuid.VersionNumber = static_cast<uint16_t>(inputId.version);

    // TODO: Use udev-joystick-blacklist here
    // https://github.com/denilsonsa/udev-joystick-blacklist

    std::array<uint8_t, BitCount(EV_MAX)> evBits;
    std::array<uint8_t, BitCount(KEY_MAX)> keyBits;
    std::array<uint8_t, BitCount(ABS_MAX)> absBits;

    std::fill(std::begin(evBits), std::end(evBits), 0);
    std::fill(std::begin(keyBits), std::end(keyBits), 0);
    std::fill(std::begin(absBits), std::end(absBits), 0);

    if ((ioctl(fd, EVIOCGBIT(0, evBits.size()), evBits.data()) < 0) ||
        (ioctl(fd, EVIOCGBIT(EV_KEY, keyBits.size()), keyBits.data()) < 0) ||
        (ioctl(fd, EVIOCGBIT(EV_ABS, absBits.size()), absBits.data()) < 0)) {
        Close();
        return false;
    }

    if (!HasBit(evBits, EV_KEY) ||
        !HasBit(evBits, EV_ABS) ||
        !HasBit(absBits, ABS_X) ||
        !HasBit(absBits, ABS_Y)) {
        // The device is not a joystick or gamepad.
        Close();
        return false;
    }

    std::tie(this->mappings, this->caps.Name) = GetMappings(uuid);

    int numOfButtons = 0;
    std::fill(std::begin(keyMap), std::end(keyMap), -1);

    for (int i = BTN_JOYSTICK; i < KEY_MAX; ++i) {
        if (HasBit(keyBits, static_cast<uint32_t>(i))) {
            const auto index = i - BTN_GAMEPAD;
            if ((index < 0) || (index >= static_cast<int>(keyMap.size()))) {
                continue;
            }
            keyMap[index] = static_cast<int8_t>(numOfButtons);

            POMDOG_ASSERT(numOfButtons >= 0);
            POMDOG_ASSERT(numOfButtons < static_cast<int>(mappings.buttons.size()));

            if (auto hasButton = HasButton(caps, mappings.buttons, numOfButtons); hasButton != nullptr) {
                (*hasButton) = true;
            }
            ++numOfButtons;
        }
    }

    for (int i = ABS_X; i <= ABS_RZ; ++i) {
        if (HasBit(absBits, i)) {
            struct input_absinfo absInfo;
            if (::ioctl(fd, EVIOCGABS(i), &absInfo) < 0) {
                continue;
            }

            POMDOG_ASSERT(i >= 0);
            POMDOG_ASSERT(i < static_cast<int>(mappings.axes.size()));

            if (auto hasAxis = HasAxis(caps, mappings, i); hasAxis != nullptr) {
                (*hasAxis) = true;
            }

            POMDOG_ASSERT(i >= 0);
            POMDOG_ASSERT(i < static_cast<int>(thumbStickInfos.size()));
            auto& info = thumbStickInfos[i];
            info.Minimum = absInfo.minimum;
            info.Range = std::max(1, absInfo.maximum - absInfo.minimum);
        }
    }

    if (caps.Name.empty()) {
        std::array<char, 256> gamepadName;
        std::fill(std::begin(gamepadName), std::end(gamepadName), 0);
        if (::ioctl(fd, EVIOCGNAME(255), gamepadName.data()) < 0) {
            Close();
            return false;
        }
        caps.Name = gamepadName.data();
    }

    GamepadHelper::ClearState(state);
    state.IsConnected = true;

    this->deviceEventIndex = deviceIndex;

    Log::Internal("Open gamepad: " + caps.Name + " at " + js);
    return true;
}

void GamepadDevice::Close()
{
    if (fd >= 0) {
        ::close(fd);
        fd = -1;
    }

    GamepadHelper::ClearState(state);
    state.IsConnected = false;

    GamepadCapabilities emptyCaps;
    std::swap(caps, emptyCaps);
}

bool GamepadDevice::HasFileDescriptor() const
{
    return fd >= 0;
}

void GamepadDevice::PollEvents()
{
    for (;;) {
        struct input_event event;

        errno = 0;
        if (::read(fd, &event, sizeof(event)) < 0) {
            if (errno == ENODEV) {
                Log::Internal("Disconnect gamepad: " + caps.Name);
                Close();
            }
            break;
        }

        switch (event.type) {
        case EV_KEY: {
            const auto physicalIndex = static_cast<int>(event.code) - BTN_GAMEPAD;
            if (physicalIndex >= static_cast<int>(keyMap.size())) {
                break;
            }
            const auto buttonIndex = keyMap[physicalIndex];
            if (auto button = GetButton(state, mappings.buttons, buttonIndex); button != nullptr) {
                (*button) = (event.value != 0) ? ButtonState::Pressed: ButtonState::Released;
            }
            break;
        }
        case EV_ABS:
            switch (event.code) {
            case ABS_HAT0X:
            case ABS_HAT0Y:
            case ABS_HAT1X:
            case ABS_HAT1Y:
            case ABS_HAT2X:
            case ABS_HAT2Y:
            case ABS_HAT3X:
            case ABS_HAT3Y: {
                const auto code = (event.code - ABS_HAT0X);
                const auto axis = code % 2;
                if (event.value == 0) {
                    if (axis == 0) {
                        state.DPad.Left = ButtonState::Released;
                        state.DPad.Right = ButtonState::Released;
                    }
                    else {
                        state.DPad.Up = ButtonState::Released;
                        state.DPad.Down = ButtonState::Released;
                    }
                }
                else if (event.value > 0) {
                    if (axis == 0) {
                        state.DPad.Right = ButtonState::Pressed;
                    }
                    else {
                        state.DPad.Down = ButtonState::Pressed;
                    }
                }
                else if (event.value < 0) {
                    if (axis == 0) {
                        state.DPad.Left = ButtonState::Pressed;
                    }
                    else {
                        state.DPad.Up = ButtonState::Pressed;
                    }
                }
                break;
            }
            case ABS_X:
            case ABS_Y:
            case ABS_Z:
            case ABS_RX:
            case ABS_RY:
            case ABS_RZ:
                static_assert(ABS_X == 0, "");
                static_assert(ABS_Y == 1, "");
                static_assert(ABS_Z == 2, "");
                static_assert(ABS_RX == 3, "");
                static_assert(ABS_RY == 4, "");
                static_assert(ABS_RZ == 5, "");
                POMDOG_ASSERT(event.code >= 0);
                POMDOG_ASSERT(event.code < static_cast<int>(mappings.axes.size()));
                POMDOG_ASSERT(event.code < static_cast<int>(thumbStickInfos.size()));

                switch (mappings.axes[event.code]) {
                case AxesKind::LeftTrigger:
                    state.Buttons.LeftTrigger = GetTriggerButtonValue(event.value);
                    break;
                case AxesKind::RightTrigger:
                    state.Buttons.RightTrigger = GetTriggerButtonValue(event.value);
                    break;
                case AxesKind::LeftStickX:
                    state.ThumbSticks.Left.X = GetThumbStickValue(event.value, thumbStickInfos[event.code]);
                    break;
                case AxesKind::LeftStickY:
                    state.ThumbSticks.Left.Y = GetThumbStickValue(event.value, thumbStickInfos[event.code]);
                    break;
                case AxesKind::RightStickX:
                    state.ThumbSticks.Right.X = GetThumbStickValue(event.value, thumbStickInfos[event.code]);
                    break;
                case AxesKind::RightStickY:
                    state.ThumbSticks.Right.Y = GetThumbStickValue(event.value, thumbStickInfos[event.code]);
                    break;
                default:
                    break;
                }
                break;
            default:
                break;
            }
            break;
        default:
            break;
        }
    }
}

GamepadLinux::GamepadLinux()
{
}

GamepadLinux::~GamepadLinux()
{
    for (auto& gamepad : gamepads) {
        if (gamepad.HasFileDescriptor()) {
            Log::Internal("Close gamepad: " + gamepad.caps.Name);
            gamepad.Close();
        }
    }
}

GamepadCapabilities GamepadLinux::GetCapabilities(PlayerIndex playerIndex) const
{
    const auto index = GamepadHelper::ToInt(playerIndex);
    POMDOG_ASSERT(index >= 0);
    POMDOG_ASSERT(index < static_cast<int>(gamepads.size()));
    return gamepads[index].caps;
}

GamepadState GamepadLinux::GetState(PlayerIndex playerIndex) const
{
    const auto index = GamepadHelper::ToInt(playerIndex);
    POMDOG_ASSERT(index >= 0);
    POMDOG_ASSERT(index < static_cast<int>(gamepads.size()));
    return gamepads[index].state;
}

void GamepadLinux::EnumerateDevices()
{
    auto gamepad = std::begin(gamepads);

    for (int i = 0; i < 32; i++) {
        while ((gamepad != std::end(gamepads)) && gamepad->HasFileDescriptor()) {
            ++gamepad;
        }
        if (gamepad == std::end(gamepads)) {
            break;
        }

        auto iter = std::find_if(std::begin(gamepads), std::end(gamepads), [&](auto& dev) {
            return (dev.HasFileDescriptor() && (dev.deviceEventIndex == i));
        });
        if (iter != std::end(gamepads)) {
            // The device is already opened.
            continue;
        }

        POMDOG_ASSERT(!gamepad->HasFileDescriptor());

        if (!gamepad->Open(i)) {
            gamepad->Close();
            continue;
        }
    }
}

void GamepadLinux::PollEvents()
{
    for (auto& gamepad : gamepads) {
        if (!gamepad.HasFileDescriptor()) {
            continue;
        }

        gamepad.PollEvents();
    }
}

} // namespace Linux
} // namespace InputSystem
} // namespace Detail
} // namespace Pomdog
<|endoftext|>


<commit_before>/*
 * Copyright 2011-2016 Branimir Karadzic. All rights reserved.
 * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
 */

#include "common.h"
#include "bgfx_utils.h"

struct PosColorVertex
{
	float m_x;
	float m_y;
	float m_z;
	uint32_t m_abgr;

	static void init()
	{
		ms_decl
			.begin()
			.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
			.add(bgfx::Attrib::Color0,   4, bgfx::AttribType::Uint8, true)
			.end();
	};

	static bgfx::VertexDecl ms_decl;
};

bgfx::VertexDecl PosColorVertex::ms_decl;

static PosColorVertex s_cubeVertices[8] =
{
	{-1.0f,  1.0f,  1.0f, 0xff000000 },
	{ 1.0f,  1.0f,  1.0f, 0xff0000ff },
	{-1.0f, -1.0f,  1.0f, 0xff00ff00 },
	{ 1.0f, -1.0f,  1.0f, 0xff00ffff },
	{-1.0f,  1.0f, -1.0f, 0xffff0000 },
	{ 1.0f,  1.0f, -1.0f, 0xffff00ff },
	{-1.0f, -1.0f, -1.0f, 0xffffff00 },
	{ 1.0f, -1.0f, -1.0f, 0xffffffff },
};

static const uint16_t s_cubeIndices[36] =
{
	0, 1, 2, // 0
	1, 3, 2,
	4, 6, 5, // 2
	5, 6, 7,
	0, 2, 4, // 4
	4, 2, 6,
	1, 5, 3, // 6
	5, 7, 3,
	0, 4, 1, // 8
	4, 5, 1,
	2, 3, 6, // 10
	6, 3, 7,
};

class ExampleCubes : public entry::AppI
{
	void init(int _argc, char** _argv) BX_OVERRIDE
	{
		Args args(_argc, _argv);

		m_width  = 1280;
		m_height = 720;
		m_debug  = BGFX_DEBUG_TEXT;
		m_reset  = BGFX_RESET_VSYNC;

		bgfx::init(args.m_type, args.m_pciId);
		bgfx::reset(m_width, m_height, m_reset);

		// Enable debug text.
		bgfx::setDebug(m_debug);

		// Set view 0 clear state.
		bgfx::setViewClear(0
				, BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
				, 0x303030ff
				, 1.0f
				, 0
				);

		// Create vertex stream declaration.
		PosColorVertex::init();

		// Create static vertex buffer.
		m_vbh = bgfx::createVertexBuffer(
				// Static data can be passed with bgfx::makeRef
				bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) )
				, PosColorVertex::ms_decl
				);

		// Create static index buffer.
		m_ibh = bgfx::createIndexBuffer(
				// Static data can be passed with bgfx::makeRef
				bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) )
				);

		// Create program from shaders.
		m_program = loadProgram("vs_cubes", "fs_cubes");

		m_timeOffset = bx::getHPCounter();
	}

	virtual int shutdown() BX_OVERRIDE
	{
		// Cleanup.
		bgfx::destroyIndexBuffer(m_ibh);
		bgfx::destroyVertexBuffer(m_vbh);
		bgfx::destroyProgram(m_program);

		// Shutdown bgfx.
		bgfx::shutdown();

		return 0;
	}

	bool update() BX_OVERRIDE
	{
		if (!entry::processEvents(m_width, m_height, m_debug, m_reset) )
		{
			int64_t now = bx::getHPCounter();
			static int64_t last = now;
			const int64_t frameTime = now - last;
			last = now;
			const double freq = double(bx::getHPFrequency() );
			const double toMs = 1000.0/freq;

			float time = (float)( (now-m_timeOffset)/double(bx::getHPFrequency() ) );

			// Use debug font to print information about this example.
			bgfx::dbgTextClear();
			bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/01-cube");
			bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Rendering simple static mesh.");
			bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs);

			float at[3]  = { 0.0f, 0.0f,   0.0f };
			float eye[3] = { 0.0f, 0.0f, -35.0f };

			// Set view and projection matrix for view 0.
			const bgfx::HMD* hmd = bgfx::getHMD();
			if (NULL != hmd && 0 != (hmd->flags & BGFX_HMD_RENDERING) )
			{
				float view[16];
				bx::mtxQuatTranslationHMD(view, hmd->eye[0].rotation, eye);
				bgfx::setViewTransform(0, view, hmd->eye[0].projection, BGFX_VIEW_STEREO, hmd->eye[1].projection);

				// Set view 0 default viewport.
				//
				// Use HMD's width/height since HMD's internal frame buffer size
				// might be much larger than window size.
				bgfx::setViewRect(0, 0, 0, hmd->width, hmd->height);
			}
			else
			{
				float view[16];
				bx::mtxLookAt(view, eye, at);

				float proj[16];
				bx::mtxProj(proj, 60.0f, float(m_width)/float(m_height), 0.1f, 100.0f);
				bgfx::setViewTransform(0, view, proj);

				// Set view 0 default viewport.
				bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) );
			}

			// This dummy draw call is here to make sure that view 0 is cleared
			// if no other draw calls are submitted to view 0.
			bgfx::touch(0);

			// Submit 11x11 cubes.
			for (uint32_t yy = 0; yy < 11; ++yy)
			{
				for (uint32_t xx = 0; xx < 11; ++xx)
				{
					float mtx[16];
					bx::mtxRotateXY(mtx, time + xx*0.21f, time + yy*0.37f);
					mtx[12] = -15.0f + float(xx)*3.0f;
					mtx[13] = -15.0f + float(yy)*3.0f;
					mtx[14] = 0.0f;

					// Set model matrix for rendering.
					bgfx::setTransform(mtx);

					// Set vertex and index buffer.
					bgfx::setVertexBuffer(m_vbh);
					bgfx::setIndexBuffer(m_ibh);

					// Set render states.
					bgfx::setState(BGFX_STATE_DEFAULT);

					// Submit primitive for rendering to view 0.
					bgfx::submit(0, m_program);
				}
			}

			// Advance to next frame. Rendering thread will be kicked to
			// process submitted rendering primitives.
			bgfx::frame();

			return true;
		}

		return false;
	}

	uint32_t m_width;
	uint32_t m_height;
	uint32_t m_debug;
	uint32_t m_reset;
	bgfx::VertexBufferHandle m_vbh;
	bgfx::IndexBufferHandle m_ibh;
	bgfx::ProgramHandle m_program;
	int64_t m_timeOffset;
};

ENTRY_IMPLEMENT_MAIN(ExampleCubes);
<commit_msg>01-cubes: Switched to tristrip to test functionality.<commit_after>/*
 * Copyright 2011-2016 Branimir Karadzic. All rights reserved.
 * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
 */

#include "common.h"
#include "bgfx_utils.h"

struct PosColorVertex
{
	float m_x;
	float m_y;
	float m_z;
	uint32_t m_abgr;

	static void init()
	{
		ms_decl
			.begin()
			.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
			.add(bgfx::Attrib::Color0,   4, bgfx::AttribType::Uint8, true)
			.end();
	};

	static bgfx::VertexDecl ms_decl;
};

bgfx::VertexDecl PosColorVertex::ms_decl;

static PosColorVertex s_cubeVertices[] =
{
	{-1.0f,  1.0f,  1.0f, 0xff000000 },
	{ 1.0f,  1.0f,  1.0f, 0xff0000ff },
	{-1.0f, -1.0f,  1.0f, 0xff00ff00 },
	{ 1.0f, -1.0f,  1.0f, 0xff00ffff },
	{-1.0f,  1.0f, -1.0f, 0xffff0000 },
	{ 1.0f,  1.0f, -1.0f, 0xffff00ff },
	{-1.0f, -1.0f, -1.0f, 0xffffff00 },
	{ 1.0f, -1.0f, -1.0f, 0xffffffff },
};

static const uint16_t s_cubeTriList[] =
{
	0, 1, 2, // 0
	1, 3, 2,
	4, 6, 5, // 2
	5, 6, 7,
	0, 2, 4, // 4
	4, 2, 6,
	1, 5, 3, // 6
	5, 7, 3,
	0, 4, 1, // 8
	4, 5, 1,
	2, 3, 6, // 10
	6, 3, 7,
};

static const uint16_t s_cubeTriStrip[] =
{
	0, 1, 2,
	3,
	7,
	1,
	5,
	0,
	4,
	2,
	6,
	7,
	4,
	5,
};

class ExampleCubes : public entry::AppI
{
	void init(int _argc, char** _argv) BX_OVERRIDE
	{
		Args args(_argc, _argv);

		m_width  = 1280;
		m_height = 720;
		m_debug  = BGFX_DEBUG_TEXT;
		m_reset  = BGFX_RESET_VSYNC;

		bgfx::init(args.m_type, args.m_pciId);
		bgfx::reset(m_width, m_height, m_reset);

		// Enable debug text.
		bgfx::setDebug(m_debug);

		// Set view 0 clear state.
		bgfx::setViewClear(0
				, BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
				, 0x303030ff
				, 1.0f
				, 0
				);

		// Create vertex stream declaration.
		PosColorVertex::init();

		// Create static vertex buffer.
		m_vbh = bgfx::createVertexBuffer(
				// Static data can be passed with bgfx::makeRef
				bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) )
				, PosColorVertex::ms_decl
				);

		// Create static index buffer.
		m_ibh = bgfx::createIndexBuffer(
				// Static data can be passed with bgfx::makeRef
				bgfx::makeRef(s_cubeTriStrip, sizeof(s_cubeTriStrip) )
				);

		// Create program from shaders.
		m_program = loadProgram("vs_cubes", "fs_cubes");

		m_timeOffset = bx::getHPCounter();
	}

	virtual int shutdown() BX_OVERRIDE
	{
		// Cleanup.
		bgfx::destroyIndexBuffer(m_ibh);
		bgfx::destroyVertexBuffer(m_vbh);
		bgfx::destroyProgram(m_program);

		// Shutdown bgfx.
		bgfx::shutdown();

		return 0;
	}

	bool update() BX_OVERRIDE
	{
		if (!entry::processEvents(m_width, m_height, m_debug, m_reset) )
		{
			int64_t now = bx::getHPCounter();
			static int64_t last = now;
			const int64_t frameTime = now - last;
			last = now;
			const double freq = double(bx::getHPFrequency() );
			const double toMs = 1000.0/freq;

			float time = (float)( (now-m_timeOffset)/double(bx::getHPFrequency() ) );

			// Use debug font to print information about this example.
			bgfx::dbgTextClear();
			bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/01-cube");
			bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Rendering simple static mesh.");
			bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs);

			float at[3]  = { 0.0f, 0.0f,   0.0f };
			float eye[3] = { 0.0f, 0.0f, -35.0f };

			// Set view and projection matrix for view 0.
			const bgfx::HMD* hmd = bgfx::getHMD();
			if (NULL != hmd && 0 != (hmd->flags & BGFX_HMD_RENDERING) )
			{
				float view[16];
				bx::mtxQuatTranslationHMD(view, hmd->eye[0].rotation, eye);
				bgfx::setViewTransform(0, view, hmd->eye[0].projection, BGFX_VIEW_STEREO, hmd->eye[1].projection);

				// Set view 0 default viewport.
				//
				// Use HMD's width/height since HMD's internal frame buffer size
				// might be much larger than window size.
				bgfx::setViewRect(0, 0, 0, hmd->width, hmd->height);
			}
			else
			{
				float view[16];
				bx::mtxLookAt(view, eye, at);

				float proj[16];
				bx::mtxProj(proj, 60.0f, float(m_width)/float(m_height), 0.1f, 100.0f);
				bgfx::setViewTransform(0, view, proj);

				// Set view 0 default viewport.
				bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) );
			}

			// This dummy draw call is here to make sure that view 0 is cleared
			// if no other draw calls are submitted to view 0.
			bgfx::touch(0);

			// Submit 11x11 cubes.
			for (uint32_t yy = 0; yy < 11; ++yy)
			{
				for (uint32_t xx = 0; xx < 11; ++xx)
				{
					float mtx[16];
					bx::mtxRotateXY(mtx, time + xx*0.21f, time + yy*0.37f);
					mtx[12] = -15.0f + float(xx)*3.0f;
					mtx[13] = -15.0f + float(yy)*3.0f;
					mtx[14] = 0.0f;

					// Set model matrix for rendering.
					bgfx::setTransform(mtx);

					// Set vertex and index buffer.
					bgfx::setVertexBuffer(m_vbh);
					bgfx::setIndexBuffer(m_ibh);

					// Set render states.
					bgfx::setState(0
						| BGFX_STATE_DEFAULT
						| BGFX_STATE_PT_TRISTRIP
						);

					// Submit primitive for rendering to view 0.
					bgfx::submit(0, m_program);
				}
			}

			// Advance to next frame. Rendering thread will be kicked to
			// process submitted rendering primitives.
			bgfx::frame();

			return true;
		}

		return false;
	}

	uint32_t m_width;
	uint32_t m_height;
	uint32_t m_debug;
	uint32_t m_reset;
	bgfx::VertexBufferHandle m_vbh;
	bgfx::IndexBufferHandle m_ibh;
	bgfx::ProgramHandle m_program;
	int64_t m_timeOffset;
};

ENTRY_IMPLEMENT_MAIN(ExampleCubes);
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999-2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(PREFIXRESOLVER_HEADER_GUARD_1357924680)
#define PREFIXRESOLVER_HEADER_GUARD_1357924680

// Base include file.  Must be first.
#include <PlatformSupport/PlatformSupportDefinitions.hpp>

#include <XalanDOM/XalanDOMString.hpp>

/**
 * This class defines an interface for classes that resolve namespace prefixes
 * to their URIs
 */
class XALAN_PLATFORMSUPPORT_EXPORT PrefixResolver
{
public:

	PrefixResolver();

	PrefixResolver(const PrefixResolver&);

	virtual
	~PrefixResolver();

	/**
	 * Retrieve a namespace corresponding to a prefix.  This assumes that
	 * the PrevixResolver hold's its own namespace context, or is a namespace
	 * context itself.
	 *
	 * @param prefix Prefix to resolve
	 * @return namespace that prefix resolves to, or null if prefix is not found
	 */
	virtual const XalanDOMString*
	getNamespaceForPrefix(const XalanDOMString&		prefix) const = 0;

	/**
	 * Retrieve the base URI for the resolver.
	 *
	 * @return URI string
	 */
	virtual const XalanDOMString&
	getURI() const = 0;
};

#endif	// PREFIXRESOLVER_HEADER_GUARD_1357924680
<commit_msg>Fixed typo and updated copyright.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(PREFIXRESOLVER_HEADER_GUARD_1357924680)
#define PREFIXRESOLVER_HEADER_GUARD_1357924680

// Base include file.  Must be first.
#include <PlatformSupport/PlatformSupportDefinitions.hpp>

#include <XalanDOM/XalanDOMString.hpp>

/**
 * This class defines an interface for classes that resolve namespace prefixes
 * to their URIs
 */
class XALAN_PLATFORMSUPPORT_EXPORT PrefixResolver
{
public:

	PrefixResolver();

	PrefixResolver(const PrefixResolver&);

	virtual
	~PrefixResolver();

	/**
	 * Retrieve a namespace corresponding to a prefix.  This assumes that
	 * the PrevixResolver holds its own namespace context, or is a namespace
	 * context itself.
	 *
	 * @param prefix Prefix to resolve
	 * @return namespace that prefix resolves to, or null if prefix is not found
	 */
	virtual const XalanDOMString*
	getNamespaceForPrefix(const XalanDOMString&		prefix) const = 0;

	/**
	 * Retrieve the base URI for the resolver.
	 *
	 * @return URI string
	 */
	virtual const XalanDOMString&
	getURI() const = 0;
};

#endif	// PREFIXRESOLVER_HEADER_GUARD_1357924680
<|endoftext|>


<commit_before>//===========================================
//  PC-BSD source code
//  Copyright (c) 2016, PC-BSD Software/iXsystems
//  Available under the 3-clause BSD license
//  See the LICENSE file for full details
//===========================================
#include "page_taskmanager.h"
#include "ui_page_taskmanager.h" //auto-generated from the .ui file

taskmanager_page::taskmanager_page(QWidget *parent, sysadm_client *core) : PageWidget(parent, core), ui(new Ui::taskmanager_ui){
  ui->setupUi(this);
}

taskmanager_page::~taskmanager_page(){

}

//Initialize the CORE <-->Page connections
void taskmanager_page::setupCore(){
  connect(CORE, SIGNAL(newReply(QString, QString, QString, QJsonValue)), this, SLOT(ParseReply(QString, QString, QString, QJsonValue)) );
}

//Page embedded, go ahead and startup any core requests
void taskmanager_page::startPage(){
  //Let the main window know the name of this page
  emit ChangePageTitle( tr("Task Manager") );

  //Now run any CORE communications
  QJsonObject jsobj;
  jsobj.insert("action", "procinfo");
  CORE->communicate("taskquery", "sysadm", "systemmanager", jsobj);

  // Get PID info every 5 seconds
  proctimer = new QTimer(this);
  connect(proctimer, SIGNAL(timeout()), this, SLOT(slotRequestProcInfo()));
  proctimer->start(5000);

  qDebug() << "Start page!";
}

// === PRIVATE SLOTS ===
void taskmanager_page::ParseReply(QString id, QString namesp, QString name, QJsonValue args){

  qDebug() << "reply" << id;

  // Read in the PID list
  if ( id == "taskquery")
  {
    if ( ! args.isObject() )
      return;
    parsePIDS(args.toObject());
  }

}

void taskmanager_page::parsePIDS(QJsonObject jsobj)
{
  ui->taskWidget->clear();

  qDebug() << "KEYS" << jsobj.keys();
  QStringList keys = jsobj.keys();
  if (keys.contains("message") ) {
    qDebug() << "MESSAGE" << jsobj.value("message").toString();
    return;
  }

  // Look for procinfo
  QJsonObject procobj = jsobj.value("procinfo").toObject();
  QStringList pids = procobj.keys();
  for ( int i=0; i < pids.size(); i++ )
  {
    QString PID = pids.at(i);
    QJsonObject pidinfo = procobj.value(PID).toObject();
    // Create the new taskWidget item
    new QTreeWidgetItem(ui->taskWidget, QStringList() << PID
        << pidinfo.value("username").toString()
        << pidinfo.value("thr").toString()
        << pidinfo.value("pri").toString()
        << pidinfo.value("nice").toString()
        << pidinfo.value("size").toString()
        << pidinfo.value("res").toString()
        << pidinfo.value("state").toString()
        << pidinfo.value("cpu").toString()
        << pidinfo.value("time").toString()
        << pidinfo.value("wcpu").toString()
        << pidinfo.value("command").toString()
        );
  }

  // Resize the widget to the new contents
  ui->taskWidget->header()->resizeSections(QHeaderView::ResizeToContents);
  ui->taskWidget->sortItems(10, Qt::DescendingOrder);
}

void taskmanager_page::slotRequestProcInfo()
{
  QJsonObject jsobj;
  jsobj.insert("action", "procinfo");
  CORE->communicate("taskquery", "sysadm", "systemmanager", jsobj);
}
<commit_msg>Cleanup the task manager PID listing widget, now we update items in place and do it every 3 seconds, this means your item doesn't lose focus as it refreshes<commit_after>//===========================================
//  PC-BSD source code
//  Copyright (c) 2016, PC-BSD Software/iXsystems
//  Available under the 3-clause BSD license
//  See the LICENSE file for full details
//===========================================
#include "page_taskmanager.h"
#include "ui_page_taskmanager.h" //auto-generated from the .ui file

taskmanager_page::taskmanager_page(QWidget *parent, sysadm_client *core) : PageWidget(parent, core), ui(new Ui::taskmanager_ui){
  ui->setupUi(this);
}

taskmanager_page::~taskmanager_page(){

}

//Initialize the CORE <-->Page connections
void taskmanager_page::setupCore(){
  connect(CORE, SIGNAL(newReply(QString, QString, QString, QJsonValue)), this, SLOT(ParseReply(QString, QString, QString, QJsonValue)) );
}

//Page embedded, go ahead and startup any core requests
void taskmanager_page::startPage(){
  //Let the main window know the name of this page
  emit ChangePageTitle( tr("Task Manager") );

  //Now run any CORE communications
  QJsonObject jsobj;
  jsobj.insert("action", "procinfo");
  CORE->communicate("taskquery", "sysadm", "systemmanager", jsobj);

  // Get PID info every 3 seconds
  proctimer = new QTimer(this);
  connect(proctimer, SIGNAL(timeout()), this, SLOT(slotRequestProcInfo()));
  proctimer->start(3000);

  qDebug() << "Start page!";
}

// === PRIVATE SLOTS ===
void taskmanager_page::ParseReply(QString id, QString namesp, QString name, QJsonValue args){

 // qDebug() << "reply" << id;

  // Read in the PID list
  if ( id == "taskquery")
  {
    if ( ! args.isObject() )
      return;
    parsePIDS(args.toObject());
  }

}

void taskmanager_page::parsePIDS(QJsonObject jsobj)
{
  //ui->taskWidget->clear();

  //qDebug() << "KEYS" << jsobj.keys();
  QStringList keys = jsobj.keys();
  if (keys.contains("message") ) {
    qDebug() << "MESSAGE" << jsobj.value("message").toString();
    return;
  }

  // Look for procinfo
  QJsonObject procobj = jsobj.value("procinfo").toObject();
  QStringList pids = procobj.keys();
  for ( int i=0; i < pids.size(); i++ )
  {
    QString PID = pids.at(i);
    QJsonObject pidinfo = procobj.value(PID).toObject();

    // Check if we have this PID already
    QList<QTreeWidgetItem *> foundItems = ui->taskWidget->findItems(PID, Qt::MatchExactly, 0);
    if ( ! foundItems.isEmpty() )
    {
      foundItems.at(0)->setText(1, pidinfo.value("username").toString());
      foundItems.at(0)->setText(2, pidinfo.value("thr").toString());
      foundItems.at(0)->setText(3, pidinfo.value("pri").toString());
      foundItems.at(0)->setText(4, pidinfo.value("nice").toString());
      foundItems.at(0)->setText(5, pidinfo.value("size").toString());
      foundItems.at(0)->setText(6, pidinfo.value("res").toString());
      foundItems.at(0)->setText(7, pidinfo.value("state").toString());
      foundItems.at(0)->setText(8, pidinfo.value("cpu").toString());
      foundItems.at(0)->setText(9, pidinfo.value("time").toString());
      foundItems.at(0)->setText(10, pidinfo.value("wcpu").toString());
      foundItems.at(0)->setText(11, pidinfo.value("command").toString());
    } else {
      // Create the new taskWidget item
      new QTreeWidgetItem(ui->taskWidget, QStringList() << PID
          << pidinfo.value("username").toString()
          << pidinfo.value("thr").toString()
          << pidinfo.value("pri").toString()
          << pidinfo.value("nice").toString()
          << pidinfo.value("size").toString()
          << pidinfo.value("res").toString()
          << pidinfo.value("state").toString()
          << pidinfo.value("cpu").toString()
          << pidinfo.value("time").toString()
          << pidinfo.value("wcpu").toString()
          << pidinfo.value("command").toString()
          );
    }
  }

  // Now loop through the UI and look for pids to remove
  for ( int i=0; i<ui->taskWidget->topLevelItemCount(); i++ ) {
    // Check if this item exists in the PID list
    if ( ! pids.contains(ui->taskWidget->topLevelItem(i)->text(0)) ) {
      // No? Remove it
      ui->taskWidget->takeTopLevelItem(i);
    }
  }

  // Resize the widget to the new contents
  ui->taskWidget->header()->resizeSections(QHeaderView::ResizeToContents);
  ui->taskWidget->sortItems(10, Qt::DescendingOrder);
}

void taskmanager_page::slotRequestProcInfo()
{
  QJsonObject jsobj;
  jsobj.insert("action", "procinfo");
  CORE->communicate("taskquery", "sysadm", "systemmanager", jsobj);
}
<|endoftext|>


<commit_before>#include "ffmpeg_encoder.hpp"

#ifdef __cplusplus
extern "C" {
#endif

#include <libavutil/pixdesc.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>

#ifdef __cplusplus
}
#endif

#include <QDebug>

bool ffmpeg_encoder::isStaticInit = false;

ffmpeg_encoder::ffmpeg_encoder(int width, int height, bool splithorizontal, const QString &filename, const double fps) :
    m_width(width),
    m_height(height),
    m_splithorizontal(splithorizontal),
    m_filename(filename),
    m_framecount(0),
    m_codec(NULL),
    m_context(NULL),
    m_out_size(0),
    m_outbuf_size(1000000),
    m_file(NULL),
    m_picture(NULL),
    m_outbuf(NULL),
    m_picture_buf(NULL)
{
  staticInit();

  /* find the mpeg1 video encoder */
  m_codec = avcodec_find_encoder(CODEC_ID_MPEG2VIDEO);

  if (!m_codec) {
    fprintf(stderr, "codec not found\n");
    ::exit(1);
  }

  m_context = avcodec_alloc_context3(NULL);
#if WIN32
  m_picture = av_frame_alloc();
#else
  m_picture = avcodec_alloc_frame();
#endif

  /* put sample parameters */
  m_context->bit_rate = 100000000;

  /* resolution must be a multiple of two */
  m_context->width = m_width;
  m_context->height = m_height;
  /* frames per second */
  AVRational av;
  av.den = 25;
  av.num = 1;
  m_context->time_base= av;//(AVRational){1,25};
  m_context->gop_size = 10; /* emit one intra frame every ten frames */
  m_context->max_b_frames=0;
  //m_context->qmax = 51;
  //m_context->qmin = 1;

  //the default for mpeg1/2
  m_context->pix_fmt =  PIX_FMT_YUV420P;
  //m_context->pix_fmt =  PIX_FMT_YUV422P;

  char cbuf[12];

  //newer versions of libavcodec have a different API (avcodex_pix_fmt_string is deprecated)

#if (LIBAVCODEC_VERSION_MAJOR <= 52)
  avcodec_pix_fmt_string(cbuf,12, m_context->pix_fmt);
#else
  av_get_pix_fmt_string(cbuf,12, m_context->pix_fmt);
#endif

  printf("AVCODEC STRING %s\n", cbuf);
  if (m_context->pix_fmt < 0)
  {
    fprintf(stderr,"invalid pix format %d",m_context->pix_fmt);
  }

  /* open codec */
  if (avcodec_open2(m_context, m_codec,NULL) < 0) {
    fprintf(stderr, "could not open codec\n");
    ::exit(1);
  }

  /*open file*/
   m_file = fopen(m_filename.toLocal8Bit(), "wb");
  if (!m_file) {
    qDebug() << "could not open " << filename;
    ::exit(1);
  }

  /* alloc image and output buffer */
  m_outbuf = new uint8_t[m_outbuf_size];
  int size = m_context->width * m_context->height;
  m_picture_buf = new uint8_t[(size * 3) / 2]; /* size for YUV 420 */
  //m_picture_buf = new uint8_t[size * 2]; /* size for YUV 422 */

  m_picture->data[0] = m_picture_buf;
  m_picture->data[1] = m_picture->data[0] + size;
  m_picture->data[2] = m_picture->data[1] + size / 4; /* size for YUV 420 */
  //m_picture->data[2] = m_picture->data[1] + size / 2; /* size for YUV 422 */
  m_picture->linesize[0] = m_context->width;
  m_picture->linesize[1] = m_context->width / 2;
  m_picture->linesize[2] = m_context->width / 2;

  m_rgb_src[0] = m_rgb_src[1] = m_rgb_src[2] = NULL;
  m_rgb_stride[0] = -m_context->width*3;
  m_rgb_stride[1] = m_rgb_stride[2] = 0;

  m_sws = sws_getContext(m_context->width, m_context->height, PIX_FMT_RGB24,
                         m_context->width, m_context->height, m_context->pix_fmt,
                         SWS_POINT,
                         NULL, NULL, NULL);
  if (m_sws == NULL)
  {
    fprintf(stderr, "Failed to get %d ---> %d\n",
            PIX_FMT_RGB24,
            m_context->pix_fmt);

    ::exit(1);
  }
}

ffmpeg_encoder::~ffmpeg_encoder()
{

  /* get the delayed frames */
  for(; m_out_size; m_framecount++) {
    fflush(stdout);
    //AVPacket pkt;
    //av_init_packet(&pkt);
    //pkt.data = m_outbuf;
    //pkt.size = m_outbuf_size;
    //m_out_size = avcodec_encode_video2(m_context, m_outbuf);
    m_out_size = avcodec_encode_video(m_context, m_outbuf, m_outbuf_size, NULL);
    printf("write frame %3d (size=%5d)\n", m_framecount, m_out_size);
    size_t a = fwrite(m_outbuf, 1, m_out_size, m_file);
  }

 /* add sequence end code to have a real mpeg file */
  m_outbuf[0] = 0x00;
  m_outbuf[1] = 0x00;
  m_outbuf[2] = 0x01;
  m_outbuf[3] = 0xb7;
  size_t a = fwrite(m_outbuf, 1, 4, m_file);
  fclose(m_file);
  delete [] m_picture_buf;
  delete [] m_outbuf;

  avcodec_close(m_context);
  av_free(m_context);
  av_free(m_picture);
  sws_freeContext(m_sws);
}

void ffmpeg_encoder::addFrame(unsigned char* buffer)
{
  // set source pointer
  m_rgb_src[0] = buffer + m_context->width*m_context->height*3 - m_context->width*3;;

  // convert to target pixel format
  sws_scale(m_sws,
            m_rgb_src, m_rgb_stride, 0, m_context->height, // src stuff
            m_picture->data, m_picture->linesize);         // dst stuff

  //printf("%d \n", m_context->height);

  /* encode the image */
  m_out_size = avcodec_encode_video(m_context, m_outbuf, m_outbuf_size, m_picture);

  //printf("encoding frame %3d (size=%5d)\n", m_framecount, m_out_size);

  size_t a = fwrite(m_outbuf, 1, m_out_size, m_file);

  m_framecount++;
}

void ffmpeg_encoder::staticInit()
{
  if (!isStaticInit)
  {
    /*must be called before using avcodec lib */
    // deprecated avcodec_init();

    /* register all the codecs (you can also register only the codec you wish to have smaller code */
    avcodec_register_all();

    isStaticInit = true;
  }
}

<commit_msg>Remove unused variables.<commit_after>#include "ffmpeg_encoder.hpp"

#ifdef __cplusplus
extern "C" {
#endif

#include <libavutil/pixdesc.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>

#ifdef __cplusplus
}
#endif

#include <QDebug>

bool ffmpeg_encoder::isStaticInit = false;

ffmpeg_encoder::ffmpeg_encoder(int width, int height, bool splithorizontal, const QString &filename, const double fps) :
    m_width(width),
    m_height(height),
    m_splithorizontal(splithorizontal),
    m_filename(filename),
    m_framecount(0),
    m_codec(NULL),
    m_context(NULL),
    m_out_size(0),
    m_outbuf_size(1000000),
    m_file(NULL),
    m_picture(NULL),
    m_outbuf(NULL),
    m_picture_buf(NULL)
{
  staticInit();

  /* find the mpeg1 video encoder */
  m_codec = avcodec_find_encoder(CODEC_ID_MPEG2VIDEO);

  if (!m_codec) {
    fprintf(stderr, "codec not found\n");
    ::exit(1);
  }

  m_context = avcodec_alloc_context3(NULL);
#if WIN32
  m_picture = av_frame_alloc();
#else
  m_picture = avcodec_alloc_frame();
#endif

  /* put sample parameters */
  m_context->bit_rate = 100000000;

  /* resolution must be a multiple of two */
  m_context->width = m_width;
  m_context->height = m_height;
  /* frames per second */
  AVRational av;
  av.den = 25;
  av.num = 1;
  m_context->time_base= av;//(AVRational){1,25};
  m_context->gop_size = 10; /* emit one intra frame every ten frames */
  m_context->max_b_frames=0;
  //m_context->qmax = 51;
  //m_context->qmin = 1;

  //the default for mpeg1/2
  m_context->pix_fmt =  PIX_FMT_YUV420P;
  //m_context->pix_fmt =  PIX_FMT_YUV422P;

  char cbuf[12];

  //newer versions of libavcodec have a different API (avcodex_pix_fmt_string is deprecated)

#if (LIBAVCODEC_VERSION_MAJOR <= 52)
  avcodec_pix_fmt_string(cbuf,12, m_context->pix_fmt);
#else
  av_get_pix_fmt_string(cbuf,12, m_context->pix_fmt);
#endif

  printf("AVCODEC STRING %s\n", cbuf);
  if (m_context->pix_fmt < 0)
  {
    fprintf(stderr,"invalid pix format %d",m_context->pix_fmt);
  }

  /* open codec */
  if (avcodec_open2(m_context, m_codec,NULL) < 0) {
    fprintf(stderr, "could not open codec\n");
    ::exit(1);
  }

  /*open file*/
   m_file = fopen(m_filename.toLocal8Bit(), "wb");
  if (!m_file) {
    qDebug() << "could not open " << filename;
    ::exit(1);
  }

  /* alloc image and output buffer */
  m_outbuf = new uint8_t[m_outbuf_size];
  int size = m_context->width * m_context->height;
  m_picture_buf = new uint8_t[(size * 3) / 2]; /* size for YUV 420 */
  //m_picture_buf = new uint8_t[size * 2]; /* size for YUV 422 */

  m_picture->data[0] = m_picture_buf;
  m_picture->data[1] = m_picture->data[0] + size;
  m_picture->data[2] = m_picture->data[1] + size / 4; /* size for YUV 420 */
  //m_picture->data[2] = m_picture->data[1] + size / 2; /* size for YUV 422 */
  m_picture->linesize[0] = m_context->width;
  m_picture->linesize[1] = m_context->width / 2;
  m_picture->linesize[2] = m_context->width / 2;

  m_rgb_src[0] = m_rgb_src[1] = m_rgb_src[2] = NULL;
  m_rgb_stride[0] = -m_context->width*3;
  m_rgb_stride[1] = m_rgb_stride[2] = 0;

  m_sws = sws_getContext(m_context->width, m_context->height, PIX_FMT_RGB24,
                         m_context->width, m_context->height, m_context->pix_fmt,
                         SWS_POINT,
                         NULL, NULL, NULL);
  if (m_sws == NULL)
  {
    fprintf(stderr, "Failed to get %d ---> %d\n",
            PIX_FMT_RGB24,
            m_context->pix_fmt);

    ::exit(1);
  }
}

ffmpeg_encoder::~ffmpeg_encoder()
{

  /* get the delayed frames */
  for(; m_out_size; m_framecount++) {
    fflush(stdout);
    //AVPacket pkt;
    //av_init_packet(&pkt);
    //pkt.data = m_outbuf;
    //pkt.size = m_outbuf_size;
    //m_out_size = avcodec_encode_video2(m_context, m_outbuf);
    m_out_size = avcodec_encode_video(m_context, m_outbuf, m_outbuf_size, NULL);
    printf("write frame %3d (size=%5d)\n", m_framecount, m_out_size);
    fwrite(m_outbuf, 1, m_out_size, m_file);
  }

 /* add sequence end code to have a real mpeg file */
  m_outbuf[0] = 0x00;
  m_outbuf[1] = 0x00;
  m_outbuf[2] = 0x01;
  m_outbuf[3] = 0xb7;
  fwrite(m_outbuf, 1, 4, m_file);
  fclose(m_file);
  delete [] m_picture_buf;
  delete [] m_outbuf;

  avcodec_close(m_context);
  av_free(m_context);
  av_free(m_picture);
  sws_freeContext(m_sws);
}

void ffmpeg_encoder::addFrame(unsigned char* buffer)
{
  // set source pointer
  m_rgb_src[0] = buffer + m_context->width*m_context->height*3 - m_context->width*3;;

  // convert to target pixel format
  sws_scale(m_sws,
            m_rgb_src, m_rgb_stride, 0, m_context->height, // src stuff
            m_picture->data, m_picture->linesize);         // dst stuff

  //printf("%d \n", m_context->height);

  /* encode the image */
  m_out_size = avcodec_encode_video(m_context, m_outbuf, m_outbuf_size, m_picture);

  //printf("encoding frame %3d (size=%5d)\n", m_framecount, m_out_size);

  fwrite(m_outbuf, 1, m_out_size, m_file);

  m_framecount++;
}

void ffmpeg_encoder::staticInit()
{
  if (!isStaticInit)
  {
    /*must be called before using avcodec lib */
    // deprecated avcodec_init();

    /* register all the codecs (you can also register only the codec you wish to have smaller code */
    avcodec_register_all();

    isStaticInit = true;
  }
}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2004-2011  See the AUTHORS file for details.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation.
 */

#include "User.h"
#include <algorithm>

class CPerform : public CModule {
	void Add(const CString& sCommand) {
		CString sPerf = sCommand.Token(1, true);

		if (sPerf.empty()) {
			PutModule("Usage: add <command>");
			return;
		}

		m_vPerform.push_back(ParsePerform(sPerf));
		PutModule("Added!");
		Save();
	}

	void Del(const CString& sCommand) {
		u_int iNum = sCommand.Token(1, true).ToUInt();

		if (iNum > m_vPerform.size() || iNum <= 0) {
			PutModule("Illegal # Requested");
			return;
		} else {
			m_vPerform.erase(m_vPerform.begin() + iNum - 1);
			PutModule("Command Erased.");
		}
		Save();
	}

	void List(const CString& sCommand) {
		CTable Table;
		unsigned int index = 1;
		CString sExpanded;

		Table.AddColumn("Id");
		Table.AddColumn("Perform");
		Table.AddColumn("Expanded");

		for (VCString::const_iterator it = m_vPerform.begin(); it != m_vPerform.end(); it++, index++) {
			Table.AddRow();
			Table.SetCell("Id", CString(index));
			Table.SetCell("Perform", *it);

			sExpanded = GetUser()->ExpandString(*it);
			if (sExpanded != *it) {
				Table.SetCell("Expanded", sExpanded);
			}
		}

		if (PutModule(Table) == 0) {
			PutModule("No commands in your perform list.");
		}
	}

	void Execute(const CString& sCommand) {
		OnIRCConnected();
		PutModule("perform commands sent");
	}

	void Swap(const CString& sCommand) {
		u_int iNumA = sCommand.Token(1).ToUInt();
		u_int iNumB = sCommand.Token(2).ToUInt();

		if (iNumA > m_vPerform.size() || iNumA <= 0 || iNumB > m_vPerform.size() || iNumB <= 0) {
			PutModule("Illegal # Requested");
		} else {
			std::iter_swap(m_vPerform.begin() + (iNumA - 1), m_vPerform.begin() + (iNumB - 1));
			PutModule("Commands Swapped.");
			Save();
		}
	}

public:
	MODCONSTRUCTOR(CPerform) {
		AddHelpCommand();
		AddCommand("Add",     static_cast<CModCommand::ModCmdFunc>(&CPerform::Add),
			"<command>");
		AddCommand("Del",     static_cast<CModCommand::ModCmdFunc>(&CPerform::Del),
			"<nr>");
		AddCommand("List",    static_cast<CModCommand::ModCmdFunc>(&CPerform::List));
		AddCommand("Execute", static_cast<CModCommand::ModCmdFunc>(&CPerform::Execute));
		AddCommand("Swap",    static_cast<CModCommand::ModCmdFunc>(&CPerform::Swap),
			"<nr> <nr>");
	}

	virtual ~CPerform() {}

	CString ParsePerform(const CString& sArg) const {
		CString sPerf = sArg;

		if (sPerf.Left(1) == "/")
			sPerf.LeftChomp();

		if (sPerf.Token(0).Equals("MSG")) {
			sPerf = "PRIVMSG " + sPerf.Token(1, true);
		}

		if ((sPerf.Token(0).Equals("PRIVMSG") ||
				sPerf.Token(0).Equals("NOTICE")) &&
				sPerf.Token(2).Left(1) != ":") {
			sPerf = sPerf.Token(0) + " " + sPerf.Token(1)
				+ " :" + sPerf.Token(2, true);
		}

		return sPerf;
	}

	virtual bool OnLoad(const CString& sArgs, CString& sMessage) {
		GetNV("Perform").Split("\n", m_vPerform, false);

		return true;
	}

	virtual void OnIRCConnected() {
		for (VCString::const_iterator it = m_vPerform.begin(); it != m_vPerform.end(); ++it) {
			PutIRC(GetUser()->ExpandString(*it));
		}
	}

	virtual CString GetWebMenuTitle() { return "Perform"; }

	virtual bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) {
		if (sPageName != "index") {
			// only accept requests to /mods/perform/
			return false;
		}

		if (WebSock.IsPost()) {
			VCString vsPerf;
			WebSock.GetRawParam("perform", true).Split("\n", vsPerf, false);
			m_vPerform.clear();

			for (VCString::const_iterator it = vsPerf.begin(); it != vsPerf.end(); ++it)
				m_vPerform.push_back(ParsePerform(*it));

			Save();
		}

		for (VCString::const_iterator it = m_vPerform.begin(); it != m_vPerform.end(); ++it) {
			CTemplate& Row = Tmpl.AddRow("PerformLoop");
			Row["Perform"] = *it;
		}

		return true;
	}

private:
	void Save() {
		CString sBuffer = "";

		for (VCString::const_iterator it = m_vPerform.begin(); it != m_vPerform.end(); ++it) {
			sBuffer += *it + "\n";
		}
		SetNV("Perform", sBuffer);
	}

	VCString m_vPerform;
};

MODULEDEFS(CPerform, "Keeps a list of commands to be executed when ZNC connects to IRC.")
<commit_msg>Remove some evil trailing whitespaces<commit_after>/*
 * Copyright (C) 2004-2011  See the AUTHORS file for details.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation.
 */

#include "User.h"
#include <algorithm>

class CPerform : public CModule {
	void Add(const CString& sCommand) {
		CString sPerf = sCommand.Token(1, true);

		if (sPerf.empty()) {
			PutModule("Usage: add <command>");
			return;
		}

		m_vPerform.push_back(ParsePerform(sPerf));
		PutModule("Added!");
		Save();
	}

	void Del(const CString& sCommand) {
		u_int iNum = sCommand.Token(1, true).ToUInt();

		if (iNum > m_vPerform.size() || iNum <= 0) {
			PutModule("Illegal # Requested");
			return;
		} else {
			m_vPerform.erase(m_vPerform.begin() + iNum - 1);
			PutModule("Command Erased.");
		}
		Save();
	}

	void List(const CString& sCommand) {
		CTable Table;
		unsigned int index = 1;
		CString sExpanded;

		Table.AddColumn("Id");
		Table.AddColumn("Perform");
		Table.AddColumn("Expanded");

		for (VCString::const_iterator it = m_vPerform.begin(); it != m_vPerform.end(); it++, index++) {
			Table.AddRow();
			Table.SetCell("Id", CString(index));
			Table.SetCell("Perform", *it);

			sExpanded = GetUser()->ExpandString(*it);
			if (sExpanded != *it) {
				Table.SetCell("Expanded", sExpanded);
			}
		}

		if (PutModule(Table) == 0) {
			PutModule("No commands in your perform list.");
		}
	}

	void Execute(const CString& sCommand) {
		OnIRCConnected();
		PutModule("perform commands sent");
	}

	void Swap(const CString& sCommand) {
		u_int iNumA = sCommand.Token(1).ToUInt();
		u_int iNumB = sCommand.Token(2).ToUInt();

		if (iNumA > m_vPerform.size() || iNumA <= 0 || iNumB > m_vPerform.size() || iNumB <= 0) {
			PutModule("Illegal # Requested");
		} else {
			std::iter_swap(m_vPerform.begin() + (iNumA - 1), m_vPerform.begin() + (iNumB - 1));
			PutModule("Commands Swapped.");
			Save();
		}
	}

public:
	MODCONSTRUCTOR(CPerform) {
		AddHelpCommand();
		AddCommand("Add",     static_cast<CModCommand::ModCmdFunc>(&CPerform::Add),
			"<command>");
		AddCommand("Del",     static_cast<CModCommand::ModCmdFunc>(&CPerform::Del),
			"<nr>");
		AddCommand("List",    static_cast<CModCommand::ModCmdFunc>(&CPerform::List));
		AddCommand("Execute", static_cast<CModCommand::ModCmdFunc>(&CPerform::Execute));
		AddCommand("Swap",    static_cast<CModCommand::ModCmdFunc>(&CPerform::Swap),
			"<nr> <nr>");
	}

	virtual ~CPerform() {}

	CString ParsePerform(const CString& sArg) const {
		CString sPerf = sArg;

		if (sPerf.Left(1) == "/")
			sPerf.LeftChomp();

		if (sPerf.Token(0).Equals("MSG")) {
			sPerf = "PRIVMSG " + sPerf.Token(1, true);
		}

		if ((sPerf.Token(0).Equals("PRIVMSG") ||
				sPerf.Token(0).Equals("NOTICE")) &&
				sPerf.Token(2).Left(1) != ":") {
			sPerf = sPerf.Token(0) + " " + sPerf.Token(1)
				+ " :" + sPerf.Token(2, true);
		}

		return sPerf;
	}

	virtual bool OnLoad(const CString& sArgs, CString& sMessage) {
		GetNV("Perform").Split("\n", m_vPerform, false);

		return true;
	}

	virtual void OnIRCConnected() {
		for (VCString::const_iterator it = m_vPerform.begin(); it != m_vPerform.end(); ++it) {
			PutIRC(GetUser()->ExpandString(*it));
		}
	}

	virtual CString GetWebMenuTitle() { return "Perform"; }

	virtual bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) {
		if (sPageName != "index") {
			// only accept requests to /mods/perform/
			return false;
		}

		if (WebSock.IsPost()) {
			VCString vsPerf;
			WebSock.GetRawParam("perform", true).Split("\n", vsPerf, false);
			m_vPerform.clear();

			for (VCString::const_iterator it = vsPerf.begin(); it != vsPerf.end(); ++it)
				m_vPerform.push_back(ParsePerform(*it));

			Save();
		}

		for (VCString::const_iterator it = m_vPerform.begin(); it != m_vPerform.end(); ++it) {
			CTemplate& Row = Tmpl.AddRow("PerformLoop");
			Row["Perform"] = *it;
		}

		return true;
	}

private:
	void Save() {
		CString sBuffer = "";

		for (VCString::const_iterator it = m_vPerform.begin(); it != m_vPerform.end(); ++it) {
			sBuffer += *it + "\n";
		}
		SetNV("Perform", sBuffer);
	}

	VCString m_vPerform;
};

MODULEDEFS(CPerform, "Keeps a list of commands to be executed when ZNC connects to IRC.")
<|endoftext|>


<commit_before>// DegRateNuclideTests.cpp
#include <vector>
#include <gtest/gtest.h>

#include "DegRateNuclide.h"
#include "CycException.h"
#include "Material.h"
#include "Timer.h"

using namespace std;

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class DegRateNuclideTest : public ::testing::Test {
  protected:
    DegRateNuclide* test_deg_rate_nuclide_;
    double test_rate_;
    CompMapPtr test_comp_;
    mat_rsrc_ptr test_mat_;
    int one_mol_;
    int u235_, am241_;
    double test_size_;
    int time_;

    virtual void SetUp(){
      // test_deg_rate_nuclide model setup
      test_deg_rate_nuclide_ = new DegRateNuclide();
      test_rate_ = 0.1;

      // composition set up
      u235_=92235;
      one_mol_=1.0;
      test_comp_= CompMapPtr(new CompMap(MASS));
      (*test_comp_)[u235_] = one_mol_;
      test_size_=10.0;

      // material creation
      test_mat_ = mat_rsrc_ptr(new Material(test_comp_));
      test_mat_->setQuantity(test_size_);
      int time_ = TI->time();
    }
    virtual void TearDown() {
      delete test_deg_rate_nuclide_;
    }
};

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, defaultConstructor) {
  ASSERT_EQ("DEGRATE_NUCLIDE", test_deg_rate_nuclide_->name());
  ASSERT_EQ(DEGRATE_NUCLIDE, test_deg_rate_nuclide_->type());
  ASSERT_FLOAT_EQ(0,test_deg_rate_nuclide_->deg_rate());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, initFunctionNoXML) {
  EXPECT_NO_THROW(test_deg_rate_nuclide_->init(test_rate_));
  ASSERT_EQ(test_rate_, test_deg_rate_nuclide_->deg_rate());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, copy) {
  EXPECT_NO_THROW(test_deg_rate_nuclide_->init(test_rate_));
  DegRateNuclide* test_copy = new DegRateNuclide();
  EXPECT_NO_THROW(test_copy->copy(test_deg_rate_nuclide_));
  EXPECT_FLOAT_EQ(test_rate_, test_copy->deg_rate());
  delete test_copy;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, absorb){
  // if you absorb a material, the conc_map should reflect that
  // you shouldn't absorb more material than you can handle. how much is that?
  EXPECT_NO_THROW(test_deg_rate_nuclide_->absorb(test_mat_));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, extract){
  // if you extract a meterial, the conc_map should reflect that
  // you shouldn't extrac more material than you have how much is that?
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, transportNuclidesDR0){
  // if the degradation rate is zero, nothing should be released
  test_rate_=0;
  EXPECT_NO_THROW(test_deg_rate_nuclide->transportNuclides());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, transportNuclidesDRhalf){
  // if the degradation rate is .5, everything should be released in two years
  // nothing more
  // check that timestep 3 doesn't crash
  // check that it doesn't keep sending material it doesn't have
  EXPECT_NO_THROW(test_deg_rate_nuclide->transportNuclides());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, transportNuclidesDR1){
  // if the degradation rate is one, everything should be released in a year
  // nothing more
  // check that timestep 2 doesn't crash
  // check that it doesn't keep sending material it doesn't have
  EXPECT_NO_THROW(test_deg_rate_nuclide->transportNuclides());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, transportNuclidesDRsmall){
  // if the degradation rate is very very small, see if the model behaves well
  // in the long term.
}

<commit_msg>fixing tests, toward #4<commit_after>// DegRateNuclideTests.cpp
#include <vector>
#include <gtest/gtest.h>

#include "DegRateNuclide.h"
#include "CycException.h"
#include "Material.h"
#include "Timer.h"

using namespace std;

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class DegRateNuclideTest : public ::testing::Test {
  protected:
    DegRateNuclide* test_deg_rate_nuclide_;
    double test_rate_;
    CompMapPtr test_comp_;
    mat_rsrc_ptr test_mat_;
    int one_mol_;
    int u235_, am241_;
    double test_size_;
    int time_;

    virtual void SetUp(){
      // test_deg_rate_nuclide model setup
      test_deg_rate_nuclide_ = new DegRateNuclide();
      test_rate_ = 0.1;

      // composition set up
      u235_=92235;
      one_mol_=1.0;
      test_comp_= CompMapPtr(new CompMap(MASS));
      (*test_comp_)[u235_] = one_mol_;
      test_size_=10.0;

      // material creation
      test_mat_ = mat_rsrc_ptr(new Material(test_comp_));
      test_mat_->setQuantity(test_size_);
      int time_ = TI->time();
    }
    virtual void TearDown() {
      delete test_deg_rate_nuclide_;
    }
};

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, defaultConstructor) {
  ASSERT_EQ("DEGRATE_NUCLIDE", test_deg_rate_nuclide_->name());
  ASSERT_EQ(DEGRATE_NUCLIDE, test_deg_rate_nuclide_->type());
  ASSERT_FLOAT_EQ(0,test_deg_rate_nuclide_->deg_rate());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, initFunctionNoXML) {
  EXPECT_NO_THROW(test_deg_rate_nuclide_->init(test_rate_));
  ASSERT_EQ(test_rate_, test_deg_rate_nuclide_->deg_rate());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, copy) {
  EXPECT_NO_THROW(test_deg_rate_nuclide_->init(test_rate_));
  DegRateNuclide* test_copy = new DegRateNuclide();
  EXPECT_NO_THROW(test_copy->copy(test_deg_rate_nuclide_));
  EXPECT_FLOAT_EQ(test_rate_, test_copy->deg_rate());
  delete test_copy;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, absorb){
  // if you absorb a material, the conc_map should reflect that
  // you shouldn't absorb more material than you can handle. how much is that?
  EXPECT_NO_THROW(test_deg_rate_nuclide_->absorb(test_mat_));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, extract){
  // if you extract a meterial, the conc_map should reflect that
  // you shouldn't extrac more material than you have how much is that?
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, transportNuclidesDR0){
  // if the degradation rate is zero, nothing should be released
  test_rate_=0;
  EXPECT_NO_THROW(test_deg_rate_nuclide->transportNuclides());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, transportNuclidesDRhalf){
  // if the degradation rate is .5, everything should be released in two years
  // nothing more
  // check that timestep 3 doesn't crash
  // check that it doesn't keep sending material it doesn't have
  EXPECT_NO_THROW(test_deg_rate_nuclide->transportNuclides());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, transportNuclidesDR1){
  // if the degradation rate is one, everything should be released in a year
  // nothing more
  // check that timestep 2 doesn't crash
  // check that it doesn't keep sending material it doesn't have
  EXPECT_NO_THROW(test_deg_rate_nuclide->transportNuclides());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, transportNuclidesDRsmall){
  // if the degradation rate is very very small, see if the model behaves well
  // in the long term.
}

<|endoftext|>


<commit_before>/**
 * @file loglik.cc
 *
 * This file contains the program to compute log-likelihood of sequences
 * according to a Hidden Markov  Model.
 *
 * Usage:
 *   loglik --type=TYPE --profile=PROFILE [OPTIONS]
 * See the usage() function for complete option list
 */

#include "fastlib/fastlib.h"
#include "support.h"
#include "discreteHMM.h"
#include "gaussianHMM.h"
#include "mixgaussHMM.h"
#include "mixtureDST.h"

using namespace hmm_support;

success_t loglik_discrete();
success_t loglik_gaussian();
success_t loglik_mixture();
void usage();

const fx_entry_doc hmm_loglik_main_entries[] = {
  {"type", FX_REQUIRED, FX_STR, NULL,
   "  HMM type : discrete | gaussian | mixture.\n"},
  {"profile", FX_REQUIRED, FX_STR, NULL,
   "  A file containing HMM profile.\n"},
  {"seqfile", FX_PARAM, FX_STR, NULL,
   "  Output file for the data sequences.\n"},
  {"logfile", FX_PARAM, FX_STR, NULL,
   "  Output file for the computed log-likelihood of the sequences.\n"},
  FX_ENTRY_DOC_DONE
};

const fx_submodule_doc hmm_loglik_main_submodules[] = {
  FX_SUBMODULE_DOC_DONE
};

const fx_module_doc hmm_loglik_main_doc = {
  hmm_loglik_main_entries, hmm_loglik_main_submodules,
  "This is a program computing log-likelihood of data sequences \n"
  "from HMM models.\n"
};

int main(int argc, char* argv[]) {
  fx_init(argc, argv, &hmm_loglik_main_doc);
  success_t s = SUCCESS_PASS;
  if (fx_param_exists(NULL,"type")) {
    const char* type = fx_param_str_req(NULL, "type");
    if (strcmp(type, "discrete")==0)
      s = loglik_discrete();
    else if (strcmp(type, "gaussian")==0)
      s = loglik_gaussian();
    else if (strcmp(type, "mixture")==0)
      s = loglik_mixture();
    else {
      printf("Unrecognized type: must be: discrete | gaussian | mixture !!!\n");
      s = SUCCESS_FAIL;
    }
  }
  else {
    printf("Unrecognized type: must be: discrete | gaussian | mixture  !!!\n");
    s = SUCCESS_FAIL;
  }
  if (!PASSED(s)) usage();
  fx_done(NULL);
}

void usage() {
  printf("\n"
	 "Usage:\n"
	 "  loglik --type=={discrete|gaussian|mixture} OPTIONS\n"
	 "[OPTIONS]\n"
	 "  --profile==file   : file contains HMM profile\n"
	 "  --seqfile==file   : file contains input sequences\n"
	 "  --logfile==file   : output file for log-likelihood of the sequences\n"
	 );
}

success_t loglik_mixture() {
  if (!fx_param_exists(NULL, "profile")) {
    printf("--profile must be defined.\n");
    return SUCCESS_FAIL;
  }
  const char* profile = fx_param_str_req(NULL, "profile");
  const char* seqin = fx_param_str(NULL, "seqfile", "seq.mix.out");
  const char* logout = fx_param_str(NULL, "logfile", "log.mix.out");

  MixtureofGaussianHMM hmm;
  hmm.InitFromFile(profile);

  ArrayList<Matrix> seqs;
  load_matrix_list(seqin, &seqs);

  TextWriter w_log;
  if (!PASSED(w_log.Open(logout))) {
    NONFATAL("Couldn't open '%s' for writing.", logout);
    return SUCCESS_FAIL;
  }

  ArrayList<double> list_loglik;
  hmm.ComputeLogLikelihood(seqs, &list_loglik);

  for (int i = 0; i < seqs.size(); i++)
    w_log.Printf("%f\n", list_loglik[i]);

  return SUCCESS_PASS;
}

success_t loglik_gaussian() {
  if (!fx_param_exists(NULL, "profile")) {
    printf("--profile must be defined.\n");
    return SUCCESS_FAIL;
  }
  const char* profile = fx_param_str_req(NULL, "profile");
  const char* seqin = fx_param_str(NULL, "seqfile", "seq.gauss.out");
  const char* logout = fx_param_str(NULL, "logfile", "log.gauss.out");

  GaussianHMM hmm;
  hmm.InitFromFile(profile);

  ArrayList<Matrix> seqs;
  load_matrix_list(seqin, &seqs);

  TextWriter w_log;
  if (!PASSED(w_log.Open(logout))) {
    NONFATAL("Couldn't open '%s' for writing.", logout);
    return SUCCESS_FAIL;
  }

  ArrayList<double> list_loglik;
  hmm.ComputeLogLikelihood(seqs, &list_loglik);

  for (int i = 0; i < seqs.size(); i++)
    w_log.Printf("%f\n", list_loglik[i]);

  return SUCCESS_PASS;
}

success_t loglik_discrete() {
  if (!fx_param_exists(NULL, "profile")) {
    printf("--profile must be defined.\n");
    return SUCCESS_FAIL;
  }
  const char* profile = fx_param_str_req(NULL, "profile");
  const char* seqin = fx_param_str(NULL, "seqfile", "seq.out");
  const char* logout = fx_param_str(NULL, "logfile", "log.out");

  DiscreteHMM hmm;
  hmm.InitFromFile(profile);

  ArrayList<Vector> seqs;
  load_vector_list(seqin, &seqs);

  TextWriter w_log;
  if (!PASSED(w_log.Open(logout))) {
    NONFATAL("Couldn't open '%s' for writing.", logout);
    return SUCCESS_FAIL;
  }

  ArrayList<double> list_loglik;
  hmm.ComputeLogLikelihood(seqs, &list_loglik);

  for (int i = 0; i < seqs.size(); i++)
    w_log.Printf("%f\n", list_loglik[i]);
  return SUCCESS_PASS;
}

<commit_msg>Documented hmm_loglik utility thoroughly<commit_after>/**
 * @file loglik.cc
 *
 * This file contains the program to compute log-likelihood of sequences
 * according to a Hidden Markov  Model.
 */

#include <fastlib/fastlib.h>
#include "support.h"
#include "discreteHMM.h"
#include "gaussianHMM.h"
#include "mixgaussHMM.h"
#include "mixtureDST.h"
#include "hmm_documentation.h"

using namespace hmm_support;

success_t loglik_discrete();
success_t loglik_gaussian();
success_t loglik_mixture();
void usage();

const fx_entry_doc hmm_loglik_main_entries[] = {
  {"input_model", FX_REQUIRED, FX_STR, NULL,
   "Input file containing the trained HMM profile.\n"},
  {"input_sequence_file", FX_REQUIRED, FX_STR, NULL,
   "Input file of data sequences whose log-likelihood is to be evaluated.\n"},
  {"output_file", FX_PARAM, FX_STR, NULL,
   "Output file for the computed log-likelihood of each input sequence.\n"
   "     (default output.<type>.lik)\n"},
  {"type", FX_REQUIRED, FX_STR, NULL,
   "HMM type: discrete | gaussian | mixture\n"},
  FX_ENTRY_DOC_DONE
};

const fx_submodule_doc hmm_loglik_main_submodules[] = {
  {"formats", &hmm_format_doc,
   "Documentation for file formats used by this program and other MLPACK HMM tools\n"},
  FX_SUBMODULE_DOC_DONE
};

const fx_module_doc hmm_loglik_main_doc = {
  hmm_loglik_main_entries, hmm_loglik_main_submodules,
  "The hmm_loglik utility calculates the log-likelihood of a set of given\n"
  "observation sequences given a trained HMM profile.  It stores the output of each\n"
  "calculation in the given output file, where line N in that file corresponds\n"
  "to the Nth input sequence.\n"
  "\n"
  "For more information on the file formats used by the MLPACK HMM utilities, see\n"
  "the documentation in the 'formats' submodule (--help=formats).\n"
};

int main(int argc, char* argv[]) {
  fx_init(argc, argv, &hmm_loglik_main_doc);
  success_t s = SUCCESS_PASS;
  if (fx_param_exists(NULL,"type")) {
    const char* type = fx_param_str_req(NULL, "type");
    if (strcmp(type, "discrete")==0)
      s = loglik_discrete();
    else if (strcmp(type, "gaussian")==0)
      s = loglik_gaussian();
    else if (strcmp(type, "mixture")==0)
      s = loglik_mixture();
    else {
      FATAL("Unrecognized HMM type; must be 'discrete', 'gaussian', or 'mixture'.\n");
      s = SUCCESS_FAIL;
    }
  }
  else {
    FATAL("Unrecognized HMM type; must be 'discrete', 'gaussian', or 'mixture'.\n");
    s = SUCCESS_FAIL;
  }

  fx_done(NULL);
}

success_t loglik_mixture() {
  const char* profile = fx_param_str_req(NULL, "input_model");
  const char* seqin = fx_param_str_req(NULL, "input_sequence_file");
  const char* logout = fx_param_str(NULL, "output_file", "output.mix.lik");

  MixtureofGaussianHMM hmm;
  hmm.InitFromFile(profile);

  ArrayList<Matrix> seqs;
  load_matrix_list(seqin, &seqs);

  TextWriter w_log;
  if (!PASSED(w_log.Open(logout))) {
    NONFATAL("Couldn't open '%s' for writing.", logout);
    return SUCCESS_FAIL;
  }

  ArrayList<double> list_loglik;
  hmm.ComputeLogLikelihood(seqs, &list_loglik);

  for (int i = 0; i < seqs.size(); i++)
    w_log.Printf("%f\n", list_loglik[i]);

  return SUCCESS_PASS;
}

success_t loglik_gaussian() {
  const char* profile = fx_param_str_req(NULL, "input_model");
  const char* seqin = fx_param_str_req(NULL, "input_sequence_file");
  const char* logout = fx_param_str(NULL, "output_file", "output.gauss.lik");

  GaussianHMM hmm;
  hmm.InitFromFile(profile);

  ArrayList<Matrix> seqs;
  load_matrix_list(seqin, &seqs);

  TextWriter w_log;
  if (!PASSED(w_log.Open(logout))) {
    NONFATAL("Couldn't open '%s' for writing.", logout);
    return SUCCESS_FAIL;
  }

  ArrayList<double> list_loglik;
  hmm.ComputeLogLikelihood(seqs, &list_loglik);

  for (int i = 0; i < seqs.size(); i++)
    w_log.Printf("%f\n", list_loglik[i]);

  return SUCCESS_PASS;
}

success_t loglik_discrete() {
  const char* profile = fx_param_str_req(NULL, "input_model");
  const char* seqin = fx_param_str_req(NULL, "input_sequence_file");
  const char* logout = fx_param_str(NULL, "output_file", "output.dis.lik");

  DiscreteHMM hmm;
  hmm.InitFromFile(profile);

  ArrayList<Vector> seqs;
  load_vector_list(seqin, &seqs);

  TextWriter w_log;
  if (!PASSED(w_log.Open(logout))) {
    NONFATAL("Couldn't open '%s' for writing.", logout);
    return SUCCESS_FAIL;
  }

  ArrayList<double> list_loglik;
  hmm.ComputeLogLikelihood(seqs, &list_loglik);

  for (int i = 0; i < seqs.size(); i++)
    w_log.Printf("%f\n", list_loglik[i]);
  return SUCCESS_PASS;
}

<|endoftext|>


<commit_before>// DegRateNuclideTests.cpp
#include <vector>
#include <gtest/gtest.h>

#include "DegRateNuclide.h"
#include "CycException.h"
#include "Material.h"
#include "Timer.h"

using namespace std;

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class DegRateNuclideTest : public ::testing::Test {
  protected:
    DegRateNuclide* test_deg_rate_nuclide_;
    double test_rate_;
    CompMapPtr test_comp_;
    mat_rsrc_ptr test_mat_;
    int one_mol_;
    int u235_, am241_;
    double test_size_;
    int time_;

    virtual void SetUp(){
      // test_deg_rate_nuclide model setup
      test_deg_rate_nuclide_ = new DegRateNuclide();
      test_rate_ = 0.1;

      // composition set up
      u235_=92235;
      one_mol_=1.0;
      test_comp_= CompMapPtr(new CompMap(MASS));
      (*test_comp_)[u235_] = one_mol_;
      test_size_=10.0;

      // material creation
      test_mat_ = mat_rsrc_ptr(new Material(test_comp_));
      test_mat_->setQuantity(test_size_);
      int time_ = TI->time();
    }
    virtual void TearDown() {
      delete test_deg_rate_nuclide_;
    }
};

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, defaultConstructor) {
  ASSERT_EQ("DEGRATE_NUCLIDE", test_deg_rate_nuclide_->name());
  ASSERT_EQ(DEGRATE_NUCLIDE, test_deg_rate_nuclide_->type());
  ASSERT_FLOAT_EQ(0,test_deg_rate_nuclide_->deg_rate());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, initFunctionNoXML) {
  EXPECT_NO_THROW(test_deg_rate_nuclide_->init(test_rate_));
  ASSERT_EQ(test_rate_, test_deg_rate_nuclide_->deg_rate());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, copy) {
  EXPECT_NO_THROW(test_deg_rate_nuclide_->init(test_rate_));
  DegRateNuclide* test_copy = new DegRateNuclide();
  EXPECT_NO_THROW(test_copy->copy(test_deg_rate_nuclide_));
  EXPECT_FLOAT_EQ(test_rate_, test_copy->deg_rate());
  delete test_copy;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, absorb){
  // if you absorb a material, the conc_map should reflect that
  // you shouldn't absorb more material than you can handle. how much is that?
  EXPECT_NO_THROW(test_deg_rate_nuclide_->absorb(test_mat_));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, extract){
  // if you extract a meterial, the conc_map should reflect that
  // you shouldn't extrac more material than you have how much is that?
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, transportNuclidesDR0){
  // if the degradation rate is zero, nothing should be released
  test_rate_=0;
  EXPECT_NO_THROW(test_deg_rate_nuclide_->transportNuclides());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, transportNuclidesDRhalf){
  // if the degradation rate is .5, everything should be released in two years
  // nothing more
  // check that timestep 3 doesn't crash
  // check that it doesn't keep sending material it doesn't have
  EXPECT_NO_THROW(test_deg_rate_nuclide_->transportNuclides());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, transportNuclidesDR1){
  // if the degradation rate is one, everything should be released in a year
  // nothing more
  // check that timestep 2 doesn't crash
  // check that it doesn't keep sending material it doesn't have
  EXPECT_NO_THROW(test_deg_rate_nuclide_->transportNuclides());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, transportNuclidesDRsmall){
  // if the degradation rate is very very small, see if the model behaves well
  // in the long term.
}

<commit_msg>test_deg_rate_nuclide_ => deg_rate_model_<commit_after>// DegRateNuclideTests.cpp
#include <vector>
#include <gtest/gtest.h>

#include "DegRateNuclide.h"
#include "CycException.h"
#include "Material.h"
#include "Timer.h"

using namespace std;

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class DegRateNuclideTest : public ::testing::Test {
  protected:
    DegRateNuclide* deg_rate_model_;
    double deg_rate_;
    CompMapPtr test_comp_;
    mat_rsrc_ptr test_mat_;
    int one_mol_;
    int u235_, am241_;
    double test_size_;
    int time_;

    virtual void SetUp(){
      // test_deg_rate_nuclide model setup
      deg_rate_model_ = new DegRateNuclide();
      deg_rate_ = 0.1;

      // composition set up
      u235_=92235;
      one_mol_=1.0;
      test_comp_= CompMapPtr(new CompMap(MASS));
      (*test_comp_)[u235_] = one_mol_;
      test_size_=10.0;

      // material creation
      test_mat_ = mat_rsrc_ptr(new Material(test_comp_));
      test_mat_->setQuantity(test_size_);
      int time_ = TI->time();
    }
    virtual void TearDown() {
      delete deg_rate_model_;
    }
};

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, defaultConstructor) {
  ASSERT_EQ("DEGRATE_NUCLIDE", deg_rate_model_->name());
  ASSERT_EQ(DEGRATE_NUCLIDE, deg_rate_model_->type());
  ASSERT_FLOAT_EQ(0,deg_rate_model_->deg_rate());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, initFunctionNoXML) {
  EXPECT_NO_THROW(deg_rate_model_->init(deg_rate_));
  ASSERT_EQ(deg_rate_, deg_rate_model_->deg_rate());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, copy) {
  EXPECT_NO_THROW(deg_rate_model_->init(deg_rate_));
  DegRateNuclide* test_copy = new DegRateNuclide();
  EXPECT_NO_THROW(test_copy->copy(deg_rate_model_));
  EXPECT_FLOAT_EQ(deg_rate_, test_copy->deg_rate());
  delete test_copy;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, absorb){
  // if you absorb a material, the conc_map should reflect that
  // you shouldn't absorb more material than you can handle. how much is that?
  EXPECT_NO_THROW(deg_rate_model_->absorb(test_mat_));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, extract){
  // if you extract a meterial, the conc_map should reflect that
  // you shouldn't extrac more material than you have how much is that?
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, transportNuclidesDR0){
  // if the degradation rate is zero, nothing should be released
  deg_rate_=0;
  EXPECT_NO_THROW(deg_rate_model_->transportNuclides());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, transportNuclidesDRhalf){
  // if the degradation rate is .5, everything should be released in two years
  // nothing more
  // check that timestep 3 doesn't crash
  // check that it doesn't keep sending material it doesn't have
  EXPECT_NO_THROW(deg_rate_model_->transportNuclides());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, transportNuclidesDR1){
  // if the degradation rate is one, everything should be released in a year
  // nothing more
  // check that timestep 2 doesn't crash
  // check that it doesn't keep sending material it doesn't have
  EXPECT_NO_THROW(deg_rate_model_->transportNuclides());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(DegRateNuclideTest, transportNuclidesDRsmall){
  // if the degradation rate is very very small, see if the model behaves well
  // in the long term.
}

<|endoftext|>


<commit_before>// This file is part of the AliceVision project.
// Copyright (c) 2016 AliceVision contributors.
// Copyright (c) 2012 openMVG contributors.
// This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

#include "Datasheet.hpp"

#include <boost/algorithm/string.hpp>

#include <iterator>
#include <algorithm>
#include <vector>

namespace aliceVision {
namespace sensorDB {

bool Datasheet::operator==(const Datasheet& ds) const
{
  bool isEqual = false;
  std::vector<std::string> vec_brand;
  boost::split(vec_brand, ds._brand, boost::is_any_of(" "));

  std::string brandlower = _brand;
  boost::algorithm::to_lower(brandlower);

  for(const auto& brand : vec_brand)
  {
    std::string brandlower2 = brand;
    boost::algorithm::to_lower(brandlower2);

    //ALICEVISION_LOG_DEBUG(brandlower << "\t" << brandlower2);
    if (brandlower == brandlower2)
    {
      std::vector<std::string> vec_model1;
      boost::split(vec_model1, ds._model, boost::is_any_of(" "));
      std::vector<std::string> vec_model2;
      boost::split(vec_model2, _model, boost::is_any_of(" "));
      bool isAllFound = true;

      for(const auto& model1 : vec_model1)
      {
        const bool hasDigit = std::any_of(model1.begin(), model1.end(), ::isdigit);;

        if ( hasDigit )
        {
          std::string modellower1 = model1;
          boost::algorithm::to_lower(modellower1);

          bool isFound = false;
          for(const auto& model2 : vec_model2)
          {
            std::string modellower2 = model2;
            boost::algorithm::to_lower(modellower2);

            if (modellower2 == modellower1)
            {
              isFound = true;
            }
          }
          if ( !isFound )
          {
            isAllFound = false;
            break;
          }
        }
      }
      if ( isAllFound )
        isEqual = true;
    }
  }
  return isEqual;
}

} // namespace sensorDB
} // namespace aliceVision
<commit_msg>[sensor] simpler code<commit_after>// This file is part of the AliceVision project.
// Copyright (c) 2016 AliceVision contributors.
// Copyright (c) 2012 openMVG contributors.
// This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

#include "Datasheet.hpp"

#include <boost/algorithm/string.hpp>

#include <iterator>
#include <algorithm>
#include <vector>

namespace aliceVision {
namespace sensorDB {

bool Datasheet::operator==(const Datasheet& ds) const
{
  bool isEqual = false;
  std::vector<std::string> vec_brand;
  boost::split(vec_brand, ds._brand, boost::is_any_of(" "));

  std::string brandlower = _brand;
  boost::algorithm::to_lower(brandlower);

  for(const auto& brand : vec_brand)
  {
    std::string brandlower2 = brand;
    boost::algorithm::to_lower(brandlower2);

    //ALICEVISION_LOG_DEBUG(brandlower << "\t" << brandlower2);
    if (brandlower == brandlower2)
    {
      std::vector<std::string> vec_model1;
      boost::split(vec_model1, ds._model, boost::is_any_of(" "));
      std::vector<std::string> vec_model2;
      boost::split(vec_model2, _model, boost::is_any_of(" "));
      bool isAllFound = true;

      for(const auto& model1 : vec_model1)
      {
        if(!std::any_of(model1.begin(), model1.end(), ::isdigit))
        {
          continue;
        }

        std::string modellower1 = model1;
        boost::algorithm::to_lower(modellower1);

        bool isFound = false;
        for(const auto& model2 : vec_model2)
        {
          std::string modellower2 = model2;
          boost::algorithm::to_lower(modellower2);

          if (modellower2 == modellower1)
          {
            isFound = true;
          }
        }
        if ( !isFound )
        {
          isAllFound = false;
          break;
        }
      }
      if ( isAllFound )
        isEqual = true;
    }
  }
  return isEqual;
}

} // namespace sensorDB
} // namespace aliceVision
<|endoftext|>