text:
using namespace DirectX;
using Microsoft::WRL::ComPtr;

namespace
{
    constexpr float c_XboxOneThumbDeadZone = .24f;  // Recommended Xbox One controller deadzone

    float ApplyLinearDeadZone(float value, float maxValue, float deadZoneSize) noexcept
    {
        if (value < -deadZoneSize)
        {
            // Increase negative values to remove the deadzone discontinuity.
            value += deadZoneSize;
        }
        else if (value > deadZoneSize)
        {
            // Decrease positive values to remove the deadzone discontinuity.
            value -= deadZoneSize;
        }
        else
        {
            // Values inside the deadzone come out zero.
            return 0;
        }

        // Scale into 0-1 range.
        const float scaledValue = value / (maxValue - deadZoneSize);
        return std::max(-1.f, std::min(scaledValue, 1.f));
    }

    void ApplyStickDeadZone(
        float x,
        float y,
        GamePad::DeadZone deadZoneMode,
        float maxValue,
        float deadZoneSize,
        _Out_ float& resultX,
        _Out_ float& resultY) noexcept
    {
        switch (deadZoneMode)
        {
        case GamePad::DEAD_ZONE_INDEPENDENT_AXES:
            resultX = ApplyLinearDeadZone(x, maxValue, deadZoneSize);
            resultY = ApplyLinearDeadZone(y, maxValue, deadZoneSize);
            break;

        case GamePad::DEAD_ZONE_CIRCULAR:
            {
                const float dist = sqrtf(x*x + y * y);
                const float wanted = ApplyLinearDeadZone(dist, maxValue, deadZoneSize);

                const float scale = (wanted > 0.f) ? (wanted / dist) : 0.f;

                resultX = std::max(-1.f, std::min(x * scale, 1.f));
                resultY = std::max(-1.f, std::min(y * scale, 1.f));
            }
            break;

        default: // GamePad::DEAD_ZONE_NONE
            resultX = ApplyLinearDeadZone(x, maxValue, 0);
            resultY = ApplyLinearDeadZone(y, maxValue, 0);
            break;
        }
    }
}

#pragma region Implementations
#ifdef USING_GAMEINPUT

#include <GameInput.h>

//======================================================================================
// GameInput
//======================================================================================

class GamePad::Impl
{
public:
    Impl(GamePad* owner) :
        mOwner(owner),
        mCtrlChanged(INVALID_HANDLE_VALUE),
        mDeviceToken(0),
        mMostRecentGamepad(0)
    {
        if (s_gamePad)
        {
            throw std::logic_error("GamePad is a singleton");
        }

        s_gamePad = this;

        ThrowIfFailed(GameInputCreate(mGameInput.GetAddressOf()));

        ThrowIfFailed(mGameInput->RegisterDeviceCallback(
            nullptr,
            GameInputKindGamepad,
            GameInputDeviceConnected,
            GameInputBlockingEnumeration,
            this,
            OnGameInputDevice,
            &mDeviceToken));
    }

    Impl(Impl&&) = default;
    Impl& operator= (Impl&&) = default;

    Impl(Impl const&) = delete;
    Impl& operator= (Impl const&) = delete;

    ~Impl()
    {
        if (mDeviceToken)
        {
            if (mGameInput)
            {
                if (!mGameInput->UnregisterCallback(mDeviceToken, UINT64_MAX))
                {
                    DebugTrace("ERROR: GameInput::UnregisterCallback [gamepad] failed");
                }
            }

            mDeviceToken = 0;
        }

        s_gamePad = nullptr;
    }

    void GetState(int player, _Out_ State& state, DeadZone deadZoneMode)
    {
        memset(&state, 0, sizeof(State));

        IGameInputDevice* device = nullptr;

        if (player >= 0 && player < MAX_PLAYER_COUNT)
        {
            device = mInputDevices[player].Get();
            if (!device)
                return;
        }
        else if (player == c_MostRecent)
        {
            player = mMostRecentGamepad;
            assert(player >= 0 && player < MAX_PLAYER_COUNT);
            device = mInputDevices[player].Get();
            if (!device)
                return;
        }
        else if (player != c_MergedInput)
        {
            return;
        }

        ComPtr<IGameInputReading> reading;
        if (SUCCEEDED(mGameInput->GetCurrentReading(GameInputKindGamepad, device, reading.GetAddressOf())))
        {
            GameInputGamepadState pad;
            if (reading->GetGamepadState(&pad))
            {
                state.connected = true;
                state.packet = reading->GetSequenceNumber(GameInputKindGamepad);

                state.buttons.a = (pad.buttons & GameInputGamepadA) != 0;
                state.buttons.b = (pad.buttons & GameInputGamepadB) != 0;
                state.buttons.x = (pad.buttons & GameInputGamepadX) != 0;
                state.buttons.y = (pad.buttons & GameInputGamepadY) != 0;
                state.buttons.leftStick = (pad.buttons & GameInputGamepadLeftThumbstick) != 0;
                state.buttons.rightStick = (pad.buttons & GameInputGamepadRightThumbstick) != 0;
                state.buttons.leftShoulder = (pad.buttons & GameInputGamepadLeftShoulder) != 0;
                state.buttons.rightShoulder = (pad.buttons & GameInputGamepadRightShoulder) != 0;
                state.buttons.view = (pad.buttons & GameInputGamepadView) != 0;
                state.buttons.menu = (pad.buttons & GameInputGamepadMenu) != 0;

                state.dpad.up = (pad.buttons & GameInputGamepadDPadUp) != 0;
                state.dpad.down = (pad.buttons & GameInputGamepadDPadDown) != 0;
                state.dpad.right = (pad.buttons & GameInputGamepadDPadRight) != 0;
                state.dpad.left = (pad.buttons & GameInputGamepadDPadLeft) != 0;

                ApplyStickDeadZone(pad.leftThumbstickX, pad.leftThumbstickY,
                    deadZoneMode, 1.f, c_XboxOneThumbDeadZone,
                    state.thumbSticks.leftX, state.thumbSticks.leftY);

                ApplyStickDeadZone(pad.rightThumbstickX, pad.rightThumbstickY,
                    deadZoneMode, 1.f, c_XboxOneThumbDeadZone,
                    state.thumbSticks.rightX, state.thumbSticks.rightY);

                state.triggers.left = pad.leftTrigger;
                state.triggers.right = pad.rightTrigger;
            }
        }
    }

    void GetCapabilities(int player, _Out_ Capabilities& caps)
    {
        if (player == c_MostRecent)
            player = mMostRecentGamepad;

        if (player >= 0 && player < MAX_PLAYER_COUNT)
        {
            IGameInputDevice* device = mInputDevices[player].Get();
            if (device)
            {
                if (device->GetDeviceStatus() & GameInputDeviceConnected)
                {
                    auto deviceInfo = device->GetDeviceInfo();
                    caps.connected = true;
                    caps.gamepadType = Capabilities::GAMEPAD;
                    caps.id = deviceInfo->deviceId;
                    caps.vid = deviceInfo->vendorId;
                    caps.pid = deviceInfo->productId;
                    return;
                }
                else
                {
                    mInputDevices[player].Reset();
                }
            }
        }

        memset(&caps, 0, sizeof(Capabilities));
    }

    bool SetVibration(int player, float leftMotor, float rightMotor, float leftTrigger, float rightTrigger) noexcept
    {
        if (player == c_MostRecent)
            player = mMostRecentGamepad;

        if (player >= 0 && player < MAX_PLAYER_COUNT)
        {
            IGameInputDevice* device = mInputDevices[player].Get();
            if (device)
            {
                GameInputRumbleParams const params =
                {
                    leftMotor,
                    rightMotor,
                    leftTrigger,
                    rightTrigger
                };

                device->SetRumbleState(&params);
                return true;
            }
        }

        return false;
    }

    void Suspend() noexcept
    {
        for (int player = 0; player < MAX_PLAYER_COUNT; ++player)
        {
            IGameInputDevice* device = mInputDevices[player].Get();
            if (device)
            {
                device->SetRumbleState(nullptr);
            }
        }
    }

    void Resume() noexcept
    {
        for (int player = 0; player < MAX_PLAYER_COUNT; ++player)
        {
            IGameInputDevice* device = mInputDevices[player].Get();
            if (device)
            {
                if (!(device->GetDeviceStatus() & GameInputDeviceConnected))
                {
                    mInputDevices[player].Reset();
                }
            }
        }
    }

    _Success_(return)
        bool GetDevice(int player, _Outptr_ IGameInputDevice** device) noexcept
    {
        if (!device)
            return false;

        if (player == c_MostRecent)
            player = mMostRecentGamepad;

        *device = nullptr;

        if (player >= 0 && player < MAX_PLAYER_COUNT)
        {
            IGameInputDevice* dev = mInputDevices[player].Get();
            if (dev)
            {
                dev->AddRef();
                *device = dev;
                return true;
            }
        }

        return false;
    }

    GamePad*    mOwner;

    static GamePad::Impl* s_gamePad;

    HANDLE mCtrlChanged;

private:
    ComPtr<IGameInput>          mGameInput;
    ComPtr<IGameInputDevice>    mInputDevices[MAX_PLAYER_COUNT];

    GameInputCallbackToken      mDeviceToken;

    int mMostRecentGamepad;

    static void CALLBACK OnGameInputDevice(
        _In_ GameInputCallbackToken,
        _In_ void * context,
        _In_ IGameInputDevice * device,
        _In_ uint64_t,
        _In_ GameInputDeviceStatus currentStatus,
        _In_ GameInputDeviceStatus) noexcept
    {
        auto impl = reinterpret_cast<GamePad::Impl*>(context);

        if (currentStatus & GameInputDeviceConnected)
        {
            size_t empty = MAX_PLAYER_COUNT;
            size_t k = 0;
            for (; k < MAX_PLAYER_COUNT; ++k)
            {
                if (impl->mInputDevices[k].Get() == device)
                {
                    impl->mMostRecentGamepad = static_cast<int>(k);
                    break;
                }
                else if (!impl->mInputDevices[k])
                {
                    if (empty >= MAX_PLAYER_COUNT)
                        empty = k;
                }
            }

            if (k >= MAX_PLAYER_COUNT)
            {
                // Silently ignore "extra" gamepads as there's no hard limit
                if (empty < MAX_PLAYER_COUNT)
                {
                    impl->mInputDevices[empty] = device;
                    impl->mMostRecentGamepad = static_cast<int>(empty);
                }
            }
        }
        else
        {
            for (size_t k = 0; k < MAX_PLAYER_COUNT; ++k)
            {
                if (impl->mInputDevices[k].Get() == device)
                {
                    impl->mInputDevices[k].Reset();
                    break;
                }
            }
        }

        if (impl->mCtrlChanged != INVALID_HANDLE_VALUE)
        {
            SetEvent(impl->mCtrlChanged);
        }
    }
};

GamePad::Impl* GamePad::Impl::s_gamePad = nullptr;

void GamePad::RegisterEvents(HANDLE ctrlChanged) noexcept
{
    pImpl->mCtrlChanged = (!ctrlChanged) ? INVALID_HANDLE_VALUE : ctrlChanged;
}

_Success_(return)
bool GamePad::GetDevice(int player, _Outptr_ IGameInputDevice * *device) noexcept
{
    return pImpl->GetDevice(player, device);
}

#elif defined(USING_WINDOWS_GAMING_INPUT)

//======================================================================================
// Windows::Gaming::Input (Windows 10)
//======================================================================================

#pragma warning(push)
#pragma warning(disable : 4471 5204 5256)
#include <windows.gaming.input.h>
#pragma warning(pop)

class GamePad::Impl
{
public:
    Impl(GamePad* owner) :
        mOwner(owner),
        mCtrlChanged(INVALID_HANDLE_VALUE),
        mUserChanged(INVALID_HANDLE_VALUE),
        mMostRecentGamepad(0),
        mStatics{},
        mGamePad{},
        mUserChangeToken{},
        mAddedToken{},
        mRemovedToken{},
        mChanged{}
    {
        using namespace Microsoft::WRL;
        using namespace Microsoft::WRL::Wrappers;
        using namespace ABI::Windows::Foundation;

        if (s_gamePad)
        {
            throw std::logic_error("GamePad is a singleton");
        }

        s_gamePad = this;

        mChanged.reset(CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE));
        if (!mChanged)
        {
            throw std::system_error(std::error_code(static_cast<int>(GetLastError()), std::system_category()), "CreateEventEx");
        }

        ThrowIfFailed(GetActivationFactory(HStringReference(RuntimeClass_Windows_Gaming_Input_Gamepad).Get(), mStatics.GetAddressOf()));

        typedef __FIEventHandler_1_Windows__CGaming__CInput__CGamepad AddedHandler;
        ThrowIfFailed(mStatics->add_GamepadAdded(Callback<AddedHandler>(GamepadAdded).Get(), &mAddedToken));

        typedef __FIEventHandler_1_Windows__CGaming__CInput__CGamepad RemovedHandler;
        ThrowIfFailed(mStatics->add_GamepadRemoved(Callback<RemovedHandler>(GamepadRemoved).Get(), &mRemovedToken));

        ScanGamePads();
    }

    Impl(Impl&&) = default;
    Impl& operator= (Impl&&) = default;

    Impl(Impl const&) = delete;
    Impl& operator= (Impl const&) = delete;

    ~Impl()
    {
        using namespace ABI::Windows::Gaming::Input;

        for (size_t j = 0; j < MAX_PLAYER_COUNT; ++j)
        {
            if (mGamePad[j])
            {
                ComPtr<IGameController> ctrl;
                HRESULT hr = mGamePad[j].As(&ctrl);
                if (SUCCEEDED(hr) && ctrl)
                {
                    std::ignore = ctrl->remove_UserChanged(mUserChangeToken[j]);
                    mUserChangeToken[j].value = 0;
                }

                mGamePad[j].Reset();
            }
        }

        if (mStatics)
        {
            std::ignore = mStatics->remove_GamepadAdded(mAddedToken);
            mAddedToken.value = 0;

            std::ignore = mStatics->remove_GamepadRemoved(mRemovedToken);
            mRemovedToken.value = 0;

            mStatics.Reset();
        }

        s_gamePad = nullptr;
    }

    void GetState(int player, _Out_ State& state, DeadZone deadZoneMode)
    {
        using namespace Microsoft::WRL;
        using namespace ABI::Windows::Gaming::Input;

        if (WaitForSingleObjectEx(mChanged.get(), 0, FALSE) == WAIT_OBJECT_0)
        {
            ScanGamePads();
        }

        if (player == c_MostRecent)
            player = mMostRecentGamepad;

        if ((player >= 0) && (player < MAX_PLAYER_COUNT))
        {
            if (mGamePad[player])
            {
                GamepadReading reading;
                HRESULT hr = mGamePad[player]->GetCurrentReading(&reading);
                if (SUCCEEDED(hr))
                {
                    state.connected = true;
                    state.packet = reading.Timestamp;

                    state.buttons.a = (reading.Buttons & GamepadButtons::GamepadButtons_A) != 0;
                    state.buttons.b = (reading.Buttons & GamepadButtons::GamepadButtons_B) != 0;
                    state.buttons.x = (reading.Buttons & GamepadButtons::GamepadButtons_X) != 0;
                    state.buttons.y = (reading.Buttons & GamepadButtons::GamepadButtons_Y) != 0;

                    state.buttons.leftStick = (reading.Buttons & GamepadButtons::GamepadButtons_LeftThumbstick) != 0;
                    state.buttons.rightStick = (reading.Buttons & GamepadButtons::GamepadButtons_RightThumbstick) != 0;

                    state.buttons.leftShoulder = (reading.Buttons & GamepadButtons::GamepadButtons_LeftShoulder) != 0;
                    state.buttons.rightShoulder = (reading.Buttons & GamepadButtons::GamepadButtons_RightShoulder) != 0;

                    state.buttons.back = (reading.Buttons & GamepadButtons::GamepadButtons_View) != 0;
                    state.buttons.start = (reading.Buttons & GamepadButtons::GamepadButtons_Menu) != 0;

                    state.dpad.up = (reading.Buttons & GamepadButtons::GamepadButtons_DPadUp) != 0;
                    state.dpad.down = (reading.Buttons & GamepadButtons::GamepadButtons_DPadDown) != 0;
                    state.dpad.right = (reading.Buttons & GamepadButtons::GamepadButtons_DPadRight) != 0;
                    state.dpad.left = (reading.Buttons & GamepadButtons::GamepadButtons_DPadLeft) != 0;

                    ApplyStickDeadZone(static_cast<float>(reading.LeftThumbstickX), static_cast<float>(reading.LeftThumbstickY),
                        deadZoneMode, 1.f, c_XboxOneThumbDeadZone,
                        state.thumbSticks.leftX, state.thumbSticks.leftY);

                    ApplyStickDeadZone(static_cast<float>(reading.RightThumbstickX), static_cast<float>(reading.RightThumbstickY),
                        deadZoneMode, 1.f, c_XboxOneThumbDeadZone,
                        state.thumbSticks.rightX, state.thumbSticks.rightY);

                    state.triggers.left = static_cast<float>(reading.LeftTrigger);
                    state.triggers.right = static_cast<float>(reading.RightTrigger);

                    return;
                }
            }
        }

        memset(&state, 0, sizeof(State));
    }

    void GetCapabilities(int player, Capabilities& caps)
    {
        using namespace Microsoft::WRL;
        using namespace Microsoft::WRL::Wrappers;
        using namespace ABI::Windows::Foundation;
        using namespace ABI::Windows::System;
        using namespace ABI::Windows::Gaming::Input;

        if (WaitForSingleObjectEx(mChanged.get(), 0, FALSE) == WAIT_OBJECT_0)
        {
            ScanGamePads();
        }

        if (player == c_MostRecent)
            player = mMostRecentGamepad;

        if ((player >= 0) && (player < MAX_PLAYER_COUNT))
        {
            if (mGamePad[player])
            {
                caps.connected = true;
                caps.gamepadType = Capabilities::GAMEPAD;
                caps.id.clear();
                caps.vid = caps.pid = 0;

                ComPtr<IGameController> ctrl;
                HRESULT hr = mGamePad[player].As(&ctrl);
                if (SUCCEEDED(hr) && ctrl)
                {
                    ComPtr<IUser> user;
                    hr = ctrl->get_User(user.GetAddressOf());
                    if (SUCCEEDED(hr) && user != nullptr)
                    {
                        HString str;
                        hr = user->get_NonRoamableId(str.GetAddressOf());
                        if (SUCCEEDED(hr))
                        {
                            caps.id = str.GetRawBuffer(nullptr);
                        }
                    }

                // Requires the Windows 10 Creators Update SDK (15063)
                #if defined(NTDDI_WIN10_RS2) && (NTDDI_VERSION >= NTDDI_WIN10_RS2)
                    ComPtr<IRawGameControllerStatics> rawStatics;
                    hr = GetActivationFactory(HStringReference(RuntimeClass_Windows_Gaming_Input_RawGameController).Get(), rawStatics.GetAddressOf());
                    if (SUCCEEDED(hr))
                    {
                        ComPtr<IRawGameController> raw;
                        hr = rawStatics->FromGameController(ctrl.Get(), raw.GetAddressOf());
                        if (SUCCEEDED(hr) && raw)
                        {
                            if (FAILED(raw->get_HardwareVendorId(&caps.vid)))
                                caps.vid = 0;

                            if (FAILED(raw->get_HardwareProductId(&caps.pid)))
                                caps.pid = 0;
                        }
                    }
                #endif // NTDDI_WIN10_RS2
                }
                return;
            }
        }

        caps.id.clear();
        caps = {};
    }

    bool SetVibration(int player, float leftMotor, float rightMotor, float leftTrigger, float rightTrigger) noexcept
    {
        using namespace ABI::Windows::Gaming::Input;

        if (player == c_MostRecent)
            player = mMostRecentGamepad;

        if ((player >= 0) && (player < MAX_PLAYER_COUNT))
        {
            if (mGamePad[player])
            {
                GamepadVibration vib;
                vib.LeftMotor = double(leftMotor);
                vib.RightMotor = double(rightMotor);
                vib.LeftTrigger = double(leftTrigger);
                vib.RightTrigger = double(rightTrigger);
                HRESULT hr = mGamePad[player]->put_Vibration(vib);

                if (SUCCEEDED(hr))
                    return true;
            }
        }

        return false;
    }

    void Suspend() noexcept
    {
        for (size_t j = 0; j < MAX_PLAYER_COUNT; ++j)
        {
            mGamePad[j].Reset();
        }
    }

    void Resume() noexcept
    {
        // Make sure we rescan gamepads
        SetEvent(mChanged.get());
    }

    GamePad*    mOwner;

    static GamePad::Impl* s_gamePad;

    HANDLE mCtrlChanged;
    HANDLE mUserChanged;

private:
    int mMostRecentGamepad;

    void ScanGamePads()
    {
        using namespace Microsoft::WRL;
        using namespace ABI::Windows::Foundation::Collections;
        using namespace ABI::Windows::Gaming::Input;

        ComPtr<IVectorView<Gamepad*>> pads;
        ThrowIfFailed(mStatics->get_Gamepads(pads.GetAddressOf()));

        unsigned int count = 0;
        ThrowIfFailed(pads->get_Size(&count));

        // Check for removed gamepads
        for (size_t j = 0; j < MAX_PLAYER_COUNT; ++j)
        {
            if (mGamePad[j])
            {
                unsigned int k = 0;
                for (; k < count; ++k)
                {
                    ComPtr<IGamepad> pad;
                    HRESULT hr = pads->GetAt(k, pad.GetAddressOf());
                    if (SUCCEEDED(hr) && (pad == mGamePad[j]))
                    {
                        break;
                    }
                }

                if (k >= count)
                {
                    ComPtr<IGameController> ctrl;
                    HRESULT hr = mGamePad[j].As(&ctrl);
                    if (SUCCEEDED(hr) && ctrl)
                    {
                        std::ignore = ctrl->remove_UserChanged(mUserChangeToken[j]);
                        mUserChangeToken[j].value = 0;
                    }

                    mGamePad[j].Reset();
                }
            }
        }

        // Check for added gamepads
        for (unsigned int j = 0; j < count; ++j)
        {
            ComPtr<IGamepad> pad;
            HRESULT hr = pads->GetAt(j, pad.GetAddressOf());
            if (SUCCEEDED(hr))
            {
                size_t empty = MAX_PLAYER_COUNT;
                size_t k = 0;
                for (; k < MAX_PLAYER_COUNT; ++k)
                {
                    if (mGamePad[k] == pad)
                    {
                        if (j == (count - 1))
                            mMostRecentGamepad = static_cast<int>(k);
                        break;
                    }
                    else if (!mGamePad[k])
                    {
                        if (empty >= MAX_PLAYER_COUNT)
                            empty = k;
                    }
                }

                if (k >= MAX_PLAYER_COUNT)
                {
                    // Silently ignore "extra" gamepads as there's no hard limit
                    if (empty < MAX_PLAYER_COUNT)
                    {
                        mGamePad[empty] = pad;
                        if (j == (count - 1))
                            mMostRecentGamepad = static_cast<int>(empty);

                        ComPtr<IGameController> ctrl;
                        hr = pad.As(&ctrl);
                        if (SUCCEEDED(hr) && ctrl)
                        {
                            typedef __FITypedEventHandler_2_Windows__CGaming__CInput__CIGameController_Windows__CSystem__CUserChangedEventArgs UserHandler;
                            ThrowIfFailed(ctrl->add_UserChanged(Callback<UserHandler>(UserChanged).Get(), &mUserChangeToken[empty]));
                        }
                    }
                }
            }
        }
    }

    ComPtr<ABI::Windows::Gaming::Input::IGamepadStatics> mStatics;
    ComPtr<ABI::Windows::Gaming::Input::IGamepad> mGamePad[MAX_PLAYER_COUNT];
    EventRegistrationToken mUserChangeToken[MAX_PLAYER_COUNT];

    EventRegistrationToken mAddedToken;
    EventRegistrationToken mRemovedToken;

    ScopedHandle mChanged;

    static HRESULT GamepadAdded(IInspectable *, ABI::Windows::Gaming::Input::IGamepad*)
    {
        if (s_gamePad)
        {
            SetEvent(s_gamePad->mChanged.get());

            if (s_gamePad->mCtrlChanged != INVALID_HANDLE_VALUE)
            {
                SetEvent(s_gamePad->mCtrlChanged);
            }
        }
        return S_OK;
    }

    static HRESULT GamepadRemoved(IInspectable *, ABI::Windows::Gaming::Input::IGamepad*)
    {
        if (s_gamePad)
        {
            SetEvent(s_gamePad->mChanged.get());

            if (s_gamePad->mCtrlChanged != INVALID_HANDLE_VALUE)
            {
                SetEvent(s_gamePad->mCtrlChanged);
            }
        }
        return S_OK;
    }

    static HRESULT UserChanged(ABI::Windows::Gaming::Input::IGameController*, ABI::Windows::System::IUserChangedEventArgs*)
    {
        if (s_gamePad)
        {
            if (s_gamePad->mUserChanged != INVALID_HANDLE_VALUE)
            {
                SetEvent(s_gamePad->mUserChanged);
            }
        }
        return S_OK;
    }
};

GamePad::Impl* GamePad::Impl::s_gamePad = nullptr;

void GamePad::RegisterEvents(HANDLE ctrlChanged, HANDLE userChanged) noexcept
{
    pImpl->mCtrlChanged = (!ctrlChanged) ? INVALID_HANDLE_VALUE : ctrlChanged;
    pImpl->mUserChanged = (!userChanged) ? INVALID_HANDLE_VALUE : userChanged;
}

#elif defined(_XBOX_ONE)

//======================================================================================
// Windows::Xbox::Input (Xbox One XDK)
//======================================================================================

#include <Windows.Xbox.Input.h>

#include <Windows.Foundation.Collections.h>

class GamePad::Impl
{
public:
    class GamepadAddedListener : public Microsoft::WRL::RuntimeClass<Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::ClassicCom>,
        ABI::Windows::Foundation::IEventHandler<ABI::Windows::Xbox::Input::GamepadAddedEventArgs *>,
        Microsoft::WRL::FtmBase>
    {
    public:
        GamepadAddedListener(HANDLE event) : mEvent(event) {}

        STDMETHOD(Invoke)(_In_ IInspectable *, _In_ ABI::Windows::Xbox::Input::IGamepadAddedEventArgs *) override
        {
            SetEvent(mEvent);

            auto pad = GamePad::Impl::s_gamePad;

            if (pad && pad->mCtrlChanged != INVALID_HANDLE_VALUE)
            {
                SetEvent(pad->mCtrlChanged);
            }
            return S_OK;
        }

    private:
        HANDLE mEvent;
    };

    class GamepadRemovedListener : public Microsoft::WRL::RuntimeClass<Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::ClassicCom>,
        ABI::Windows::Foundation::IEventHandler<ABI::Windows::Xbox::Input::GamepadRemovedEventArgs *>,
        Microsoft::WRL::FtmBase>
    {
    public:
        GamepadRemovedListener(HANDLE event) : mEvent(event) {}

        STDMETHOD(Invoke)(_In_ IInspectable *, _In_ ABI::Windows::Xbox::Input::IGamepadRemovedEventArgs *) override
        {
            SetEvent(mEvent);

            auto pad = GamePad::Impl::s_gamePad;

            if (pad && pad->mCtrlChanged != INVALID_HANDLE_VALUE)
            {
                SetEvent(pad->mCtrlChanged);
            }
            return S_OK;
        }

    private:
        HANDLE mEvent;
    };

    class UserPairingListener : public Microsoft::WRL::RuntimeClass<Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::ClassicCom>,
        ABI::Windows::Foundation::IEventHandler<ABI::Windows::Xbox::Input::ControllerPairingChangedEventArgs *>,
        Microsoft::WRL::FtmBase>
    {
    public:
        UserPairingListener() noexcept {}

        STDMETHOD(Invoke)(_In_ IInspectable *, _In_ ABI::Windows::Xbox::Input::IControllerPairingChangedEventArgs *) override
        {
            auto pad = GamePad::Impl::s_gamePad;

            if (pad && pad->mUserChanged != INVALID_HANDLE_VALUE)
            {
                SetEvent(pad->mUserChanged);
            }
            return S_OK;
        }
    };

    Impl(GamePad *owner) :
        mOwner(owner),
        mCtrlChanged(INVALID_HANDLE_VALUE),
        mUserChanged(INVALID_HANDLE_VALUE),
        mMostRecentGamepad(0),
        mStatics{},
        mStaticsCtrl{},
        mGamePad{},
        mAddedToken{},
        mRemovedToken{},
        mUserParingToken{},
        mChanged{}
    {
        using namespace Microsoft::WRL;
        using namespace Microsoft::WRL::Wrappers;
        using namespace ABI::Windows::Foundation;

        if (s_gamePad)
        {
            throw std::logic_error("GamePad is a singleton");
        }

        s_gamePad = this;

        mChanged.reset(CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE));
        if (!mChanged)
        {
            throw std::system_error(std::error_code(static_cast<int>(GetLastError()), std::system_category()), "CreateEventEx");
        }

        ThrowIfFailed(GetActivationFactory(HStringReference(RuntimeClass_Windows_Xbox_Input_Gamepad).Get(), mStatics.GetAddressOf()));

        ThrowIfFailed(GetActivationFactory(HStringReference(RuntimeClass_Windows_Xbox_Input_Controller).Get(), mStaticsCtrl.GetAddressOf()));

        ThrowIfFailed(mStatics->add_GamepadAdded(Make<GamepadAddedListener>(mChanged.get()).Get(), &mAddedToken));

        ThrowIfFailed(mStatics->add_GamepadRemoved(Make<GamepadRemovedListener>(mChanged.get()).Get(), &mRemovedToken));

        ThrowIfFailed(mStaticsCtrl->add_ControllerPairingChanged(Make<UserPairingListener>().Get(), &mUserParingToken));

        ScanGamePads();
    }

    ~Impl()
    {
        if (mStatics)
        {
            std::ignore = mStatics->remove_GamepadAdded(mAddedToken);
            mAddedToken.value = 0;

            std::ignore = mStatics->remove_GamepadRemoved(mRemovedToken);
            mRemovedToken.value = 0;

            mStatics.Reset();
        }

        if (mStaticsCtrl)
        {
            std::ignore = mStaticsCtrl->remove_ControllerPairingChanged(mUserParingToken);
            mUserParingToken.value = 0;

            mStaticsCtrl.Reset();
        }

        s_gamePad = nullptr;
    }

    void GetState(int player, _Out_ State& state, DeadZone deadZoneMode)
    {
        using namespace Microsoft::WRL;
        using namespace ABI::Windows::Xbox::Input;

        if (WaitForSingleObjectEx(mChanged.get(), 0, FALSE) == WAIT_OBJECT_0)
        {
            ScanGamePads();
        }

        if (player == c_MostRecent)
            player = mMostRecentGamepad;

        if ((player >= 0) && (player < MAX_PLAYER_COUNT))
        {
            if (mGamePad[player])
            {
                RawGamepadReading reading;
                HRESULT hr = mGamePad[player]->GetRawCurrentReading(&reading);
                if (SUCCEEDED(hr))
                {
                    state.connected = true;
                    state.packet = reading.Timestamp;

                    state.buttons.a = (reading.Buttons & GamepadButtons::GamepadButtons_A) != 0;
                    state.buttons.b = (reading.Buttons & GamepadButtons::GamepadButtons_B) != 0;
                    state.buttons.x = (reading.Buttons & GamepadButtons::GamepadButtons_X) != 0;
                    state.buttons.y = (reading.Buttons & GamepadButtons::GamepadButtons_Y) != 0;

                    state.buttons.leftStick = (reading.Buttons & GamepadButtons::GamepadButtons_LeftThumbstick) != 0;
                    state.buttons.rightStick = (reading.Buttons & GamepadButtons::GamepadButtons_RightThumbstick) != 0;

                    state.buttons.leftShoulder = (reading.Buttons & GamepadButtons::GamepadButtons_LeftShoulder) != 0;
                    state.buttons.rightShoulder = (reading.Buttons & GamepadButtons::GamepadButtons_RightShoulder) != 0;

                    state.buttons.back = (reading.Buttons & GamepadButtons::GamepadButtons_View) != 0;
                    state.buttons.start = (reading.Buttons & GamepadButtons::GamepadButtons_Menu) != 0;

                    state.dpad.up = (reading.Buttons & GamepadButtons::GamepadButtons_DPadUp) != 0;
                    state.dpad.down = (reading.Buttons & GamepadButtons::GamepadButtons_DPadDown) != 0;
                    state.dpad.right = (reading.Buttons & GamepadButtons::GamepadButtons_DPadRight) != 0;
                    state.dpad.left = (reading.Buttons & GamepadButtons::GamepadButtons_DPadLeft) != 0;

                    ApplyStickDeadZone(reading.LeftThumbstickX, reading.LeftThumbstickY,
                        deadZoneMode, 1.f, c_XboxOneThumbDeadZone,
                        state.thumbSticks.leftX, state.thumbSticks.leftY);

                    ApplyStickDeadZone(reading.RightThumbstickX, reading.RightThumbstickY,
                        deadZoneMode, 1.f, c_XboxOneThumbDeadZone,
                        state.thumbSticks.rightX, state.thumbSticks.rightY);

                    state.triggers.left = reading.LeftTrigger;
                    state.triggers.right = reading.RightTrigger;

                    return;
                }
            }
        }

        memset(&state, 0, sizeof(State));
    }

    void GetCapabilities(int player, _Out_ Capabilities& caps)
    {
        using namespace Microsoft::WRL;
        using namespace ABI::Windows::Xbox::Input;

        if (WaitForSingleObjectEx(mChanged.get(), 0, FALSE) == WAIT_OBJECT_0)
        {
            ScanGamePads();
        }

        if (player == c_MostRecent)
            player = mMostRecentGamepad;

        if ((player >= 0) && (player < MAX_PLAYER_COUNT))
        {
            if (mGamePad[player])
            {
                caps.connected = true;
                caps.gamepadType = Capabilities::UNKNOWN;
                caps.id = 0;
                caps.vid = caps.pid = 0;

                ComPtr<IController> ctrl;
                HRESULT hr = mGamePad[player].As(&ctrl);
                if (SUCCEEDED(hr) && ctrl)
                {
                    hr = ctrl->get_Id(&caps.id);
                    if (FAILED(hr))
                        caps.id = 0;

                    Wrappers::HString str;
                    hr = ctrl->get_Type(str.GetAddressOf());
                    if (SUCCEEDED(hr))
                    {
                        const wchar_t* typeStr = str.GetRawBuffer(nullptr);
                        if (_wcsicmp(typeStr, L"Windows.Xbox.Input.Gamepad") == 0)
                        {
                            caps.gamepadType = Capabilities::GAMEPAD;
                        }
                        else if (_wcsicmp(typeStr, L"Microsoft.Xbox.Input.ArcadeStick") == 0)
                        {
                            caps.gamepadType = Capabilities::ARCADE_STICK;
                        }
                        else if (_wcsicmp(typeStr, L"Microsoft.Xbox.Input.Wheel") == 0)
                        {
                            caps.gamepadType = Capabilities::WHEEL;
                        }
                    }
                }

                ComPtr<IController3> ctrl3;
                hr = mGamePad[player].As(&ctrl3);
                if (SUCCEEDED(hr) && ctrl3)
                {
                    if (FAILED(ctrl3->get_HardwareVendorId(&caps.vid)))
                        caps.vid = 0;

                    if (FAILED(ctrl3->get_HardwareProductId(&caps.pid)))
                        caps.pid = 0;
                }

                return;
            }
        }

        memset(&caps, 0, sizeof(Capabilities));
    }

    bool SetVibration(int player, float leftMotor, float rightMotor, float leftTrigger, float rightTrigger) noexcept
    {
        using namespace ABI::Windows::Xbox::Input;

        if (player == c_MostRecent)
            player = mMostRecentGamepad;

        if ((player >= 0) && (player < MAX_PLAYER_COUNT))
        {
            if (mGamePad[player])
            {
                HRESULT hr;
                try
                {
                    GamepadVibration vib;
                    vib.LeftMotorLevel = leftMotor;
                    vib.RightMotorLevel = rightMotor;
                    vib.LeftTriggerLevel = leftTrigger;
                    vib.RightTriggerLevel = rightTrigger;
                    hr = mGamePad[player]->SetVibration(vib);
                }
                catch (...)
                {
                    // Handle case where gamepad might be invalid
                    hr = E_FAIL;
                }

                if (SUCCEEDED(hr))
                    return true;
            }
        }

        return false;
    }

    void Suspend() noexcept
    {
        for (size_t j = 0; j < MAX_PLAYER_COUNT; ++j)
        {
            mGamePad[j].Reset();
        }
    }

    void Resume() noexcept
    {
        // Make sure we rescan gamepads
        SetEvent(mChanged.get());
    }

    GamePad*    mOwner;

    static GamePad::Impl* s_gamePad;

    HANDLE mCtrlChanged;
    HANDLE mUserChanged;

private:
    int mMostRecentGamepad;

    void ScanGamePads()
    {
        using namespace ABI::Windows::Foundation::Collections;
        using namespace ABI::Windows::Xbox::Input;

        ComPtr<IVectorView<IGamepad*>> pads;
        ThrowIfFailed(mStatics->get_Gamepads(pads.GetAddressOf()));

        unsigned int count = 0;
        ThrowIfFailed(pads->get_Size(&count));

        // Check for removed gamepads
        for (size_t j = 0; j < MAX_PLAYER_COUNT; ++j)
        {
            if (mGamePad[j])
            {
                unsigned int k = 0;
                for (; k < count; ++k)
                {
                    ComPtr<IGamepad> pad;
                    HRESULT hr = pads->GetAt(k, pad.GetAddressOf());
                    if (SUCCEEDED(hr) && (pad == mGamePad[j]))
                    {
                        break;
                    }
                }

                if (k >= count)
                {
                    mGamePad[j].Reset();
                }
            }
        }

        // Check for added gamepads
        for (unsigned int j = 0; j < count; ++j)
        {
            ComPtr<IGamepad> pad;
            HRESULT hr = pads->GetAt(j, pad.GetAddressOf());
            if (SUCCEEDED(hr))
            {
                size_t empty = MAX_PLAYER_COUNT;
                size_t k = 0;
                for (; k < MAX_PLAYER_COUNT; ++k)
                {
                    if (mGamePad[k] == pad)
                    {
                        if (!j)
                            mMostRecentGamepad = static_cast<int>(k);
                        break;
                    }
                    else if (!mGamePad[k])
                    {
                        if (empty >= MAX_PLAYER_COUNT)
                            empty = k;
                    }
                }

                if (k >= MAX_PLAYER_COUNT)
                {
                    if (empty >= MAX_PLAYER_COUNT)
                    {
                        throw std::runtime_error("Too many gamepads found");
                    }

                    mGamePad[empty] = pad;
                    if (!j)
                        mMostRecentGamepad = static_cast<int>(empty);
                }
            }
        }
    }

    ComPtr<ABI::Windows::Xbox::Input::IGamepadStatics> mStatics;
    ComPtr<ABI::Windows::Xbox::Input::IControllerStatics> mStaticsCtrl;
    ComPtr<ABI::Windows::Xbox::Input::IGamepad> mGamePad[MAX_PLAYER_COUNT];

    EventRegistrationToken mAddedToken;
    EventRegistrationToken mRemovedToken;
    EventRegistrationToken mUserParingToken;

    ScopedHandle mChanged;
};

GamePad::Impl* GamePad::Impl::s_gamePad = nullptr;

void GamePad::RegisterEvents(HANDLE ctrlChanged, HANDLE userChanged) noexcept
{
    pImpl->mCtrlChanged = (!ctrlChanged) ? INVALID_HANDLE_VALUE : ctrlChanged;
    pImpl->mUserChanged = (!userChanged) ? INVALID_HANDLE_VALUE : userChanged;
}

#elif defined(USING_XINPUT)

//======================================================================================
// XInput
//======================================================================================

#include <Xinput.h>

static_assert(GamePad::MAX_PLAYER_COUNT == XUSER_MAX_COUNT, "xinput.h mismatch");

class GamePad::Impl
{
public:
    Impl(GamePad* owner) :
        mOwner(owner),
        mConnected{},
        mLastReadTime{}
    #if (_WIN32_WINNT < _WIN32_WINNT_WIN8)
        , mLeftMotor{}
        , mRightMotor{}
        , mSuspended(false)
    #endif
    {
        for (int j = 0; j < XUSER_MAX_COUNT; ++j)
        {
            ClearSlot(j, 0);
        }

        if (s_gamePad)
        {
            throw std::logic_error("GamePad is a singleton");
        }

        s_gamePad = this;
    }

    ~Impl()
    {
        s_gamePad = nullptr;
    }

    void GetState(int player, _Out_ State& state, DeadZone deadZoneMode)
    {
        if (player == c_MostRecent)
            player = GetMostRecent();

        const ULONGLONG time = GetTickCount64();

        if (!ThrottleRetry(player, time))
        {
        #if (_WIN32_WINNT < _WIN32_WINNT_WIN8)
            if (mSuspended)
            {
                memset(&state, 0, sizeof(State));
                state.connected = mConnected[player];
                return;
            }
        #endif

            XINPUT_STATE xstate;
            const DWORD result = XInputGetState(DWORD(player), &xstate);
            if (result == ERROR_DEVICE_NOT_CONNECTED)
            {
                ClearSlot(player, time);
            }
            else
            {
                if (!mConnected[player])
                    mLastReadTime[player] = time;

                mConnected[player] = true;

                state.connected = true;
                state.packet = xstate.dwPacketNumber;

                const WORD xbuttons = xstate.Gamepad.wButtons;
                state.buttons.a = (xbuttons & XINPUT_GAMEPAD_A) != 0;
                state.buttons.b = (xbuttons & XINPUT_GAMEPAD_B) != 0;
                state.buttons.x = (xbuttons & XINPUT_GAMEPAD_X) != 0;
                state.buttons.y = (xbuttons & XINPUT_GAMEPAD_Y) != 0;
                state.buttons.leftStick = (xbuttons & XINPUT_GAMEPAD_LEFT_THUMB) != 0;
                state.buttons.rightStick = (xbuttons & XINPUT_GAMEPAD_RIGHT_THUMB) != 0;
                state.buttons.leftShoulder = (xbuttons & XINPUT_GAMEPAD_LEFT_SHOULDER) != 0;
                state.buttons.rightShoulder = (xbuttons & XINPUT_GAMEPAD_RIGHT_SHOULDER) != 0;
                state.buttons.back = (xbuttons & XINPUT_GAMEPAD_BACK) != 0;
                state.buttons.start = (xbuttons & XINPUT_GAMEPAD_START) != 0;

                state.dpad.up = (xbuttons & XINPUT_GAMEPAD_DPAD_UP) != 0;
                state.dpad.down = (xbuttons & XINPUT_GAMEPAD_DPAD_DOWN) != 0;
                state.dpad.right = (xbuttons & XINPUT_GAMEPAD_DPAD_RIGHT) != 0;
                state.dpad.left = (xbuttons & XINPUT_GAMEPAD_DPAD_LEFT) != 0;

                if (deadZoneMode == DEAD_ZONE_NONE)
                {
                    state.triggers.left = ApplyLinearDeadZone(float(xstate.Gamepad.bLeftTrigger), 255.f, 0.f);
                    state.triggers.right = ApplyLinearDeadZone(float(xstate.Gamepad.bRightTrigger), 255.f, 0.f);
                }
                else
                {
                    state.triggers.left = ApplyLinearDeadZone(float(xstate.Gamepad.bLeftTrigger), 255.f, float(XINPUT_GAMEPAD_TRIGGER_THRESHOLD));
                    state.triggers.right = ApplyLinearDeadZone(float(xstate.Gamepad.bRightTrigger), 255.f, float(XINPUT_GAMEPAD_TRIGGER_THRESHOLD));
                }

                ApplyStickDeadZone(float(xstate.Gamepad.sThumbLX), float(xstate.Gamepad.sThumbLY),
                    deadZoneMode, 32767.f, float(XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE),
                    state.thumbSticks.leftX, state.thumbSticks.leftY);

                ApplyStickDeadZone(float(xstate.Gamepad.sThumbRX), float(xstate.Gamepad.sThumbRY),
                    deadZoneMode, 32767.f, float(XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE),
                    state.thumbSticks.rightX, state.thumbSticks.rightY);

                return;
            }
        }

        memset(&state, 0, sizeof(State));
    }

    void GetCapabilities(int player, _Out_ Capabilities& caps)
    {
        if (player == c_MostRecent)
            player = GetMostRecent();

        const ULONGLONG time = GetTickCount64();

        if (!ThrottleRetry(player, time))
        {
            XINPUT_CAPABILITIES xcaps;
            const DWORD result = XInputGetCapabilities(DWORD(player), 0, &xcaps);
            if (result == ERROR_DEVICE_NOT_CONNECTED)
            {
                ClearSlot(player, time);
            }
            else
            {
                if (!mConnected[player])
                    mLastReadTime[player] = time;

                mConnected[player] = true;

                caps.connected = true;
                caps.id = uint64_t(player);
                if (xcaps.Type == XINPUT_DEVTYPE_GAMEPAD)
                {
                    static_assert(Capabilities::GAMEPAD == XINPUT_DEVSUBTYPE_GAMEPAD, "xinput.h mismatch");
                #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
                    static_assert(XINPUT_DEVSUBTYPE_WHEEL == Capabilities::WHEEL, "xinput.h mismatch");
                    static_assert(XINPUT_DEVSUBTYPE_ARCADE_STICK == Capabilities::ARCADE_STICK, "xinput.h mismatch");
                #ifndef __MINGW32__
                    static_assert(XINPUT_DEVSUBTYPE_FLIGHT_STICK == Capabilities::FLIGHT_STICK, "xinput.h mismatch");
                #endif
                    static_assert(XINPUT_DEVSUBTYPE_DANCE_PAD == Capabilities::DANCE_PAD, "xinput.h mismatch");
                    static_assert(XINPUT_DEVSUBTYPE_GUITAR == Capabilities::GUITAR, "xinput.h mismatch");
                    static_assert(XINPUT_DEVSUBTYPE_GUITAR_ALTERNATE == Capabilities::GUITAR_ALTERNATE, "xinput.h mismatch");
                    static_assert(XINPUT_DEVSUBTYPE_DRUM_KIT == Capabilities::DRUM_KIT, "xinput.h mismatch");
                    static_assert(XINPUT_DEVSUBTYPE_GUITAR_BASS == Capabilities::GUITAR_BASS, "xinput.h mismatch");
                    static_assert(XINPUT_DEVSUBTYPE_ARCADE_PAD == Capabilities::ARCADE_PAD, "xinput.h mismatch");
                #endif

                    caps.gamepadType = Capabilities::Type(xcaps.SubType);
                }

                // Hard-coded VID/PID
                caps.vid = 0x045E;
            #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
                caps.pid = (xcaps.Flags & XINPUT_CAPS_WIRELESS) ? 0x0719 : 0;
            #else
                caps.pid = 0;
            #endif

                return;
            }
        }

        memset(&caps, 0, sizeof(Capabilities));
    }

    bool SetVibration(int player, float leftMotor, float rightMotor, float leftTrigger, float rightTrigger) noexcept
    {
        if (player == c_MostRecent)
            player = GetMostRecent();

        const ULONGLONG time = GetTickCount64();

        if (ThrottleRetry(player, time))
        {
            return false;
        }

        // XInput does not provide a way to set the left/right trigger impulse motors on the Xbox One Controller,
        // and these motors are not present on the Xbox 360 Common Controller
        UNREFERENCED_PARAMETER(leftTrigger);
        UNREFERENCED_PARAMETER(rightTrigger);

    #if (_WIN32_WINNT < _WIN32_WINNT_WIN8)
        mLeftMotor[player] = leftMotor;
        mRightMotor[player] = rightMotor;

        if (mSuspended)
            return mConnected[player];
    #endif

        XINPUT_VIBRATION xvibration;
        xvibration.wLeftMotorSpeed = WORD(leftMotor * 0xFFFF);
        xvibration.wRightMotorSpeed = WORD(rightMotor * 0xFFFF);
        const DWORD result = XInputSetState(DWORD(player), &xvibration);
        if (result == ERROR_DEVICE_NOT_CONNECTED)
        {
            ClearSlot(player, time);
            return false;
        }
        else
        {
            if (!mConnected[player])
                mLastReadTime[player] = time;

            mConnected[player] = true;
            return (result == ERROR_SUCCESS);
        }
    }

    void Suspend() noexcept
    {
    #if (_WIN32_WINNT >= _WIN32_WINNT_WIN10)
        // XInput focus is handled automatically on Windows 10
    #elif (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
        XInputEnable(FALSE);
    #else
        // For XInput 9.1.0, we have to emulate the behavior of XInputEnable( FALSE )
        if (!mSuspended)
        {
            for (size_t j = 0; j < XUSER_MAX_COUNT; ++j)
            {
                if (mConnected[j])
                {
                    XINPUT_VIBRATION xvibration;
                    xvibration.wLeftMotorSpeed = xvibration.wRightMotorSpeed = 0;
                    std::ignore = XInputSetState(DWORD(j), &xvibration);
                }
            }

            mSuspended = true;
        }
    #endif
    }

    void Resume() noexcept
    {
    #if (_WIN32_WINNT >= _WIN32_WINNT_WIN10)
        // XInput focus is handled automatically on Windows 10
    #elif (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
        XInputEnable(TRUE);
    #else
        // For XInput 9.1.0, we have to emulate the behavior of XInputEnable( TRUE )
        if (mSuspended)
        {
            const ULONGLONG time = GetTickCount64();

            for (int j = 0; j < XUSER_MAX_COUNT; ++j)
            {
                if (mConnected[j])
                {
                    XINPUT_VIBRATION xvibration;
                    xvibration.wLeftMotorSpeed = WORD(mLeftMotor[j] * 0xFFFF);
                    xvibration.wRightMotorSpeed = WORD(mRightMotor[j] * 0xFFFF);
                    const DWORD result = XInputSetState(DWORD(j), &xvibration);
                    if (result == ERROR_DEVICE_NOT_CONNECTED)
                    {
                        ClearSlot(j, time);
                    }
                }
            }

            mSuspended = false;
        }
    #endif
    }

    GamePad*    mOwner;

    static GamePad::Impl* s_gamePad;

private:
    bool        mConnected[XUSER_MAX_COUNT];
    ULONGLONG   mLastReadTime[XUSER_MAX_COUNT];

#if (_WIN32_WINNT < _WIN32_WINNT_WIN8)
    // Variables for emulating XInputEnable on XInput 9.1.0
    float       mLeftMotor[XUSER_MAX_COUNT];
    float       mRightMotor[XUSER_MAX_COUNT];
    bool        mSuspended;
#endif

    bool ThrottleRetry(int player, ULONGLONG time)
    {
        // This function minimizes a potential performance issue with XInput on Windows when
        // checking a disconnected controller slot which requires device enumeration.
        // This throttling keeps checks for newly connected gamepads to about once a second

        if ((player < 0) || (player >= XUSER_MAX_COUNT))
            return true;

        if (mConnected[player])
            return false;

        for (int j = 0; j < XUSER_MAX_COUNT; ++j)
        {
            if (!mConnected[j])
            {
                const LONGLONG delta = LONGLONG(time) - LONGLONG(mLastReadTime[j]);

                LONGLONG interval = 1000;
                if (j != player)
                    interval /= 4;

                if ((delta >= 0) && (delta < interval))
                    return true;
            }
        }

        return false;
    }

    void ClearSlot(int player, ULONGLONG time)
    {
        mConnected[player] = false;
        mLastReadTime[player] = time;
    #if (_WIN32_WINNT < _WIN32_WINNT_WIN8)
        mLeftMotor[player] = mRightMotor[player] = 0.f;
    #endif
    }

    int GetMostRecent()
    {
        int player = -1;
        ULONGLONG time = 0;

        for (size_t j = 0; j < XUSER_MAX_COUNT; ++j)
        {
            if (mConnected[j] && (mLastReadTime[j] > time))
            {
                time = mLastReadTime[j];
                player = static_cast<int>(j);
            }
        }

        return player;
    }
};

GamePad::Impl* GamePad::Impl::s_gamePad = nullptr;

#else

#error Unknown GamePad implementation

#endif
#pragma endregion

#pragma warning( disable : 4355 )

// Public constructor.
GamePad::GamePad() noexcept(false)
    : pImpl(std::make_unique<Impl>(this))
{
}

// Move constructor.
GamePad::GamePad(GamePad&& moveFrom) noexcept
    : pImpl(std::move(moveFrom.pImpl))
{
    pImpl->mOwner = this;
}

// Move assignment.
GamePad& GamePad::operator= (GamePad&& moveFrom) noexcept
{
    pImpl = std::move(moveFrom.pImpl);
    pImpl->mOwner = this;
    return *this;
}

// Public destructor.
GamePad::~GamePad() = default;

GamePad::State GamePad::GetState(int player, DeadZone deadZoneMode)
{
    State state;
    pImpl->GetState(player, state, deadZoneMode);
    return state;
}

GamePad::Capabilities GamePad::GetCapabilities(int player)
{
    Capabilities caps;
    pImpl->GetCapabilities(player, caps);
    return caps;
}

bool GamePad::SetVibration(int player, float leftMotor, float rightMotor, float leftTrigger, float rightTrigger) noexcept
{
    return pImpl->SetVibration(player, leftMotor, rightMotor, leftTrigger, rightTrigger);
}

void GamePad::Suspend() noexcept
{
    pImpl->Suspend();
}

void GamePad::Resume() noexcept
{
    pImpl->Resume();
}

GamePad& GamePad::Get()
{
    if (!Impl::s_gamePad || !Impl::s_gamePad->mOwner)
        throw std::logic_error("GamePad singleton not created");

    return *Impl::s_gamePad->mOwner;
}

//======================================================================================
// ButtonStateTracker
//======================================================================================

#define UPDATE_BUTTON_STATE(field) field = static_cast<ButtonState>( ( !!state.buttons.field ) | ( ( !!state.buttons.field ^ !!lastState.buttons.field ) << 1 ) )

void GamePad::ButtonStateTracker::Update(const GamePad::State& state) noexcept
{
    UPDATE_BUTTON_STATE(a);

    assert((!state.buttons.a && !lastState.buttons.a) == (a == UP));
    assert((state.buttons.a && lastState.buttons.a) == (a == HELD));
    assert((!state.buttons.a && lastState.buttons.a) == (a == RELEASED));
    assert((state.buttons.a && !lastState.buttons.a) == (a == PRESSED));

    UPDATE_BUTTON_STATE(b);
    UPDATE_BUTTON_STATE(x);
    UPDATE_BUTTON_STATE(y);

    UPDATE_BUTTON_STATE(leftStick);
    UPDATE_BUTTON_STATE(rightStick);

    UPDATE_BUTTON_STATE(leftShoulder);
    UPDATE_BUTTON_STATE(rightShoulder);

    UPDATE_BUTTON_STATE(back);
    UPDATE_BUTTON_STATE(start);

    dpadUp = static_cast<ButtonState>((!!state.dpad.up) | ((!!state.dpad.up ^ !!lastState.dpad.up) << 1));
    dpadDown = static_cast<ButtonState>((!!state.dpad.down) | ((!!state.dpad.down ^ !!lastState.dpad.down) << 1));
    dpadLeft = static_cast<ButtonState>((!!state.dpad.left) | ((!!state.dpad.left ^ !!lastState.dpad.left) << 1));
    dpadRight = static_cast<ButtonState>((!!state.dpad.right) | ((!!state.dpad.right ^ !!lastState.dpad.right) << 1));

    assert((!state.dpad.up && !lastState.dpad.up) == (dpadUp == UP));
    assert((state.dpad.up && lastState.dpad.up) == (dpadUp == HELD));
    assert((!state.dpad.up && lastState.dpad.up) == (dpadUp == RELEASED));
    assert((state.dpad.up && !lastState.dpad.up) == (dpadUp == PRESSED));

    // Handle 'threshold' tests which emulate buttons

    bool threshold = state.IsLeftThumbStickUp();
    leftStickUp = static_cast<ButtonState>((!!threshold) | ((!!threshold ^ !!lastState.IsLeftThumbStickUp()) << 1));

    threshold = state.IsLeftThumbStickDown();
    leftStickDown = static_cast<ButtonState>((!!threshold) | ((!!threshold ^ !!lastState.IsLeftThumbStickDown()) << 1));

    threshold = state.IsLeftThumbStickLeft();
    leftStickLeft = static_cast<ButtonState>((!!threshold) | ((!!threshold ^ !!lastState.IsLeftThumbStickLeft()) << 1));

    threshold = state.IsLeftThumbStickRight();
    leftStickRight = static_cast<ButtonState>((!!threshold) | ((!!threshold ^ !!lastState.IsLeftThumbStickRight()) << 1));

    threshold = state.IsRightThumbStickUp();
    rightStickUp = static_cast<ButtonState>((!!threshold) | ((!!threshold ^ !!lastState.IsRightThumbStickUp()) << 1));

    threshold = state.IsRightThumbStickDown();
    rightStickDown = static_cast<ButtonState>((!!threshold) | ((!!threshold ^ !!lastState.IsRightThumbStickDown()) << 1));

    threshold = state.IsRightThumbStickLeft();
    rightStickLeft = static_cast<ButtonState>((!!threshold) | ((!!threshold ^ !!lastState.IsRightThumbStickLeft()) << 1));

    threshold = state.IsRightThumbStickRight();
    rightStickRight = static_cast<ButtonState>((!!threshold) | ((!!threshold ^ !!lastState.IsRightThumbStickRight()) << 1));

    threshold = state.IsLeftTriggerPressed();
    leftTrigger = static_cast<ButtonState>((!!threshold) | ((!!threshold ^ !!lastState.IsLeftTriggerPressed()) << 1));

    threshold = state.IsRightTriggerPressed();
    rightTrigger = static_cast<ButtonState>((!!threshold) | ((!!threshold ^ !!lastState.IsRightTriggerPressed()) << 1));

    lastState = state;
}

#undef UPDATE_BUTTON_STATE

void GamePad::ButtonStateTracker::Reset() noexcept
{
    memset(this, 0, sizeof(ButtonStateTracker));
}


text:
package com.github.scr.hashmap.maps;

import com.github.scr.hashmap.collections.*;
import com.github.scr.hashmap.sets.BufferCharSequenceSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.*;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.util.Map;

/**
 * Created by scr on 7/3/15.
 */
public class BufferCharSequenceMaps {
    private static final Logger LOGGER = LoggerFactory.getLogger(BufferCharSequenceMaps.class);

    // Integer
    public static BufferCharSequenceMap<Integer> intMap(Path filePath) throws IOException {
        try (FileChannel fileChannel = FileChannel.open(filePath)) {
            MappedByteBuffer byteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0L, fileChannel.size());
            return intMap(byteBuffer);
        }
    }

    public static BufferCharSequenceMap<Integer> intMap(ByteBuffer byteBuffer) {
        BufferCharSequenceSet keys = new BufferCharSequenceSet(byteBuffer);
        IndexedCollection<Integer> vals = BufferCollections.ofInt(byteBuffer);
        return new BufferCharSequenceMap<>(keys, vals);
    }

    public static <K extends CharSequence> BufferCharSequenceMap<Integer> intMap(Map<K, Integer> map) {
        BufferCharSequenceSet keys = new BufferCharSequenceSet(map.keySet());
        int numKeys = keys.size();
        IntBuffer valBuffer = IntBuffer.allocate(numKeys);
        map.forEach((k, v) -> {
            try {
                valBuffer.put(keys.getIndex(k), v);
            } catch (Exception e) {
                LOGGER.error("Error getting index for {} -> {}", k, v, e);
                keys.getIndex(k);
            }
        });
        return new BufferCharSequenceMap<>(keys, new IntBufferCollection(valBuffer));
    }

    // Float
    public static BufferCharSequenceMap<Float> floatMap(Path filePath) throws IOException {
        try (FileChannel fileChannel = FileChannel.open(filePath)) {
            MappedByteBuffer byteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0L, fileChannel.size());
            return floatMap(byteBuffer);
        }
    }

    public static BufferCharSequenceMap<Float> floatMap(ByteBuffer byteBuffer) {
        BufferCharSequenceSet keys = new BufferCharSequenceSet(byteBuffer);
        IndexedCollection<Float> vals = BufferCollections.ofFloat(byteBuffer);
        return new BufferCharSequenceMap<>(keys, vals);
    }

    public static BufferCharSequenceMap<Float> floatMap(Map<? extends CharSequence, Float> map) {
        BufferCharSequenceSet keys = new BufferCharSequenceSet(map.keySet());
        FloatBuffer valBuffer = FloatBuffer.allocate(keys.size());
        map.forEach((k, v) -> {
            valBuffer.put(keys.getIndex(k), v);
        });
        return new BufferCharSequenceMap<>(keys, new FloatBufferCollection(valBuffer));
    }

    // Double
    public static BufferCharSequenceMap<Double> doubleMap(Path filePath) throws IOException {
        try (FileChannel fileChannel = FileChannel.open(filePath)) {
            MappedByteBuffer byteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0L, fileChannel.size());
            return doubleMap(byteBuffer);
        }
    }

    public static BufferCharSequenceMap<Double> doubleMap(ByteBuffer byteBuffer) {
        BufferCharSequenceSet keys = new BufferCharSequenceSet(byteBuffer);
        IndexedCollection<Double> vals = BufferCollections.ofDouble(byteBuffer);
        return new BufferCharSequenceMap<>(keys, vals);
    }

    public static BufferCharSequenceMap<Double> doubleMap(Map<? extends CharSequence, Double> map) {
        BufferCharSequenceSet keys = new BufferCharSequenceSet(map.keySet());
        DoubleBuffer valBuffer = DoubleBuffer.allocate(keys.size());
        map.forEach((k, v) -> {
            valBuffer.put(keys.getIndex(k), v);
        });
        return new BufferCharSequenceMap<>(keys, new DoubleBufferCollection(valBuffer));
    }

    // Long
    public static BufferCharSequenceMap<Long> longMap(Path filePath) throws IOException {
        try (FileChannel fileChannel = FileChannel.open(filePath)) {
            MappedByteBuffer byteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0L, fileChannel.size());
            return longMap(byteBuffer);
        }
    }

    public static BufferCharSequenceMap<Long> longMap(ByteBuffer byteBuffer) {
        BufferCharSequenceSet keys = new BufferCharSequenceSet(byteBuffer);
        IndexedCollection<Long> vals = BufferCollections.ofLong(byteBuffer);
        return new BufferCharSequenceMap<>(keys, vals);
    }

    public static BufferCharSequenceMap<Long> longMap(Map<? extends CharSequence, Long> map) {
        BufferCharSequenceSet keys = new BufferCharSequenceSet(map.keySet());
        LongBuffer valBuffer = LongBuffer.allocate(keys.size());
        map.forEach((k, v) -> {
            valBuffer.put(keys.getIndex(k), v);
        });
        return new BufferCharSequenceMap<>(keys, new LongBufferCollection(valBuffer));
    }

    // Short
    public static BufferCharSequenceMap<Short> shortMap(Path filePath) throws IOException {
        try (FileChannel fileChannel = FileChannel.open(filePath)) {
            MappedByteBuffer byteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0L, fileChannel.size());
            return shortMap(byteBuffer);
        }
    }

    public static BufferCharSequenceMap<Short> shortMap(ByteBuffer byteBuffer) {
        BufferCharSequenceSet keys = new BufferCharSequenceSet(byteBuffer);
        IndexedCollection<Short> vals = BufferCollections.ofShort(byteBuffer);
        return new BufferCharSequenceMap<>(keys, vals);
    }

    public static BufferCharSequenceMap<Short> shortMap(Map<? extends CharSequence, Short> map) {
        BufferCharSequenceSet keys = new BufferCharSequenceSet(map.keySet());
        ShortBuffer valBuffer = ShortBuffer.allocate(keys.size());
        map.forEach((k, v) -> {
            valBuffer.put(keys.getIndex(k), v);
        });
        return new BufferCharSequenceMap<>(keys, new ShortBufferCollection(valBuffer));
    }

    // Byte
    public static BufferCharSequenceMap<Byte> byteMap(Path filePath) throws IOException {
        try (FileChannel fileChannel = FileChannel.open(filePath)) {
            MappedByteBuffer byteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0L, fileChannel.size());
            return byteMap(byteBuffer);
        }
    }

    public static BufferCharSequenceMap<Byte> byteMap(ByteBuffer byteBuffer) {
        BufferCharSequenceSet keys = new BufferCharSequenceSet(byteBuffer);
        IndexedCollection<Byte> vals = BufferCollections.ofByte(byteBuffer);
        return new BufferCharSequenceMap<>(keys, vals);
    }

    public static BufferCharSequenceMap<Byte> byteMap(Map<? extends CharSequence, Byte> map) {
        BufferCharSequenceSet keys = new BufferCharSequenceSet(map.keySet());
        ByteBuffer valBuffer = ByteBuffer.allocate(keys.size());
        map.forEach((k, v) -> {
            valBuffer.put(keys.getIndex(k), v);
        });
        return new BufferCharSequenceMap<>(keys, new ByteBufferCollection(valBuffer));
    }

    // Character
    public static BufferCharSequenceMap<Character> characterMap(Path filePath) throws IOException {
        try (FileChannel fileChannel = FileChannel.open(filePath)) {
            MappedByteBuffer byteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0L, fileChannel.size());
            return characterMap(byteBuffer);
        }
    }

    public static BufferCharSequenceMap<Character> characterMap(ByteBuffer byteBuffer) {
        BufferCharSequenceSet keys = new BufferCharSequenceSet(byteBuffer);
        IndexedCollection<Character> vals = BufferCollections.ofCharacter(byteBuffer);
        return new BufferCharSequenceMap<>(keys, vals);
    }

    public static BufferCharSequenceMap<Character> characterMap(Map<? extends CharSequence, Character> map) {
        BufferCharSequenceSet keys = new BufferCharSequenceSet(map.keySet());
        CharBuffer valBuffer = CharBuffer.allocate(keys.size());
        map.forEach((k, v) -> {
            valBuffer.put(keys.getIndex(k), v);
        });
        return new BufferCharSequenceMap<>(keys, new CharacterBufferCollection(valBuffer));
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include "exodusII.h"

/*!
\deprecated Use ex_put_set()(exoid, EX_NODE_SET, node_set_id, node_set_node_list, NULL)

The function ex_put_node_set() writes the node list for a single node
set. The function ex_put_node_set_param() must be called before this
routine is invoked.

\return In case of an error, ex_put_node_set() returns a negative
number; a warning will return a positive number.  Possible causes of
errors include:
  -  data file not properly opened with call to ex_create() or ex_open()
  -  data file opened for read only.
  -  data file not initialized properly with call to ex_put_init().
  -  ex_put_node_set_param() not called previously.

\param[in] exoid              exodus file ID returned from a previous call to ex_create() or ex_open().
\param[in] node_set_id        The node set ID.
\param[in] node_set_node_list Array containing the node list for the node set. Internal node IDs are
                              used in this list (See Section LocalNodeIds).

Refer to the description of ex_put_node_set_param() for a sample code
segment to write out a node set.
*/

int ex_put_node_set (int   exoid,
                     int   node_set_id,
                     const int  *node_set_node_list)
{
  return ex_put_set(exoid, EX_NODE_SET, node_set_id,
        node_set_node_list, NULL);
}


text:
<?php

namespace DhErrorLogging\Sender\Factory;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use DhErrorLogging\Sender\ResponseSender;

class ResponseSenderFactory implements FactoryInterface
{
    /**
     * {@inheritDoc}
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        // get request
        $request = $serviceLocator->get('Request');
        $response = $serviceLocator->get('Response');
        $options = $serviceLocator->get('DhErrorLogging\Options\ModuleOptions');
        //var_dump($response);die();

        return new ResponseSender($request, $response, $options);
    }
}


text:
package com.mossle.plm.data;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import com.mossle.core.csv.CsvProcessor;

import com.mossle.plm.persistence.manager.PlmProductManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PlmDeployer {
    private static Logger logger = LoggerFactory.getLogger(PlmDeployer.class);
    private PlmProductManager plmProductManager;
    private String dataFilePath = "data/plm-product.csv";
    private String dataFileEncoding = "GB2312";
    private String defaultTenantId = "1";
    private boolean enable = true;

    @PostConstruct
    public void process() throws Exception {
        if (!enable) {
            logger.info("skip init plm data");

            return;
        }

        PlmProductCallback plmProductCallback = new PlmProductCallback();
        plmProductCallback.setPlmProductManager(plmProductManager);
        plmProductCallback.setDefaultTenantId(defaultTenantId);
        new CsvProcessor().process(dataFilePath, dataFileEncoding,
                plmProductCallback);
    }

    @Resource
    public void setPlmProductManager(PlmProductManager plmProductManager) {
        this.plmProductManager = plmProductManager;
    }

    public void setDefaultTenantId(String defaultTenantId) {
        this.defaultTenantId = defaultTenantId;
    }
}


text:
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.deserializer;

import java.util.Properties;

import javax.xml.namespace.QName;

import org.apache.axiom.om.OMAttribute;
import org.apache.axiom.om.OMElement;
import org.apache.synapse.Mediator;
import org.apache.synapse.SynapseConstants;
import org.apache.synapse.config.xml.AbstractMediatorFactory;
import org.wso2.carbon.mediator.bam.BamMediator;
import org.wso2.carbon.mediator.bam.config.stream.StreamConfiguration;

public class BamMediatorExtFactory extends AbstractMediatorFactory {

    public static final QName BAM_Q = new QName(SynapseConstants.SYNAPSE_NAMESPACE, "bam");

    public Mediator createSpecificMediator(OMElement omElement, Properties properties) {

        BamMediator bam = new BamMediator();

        bam.setServerProfile(this.getServerProfileName(omElement));
        bam.getStream().setStreamConfiguration(new StreamConfiguration());
        bam.getStream().getStreamConfiguration().setName(this.getStreamName(omElement));
        bam.getStream().getStreamConfiguration().setVersion(this.getStreamVersion(omElement));
        addAllCommentChildrenToList(omElement, bam.getCommentsList());

        return bam;
    }

    public QName getTagQName() {
        return BAM_Q;
    }

    private String getServerProfileName(OMElement omElement) {
        OMElement serverProfileElement = omElement
                .getFirstChildWithName(new QName(SynapseConstants.SYNAPSE_NAMESPACE, "serverProfile"));

        if (serverProfileElement != null) {
            OMAttribute serverProfileAttr = serverProfileElement.getAttribute(new QName("name"));
            if (serverProfileAttr != null) {
                return serverProfileAttr.getAttributeValue();
            }
        }
        return null;
    }

    private String getStreamName(OMElement omElement) {

        OMElement serverProfileElement = omElement
                .getFirstChildWithName(new QName(SynapseConstants.SYNAPSE_NAMESPACE, "serverProfile"));

        if (serverProfileElement != null) {
            OMElement streamConfigElement = serverProfileElement
                    .getFirstChildWithName(new QName(SynapseConstants.SYNAPSE_NAMESPACE, "streamConfig"));

            if (streamConfigElement != null) {
                OMAttribute streamNameAttr = streamConfigElement.getAttribute(new QName("name"));
                if (streamNameAttr != null) {
                    return streamNameAttr.getAttributeValue();
                }
            }
        }

        return null;
    }

    private String getStreamVersion(OMElement omElement) {

        OMElement serverProfileElement = omElement
                .getFirstChildWithName(new QName(SynapseConstants.SYNAPSE_NAMESPACE, "serverProfile"));

        if (serverProfileElement != null) {
            OMElement streamConfigElement = serverProfileElement
                    .getFirstChildWithName(new QName(SynapseConstants.SYNAPSE_NAMESPACE, "streamConfig"));

            if (streamConfigElement != null) {
                OMAttribute streamVersionAttr = streamConfigElement.getAttribute(new QName("version"));
                if (streamVersionAttr != null) {
                    return streamVersionAttr.getAttributeValue();
                }
            }
        }

        return null;
    }
}


text:
// Package constants contains well known constants for kind clusters
package constants

// DefaultClusterName is the default cluster Context name
const DefaultClusterName = "kind"

/* node role value constants */
const (
	// ControlPlaneNodeRoleValue identifies a node that hosts a Kubernetes
	// control-plane.
	//
	// NOTE: in single node clusters, control-plane nodes act as worker nodes
	ControlPlaneNodeRoleValue string = "control-plane"

	// WorkerNodeRoleValue identifies a node that hosts a Kubernetes worker
	WorkerNodeRoleValue string = "worker"

	// ExternalLoadBalancerNodeRoleValue identifies a node that hosts an
	// external load balancer for the API server in HA configurations.
	//
	// Please note that `kind` nodes hosting external load balancer are not
	// kubernetes nodes
	ExternalLoadBalancerNodeRoleValue string = "external-load-balancer"

	// ExternalEtcdNodeRoleValue identifies a node that hosts an external-etcd
	// instance.
	//
	// WARNING: this node type is not yet implemented!
	//
	// Please note that `kind` nodes hosting external etcd are not
	// kubernetes nodes
	ExternalEtcdNodeRoleValue string = "external-etcd"
)


text:
$.ajaxSetup({cache: false});

function updateShortDescription(quesID, short_des){
	document.removeChild(".edit-short")
}

function updateQuesVotes(quesID, type){
	var URL = new String('/question/')
	URL = URL.concat(quesID, '/vote/')
	console.log(URL)
	$.ajax({
		type: 'POST',
		url: URL,
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify({ voteType: type }),
		success: function(status){
			console.log(status)
			status = JSON.parse(status)
			if(type=='upvote')
				$(this).addClass('upvoted').removeClass("downvoted");
			else if(type=='downvote')
				$(this).addClass('downvoted').removeClass("upvoted");
			else
				$(this).removeClass("upvoted").removeClass("downvoted");
			if(status['type']=='notAllowed')
				alert('You are not allowed to vote your own question')
			else {
				document.getElementById("qvote-count").innerHTML = status['count']
				if(status['type']=='upvote')
					alert('You have successfully upvoted.')
				else if(status['type']=='downvote')
					alert('You have successfully downvoted.')
				else
					alert('Your vote has been removed.')
			}
		},
		cache: false
	});
}

function setBookmark(quesID){
	var URL = new String('/question/')
	URL = URL.concat(quesID, '/bookmark/')
	console.log(URL)
	$.ajax({
		type: 'POST',
		url: URL,
		contentType: 'application/json; charset=utf-8',
		success: function(status){
			console.log(status)
			status = JSON.parse(status)
			if(status['status'] == 'true')
				$(this).addClass('bookmarked')
			else
				$(this).removeClass("bookmarked")
			alert(status['message']);
		},
		cache: false
	});
}

function setQuesFlag(quesID){
	var URL = new String('/question/')
	URL = URL.concat(quesID, '/flag/')
	console.log(URL)
	$.ajax({
		type: 'POST',
		url: URL,
		contentType: 'application/json; charset=utf-8',
		success: function(status){
			console.log(status)
			status = JSON.parse(status)
			if(status['flag'] == 'flagged')
				$(this).addClass('flagged')
			else if(status['flag'] == 'flagRemoved')
				$(this).removeClass("flagged")
			alert(status['message']);
		},
		cache: false
	});
}

function updateAnsVotes(ansID, type){
	var URL = new String('/answer/')
	URL = URL.concat(ansID, '/vote/')
	console.log(URL)
	$.ajax({
		type: 'POST',
		url: URL,
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify({ voteType: type }),
		success: function(status){
			console.log(status)
			status = JSON.parse(status)
			if(type=='upvote')
				$(this).addClass('upvoted').removeClass("downvoted");
			else if(type=='downvote')
				$(this).addClass('downvoted').removeClass("upvoted");
			else
				$(this).removeClass("upvoted").removeClass("downvoted");
			if(status['type']=='notAllowed')
				alert('You are not allowed to vote your own answer')
			else {
				document.getElementById(ansID).getElementsByTagName("span")[0].innerHTML = status['count']
				if(status['type']=='upvote')
					alert('You have successfully upvoted.')
				else if(status['type']=='downvote')
					alert('You have successfully downvoted.')
				else
					alert('Your vote has been removed.')
			}
		},
		cache: false
	});
}

function setAnsFlag(ansID){
	var URL = new String('/answer/')
	URL = URL.concat(ansID, '/flag/')
	console.log(URL)
	$.ajax({
		type: 'POST',
		url: URL,
		contentType: 'application/json; charset=utf-8',
		success: function(status){
			console.log(status)
			status = JSON.parse(status)
			if(status['flag'] == 'flagged')
				$(this).addClass('flagged')
			else if(status['flag'] == 'flagRemoved')
				$(this).removeClass("flagged")
			alert(status['message']);
		},
		cache: false
	});
}

function setAcceptedAns(quesID, ansID){
	var URL = new String('/question/')
	URL = URL.concat(quesID, '/setAccepted/', ansID)
	console.log(URL)
	$.ajax({
		type: 'POST',
		url: URL,
		contentType: 'application/json; charset=utf-8',
		success: function(status){
			console.log(status)
			status = JSON.parse(status)
			if(status['status'] == 'set')
				$(this).addClass('accepted-on')
			else if(status['status'] == 'removed')
				$(this).removeClass("accepted-on")
			alert(status['message']);
		},
		cache: false
	});
}


text:
namespace NntpLib.Net
{
    public static class AuthExtensions
    {
        public static NntpResponse AuthInfoUser(this INntpConnection connection, string username)
        {
            var command = string.Format("AUTHINFO USER {0}", username);

            return connection.ExecuteCommand(command);
        }

        public static NntpResponse AuthInfoPass(this INntpConnection connection, string password)
        {
            var command = string.Format("AUTHINFO PASS {0}", password);

            return connection.ExecuteCommand(command);
        }

        public static NntpResponse AuthInfoSasl(this INntpConnection conneciton, string mechanism, string intitialResponse)
        {
            throw new PullRequestException();
        }
    }
}


text:
package org.apache.jackrabbit.core.integration.random.operation;

import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Session;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Arrays;

/**
 * OperationFactory hides operation instantiation.
 */
public class OperationFactory {

    private final Random rand = new Random();

    private final Session session;

    private int nodeCount = 0;

    public OperationFactory(Session s) {
        this.session = s;
    }

    /**
     * Creates a series of random content operations using nodes as
     * a source of nodes to operate on.
     */
    public Operation randomContentOperations(NodeIterator nodes,
                                             int minOperations,
                                             int maxOperations)
            throws Exception {
        return new RandomContentOperations(this, session, nodes,
                minOperations + rand.nextInt(maxOperations - minOperations));
    }

    /**
     * Creates random operations for all the nodes op returns on
     * {@link Operation#execute()}.
     */
    public Operation randomContentOperation(Operation op) throws Exception {
        NodeIterator it = op.execute();
        List ops = new ArrayList();
        while (it.hasNext()) {
            Node n = it.nextNode();
            String path = n.getPath();
            switch (rand.nextInt(3)) { // TODO keep in sync with case list
                case 0:
                    ops.add(new AddNode(session, path, "payload" + nodeCount++));
                    break;
                case 1:
                    // limit to 10 distinct properties
                    ops.add(new SetProperty(session, path, "prop" + rand.nextInt(10)));
                    break;
                case 2:
                    ops.add(new Remove(session, path, "payload"));
                    break;
            }
        }
        if (ops.size() == 1) {
            return (Operation) ops.get(0);
        } else {
            OperationSequence sequence = new OperationSequence(session, ops);
            return sequence;
        }
    }

    /**
     * Creates a series of random version operations using nodes as
     * a source of nodes to operate on.
     */
    public Operation randomVersionOperations(NodeIterator nodes,
                                             int minOperations,
                                             int maxOperations)
            throws Exception {
        return new RandomVersionOperations(this, session, nodes,
                minOperations + rand.nextInt(maxOperations - minOperations));
    }

    /**
     * Creates random operations for all the nodes op returns on
     * {@link Operation#execute()}.
     */
    public Operation randomVersionOperation(Operation op) throws Exception {
        NodeIterator it = op.execute();
        List ops = new ArrayList();
        while (it.hasNext()) {
            Node n = it.nextNode();
            String path = n.getPath();
            switch (rand.nextInt(6)) { // TODO keep in sync with case list
                case 0:
                    ops.add(new Checkin(session, path));
                    break;
                case 1:
                    ops.add(new Checkout(session, path));
                    break;
                case 2:
                    //ops.add(new Restore(session, path));
                    break;
                case 3:
                    ops.add(new AddVersionLabel(session, path));
                    break;
                case 4:
                    ops.add(new RemoveVersionLabel(session, path));
                    break;
                case 5:
                    ops.add(new RemoveVersion(session, path));
                    break;
            }
        }
        if (ops.size() == 1) {
            return (Operation) ops.get(0);
        } else {
            OperationSequence sequence = new OperationSequence(session, ops);
            return sequence;
        }
    }

    /**
     * Wraps an XA transaction operation around op.
     */
    public Operation runInTransaction(Operation op) {
        return new XATransaction(session, op);
    }

    /**
     * Creates a new operation that contains the passed ops.
     */
    public Operation runInSequence(Operation[] ops) {
        return new OperationSequence(session, Arrays.asList(ops));
    }

    /**
     * Creates a save operation on the node with the given path.
     */
    public Operation save(String path) {
        return new Save(session, path);
    }

    /**
     * Creates an operation the return the node with the given path.
     */
    public Operation getNode(String path) {
         return new GetNode(session, path);
    }

    /**
     * Creates an operation that returns all nodes that are visited by traversing
     * the node hierarchy starting at the node with the given path.
     */
    public Operation traverseNodes(String path) {
         return new TraverseNodes(session, path);
    }

    /**
     * Creates a node hierarchy.
     */
    public Operation createNodes(String path,
                                 int numLevels,
                                 int nodesPerLevel,
                                 String[] mixins,
                                 int saveInterval) {
        return new CreateNodes(session, path, numLevels,
                nodesPerLevel, mixins, saveInterval);
    }

    /**
     * Creates an iterator that randomly returns nodes produced by op.
     * Please note that the returned iterator always returns true
     * for {@link NodeIterator#hasNext()}!!!
     */
    public NodeIterator getRandomNodes(Operation op) throws Exception {
        return new GetRandomNodes(session, op).execute();
    }
}


text:
Reports references from a nested class to non-constant private members of an outer class.
For such references, javac will generate package-private synthetic accessor methods,
which may compromise the security because members appearing to be private will in fact be accessible from the entire package.

  A nested class and its outer class are compiled to separate
  class files. The Java virtual machine normally prohibits access from a class to private fields and methods of
  another class. To enable access from a nested class to private members of an outer class, javac creates a package-private
  synthetic accessor method.

  By making the private member package-private instead, the actual accessibility is made explicit.
  This also saves a little bit of memory, which may improve performance in resource constrained environments.

  This inspection only reports if the language level of the project or module is 10 or lower.
  Under Java 11 and higher accessor methods are not generated anymore,
  because of nest-based access control (JEP 181).

Example:

  class Outer {
    private void x() {}

    class Inner {
      void y() {
        x();
      }
    }
  }

After the quick fix is applied:

  class Outer {
    void x() {}

    class Inner {
      void y() {
        x();
      }
    }
  }


text:
@interface EZPAddressSynchronousTests : XCTestCase
@property (strong) EZPClient *client;
@end

@implementation EZPAddressSynchronousTests

- (void)setUp {
    [super setUp];
    self.client = [EZPClient defaultClient];
}

- (void)tearDown {
    self.client = nil;
    [super tearDown];
}

- (void)testCreateAndRetrieve {
    NSDictionary *parameters = [[self toAddress] toDictionaryWithPrefix:@"address"];
    EZPAddress *address = [self.client createAndVerifyAddressWithParameters:parameters];
    XCTAssertNotNil(address.itemId);
    XCTAssertEqualObjects(address.company.lowercaseString, @"Simpler Postage Inc".lowercaseString);
    XCTAssertNil(address.name);

    EZPAddress *retrieved = [self.client retrieveAddress:address.itemId];
    XCTAssertTrue([address.itemId isEqualToString:retrieved.itemId]);
}

- (void)testCreateInstance {
    EZPAddress *address = [self toAddress];
    [self.client createAddressSynchronously:address];
    XCTAssertNotNil(address.itemId);
}

- (void)testCreateAndVerify {
    NSDictionary *parameters = [[self toAddress] toDictionaryWithPrefix:@"address"];
    EZPAddress *address = [self.client createAndVerifyAddressWithParameters:parameters];
    XCTAssertNotNil(address.itemId);
    XCTAssertEqualObjects(address.company.lowercaseString, @"Simpler Postage Inc".lowercaseString);
    XCTAssertNil(address.name);
}

- (void)testVerify {
    NSDictionary *parameters = [[self toAddress] toDictionaryWithPrefix:@"address"];
    EZPAddress *address = [self.client createAddressWithParameters:parameters];
    [self.client verifyAddressSynchronously:address withCarrier:nil];

    XCTAssertNotNil(address.itemId);
    XCTAssertEqualObjects(address.company.lowercaseString, @"Simpler Postage Inc".lowercaseString);
    XCTAssertNil(address.name);
    XCTAssertTrue(address.residential);
}

- (void)testVerifyCarrier {
    NSDictionary *parameters = [[self toAddress] toDictionaryWithPrefix:@"address"];
    EZPAddress *address = [self.client createAddressWithParameters:parameters];
    [self.client verifyAddressSynchronously:address withCarrier:@"usps"];
    XCTAssertNotNil(address.itemId);
    XCTAssertEqualObjects(address.company.lowercaseString, @"Simpler Postage Inc".lowercaseString);
    // NOTE(rodionovd): apperently EasyPost combines street1 and street2 here
    XCTAssertEqualObjects([address.street1 stringByAppendingString:address.street2], @"164 TOWNSEND ST UNIT 1");
    XCTAssertNil(address.name);
}

- (void)testVerifyBeforeCreate {
    EZPAddress *address = [self toAddress];
    [self.client verifyAddressSynchronously:address withCarrier:nil];
    XCTAssertNotNil(address.itemId);
}

#pragma mark

- (EZPAddress *)toAddress {
    NSDictionary *toAddressDictionary = @{@"company": @"Simpler Postage Inc",
                                          @"street1": @"164 Townsend Street",
                                          @"street2": @"Unit 1",
                                          @"city": @"San Francisco",
                                          @"state": @"CA",
                                          @"country": @"US",
                                          @"zip": @"94107",
                                          @"residential": @YES};
    EZPAddress *toAddress = [[EZPAddress alloc] initWithDictionary:toAddressDictionary];
    XCTAssertNotNil(toAddress);
    return toAddress;
}

@end


text:
package com.vonage.client.voice.ncco;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class RecordingFormatTest {
    @Test
    public void testFromString() throws Exception {
        assertEquals(RecordingFormat.MP3, RecordingFormat.fromString("mp3"));
        assertEquals(RecordingFormat.WAV, RecordingFormat.fromString("wav"));
        assertEquals(RecordingFormat.UNKNOWN, RecordingFormat.fromString("test unknown"));
    }

    @Test
    public void testToString() throws Exception {
        assertEquals("mp3", RecordingFormat.MP3.toString());
        assertEquals("wav", RecordingFormat.WAV.toString());
    }
}


text:
using System;
using System.Collections.Generic;
using PX.SurveyMonkeyReader.Models;
using PX.SurveyMonkeyReader.Repository;

namespace PX.SurveyMonkeyReader
{
    public class SurveyMonkeyReader
    {
        private const int ResultsPerPage = 100;

        private readonly string _surveyId;
        private readonly ApiRepository _repository;

        public SurveyMonkeyReader(string surveyId, string accessToken)
        {
            _surveyId = surveyId;
            _repository = new ApiRepository(accessToken, ResultsPerPage);
        }

        public SurveyQuestion GetSurveyQuestion(long questionId)
        {
            return _repository.GetSingleSurveyQuestion(_surveyId, questionId);
        }

        public List<SurveyResponse> GetSurveyResponsesByDateRange(DateTime? startDate, DateTime? endDate = null)
        {
            var surveyLastModified = _repository.GetSurveyLastModifiedDateTime(_surveyId);

            var surveyResponses = new List<SurveyResponse>();
            int page = 1;
            bool isLastPage = false;
            do
            {
                var newSurveyResponses = _repository.GetSurveyResponsesByIdAndDateRange(_surveyId, startDate, endDate, page, out isLastPage);

                foreach (var response in newSurveyResponses)
                {
                    foreach (var question in response.Questions)
                    {
                        question.SurveyLastModified = surveyLastModified.GetValueOrDefault();
                    }
                }

                surveyResponses.AddRange(newSurveyResponses);

                page += 1;

            } while (!isLastPage);

            return surveyResponses;
        }
    }
}


text:
package kr.pe.kwonnam.freemarkerdynamicqlbuilder.directives;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.*;
import org.junit.Before;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
public class AbstractQlDirectiveTest {
    private Configuration freemarkerConfiguration;

    private StringTemplateLoader templateLoader;

    private Map<String, Object> dataModel;

    @Before
    public void setUp() throws Exception {
        freemarkerConfiguration = new Configuration(Configuration.VERSION_2_3_23);

        templateLoader = new StringTemplateLoader();

        freemarkerConfiguration.setTemplateLoader(templateLoader);
        freemarkerConfiguration.setDefaultEncoding("UTF-8");
        freemarkerConfiguration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        freemarkerConfiguration.setNumberFormat("0.######");

        Map<String, TemplateDirectiveModel> qlDirectives = new HashMap<String, TemplateDirectiveModel>();
        qlDirectives.put("trim", new TrimDirective());
        qlDirectives.put("where", new WhereDirective());
        qlDirectives.put("set", new SetDirective());

        freemarkerConfiguration.setSharedVariable("ql", qlDirectives);

        dataModel = new HashMap<String, Object>();
    }

    protected String processTemplate(String templateSource) throws IOException, TemplateException {
        Template template = new Template("template", templateSource, freemarkerConfiguration);
        StringWriter out = new StringWriter();

        template.process(dataModel, out);

        return out.toString();
    }

}


text:
<?php

namespace Lexik\Bundle\FormFilterBundle\Filter\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Filter type for date range field.
 *
 * @author Cédric Girard <c.girard@lexik.fr>
 */
class DateTimeRangeFilterType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('left_datetime', DateTimeFilterType::class, $options['left_datetime_options']);
        $builder->add('right_datetime', DateTimeFilterType::class, $options['right_datetime_options']);

        $builder->setAttribute('filter_value_keys', array(
            'left_datetime'  => $options['left_datetime_options'],
            'right_datetime' => $options['right_datetime_options'],
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver
            ->setDefaults(array(
                'required'               => false,
                'left_datetime_options'  => array(),
                'right_datetime_options' => array(),
                'data_extraction_method' => 'value_keys',
            ))
            ->setAllowedValues('data_extraction_method', array('value_keys'))
        ;
    }

    /**
     * @return string
     */
    public function getBlockPrefix()
    {
        return 'filter_datetime_range';
    }
}


text: # Learning Track App


text:
package com.webcohesion.enunciate.modules.c_client;

import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.template.Configuration;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;

import java.util.List;
import java.util.Map;

/**
 * A method used in templates to output the prefix for a given namespace.
 *
 * @author Ryan Heaton
 */
public class PrefixMethod implements TemplateMethodModelEx {

  private final Map<String, String> ns2prefix;

  public PrefixMethod(Map<String, String> ns2prefix) {
    this.ns2prefix = ns2prefix;
  }

  /**
   * Returns the qname of the element that has the first parameter as the namespace, the second as the element.
   *
   * @param list The arguments.
   * @return The qname.
   */
  public Object exec(List list) throws TemplateModelException {
    if (list.size() < 1) {
      throw new TemplateModelException("The prefix method must have a namespace as a parameter.");
    }

    String namespace = (String) new BeansWrapperBuilder(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS).build().unwrap((TemplateModel) list.get(0));
    String prefix = this.ns2prefix.get(namespace);
    if (prefix == null) {
      throw new TemplateModelException("No prefix specified for {" + namespace + "}");
    }
    return CXMLClientModule.scrubIdentifier(prefix);
  }

}


text:
<?php namespace OneAuth\OAuth;

abstract class Token
{
	/**
	 * Create a new token object.
	 *
	 *     $token = Token::make($name);
	 *
	 * @param   string  token type
	 * @param   array   token options
	 * @return  Token
	 */
	public static function make($name, array $options = NULL)
	{
		switch ($name)
		{
			case 'access' :
				return new Token\Access($options);
				break;
			case 'request' :
				return new Token\Request($options);
				break;
		}
	}

	/**
	 * @var  string  token type name: request, access
	 */
	protected $name;

	/**
	 * @var  string  access token key
	 */
	protected $access_token;

	/**
	 * @var  string  token secret
	 */
	protected $secret;

	/**
	 * @var  string  refresh token key
	 */
	protected $refresh_token;

	/**
	 * @var  string  uid
	 */
	protected $uid;

	/**
	 * Sets the token and secret values.
	 *
	 * @param   array   token options
	 * @return  void
	 */
	public function __construct(array $options = NULL)
	{
		if ( ! isset($options['access_token']))
		{
			throw new Exception('Required option not passed: access_token');
		}

		if ( ! isset($options['secret']))
		{
			throw new Exception('Required option not passed: secret');
		}

		$this->access_token = $options['access_token'];

		$this->secret = $options['secret'];

		// If we have a uid lets use it
		array_get($options, 'uid') and $this->uid = $options['uid'];
	}

	/**
	 * Return the value of any protected class variable.
	 *
	 *     // Get the token secret
	 *     $secret = $token->secret;
	 *
	 * @param   string  variable name
	 * @return  mixed
	 */
	public function __get($key)
	{
		return $this->$key;
	}

	/**
	 * Return a boolean if the property is set
	 *
	 *     // Get the token secret
	 *     if ($token->secret) exit('YAY SECRET');
	 *
	 * @param   string  variable name
	 * @return  bool
	 */
	public function __isset($key)
	{
		return isset($this->$key);
	}

	/**
	 * Returns the token key.
	 *
	 * @return  string
	 */
	public function __toString()
	{
		return (string) $this->access_token;
	}
}