<commit_before>/*
 * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the <organization> nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "CppUTest/TestHarness.h"
#include "CppUTest/SimpleString.h"
#include "CppUTest/Extensions/SimpleStringFromStdInt.h"
#include <stdint.h>

TEST_GROUP(SimpleStringFromStdint)
{
};

using namespace std;

//uint64_t silently not supported in C++
TEST(SimpleStringFromStdint, Uint64_t)
{
//I'd like this test, but can't get it to pass
//    uint64_t = 0xffffffffffffffff;
//
//    SimpleString result = StringFrom(i);
//    CHECK_EQUAL("18446744073709551615 (0xffffffffffffffff)", result);

    uint64_t i = 10;
    SimpleString result = StringFrom(i);
    CHECK_EQUAL("uint64_t not supported", result);

}

TEST(SimpleStringFromStdint, Int64_t)
{
//I'd like this test, but can't get it to pass
//    int64_t i = 0xffffffffffffffff>>1;
//
//    SimpleString result = StringFrom(i);
//    CHECK_EQUAL("something", result);

    int64_t i = 10;
    SimpleString result = StringFrom(i);
    CHECK_EQUAL("int64_t not supported", result);

}

TEST(SimpleStringFromStdint, Uint32_t)
{
    uint32_t i = 0xffffffff;

    SimpleString result = StringFrom(i);
    CHECK_EQUAL("4294967295 (0xffffffff)", result);
}

TEST(SimpleStringFromStdint, Uint16_t)
{
    uint16_t i = 0xffff;

    SimpleString result = StringFrom(i);
    CHECK_EQUAL("65535 (0xffff)", result);
}

TEST(SimpleStringFromStdint, Uint8_t)
{
    uint8_t i = 0xff;

    SimpleString result = StringFrom(i);
    CHECK_EQUAL("255 (0xff)", result);
}

IGNORE_TEST(SimpleStringFromStdint, CHECK_EQUAL_Uint64_t)
{
//    uint64_t i = 0xffffffffffffffff;
//    CHECK_EQUAL(i, i);
}

TEST(SimpleStringFromStdint, CHECK_EQUAL_Uint32_t)
{
    uint32_t i = 0xffffffff;
    CHECK_EQUAL(i, i);
}

TEST(SimpleStringFromStdint, CHECK_EQUAL_Uint16_t)
{
    uint16_t i = 0xffff;
    CHECK_EQUAL(i, i);
}

TEST(SimpleStringFromStdint, CHECK_EQUAL_Uint8_t)
{
    uint8_t i = 0xff;
    CHECK_EQUAL(i, i);
}

<commit_msg>I -> i<commit_after>/*
 * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the <organization> nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "CppUTest/TestHarness.h"
#include "CppUTest/SimpleString.h"
#include "CppUTest/Extensions/SimpleStringFromStdint.h"
#include <stdint.h>

TEST_GROUP(SimpleStringFromStdint)
{
};

using namespace std;

//uint64_t silently not supported in C++
TEST(SimpleStringFromStdint, Uint64_t)
{
//I'd like this test, but can't get it to pass
//    uint64_t = 0xffffffffffffffff;
//
//    SimpleString result = StringFrom(i);
//    CHECK_EQUAL("18446744073709551615 (0xffffffffffffffff)", result);

    uint64_t i = 10;
    SimpleString result = StringFrom(i);
    CHECK_EQUAL("uint64_t not supported", result);

}

TEST(SimpleStringFromStdint, Int64_t)
{
//I'd like this test, but can't get it to pass
//    int64_t i = 0xffffffffffffffff>>1;
//
//    SimpleString result = StringFrom(i);
//    CHECK_EQUAL("something", result);

    int64_t i = 10;
    SimpleString result = StringFrom(i);
    CHECK_EQUAL("int64_t not supported", result);

}

TEST(SimpleStringFromStdint, Uint32_t)
{
    uint32_t i = 0xffffffff;

    SimpleString result = StringFrom(i);
    CHECK_EQUAL("4294967295 (0xffffffff)", result);
}

TEST(SimpleStringFromStdint, Uint16_t)
{
    uint16_t i = 0xffff;

    SimpleString result = StringFrom(i);
    CHECK_EQUAL("65535 (0xffff)", result);
}

TEST(SimpleStringFromStdint, Uint8_t)
{
    uint8_t i = 0xff;

    SimpleString result = StringFrom(i);
    CHECK_EQUAL("255 (0xff)", result);
}

IGNORE_TEST(SimpleStringFromStdint, CHECK_EQUAL_Uint64_t)
{
//    uint64_t i = 0xffffffffffffffff;
//    CHECK_EQUAL(i, i);
}

TEST(SimpleStringFromStdint, CHECK_EQUAL_Uint32_t)
{
    uint32_t i = 0xffffffff;
    CHECK_EQUAL(i, i);
}

TEST(SimpleStringFromStdint, CHECK_EQUAL_Uint16_t)
{
    uint16_t i = 0xffff;
    CHECK_EQUAL(i, i);
}

TEST(SimpleStringFromStdint, CHECK_EQUAL_Uint8_t)
{
    uint8_t i = 0xff;
    CHECK_EQUAL(i, i);
}

<|endoftext|>


<commit_before>/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */
/* vim:set et sw=4 ts=4 sts=4: */
#include "ut_wallpaperwidget.h"
#include "wallpaperwidget.h"
#include "wallpaperbusinesslogic.h"
#include "wallpaperdescriptor.h"
#include "wallpapercurrentdescriptor.h"
#include "wallpapermodel.h"

#include <MApplication>

//#define DEBUG
#include "../../src/debug.h"

/******************************************************************************
 * SignalSink implementation.
 */
SignalSink::SignalSink () :
    m_ChangeWidgetCame (false)
{
    m_WidgetID = 0;
}

void
SignalSink::changeWidget (
		int widgetId)
{
    m_ChangeWidgetCame = true;
    m_WidgetID = widgetId;
}

void
SignalSink::reset()
{
    m_WallpaperImageEditRequestedCame = false;
}

void
SignalSink::imageEditRequested()
{
    SYS_DEBUG ("");
    m_WallpaperImageEditRequestedCame = true;
}
/******************************************************************************
 * Ut_WallpaperWidget implementation.
 */
void
Ut_WallpaperWidget::init()
{
}

void
Ut_WallpaperWidget::cleanup()
{
}

static int argc = 1;
static char *app_name = (char*) "./Ut_WallpaperWidget";

void
Ut_WallpaperWidget::initTestCase()
{
    bool connectSuccess;

    m_App = new MApplication (argc, &app_name);
    m_BusinessLogic = new WallpaperBusinessLogic;

    m_Widget = new WallpaperWidget (m_BusinessLogic);
    connectSuccess = connect (
            m_Widget, SIGNAL(changeWidget(int)),
            &m_Sink, SLOT(changeWidget(int)));
    QVERIFY(connectSuccess);

    connectSuccess = connect(
            m_BusinessLogic, SIGNAL(imageEditRequested()),
            &m_Sink, SLOT(imageEditRequested()));
    QVERIFY(connectSuccess);

    QTest::qWait (150);
    QVERIFY (m_Widget->m_ImageList);
}

void
Ut_WallpaperWidget::cleanupTestCase()
{
    delete m_BusinessLogic;
    delete m_Widget;
    m_App->deleteLater ();
}

/*!
 * Tests what happens when a decriptor is activated. The widget have to set the
 * edited image in the businesslogic and it has to send a signal to show that
 * the editor widget should be shown.
 * FIXME:
 *   1) maybe we could send a signal of the list, that way we could check the
 *   connection also.
 *   2) Maybe we should not use the literal 1 here.
 */
void
Ut_WallpaperWidget::testImageActivated ()
{
    WallpaperDescriptor *curr = WallpaperCurrentDescriptor::instance ();

    m_Widget->slotImageActivated (curr);
    // The loading of the image is happening in a separate thread, we need to
    // give a chance to be executed.
    QTest::qWait (500);

    QVERIFY (m_Widget->m_WallpaperBusinessLogic->editedImage() == curr);
    QVERIFY (m_Sink.m_ChangeWidgetCame);
    QVERIFY (m_Sink.m_WidgetID == 1);
}

void
Ut_WallpaperWidget::testGalleryImageSelected()
{
    m_Widget->galleryImageSelected("file:///nodir/NoSuchFile.png");
    QVERIFY(m_Sink.m_WallpaperImageEditRequestedCame);
}

void
Ut_WallpaperWidget::testImageBrowserDismissed()
{
    m_Widget->imageBrowserDismissed();
    QVERIFY (m_Widget->m_noImageBrowser);
}

QTEST_APPLESS_MAIN(Ut_WallpaperWidget)

<commit_msg>Trying to fix a test case.<commit_after>/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */
/* vim:set et sw=4 ts=4 sts=4: */
#include "ut_wallpaperwidget.h"
#include "wallpaperwidget.h"
#include "wallpaperbusinesslogic.h"
#include "wallpaperdescriptor.h"
#include "wallpapercurrentdescriptor.h"
#include "wallpapermodel.h"

#include <MApplication>

//#define DEBUG
#include "../../src/debug.h"

/******************************************************************************
 * SignalSink implementation.
 */
SignalSink::SignalSink () :
    m_ChangeWidgetCame (false)
{
    m_WidgetID = 0;
}

void
SignalSink::changeWidget (
		int widgetId)
{
    m_ChangeWidgetCame = true;
    m_WidgetID = widgetId;
}

void
SignalSink::reset()
{
    m_WallpaperImageEditRequestedCame = false;
}

void
SignalSink::imageEditRequested()
{
    SYS_DEBUG ("");
    m_WallpaperImageEditRequestedCame = true;
}
/******************************************************************************
 * Ut_WallpaperWidget implementation.
 */
void
Ut_WallpaperWidget::init()
{
}

void
Ut_WallpaperWidget::cleanup()
{
}

static int argc = 1;
static char *app_name = (char*) "./Ut_WallpaperWidget";

void
Ut_WallpaperWidget::initTestCase()
{
    bool connectSuccess;

    m_App = new MApplication (argc, &app_name);
    m_BusinessLogic = new WallpaperBusinessLogic;

    m_Widget = new WallpaperWidget (m_BusinessLogic);
    connectSuccess = connect (
            m_Widget, SIGNAL(changeWidget(int)),
            &m_Sink, SLOT(changeWidget(int)));
    QVERIFY(connectSuccess);

    connectSuccess = connect(
            m_BusinessLogic, SIGNAL(imageEditRequested()),
            &m_Sink, SLOT(imageEditRequested()));
    QVERIFY(connectSuccess);

    QTest::qWait (150);
    QVERIFY (m_Widget->m_ImageList);
}

void
Ut_WallpaperWidget::cleanupTestCase()
{
    delete m_BusinessLogic;
    delete m_Widget;
    m_App->deleteLater ();
}

/*!
 * Tests what happens when a decriptor is activated. The widget have to set the
 * edited image in the businesslogic and it has to send a signal to show that
 * the editor widget should be shown.
 * FIXME:
 *   1) maybe we could send a signal of the list, that way we could check the
 *   connection also.
 *   2) Maybe we should not use the literal 1 here.
 */
void
Ut_WallpaperWidget::testImageActivated ()
{
    WallpaperDescriptor *curr = WallpaperCurrentDescriptor::instance ();

    m_Widget->slotImageActivated (curr);
    // The loading of the image is happening in a separate thread, we need to
    // give a chance to be executed.
    QTest::qWait (500);

    QVERIFY (m_Widget->m_WallpaperBusinessLogic->editedImage() == curr);
    QVERIFY (m_Sink.m_ChangeWidgetCame);
    QVERIFY (m_Sink.m_WidgetID == 1);
}

void
Ut_WallpaperWidget::testGalleryImageSelected()
{
    m_Widget->galleryImageSelected("file:///nodir/NoSuchFile.png");
    // The loading of the image is happening in a separate thread, we need to
    // give a chance to be executed.
    QTest::qWait (500);
    QVERIFY(m_Sink.m_WallpaperImageEditRequestedCame);
}

void
Ut_WallpaperWidget::testImageBrowserDismissed()
{
    m_Widget->imageBrowserDismissed();
    QVERIFY (m_Widget->m_noImageBrowser);
}

QTEST_APPLESS_MAIN(Ut_WallpaperWidget)

<|endoftext|>


<commit_before>/***********************************************************************
    filename:   CEGUIAnimationInstance.cpp
    created:    7/8/2010
    author:     Martin Preisler

    purpose:    Implements the AnimationInstance class
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUIAnimationInstance.h"
#include "CEGUIAnimation.h"
#include "CEGUIExceptions.h"
#include "CEGUIWindow.h"
#include "CEGUIAffector.h"

// Start of CEGUI namespace section
namespace CEGUI
{

//----------------------------------------------------------------------------//
const String AnimationInstance::EventNamespace("AnimationInstance");

const String AnimationInstance::EventAnimationStarted("AnimationStarted");
const String AnimationInstance::EventAnimationStopped("AnimationStopped");
const String AnimationInstance::EventAnimationPaused("AnimationPaused");
const String AnimationInstance::EventAnimationUnpaused("AnimationUnpaused");
const String AnimationInstance::EventAnimationEnded("AnimationEnded");
const String AnimationInstance::EventAnimationLooped("AnimationLooped");

//----------------------------------------------------------------------------//
AnimationInstance::AnimationInstance(Animation* definition):
    d_definition(definition),

    d_target(0),
    d_eventReceiver(0),
    d_eventSender(0),

    d_position(0.0),
    d_speed(1.0),
    d_bounceBackwards(false),
    d_running(false),
    d_skipNextStep(false),
    // default behaviour is to never skip
    d_maxStepDeltaSkip(-1.0f),
    // default behaviour is to never clamp
    d_maxStepDeltaClamp(-1.0f)
{}

//----------------------------------------------------------------------------//
AnimationInstance::~AnimationInstance(void)
{
    if (d_eventSender)
    {
        d_definition->autoUnsubscribe(this);
    }
}

//----------------------------------------------------------------------------//
Animation* AnimationInstance::getDefinition() const
{
    return d_definition;
}

//----------------------------------------------------------------------------//
void AnimationInstance::setTarget(PropertySet* target)
{
    d_target = target;

    purgeSavedPropertyValues();

    if (d_definition->getAutoStart() && !isRunning())
    {
        start();
    }
}

//----------------------------------------------------------------------------//
PropertySet* AnimationInstance::getTarget() const
{
    return d_target;
}

//----------------------------------------------------------------------------//
void AnimationInstance::setEventReceiver(EventSet* receiver)
{
    d_eventReceiver = receiver;
}

//----------------------------------------------------------------------------//
EventSet* AnimationInstance::getEventReceiver() const
{
    return d_eventReceiver;
}

//----------------------------------------------------------------------------//
void AnimationInstance::setEventSender(EventSet* sender)
{
    if (d_eventSender)
    {
        d_definition->autoUnsubscribe(this);
    }

    d_eventSender = sender;

    if (d_eventSender)
    {
        d_definition->autoSubscribe(this);
    }
}

//----------------------------------------------------------------------------//
EventSet* AnimationInstance::getEventSender() const
{
    return d_eventSender;
}

//----------------------------------------------------------------------------//
void AnimationInstance::setTargetWindow(Window* target)
{
    setTarget(target);
    setEventReceiver(target);
    setEventSender(target);
}

//----------------------------------------------------------------------------//
void AnimationInstance::setPosition(float position)
{
    if (position < 0.0 || position > d_definition->getDuration())
    {
        CEGUI_THROW(InvalidRequestException(
                        "AnimationInstance::setPosition: Unable to set position "
                        "of this animation instace because given position isn't "
                        "in interval [0.0, duration of animation]."));
    }

    d_position = position;
}

//----------------------------------------------------------------------------//
float AnimationInstance::getPosition() const
{
    return d_position;
}

//----------------------------------------------------------------------------//
void AnimationInstance::setSpeed(float speed)
{
    // first sort out the adventurous users
    if (speed < 0.0f)
    {
        CEGUI_THROW(InvalidRequestException(
                        "AnimationInstance::setSpeed: You can't set playback speed "
                        "to a value that's lower than 0.0"));
    }

    if (speed == 0.0f)
    {
        CEGUI_THROW(InvalidRequestException(
                        "AnimationInstance::setSpeed: You can't set playback speed "
                        "to zero, please use AnimationInstance::pause instead"));
    }

    d_speed = speed;
}

//----------------------------------------------------------------------------//
float AnimationInstance::getSpeed() const
{
    return d_speed;
}

//----------------------------------------------------------------------------//
void AnimationInstance::setSkipNextStep(bool skip)
{
    d_skipNextStep = skip;
}

//----------------------------------------------------------------------------//
bool AnimationInstance::getSkipNextStep() const
{
    return d_skipNextStep;
}

//----------------------------------------------------------------------------//
void AnimationInstance::setMaxStepDeltaSkip(float maxDelta)
{
    d_maxStepDeltaSkip = maxDelta;
}

//----------------------------------------------------------------------------//
float AnimationInstance::getMaxStepDeltaSkip() const
{
    return d_maxStepDeltaSkip;
}

//----------------------------------------------------------------------------//
void AnimationInstance::setMaxStepDeltaClamp(float maxDelta)
{
    d_maxStepDeltaClamp = maxDelta;
}

//----------------------------------------------------------------------------//
float AnimationInstance::getMaxStepDeltaClamp() const
{
    return d_maxStepDeltaClamp;
}

//----------------------------------------------------------------------------//
void AnimationInstance::start(bool skipNextStep)
{
    setPosition(0.0);
    d_running = true;
    d_skipNextStep = skipNextStep;
    onAnimationStarted();
}

//----------------------------------------------------------------------------//
void AnimationInstance::stop()
{
    setPosition(0.0);
    d_running = false;
    onAnimationStopped();
}

//----------------------------------------------------------------------------//
void AnimationInstance::pause()
{
    d_running = false;
    onAnimationPaused();
}

//----------------------------------------------------------------------------//
void AnimationInstance::unpause(bool skipNextStep)
{
    d_running = true;
    d_skipNextStep = skipNextStep;
    onAnimationUnpaused();
}

//----------------------------------------------------------------------------//
void AnimationInstance::togglePause(bool skipNextStep)
{
    if (isRunning())
    {
        pause();
    }
    else
    {
        unpause(skipNextStep);
    }
}

//----------------------------------------------------------------------------//
bool AnimationInstance::isRunning() const
{
    return d_running;
}

//----------------------------------------------------------------------------//
void AnimationInstance::step(float delta)
{
    if (!d_running)
    {
        // nothing to do if this animation instance isn't running
        return;
    }

    if (delta < 0.0f)
    {
        CEGUI_THROW(InvalidRequestException(
                        "AnimationInstance::step: You can't step the Animation Instance "
                        "with negative delta! You can't reverse the flow of time, stop "
                        "trying!"));
    }

    // first we deal with delta size
    if (d_maxStepDeltaSkip > 0.0f && delta > d_maxStepDeltaSkip)
    {
        // skip the step entirely if delta gets over the threshold
        // note that default value is 0.0f which means this never gets triggered
        delta = 0.0f;
    }

    if (d_maxStepDeltaClamp > 0.0f)
    {
        // clamp to threshold, note that default value is -1.0f which means
        // this line does nothing (delta should always be larger or equal than 0.0f
        delta = std::min(delta, d_maxStepDeltaClamp);
    }

    // if asked to do so, we skip this step, but mark that the next one
    // shouldn't be skipped
    // NB: This gets rid of annoying animation skips when FPS gets too low
    //     after complex layout loading, etc...
    if (d_skipNextStep)
    {
        d_skipNextStep = false;
        // we skip the step by setting delta to 0, this doesn't step the time
        // but still sets the animation position accordingly
        delta = 0.0f;
    }

    const float duration = d_definition->getDuration();

    // we modify the delta according to playback speed
    delta *= d_speed;

    // the position could have gotten out of the desired range, we have to
    // alter it depending on replay method of our animation definition

    // first a simple clamp with RM_Once
    if (d_definition->getReplayMode() == Animation::RM_Once)
    {
        float newPosition = d_position + delta;

        newPosition = std::max(0.0f, newPosition);

        if (newPosition >= duration)
        {
            newPosition = duration;

            stop();
            onAnimationEnded();
        }

        setPosition(newPosition);
    }
    // a both sided wrap with RM_Loop
    else if (d_definition->getReplayMode() == Animation::RM_Loop)
    {
        float newPosition = d_position + delta;

        while (newPosition > duration)
        {
            newPosition -= duration;
            onAnimationLooped();
        }

        setPosition(newPosition);
    }
    // bounce back and forth with RM_Bounce
    else if (d_definition->getReplayMode() == Animation::RM_Bounce)
    {
        if (d_bounceBackwards)
        {
            delta = -delta;
        }

        float newPosition = d_position + delta;

        while (newPosition <= 0 || newPosition > duration)
        {
            if (newPosition <= 0)
            {
                d_bounceBackwards = false;

                newPosition = -newPosition;
                onAnimationLooped();
            }

            if (newPosition > duration)
            {
                d_bounceBackwards = true;

                newPosition = 2.0f * duration - newPosition;
                onAnimationLooped();
            }
        }

        setPosition(newPosition);
    }

    apply();
}

//----------------------------------------------------------------------------//
bool AnimationInstance::handleStart(const CEGUI::EventArgs& e)
{
    start();

    return true;
}

//----------------------------------------------------------------------------//
bool AnimationInstance::handleStop(const CEGUI::EventArgs& e)
{
    stop();

    return true;
}

//----------------------------------------------------------------------------//
bool AnimationInstance::handlePause(const CEGUI::EventArgs& e)
{
    pause();

    return true;
}

//----------------------------------------------------------------------------//
bool AnimationInstance::handleUnpause(const CEGUI::EventArgs& e)
{
    unpause();

    return true;
}

//----------------------------------------------------------------------------//
bool AnimationInstance::handleTogglePause(const CEGUI::EventArgs& e)
{
    togglePause();

    return true;
}

//----------------------------------------------------------------------------//
void AnimationInstance::savePropertyValue(const String& propertyName)
{
    assert(d_target);

    d_savedPropertyValues[propertyName] = d_target->getProperty(propertyName);
}

//----------------------------------------------------------------------------//
void AnimationInstance::purgeSavedPropertyValues(void)
{
    d_savedPropertyValues.clear();
}

//----------------------------------------------------------------------------//
const String& AnimationInstance::getSavedPropertyValue(const String& propertyName)
{
    PropertyValueMap::iterator it = d_savedPropertyValues.find(propertyName);

    if (it == d_savedPropertyValues.end())
    {
        // even though we explicitly save all used property values when
        // starting the animation, this can happen when user changes
        // animation definition whilst the animation is running
        // (Yes, it's nasty, but people do nasty things)
        savePropertyValue(propertyName);
        return getSavedPropertyValue(propertyName);
    }

    return it->second;
}

//----------------------------------------------------------------------------//
void AnimationInstance::addAutoConnection(Event::Connection conn)
{
    d_autoConnections.push_back(conn);
}

//----------------------------------------------------------------------------//
void AnimationInstance::unsubscribeAutoConnections()
{
    for (ConnectionTracker::iterator it = d_autoConnections.begin();
         it != d_autoConnections.end(); ++it)
    {
        (*it)->disconnect();
    }

    d_autoConnections.clear();
}

//----------------------------------------------------------------------------//
void AnimationInstance::apply()
{
    if (d_target)
    {
        d_definition->apply(this);
    }
}

//----------------------------------------------------------------------------//
void AnimationInstance::onAnimationStarted()
{
    purgeSavedPropertyValues();
    d_definition->savePropertyValues(this);

    if (d_eventReceiver)
    {
        AnimationEventArgs args(this);
        d_eventReceiver->fireEvent(EventAnimationStarted, args, EventNamespace);
    }
}

//----------------------------------------------------------------------------//
void AnimationInstance::onAnimationStopped()
{
    if (d_eventReceiver)
    {
        AnimationEventArgs args(this);
        d_eventReceiver->fireEvent(EventAnimationStopped, args, EventNamespace);
    }
}

//----------------------------------------------------------------------------//
void AnimationInstance::onAnimationPaused()
{
    if (d_eventReceiver)
    {
        AnimationEventArgs args(this);
        d_eventReceiver->fireEvent(EventAnimationPaused, args, EventNamespace);
    }
}

//----------------------------------------------------------------------------//
void AnimationInstance::onAnimationUnpaused()
{
    if (d_eventReceiver)
    {
        AnimationEventArgs args(this);
        d_eventReceiver->fireEvent(EventAnimationUnpaused, args, EventNamespace);
    }
}

//----------------------------------------------------------------------------//
void AnimationInstance::onAnimationEnded()
{
    if (d_eventReceiver)
    {
        AnimationEventArgs args(this);
        d_eventReceiver->fireEvent(EventAnimationEnded, args, EventNamespace);
    }
}

//----------------------------------------------------------------------------//
void AnimationInstance::onAnimationLooped()
{
    if (d_eventReceiver)
    {
        AnimationEventArgs args(this);
        d_eventReceiver->fireEvent(EventAnimationLooped, args, EventNamespace);
    }
}

//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section

<commit_msg>Do not start or unpause an animation with no definition or 0 duration<commit_after>/***********************************************************************
    filename:   CEGUIAnimationInstance.cpp
    created:    7/8/2010
    author:     Martin Preisler

    purpose:    Implements the AnimationInstance class
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUIAnimationInstance.h"
#include "CEGUIAnimation.h"
#include "CEGUIExceptions.h"
#include "CEGUIWindow.h"
#include "CEGUIAffector.h"
#include "CEGUILogger.h"

// Start of CEGUI namespace section
namespace CEGUI
{

//----------------------------------------------------------------------------//
const String AnimationInstance::EventNamespace("AnimationInstance");

const String AnimationInstance::EventAnimationStarted("AnimationStarted");
const String AnimationInstance::EventAnimationStopped("AnimationStopped");
const String AnimationInstance::EventAnimationPaused("AnimationPaused");
const String AnimationInstance::EventAnimationUnpaused("AnimationUnpaused");
const String AnimationInstance::EventAnimationEnded("AnimationEnded");
const String AnimationInstance::EventAnimationLooped("AnimationLooped");

//----------------------------------------------------------------------------//
AnimationInstance::AnimationInstance(Animation* definition):
    d_definition(definition),

    d_target(0),
    d_eventReceiver(0),
    d_eventSender(0),

    d_position(0.0),
    d_speed(1.0),
    d_bounceBackwards(false),
    d_running(false),
    d_skipNextStep(false),
    // default behaviour is to never skip
    d_maxStepDeltaSkip(-1.0f),
    // default behaviour is to never clamp
    d_maxStepDeltaClamp(-1.0f)
{}

//----------------------------------------------------------------------------//
AnimationInstance::~AnimationInstance(void)
{
    if (d_eventSender)
    {
        d_definition->autoUnsubscribe(this);
    }
}

//----------------------------------------------------------------------------//
Animation* AnimationInstance::getDefinition() const
{
    return d_definition;
}

//----------------------------------------------------------------------------//
void AnimationInstance::setTarget(PropertySet* target)
{
    d_target = target;

    purgeSavedPropertyValues();

    if (d_definition->getAutoStart() && !isRunning())
    {
        start();
    }
}

//----------------------------------------------------------------------------//
PropertySet* AnimationInstance::getTarget() const
{
    return d_target;
}

//----------------------------------------------------------------------------//
void AnimationInstance::setEventReceiver(EventSet* receiver)
{
    d_eventReceiver = receiver;
}

//----------------------------------------------------------------------------//
EventSet* AnimationInstance::getEventReceiver() const
{
    return d_eventReceiver;
}

//----------------------------------------------------------------------------//
void AnimationInstance::setEventSender(EventSet* sender)
{
    if (d_eventSender)
    {
        d_definition->autoUnsubscribe(this);
    }

    d_eventSender = sender;

    if (d_eventSender)
    {
        d_definition->autoSubscribe(this);
    }
}

//----------------------------------------------------------------------------//
EventSet* AnimationInstance::getEventSender() const
{
    return d_eventSender;
}

//----------------------------------------------------------------------------//
void AnimationInstance::setTargetWindow(Window* target)
{
    setTarget(target);
    setEventReceiver(target);
    setEventSender(target);
}

//----------------------------------------------------------------------------//
void AnimationInstance::setPosition(float position)
{
    if (position < 0.0 || position > d_definition->getDuration())
    {
        CEGUI_THROW(InvalidRequestException(
                        "AnimationInstance::setPosition: Unable to set position "
                        "of this animation instace because given position isn't "
                        "in interval [0.0, duration of animation]."));
    }

    d_position = position;
}

//----------------------------------------------------------------------------//
float AnimationInstance::getPosition() const
{
    return d_position;
}

//----------------------------------------------------------------------------//
void AnimationInstance::setSpeed(float speed)
{
    // first sort out the adventurous users
    if (speed < 0.0f)
    {
        CEGUI_THROW(InvalidRequestException(
                        "AnimationInstance::setSpeed: You can't set playback speed "
                        "to a value that's lower than 0.0"));
    }

    if (speed == 0.0f)
    {
        CEGUI_THROW(InvalidRequestException(
                        "AnimationInstance::setSpeed: You can't set playback speed "
                        "to zero, please use AnimationInstance::pause instead"));
    }

    d_speed = speed;
}

//----------------------------------------------------------------------------//
float AnimationInstance::getSpeed() const
{
    return d_speed;
}

//----------------------------------------------------------------------------//
void AnimationInstance::setSkipNextStep(bool skip)
{
    d_skipNextStep = skip;
}

//----------------------------------------------------------------------------//
bool AnimationInstance::getSkipNextStep() const
{
    return d_skipNextStep;
}

//----------------------------------------------------------------------------//
void AnimationInstance::setMaxStepDeltaSkip(float maxDelta)
{
    d_maxStepDeltaSkip = maxDelta;
}

//----------------------------------------------------------------------------//
float AnimationInstance::getMaxStepDeltaSkip() const
{
    return d_maxStepDeltaSkip;
}

//----------------------------------------------------------------------------//
void AnimationInstance::setMaxStepDeltaClamp(float maxDelta)
{
    d_maxStepDeltaClamp = maxDelta;
}

//----------------------------------------------------------------------------//
float AnimationInstance::getMaxStepDeltaClamp() const
{
    return d_maxStepDeltaClamp;
}

//----------------------------------------------------------------------------//
void AnimationInstance::start(bool skipNextStep)
{
    setPosition(0.0);
    d_skipNextStep = skipNextStep;

    if (d_definition && d_definition->getDuration() > 0)
    {
        d_running = true;
        onAnimationStarted();
    }
    else
    {
        Logger::getSingleton().logEvent(
            "AnimationInstance::start - Starting an animation instance with "
            "no animation definition or 0 duration has no effect!", Warnings);
        onAnimationStarted();
        onAnimationEnded();
    }
}

//----------------------------------------------------------------------------//
void AnimationInstance::stop()
{
    setPosition(0.0);
    d_running = false;
    onAnimationStopped();
}

//----------------------------------------------------------------------------//
void AnimationInstance::pause()
{
    d_running = false;
    onAnimationPaused();
}

//----------------------------------------------------------------------------//
void AnimationInstance::unpause(bool skipNextStep)
{
    d_skipNextStep = skipNextStep;

    if (d_definition && d_definition->getDuration() > 0)
    {
        d_running = true;
        onAnimationUnpaused();
    }
    else
    {
        Logger::getSingleton().logEvent(
            "AnimationInstance::unpause - Unpausing an animation instance with "
            "no animation definition or 0 duration has no effect!", Warnings);
        onAnimationUnpaused();
        onAnimationEnded();
    }
}

//----------------------------------------------------------------------------//
void AnimationInstance::togglePause(bool skipNextStep)
{
    if (isRunning())
    {
        pause();
    }
    else
    {
        unpause(skipNextStep);
    }
}

//----------------------------------------------------------------------------//
bool AnimationInstance::isRunning() const
{
    return d_running;
}

//----------------------------------------------------------------------------//
void AnimationInstance::step(float delta)
{
    if (!d_running)
    {
        // nothing to do if this animation instance isn't running
        return;
    }

    if (delta < 0.0f)
    {
        CEGUI_THROW(InvalidRequestException(
                        "AnimationInstance::step: You can't step the Animation Instance "
                        "with negative delta! You can't reverse the flow of time, stop "
                        "trying!"));
    }

    // first we deal with delta size
    if (d_maxStepDeltaSkip > 0.0f && delta > d_maxStepDeltaSkip)
    {
        // skip the step entirely if delta gets over the threshold
        // note that default value is 0.0f which means this never gets triggered
        delta = 0.0f;
    }

    if (d_maxStepDeltaClamp > 0.0f)
    {
        // clamp to threshold, note that default value is -1.0f which means
        // this line does nothing (delta should always be larger or equal than 0.0f
        delta = std::min(delta, d_maxStepDeltaClamp);
    }

    // if asked to do so, we skip this step, but mark that the next one
    // shouldn't be skipped
    // NB: This gets rid of annoying animation skips when FPS gets too low
    //     after complex layout loading, etc...
    if (d_skipNextStep)
    {
        d_skipNextStep = false;
        // we skip the step by setting delta to 0, this doesn't step the time
        // but still sets the animation position accordingly
        delta = 0.0f;
    }

    const float duration = d_definition->getDuration();

    // we modify the delta according to playback speed
    delta *= d_speed;

    // the position could have gotten out of the desired range, we have to
    // alter it depending on replay method of our animation definition

    // first a simple clamp with RM_Once
    if (d_definition->getReplayMode() == Animation::RM_Once)
    {
        float newPosition = d_position + delta;

        newPosition = std::max(0.0f, newPosition);

        if (newPosition >= duration)
        {
            newPosition = duration;

            stop();
            onAnimationEnded();
        }

        setPosition(newPosition);
    }
    // a both sided wrap with RM_Loop
    else if (d_definition->getReplayMode() == Animation::RM_Loop)
    {
        float newPosition = d_position + delta;

        while (newPosition > duration)
        {
            newPosition -= duration;
            onAnimationLooped();
        }

        setPosition(newPosition);
    }
    // bounce back and forth with RM_Bounce
    else if (d_definition->getReplayMode() == Animation::RM_Bounce)
    {
        if (d_bounceBackwards)
        {
            delta = -delta;
        }

        float newPosition = d_position + delta;

        while (newPosition <= 0 || newPosition > duration)
        {
            if (newPosition <= 0)
            {
                d_bounceBackwards = false;

                newPosition = -newPosition;
                onAnimationLooped();
            }

            if (newPosition > duration)
            {
                d_bounceBackwards = true;

                newPosition = 2.0f * duration - newPosition;
                onAnimationLooped();
            }
        }

        setPosition(newPosition);
    }

    apply();
}

//----------------------------------------------------------------------------//
bool AnimationInstance::handleStart(const CEGUI::EventArgs& e)
{
    start();

    return true;
}

//----------------------------------------------------------------------------//
bool AnimationInstance::handleStop(const CEGUI::EventArgs& e)
{
    stop();

    return true;
}

//----------------------------------------------------------------------------//
bool AnimationInstance::handlePause(const CEGUI::EventArgs& e)
{
    pause();

    return true;
}

//----------------------------------------------------------------------------//
bool AnimationInstance::handleUnpause(const CEGUI::EventArgs& e)
{
    unpause();

    return true;
}

//----------------------------------------------------------------------------//
bool AnimationInstance::handleTogglePause(const CEGUI::EventArgs& e)
{
    togglePause();

    return true;
}

//----------------------------------------------------------------------------//
void AnimationInstance::savePropertyValue(const String& propertyName)
{
    assert(d_target);

    d_savedPropertyValues[propertyName] = d_target->getProperty(propertyName);
}

//----------------------------------------------------------------------------//
void AnimationInstance::purgeSavedPropertyValues(void)
{
    d_savedPropertyValues.clear();
}

//----------------------------------------------------------------------------//
const String& AnimationInstance::getSavedPropertyValue(const String& propertyName)
{
    PropertyValueMap::iterator it = d_savedPropertyValues.find(propertyName);

    if (it == d_savedPropertyValues.end())
    {
        // even though we explicitly save all used property values when
        // starting the animation, this can happen when user changes
        // animation definition whilst the animation is running
        // (Yes, it's nasty, but people do nasty things)
        savePropertyValue(propertyName);
        return getSavedPropertyValue(propertyName);
    }

    return it->second;
}

//----------------------------------------------------------------------------//
void AnimationInstance::addAutoConnection(Event::Connection conn)
{
    d_autoConnections.push_back(conn);
}

//----------------------------------------------------------------------------//
void AnimationInstance::unsubscribeAutoConnections()
{
    for (ConnectionTracker::iterator it = d_autoConnections.begin();
         it != d_autoConnections.end(); ++it)
    {
        (*it)->disconnect();
    }

    d_autoConnections.clear();
}

//----------------------------------------------------------------------------//
void AnimationInstance::apply()
{
    if (d_target)
    {
        d_definition->apply(this);
    }
}

//----------------------------------------------------------------------------//
void AnimationInstance::onAnimationStarted()
{
    purgeSavedPropertyValues();
    d_definition->savePropertyValues(this);

    if (d_eventReceiver)
    {
        AnimationEventArgs args(this);
        d_eventReceiver->fireEvent(EventAnimationStarted, args, EventNamespace);
    }
}

//----------------------------------------------------------------------------//
void AnimationInstance::onAnimationStopped()
{
    if (d_eventReceiver)
    {
        AnimationEventArgs args(this);
        d_eventReceiver->fireEvent(EventAnimationStopped, args, EventNamespace);
    }
}

//----------------------------------------------------------------------------//
void AnimationInstance::onAnimationPaused()
{
    if (d_eventReceiver)
    {
        AnimationEventArgs args(this);
        d_eventReceiver->fireEvent(EventAnimationPaused, args, EventNamespace);
    }
}

//----------------------------------------------------------------------------//
void AnimationInstance::onAnimationUnpaused()
{
    if (d_eventReceiver)
    {
        AnimationEventArgs args(this);
        d_eventReceiver->fireEvent(EventAnimationUnpaused, args, EventNamespace);
    }
}

//----------------------------------------------------------------------------//
void AnimationInstance::onAnimationEnded()
{
    if (d_eventReceiver)
    {
        AnimationEventArgs args(this);
        d_eventReceiver->fireEvent(EventAnimationEnded, args, EventNamespace);
    }
}

//----------------------------------------------------------------------------//
void AnimationInstance::onAnimationLooped()
{
    if (d_eventReceiver)
    {
        AnimationEventArgs args(this);
        d_eventReceiver->fireEvent(EventAnimationLooped, args, EventNamespace);
    }
}

//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section

<|endoftext|>


<commit_before>#include "medida/reporting/udp_reporter.h"

#include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <string>
#include "util.h"
#include <cstring>
#include <cassert>

extern "C" {
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <errno.h>
#include <unistd.h>
}

namespace medida {
    namespace reporting {
        class UdpSender {//_NOT_ thread safe

            std::string host_;
            std::uint16_t port_;
            std::uint32_t reconnect_after_;
            std::uint64_t messages_sent_;
            bool connected_;

            std::vector<int> connections_;

            void disconnect() {
                assert(connected_);
                connected_ = false;

                for (int conn : connections_) {
                    close(conn);
                }
                connections_.clear();
            }

            void reconnect() {
                assert(! connected_);

                char buff[256];
                struct addrinfo hints, *res = NULL, *r;
                memset(&hints, 0, sizeof(hints));
                hints.ai_family = AF_INET;
                hints.ai_socktype = SOCK_DGRAM;
                auto port_str = std::to_string(port_);
                int ret = getaddrinfo(host_.c_str(), port_str.c_str(), &hints, &res);
                if (ret != 0) {
                    std::cerr << "Couldn't get addrinfo: " << strerror_r(ret, buff, sizeof(buff)) << "\n";
                    return;
                }

                for (r = res; r != NULL; r = r->ai_next) {
                    int sock = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
                    if (sock < 0) {
                        std::cerr << "Couldn't create socket: " << strerror_r(errno, buff, sizeof(buff)) << "\n";
                        continue;
                    }

                    if (connect(sock, r->ai_addr, r->ai_addrlen) < 0) {
                        std::cerr << "Failed to connect socket: " << sock << " error: " << strerror_r(errno, buff, sizeof(buff)) << "\n";
                        close(sock);
                        continue;
                    }

                    connections_.push_back(sock);
                }

                freeaddrinfo(res);

                connected_ = true;
            }

            void do_send(const char* msg, int len) {
                if (! connected_) return;
                for (auto conn : connections_) {
                    auto sent = ::send(conn, msg, len, 0);
                    if (sent < 0) {
                        std::cerr << "Failed to report metric (errno: "  << errno << ", fd: " << conn << ")\n";
                    }
                    assert(sent == len);
                }
            }

        public:
            UdpSender(const std::string& host, std::uint16_t port, std::uint32_t reconnect_after) :
                host_(host), port_(port), reconnect_after_(reconnect_after), messages_sent_(0), connected_(false) { }

            ~UdpSender() { if (connected_) disconnect(); }

            void send(std::string&& msg) {
                if (connected_ && ((messages_sent_++ % reconnect_after_) == 0)) {
                    disconnect();
                }
                if (! connected_) reconnect();
                do_send(msg.c_str(), msg.length());
            }
        };

        class UdpReporter::Impl : public MetricProcessor {

        public:
            Impl(MetricsRegistry &registry, Formatter& formatter, std::uint16_t port, const std::string& hostname, std::uint32_t reconnect_after);

            ~Impl();

            void run();

            using MetricProcessor::process;

            void process(Counter& counter);

            void process(Meter& meter);

            void process(Histogram& histogram);

            void process(Timer& timer);

            template <typename... Args> void send(Args... args);

        private:
            medida::MetricsRegistry& registry_;

            Formatter& format_;

            UdpSender sender_;
        };

        UdpReporter::UdpReporter(MetricsRegistry &registry, Formatter& formatter, std::uint16_t port, const std::string& hostname, std::uint32_t reconnect_after)
            : AbstractPollingReporter(),
              impl_ {new UdpReporter::Impl {registry, formatter, port, hostname, reconnect_after}} { }

        UdpReporter::~UdpReporter() { }

        void UdpReporter::run() {
            impl_->run();
        }

// === Implementation ===

        UdpReporter::Impl::Impl(MetricsRegistry &registry, Formatter& formatter, std::uint16_t port, const std::string& hostname, std::uint32_t reconnect_after)
            :registry_ (registry), format_ (formatter), sender_(hostname, port, reconnect_after) { }

        UdpReporter::Impl::~Impl() { }

        void UdpReporter::Impl::run() {
            for (auto& kv : registry_.get_all_metrics()) {
                auto name = kv.first;
                auto metric = kv.second;
                format_.set_name(name.to_string());
                metric->process(*this);
            }
        }

        template <typename... Args> void UdpReporter::Impl::send(Args... args) {
            sender_.send(format_(args...));
        }

        void UdpReporter::Impl::process(Counter& counter) {
            send("counter", "count", counter.count());
        }

        void UdpReporter::Impl::process(Meter& meter) {
            auto event_type = meter.event_type();
            auto unit = format_rate_unit(meter.rate_unit());
            send("meter", "count", meter.count());
            send("meter", event_type, "mean_rate", meter.mean_rate(), unit);
            send("meter", event_type, "1min_rate", meter.one_minute_rate(), unit);
            send("meter", event_type, "5min_rate", meter.five_minute_rate(), unit);
            send("meter", event_type, "15min_rate", meter.fifteen_minute_rate(), unit);
        }

        void UdpReporter::Impl::process(Histogram& histogram) {
            auto snapshot = histogram.snapshot();
            send("histogram", "min", histogram.min());
            send("histogram", "max", histogram.max());
            send("histogram", "mean", histogram.mean());
            send("histogram", "std_dev", histogram.std_dev());
            send("histogram", "median", snapshot.median());
            send("histogram", "75pct", snapshot.percentile_75());
            send("histogram", "95pct", snapshot.percentile_95());
            send("histogram", "98pct", snapshot.percentile_98());
            send("histogram", "99pct", snapshot.percentile_99());
            send("histogram", "999pct", snapshot.percentile_999());
        }

        void UdpReporter::Impl::process(Timer& timer) {
            auto snapshot = timer.snapshot();
            auto event_type = timer.event_type();
            auto rate_unit = format_rate_unit(timer.rate_unit());
            auto duration_unit = format_rate_unit(timer.duration_unit());

            send("timer", "count", timer.count());
            send("timer", event_type, "mean_rate", timer.mean_rate(), rate_unit);
            send("timer", event_type, "1min_rate", timer.one_minute_rate(), rate_unit);
            send("timer", event_type, "5min_rate", timer.five_minute_rate(), rate_unit);
            send("timer", event_type, "15min_rate", timer.fifteen_minute_rate(), rate_unit);
            send("timer", "min", timer.min(), duration_unit);
            send("timer", "max", timer.max(), duration_unit);
            send("timer", "mean", timer.mean(), duration_unit);
            send("timer", "std_dev", timer.std_dev(), duration_unit);
            send("timer", "median", snapshot.median(), duration_unit);
            send("timer", "75pct", snapshot.percentile_75(), duration_unit);
            send("timer", "95pct", snapshot.percentile_95(), duration_unit);
            send("timer", "98pct", snapshot.percentile_98(), duration_unit);
            send("timer", "99pct", snapshot.percentile_99(), duration_unit);
            send("timer", "999pct", snapshot.percentile_999(), duration_unit);
        }
    }
}
<commit_msg>Report errors on udp-send failing<commit_after>#include "medida/reporting/udp_reporter.h"

#include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <string>
#include "util.h"
#include <cstring>
#include <cassert>

extern "C" {
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <errno.h>
#include <unistd.h>
}

namespace medida {
    namespace reporting {
        class UdpSender {//_NOT_ thread safe

            std::string host_;
            std::uint16_t port_;
            std::uint32_t reconnect_after_;
            std::uint64_t messages_sent_;
            bool connected_;

            std::vector<int> connections_;

            char buff[256];

            const char* err_str(int err_code) {
                return strerror_r(err_code, buff, sizeof(buff));
            }

            void disconnect() {
                assert(connected_);
                connected_ = false;

                for (int conn : connections_) {
                    close(conn);
                }
                connections_.clear();
            }

            void reconnect() {
                assert(! connected_);

                struct addrinfo hints, *res = NULL, *r;
                memset(&hints, 0, sizeof(hints));
                hints.ai_family = AF_INET;
                hints.ai_socktype = SOCK_DGRAM;
                auto port_str = std::to_string(port_);
                int ret = getaddrinfo(host_.c_str(), port_str.c_str(), &hints, &res);
                if (ret != 0) {
                    std::cerr << "Couldn't get addrinfo: " << err_str(ret) << "\n";
                    return;
                }

                for (r = res; r != NULL; r = r->ai_next) {
                    int sock = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
                    if (sock < 0) {
                        int err = errno;
                        std::cerr << "Couldn't create socket: " << err_str(err) << "\n";
                        continue;
                    }

                    if (connect(sock, r->ai_addr, r->ai_addrlen) < 0) {
                        int err = errno;
                        std::cerr << "Failed to connect socket: " << sock << " error: " << err_str(err) << "\n";
                        close(sock);
                        continue;
                    }

                    connections_.push_back(sock);
                }

                freeaddrinfo(res);

                connected_ = true;
            }

            void do_send(const char* msg, int len) {
                if (! connected_) return;
                for (auto conn : connections_) {
                    auto sent = ::send(conn, msg, len, 0);
                    if (sent < 0) {
                        int err = errno;
                        std::cerr << "Failed to report metric (errno: " << err << ", error: '"  << err_str(err) << "', fd: " << conn << ")\n";
                    } else assert(sent == len);
                }
            }

        public:
            UdpSender(const std::string& host, std::uint16_t port, std::uint32_t reconnect_after) :
                host_(host), port_(port), reconnect_after_(reconnect_after), messages_sent_(0), connected_(false) { }

            ~UdpSender() { if (connected_) disconnect(); }

            void send(std::string&& msg) {
                if (connected_ && ((messages_sent_++ % reconnect_after_) == 0)) {
                    disconnect();
                }
                if (! connected_) reconnect();
                do_send(msg.c_str(), msg.length());
            }
        };

        class UdpReporter::Impl : public MetricProcessor {

        public:
            Impl(MetricsRegistry &registry, Formatter& formatter, std::uint16_t port, const std::string& hostname, std::uint32_t reconnect_after);

            ~Impl();

            void run();

            using MetricProcessor::process;

            void process(Counter& counter);

            void process(Meter& meter);

            void process(Histogram& histogram);

            void process(Timer& timer);

            template <typename... Args> void send(Args... args);

        private:
            medida::MetricsRegistry& registry_;

            Formatter& format_;

            UdpSender sender_;
        };

        UdpReporter::UdpReporter(MetricsRegistry &registry, Formatter& formatter, std::uint16_t port, const std::string& hostname, std::uint32_t reconnect_after)
            : AbstractPollingReporter(),
              impl_ {new UdpReporter::Impl {registry, formatter, port, hostname, reconnect_after}} { }

        UdpReporter::~UdpReporter() { }

        void UdpReporter::run() {
            impl_->run();
        }

// === Implementation ===

        UdpReporter::Impl::Impl(MetricsRegistry &registry, Formatter& formatter, std::uint16_t port, const std::string& hostname, std::uint32_t reconnect_after)
            :registry_ (registry), format_ (formatter), sender_(hostname, port, reconnect_after) { }

        UdpReporter::Impl::~Impl() { }

        void UdpReporter::Impl::run() {
            for (auto& kv : registry_.get_all_metrics()) {
                auto name = kv.first;
                auto metric = kv.second;
                format_.set_name(name.to_string());
                metric->process(*this);
            }
        }

        template <typename... Args> void UdpReporter::Impl::send(Args... args) {
            sender_.send(format_(args...));
        }

        void UdpReporter::Impl::process(Counter& counter) {
            send("counter", "count", counter.count());
        }

        void UdpReporter::Impl::process(Meter& meter) {
            auto event_type = meter.event_type();
            auto unit = format_rate_unit(meter.rate_unit());
            send("meter", "count", meter.count());
            send("meter", event_type, "mean_rate", meter.mean_rate(), unit);
            send("meter", event_type, "1min_rate", meter.one_minute_rate(), unit);
            send("meter", event_type, "5min_rate", meter.five_minute_rate(), unit);
            send("meter", event_type, "15min_rate", meter.fifteen_minute_rate(), unit);
        }

        void UdpReporter::Impl::process(Histogram& histogram) {
            auto snapshot = histogram.snapshot();
            send("histogram", "min", histogram.min());
            send("histogram", "max", histogram.max());
            send("histogram", "mean", histogram.mean());
            send("histogram", "std_dev", histogram.std_dev());
            send("histogram", "median", snapshot.median());
            send("histogram", "75pct", snapshot.percentile_75());
            send("histogram", "95pct", snapshot.percentile_95());
            send("histogram", "98pct", snapshot.percentile_98());
            send("histogram", "99pct", snapshot.percentile_99());
            send("histogram", "999pct", snapshot.percentile_999());
        }

        void UdpReporter::Impl::process(Timer& timer) {
            auto snapshot = timer.snapshot();
            auto event_type = timer.event_type();
            auto rate_unit = format_rate_unit(timer.rate_unit());
            auto duration_unit = format_rate_unit(timer.duration_unit());

            send("timer", "count", timer.count());
            send("timer", event_type, "mean_rate", timer.mean_rate(), rate_unit);
            send("timer", event_type, "1min_rate", timer.one_minute_rate(), rate_unit);
            send("timer", event_type, "5min_rate", timer.five_minute_rate(), rate_unit);
            send("timer", event_type, "15min_rate", timer.fifteen_minute_rate(), rate_unit);
            send("timer", "min", timer.min(), duration_unit);
            send("timer", "max", timer.max(), duration_unit);
            send("timer", "mean", timer.mean(), duration_unit);
            send("timer", "std_dev", timer.std_dev(), duration_unit);
            send("timer", "median", snapshot.median(), duration_unit);
            send("timer", "75pct", snapshot.percentile_75(), duration_unit);
            send("timer", "95pct", snapshot.percentile_95(), duration_unit);
            send("timer", "98pct", snapshot.percentile_98(), duration_unit);
            send("timer", "99pct", snapshot.percentile_99(), duration_unit);
            send("timer", "999pct", snapshot.percentile_999(), duration_unit);
        }
    }
}
<|endoftext|>


<commit_before>#include <LightGBM/objective_function.h>
#include "regression_objective.hpp"
#include "binary_objective.hpp"
#include "rank_objective.hpp"
#include "multiclass_objective.hpp"
#include "xentropy_objective.hpp"

namespace LightGBM {

ObjectiveFunction* ObjectiveFunction::CreateObjectiveFunction(const std::string& type, const Config& config) {
  if (type == std::string("regression") || type == std::string("regression_l2")
      || type == std::string("mean_squared_error") || type == std::string("mse")
      || type == std::string("l2_root") || type == std::string("root_mean_squared_error") || type == std::string("rmse")) {
    return new RegressionL2loss(config);
  } else if (type == std::string("regression_l1") || type == std::string("mean_absolute_error")  || type == std::string("mae")) {
    return new RegressionL1loss(config);
  } else if (type == std::string("quantile")) {
    return new RegressionQuantileloss(config);
  } else if (type == std::string("huber")) {
    return new RegressionHuberLoss(config);
  } else if (type == std::string("fair")) {
    return new RegressionFairLoss(config);
  } else if (type == std::string("poisson")) {
    return new RegressionPoissonLoss(config);
  } else if (type == std::string("binary")) {
    return new BinaryLogloss(config);
  } else if (type == std::string("lambdarank")) {
    return new LambdarankNDCG(config);
  } else if (type == std::string("multiclass") || type == std::string("softmax")) {
    return new MulticlassSoftmax(config);
  } else if (type == std::string("multiclassova") || type == std::string("multiclass_ova") || type == std::string("ova") || type == std::string("ovr")) {
    return new MulticlassOVA(config);
  } else if (type == std::string("xentropy") || type == std::string("cross_entropy")) {
    return new CrossEntropy(config);
  } else if (type == std::string("xentlambda") || type == std::string("cross_entropy_lambda")) {
    return new CrossEntropyLambda(config);
  } else if (type == std::string("mean_absolute_percentage_error") || type == std::string("mape")) {
    return new RegressionMAPELOSS(config);
  } else if (type == std::string("gamma")) {
    return new RegressionGammaLoss(config);
  } else if (type == std::string("tweedie")) {
    return new RegressionTweedieLoss(config);
  } else if (type == std::string("none") || type == std::string("null") || type == std::string("custom")) {
    return nullptr;
  }
  Log::Fatal("Unknown objective type name: %s", type.c_str());
}

ObjectiveFunction* ObjectiveFunction::CreateObjectiveFunction(const std::string& str) {
  auto strs = Common::Split(str.c_str(), ' ');
  auto type = strs[0];
  if (type == std::string("regression")) {
    return new RegressionL2loss(strs);
  } else if (type == std::string("regression_l1")) {
    return new RegressionL1loss(strs);
  } else if (type == std::string("quantile")) {
    return new RegressionQuantileloss(strs);
  } else if (type == std::string("huber")) {
    return new RegressionHuberLoss(strs);
  } else if (type == std::string("fair")) {
    return new RegressionFairLoss(strs);
  } else if (type == std::string("poisson")) {
    return new RegressionPoissonLoss(strs);
  } else if (type == std::string("binary")) {
    return new BinaryLogloss(strs);
  } else if (type == std::string("lambdarank")) {
    return new LambdarankNDCG(strs);
  } else if (type == std::string("multiclass")) {
    return new MulticlassSoftmax(strs);
  } else if (type == std::string("multiclassova")) {
    return new MulticlassOVA(strs);
  } else if (type == std::string("xentropy") || type == std::string("cross_entropy")) {
    return new CrossEntropy(strs);
  } else if (type == std::string("xentlambda") || type == std::string("cross_entropy_lambda")) {
    return new CrossEntropyLambda(strs);
  } else if (type == std::string("gamma")) {
    return new RegressionGammaLoss(strs);
  } else if (type == std::string("tweedie")) {
    return new RegressionTweedieLoss(strs);
  } else if (type == std::string("none") || type == std::string("null") || type == std::string("custom")) {
    return nullptr;
  }
  Log::Fatal("Unknown objective type name: %s", type.c_str());
}

}  // namespace LightGBM
<commit_msg>fix #1461<commit_after>#include <LightGBM/objective_function.h>
#include "regression_objective.hpp"
#include "binary_objective.hpp"
#include "rank_objective.hpp"
#include "multiclass_objective.hpp"
#include "xentropy_objective.hpp"

namespace LightGBM {

ObjectiveFunction* ObjectiveFunction::CreateObjectiveFunction(const std::string& type, const Config& config) {
  if (type == std::string("regression") || type == std::string("regression_l2")
      || type == std::string("mean_squared_error") || type == std::string("mse")
      || type == std::string("l2_root") || type == std::string("root_mean_squared_error") || type == std::string("rmse")) {
    return new RegressionL2loss(config);
  } else if (type == std::string("regression_l1") || type == std::string("mean_absolute_error")  || type == std::string("mae")) {
    return new RegressionL1loss(config);
  } else if (type == std::string("quantile")) {
    return new RegressionQuantileloss(config);
  } else if (type == std::string("huber")) {
    return new RegressionHuberLoss(config);
  } else if (type == std::string("fair")) {
    return new RegressionFairLoss(config);
  } else if (type == std::string("poisson")) {
    return new RegressionPoissonLoss(config);
  } else if (type == std::string("binary")) {
    return new BinaryLogloss(config);
  } else if (type == std::string("lambdarank")) {
    return new LambdarankNDCG(config);
  } else if (type == std::string("multiclass") || type == std::string("softmax")) {
    return new MulticlassSoftmax(config);
  } else if (type == std::string("multiclassova") || type == std::string("multiclass_ova") || type == std::string("ova") || type == std::string("ovr")) {
    return new MulticlassOVA(config);
  } else if (type == std::string("xentropy") || type == std::string("cross_entropy")) {
    return new CrossEntropy(config);
  } else if (type == std::string("xentlambda") || type == std::string("cross_entropy_lambda")) {
    return new CrossEntropyLambda(config);
  } else if (type == std::string("mean_absolute_percentage_error") || type == std::string("mape")) {
    return new RegressionMAPELOSS(config);
  } else if (type == std::string("gamma")) {
    return new RegressionGammaLoss(config);
  } else if (type == std::string("tweedie")) {
    return new RegressionTweedieLoss(config);
  } else if (type == std::string("none") || type == std::string("null") || type == std::string("custom")) {
    return nullptr;
  }
  Log::Fatal("Unknown objective type name: %s", type.c_str());
}

ObjectiveFunction* ObjectiveFunction::CreateObjectiveFunction(const std::string& str) {
  auto strs = Common::Split(str.c_str(), ' ');
  auto type = strs[0];
  if (type == std::string("regression")) {
    return new RegressionL2loss(strs);
  } else if (type == std::string("regression_l1")) {
    return new RegressionL1loss(strs);
  } else if (type == std::string("quantile")) {
    return new RegressionQuantileloss(strs);
  } else if (type == std::string("huber")) {
    return new RegressionHuberLoss(strs);
  } else if (type == std::string("fair")) {
    return new RegressionFairLoss(strs);
  } else if (type == std::string("poisson")) {
    return new RegressionPoissonLoss(strs);
  } else if (type == std::string("binary")) {
    return new BinaryLogloss(strs);
  } else if (type == std::string("lambdarank")) {
    return new LambdarankNDCG(strs);
  } else if (type == std::string("multiclass")) {
    return new MulticlassSoftmax(strs);
  } else if (type == std::string("multiclassova")) {
    return new MulticlassOVA(strs);
  } else if (type == std::string("xentropy") || type == std::string("cross_entropy")) {
    return new CrossEntropy(strs);
  } else if (type == std::string("xentlambda") || type == std::string("cross_entropy_lambda")) {
    return new CrossEntropyLambda(strs);
  } else if (type == std::string("mean_absolute_percentage_error") || type == std::string("mape")) {
    return new RegressionMAPELOSS(strs);
  } else if (type == std::string("gamma")) {
    return new RegressionGammaLoss(strs);
  } else if (type == std::string("tweedie")) {
    return new RegressionTweedieLoss(strs);
  } else if (type == std::string("none") || type == std::string("null") || type == std::string("custom")) {
    return nullptr;
  }
  Log::Fatal("Unknown objective type name: %s", type.c_str());
}

}  // namespace LightGBM
<|endoftext|>


<commit_before>//
// Copyright © 2020 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//

#pragma once

#include <tensorflow/lite/c/common.h>
#include <tensorflow/lite/interpreter.h>

#include <doctest/doctest.h>

#include <half/half.hpp>

using Half = half_float::half;

namespace armnnDelegate
{

/// Can be used to assign input data from a vector to a model input.
/// Example usage can be found in ResizeTesthelper.hpp
template <typename T>
void FillInput(std::unique_ptr<tflite::Interpreter>& interpreter, int inputIndex, std::vector<T>& inputValues)
{
    auto tfLiteDelegateInputId = interpreter->inputs()[inputIndex];
    auto tfLiteDelageInputData = interpreter->typed_tensor<T>(tfLiteDelegateInputId);
    for (unsigned int i = 0; i < inputValues.size(); ++i)
    {
        tfLiteDelageInputData[i] = inputValues[i];
    }
}

/// Can be used to compare bool data coming from a tflite interpreter
/// Boolean types get converted to a bit representation in a vector. vector.data() returns a void pointer
/// instead of a pointer to bool. Therefore a special function to compare to vector of bool is required
void CompareData(std::vector<bool>& tensor1, bool tensor2[], size_t tensorSize);
void CompareData(bool tensor1[], bool tensor2[], size_t tensorSize);

/// Can be used to compare float data coming from a tflite interpreter with a tolerance of limit_of_float*100
void CompareData(float tensor1[], float tensor2[], size_t tensorSize);

/// Can be used to compare int8_t data coming from a tflite interpreter with a tolerance of 1
void CompareData(int8_t tensor1[], int8_t tensor2[], size_t tensorSize);

/// Can be used to compare uint8_t data coming from a tflite interpreter with a tolerance of 1
void CompareData(uint8_t tensor1[], uint8_t tensor2[], size_t tensorSize);

/// Can be used to compare int16_t data coming from a tflite interpreter with a tolerance of 1
void CompareData(int16_t tensor1[], int16_t tensor2[], size_t tensorSize);

/// Can be used to compare Half (Float16) data with a tolerance of limit_of_float*100
void CompareData(Half tensor1[], Half tensor2[], size_t tensorSize);

/// Can be used to compare TfLiteFloat16 data coming from a tflite interpreter
void CompareData(TfLiteFloat16 tensor1[], TfLiteFloat16 tensor2[], size_t tensorSize);

/// Can be used to compare Half (Float16) data and TfLiteFloat16 data coming from a tflite interpreter
void CompareData(TfLiteFloat16 tensor1[], Half tensor2[], size_t tensorSize);

/// Can be used to compare the output tensor shape and values
/// from armnnDelegateInterpreter and tfLiteInterpreter.
/// Example usage can be found in ControlTestHelper.hpp
template <typename T>
void CompareOutputData(std::unique_ptr<tflite::Interpreter>& tfLiteInterpreter,
                       std::unique_ptr<tflite::Interpreter>& armnnDelegateInterpreter,
                       std::vector<int32_t>& expectedOutputShape,
                       std::vector<T>& expectedOutputValues,
                       unsigned int outputIndex = 0)
{
    auto tfLiteDelegateOutputId = tfLiteInterpreter->outputs()[outputIndex];
    auto tfLiteDelegateOutputTensor = tfLiteInterpreter->tensor(tfLiteDelegateOutputId);
    auto tfLiteDelegateOutputData = tfLiteInterpreter->typed_tensor<T>(tfLiteDelegateOutputId);
    auto armnnDelegateOutputId = armnnDelegateInterpreter->outputs()[outputIndex];
    auto armnnDelegateOutputTensor = armnnDelegateInterpreter->tensor(armnnDelegateOutputId);
    auto armnnDelegateOutputData = armnnDelegateInterpreter->typed_tensor<T>(armnnDelegateOutputId);

    CHECK(expectedOutputShape.size() == tfLiteDelegateOutputTensor->dims->size);
    CHECK(expectedOutputShape.size() == armnnDelegateOutputTensor->dims->size);

    for (size_t i = 0; i < expectedOutputShape.size(); i++)
    {
        CHECK(expectedOutputShape[i] == armnnDelegateOutputTensor->dims->data[i]);
        CHECK(tfLiteDelegateOutputTensor->dims->data[i] == expectedOutputShape[i]);
        CHECK(tfLiteDelegateOutputTensor->dims->data[i] == armnnDelegateOutputTensor->dims->data[i]);
    }

    armnnDelegate::CompareData(expectedOutputValues.data(), armnnDelegateOutputData    , expectedOutputValues.size());
    armnnDelegate::CompareData(tfLiteDelegateOutputData   , expectedOutputValues.data(), expectedOutputValues.size());
    armnnDelegate::CompareData(tfLiteDelegateOutputData   , armnnDelegateOutputData    , expectedOutputValues.size());
}

} // namespace armnnDelegate
<commit_msg>IVGCVSW-5654 Fix failing float 16 delegate tests on android<commit_after>//
// Copyright © 2020 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//

#pragma once

#include <tensorflow/lite/c/common.h>
#include <tensorflow/lite/interpreter.h>

#include <doctest/doctest.h>

#include <half/half.hpp>

using Half = half_float::half;

namespace armnnDelegate
{

/// Can be used to assign input data from a vector to a model input.
/// Example usage can be found in ResizeTesthelper.hpp
template <typename T>
void FillInput(std::unique_ptr<tflite::Interpreter>& interpreter, int inputIndex, std::vector<T>& inputValues)
{
    auto tfLiteDelegateInputId = interpreter->inputs()[inputIndex];
    auto tfLiteDelageInputData = interpreter->typed_tensor<T>(tfLiteDelegateInputId);
    for (unsigned int i = 0; i < inputValues.size(); ++i)
    {
        tfLiteDelageInputData[i] = inputValues[i];
    }
}

template <>
void FillInput(std::unique_ptr<tflite::Interpreter>& interpreter, int inputIndex, std::vector<Half>& inputValues);

/// Can be used to compare bool data coming from a tflite interpreter
/// Boolean types get converted to a bit representation in a vector. vector.data() returns a void pointer
/// instead of a pointer to bool. Therefore a special function to compare to vector of bool is required
void CompareData(std::vector<bool>& tensor1, bool tensor2[], size_t tensorSize);
void CompareData(bool tensor1[], bool tensor2[], size_t tensorSize);

/// Can be used to compare float data coming from a tflite interpreter with a tolerance of limit_of_float*100
void CompareData(float tensor1[], float tensor2[], size_t tensorSize);

/// Can be used to compare int8_t data coming from a tflite interpreter with a tolerance of 1
void CompareData(int8_t tensor1[], int8_t tensor2[], size_t tensorSize);

/// Can be used to compare uint8_t data coming from a tflite interpreter with a tolerance of 1
void CompareData(uint8_t tensor1[], uint8_t tensor2[], size_t tensorSize);

/// Can be used to compare int16_t data coming from a tflite interpreter with a tolerance of 1
void CompareData(int16_t tensor1[], int16_t tensor2[], size_t tensorSize);

/// Can be used to compare Half (Float16) data with a tolerance of limit_of_float*100
void CompareData(Half tensor1[], Half tensor2[], size_t tensorSize);

/// Can be used to compare TfLiteFloat16 data coming from a tflite interpreter
void CompareData(TfLiteFloat16 tensor1[], TfLiteFloat16 tensor2[], size_t tensorSize);

/// Can be used to compare Half (Float16) data and TfLiteFloat16 data coming from a tflite interpreter
void CompareData(TfLiteFloat16 tensor1[], Half tensor2[], size_t tensorSize);

/// Can be used to compare the output tensor shape and values
/// from armnnDelegateInterpreter and tfLiteInterpreter.
/// Example usage can be found in ControlTestHelper.hpp
template <typename T>
void CompareOutputData(std::unique_ptr<tflite::Interpreter>& tfLiteInterpreter,
                       std::unique_ptr<tflite::Interpreter>& armnnDelegateInterpreter,
                       std::vector<int32_t>& expectedOutputShape,
                       std::vector<T>& expectedOutputValues,
                       unsigned int outputIndex = 0)
{
    auto tfLiteDelegateOutputId = tfLiteInterpreter->outputs()[outputIndex];
    auto tfLiteDelegateOutputTensor = tfLiteInterpreter->tensor(tfLiteDelegateOutputId);
    auto tfLiteDelegateOutputData = tfLiteInterpreter->typed_tensor<T>(tfLiteDelegateOutputId);
    auto armnnDelegateOutputId = armnnDelegateInterpreter->outputs()[outputIndex];
    auto armnnDelegateOutputTensor = armnnDelegateInterpreter->tensor(armnnDelegateOutputId);
    auto armnnDelegateOutputData = armnnDelegateInterpreter->typed_tensor<T>(armnnDelegateOutputId);

    CHECK(expectedOutputShape.size() == tfLiteDelegateOutputTensor->dims->size);
    CHECK(expectedOutputShape.size() == armnnDelegateOutputTensor->dims->size);

    for (size_t i = 0; i < expectedOutputShape.size(); i++)
    {
        CHECK(expectedOutputShape[i] == armnnDelegateOutputTensor->dims->data[i]);
        CHECK(tfLiteDelegateOutputTensor->dims->data[i] == expectedOutputShape[i]);
        CHECK(tfLiteDelegateOutputTensor->dims->data[i] == armnnDelegateOutputTensor->dims->data[i]);
    }

    armnnDelegate::CompareData(expectedOutputValues.data(), armnnDelegateOutputData    , expectedOutputValues.size());
    armnnDelegate::CompareData(tfLiteDelegateOutputData   , expectedOutputValues.data(), expectedOutputValues.size());
    armnnDelegate::CompareData(tfLiteDelegateOutputData   , armnnDelegateOutputData    , expectedOutputValues.size());
}

} // namespace armnnDelegate
<|endoftext|>


<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/third_party/quiche/src/quic/core/congestion_control/pacing_sender.h"

#include "net/third_party/quiche/src/quic/core/quic_bandwidth.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_flag_utils.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"

namespace quic {
namespace {

// Configured maximum size of the burst coming out of quiescence.  The burst
// is never larger than the current CWND in packets.
static const uint32_t kInitialUnpacedBurst = 10;

}  // namespace

PacingSender::PacingSender()
    : sender_(nullptr),
      max_pacing_rate_(QuicBandwidth::Zero()),
      burst_tokens_(kInitialUnpacedBurst),
      ideal_next_packet_send_time_(QuicTime::Zero()),
      initial_burst_size_(kInitialUnpacedBurst),
      lumpy_tokens_(0),
      alarm_granularity_(QuicTime::Delta::FromMilliseconds(1)),
      pacing_limited_(false) {
  if (GetQuicReloadableFlag(quic_donot_reset_ideal_next_packet_send_time)) {
    QUIC_RELOADABLE_FLAG_COUNT(quic_donot_reset_ideal_next_packet_send_time);
  }
}

PacingSender::~PacingSender() {}

void PacingSender::set_sender(SendAlgorithmInterface* sender) {
  DCHECK(sender != nullptr);
  sender_ = sender;
}

void PacingSender::OnCongestionEvent(bool rtt_updated,
                                     QuicByteCount bytes_in_flight,
                                     QuicTime event_time,
                                     const AckedPacketVector& acked_packets,
                                     const LostPacketVector& lost_packets) {
  DCHECK(sender_ != nullptr);
  if (!lost_packets.empty()) {
    // Clear any burst tokens when entering recovery.
    burst_tokens_ = 0;
  }
  sender_->OnCongestionEvent(rtt_updated, bytes_in_flight, event_time,
                             acked_packets, lost_packets);
}

void PacingSender::OnPacketSent(
    QuicTime sent_time,
    QuicByteCount bytes_in_flight,
    QuicPacketNumber packet_number,
    QuicByteCount bytes,
    HasRetransmittableData has_retransmittable_data) {
  DCHECK(sender_ != nullptr);
  sender_->OnPacketSent(sent_time, bytes_in_flight, packet_number, bytes,
                        has_retransmittable_data);
  if (has_retransmittable_data != HAS_RETRANSMITTABLE_DATA) {
    return;
  }
  // If in recovery, the connection is not coming out of quiescence.
  if (bytes_in_flight == 0 && !sender_->InRecovery()) {
    // Add more burst tokens anytime the connection is leaving quiescence, but
    // limit it to the equivalent of a single bulk write, not exceeding the
    // current CWND in packets.
    burst_tokens_ = std::min(
        initial_burst_size_,
        static_cast<uint32_t>(sender_->GetCongestionWindow() / kDefaultTCPMSS));
  }
  if (burst_tokens_ > 0) {
    --burst_tokens_;
    if (!GetQuicReloadableFlag(quic_donot_reset_ideal_next_packet_send_time)) {
      ideal_next_packet_send_time_ = QuicTime::Zero();
    }
    pacing_limited_ = false;
    return;
  }
  // The next packet should be sent as soon as the current packet has been
  // transferred.  PacingRate is based on bytes in flight including this packet.
  QuicTime::Delta delay =
      PacingRate(bytes_in_flight + bytes).TransferTime(bytes);
  if (!pacing_limited_ || lumpy_tokens_ == 0) {
    // Reset lumpy_tokens_ if either application or cwnd throttles sending or
    // token runs out.
    lumpy_tokens_ = std::max(
        1u, std::min(static_cast<uint32_t>(
                         GetQuicFlag(FLAGS_quic_lumpy_pacing_size)),
                     static_cast<uint32_t>(
                         (sender_->GetCongestionWindow() *
                          GetQuicFlag(FLAGS_quic_lumpy_pacing_cwnd_fraction)) /
                         kDefaultTCPMSS)));
    if (GetQuicReloadableFlag(quic_no_lumpy_pacing_at_low_bw) &&
        sender_->BandwidthEstimate() <
            QuicBandwidth::FromKBitsPerSecond(1200)) {
      // Below 1.2Mbps, send 1 packet at once, because one full-sized packet
      // is about 10ms of queueing.
      lumpy_tokens_ = 1u;
    }
  }
  --lumpy_tokens_;
  if (pacing_limited_) {
    // Make up for lost time since pacing throttles the sending.
    ideal_next_packet_send_time_ = ideal_next_packet_send_time_ + delay;
  } else {
    ideal_next_packet_send_time_ =
        std::max(ideal_next_packet_send_time_ + delay, sent_time + delay);
  }
  // Stop making up for lost time if underlying sender prevents sending.
  pacing_limited_ = sender_->CanSend(bytes_in_flight + bytes);
}

void PacingSender::OnApplicationLimited() {
  // The send is application limited, stop making up for lost time.
  pacing_limited_ = false;
}

QuicTime::Delta PacingSender::TimeUntilSend(
    QuicTime now,
    QuicByteCount bytes_in_flight) const {
  DCHECK(sender_ != nullptr);

  if (!sender_->CanSend(bytes_in_flight)) {
    // The underlying sender prevents sending.
    return QuicTime::Delta::Infinite();
  }

  if (burst_tokens_ > 0 || bytes_in_flight == 0 || lumpy_tokens_ > 0) {
    // Don't pace if we have burst tokens available or leaving quiescence.
    return QuicTime::Delta::Zero();
  }

  // If the next send time is within the alarm granularity, send immediately.
  if (ideal_next_packet_send_time_ > now + alarm_granularity_) {
    QUIC_DVLOG(1) << "Delaying packet: "
                  << (ideal_next_packet_send_time_ - now).ToMicroseconds();
    return ideal_next_packet_send_time_ - now;
  }

  QUIC_DVLOG(1) << "Sending packet now. ideal_next_packet_send_time: "
                << ideal_next_packet_send_time_ << ", now: " << now;
  return QuicTime::Delta::Zero();
}

QuicBandwidth PacingSender::PacingRate(QuicByteCount bytes_in_flight) const {
  DCHECK(sender_ != nullptr);
  if (!max_pacing_rate_.IsZero()) {
    return QuicBandwidth::FromBitsPerSecond(
        std::min(max_pacing_rate_.ToBitsPerSecond(),
                 sender_->PacingRate(bytes_in_flight).ToBitsPerSecond()));
  }
  return sender_->PacingRate(bytes_in_flight);
}

}  // namespace quic
<commit_msg>gfe-relnote: (n/a) Add a flag count for --gfe2_reloadable_flag_quic_no_lumpy_pacing_at_low_bw. Flag count only.<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/third_party/quiche/src/quic/core/congestion_control/pacing_sender.h"

#include "net/third_party/quiche/src/quic/core/quic_bandwidth.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_flag_utils.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"

namespace quic {
namespace {

// Configured maximum size of the burst coming out of quiescence.  The burst
// is never larger than the current CWND in packets.
static const uint32_t kInitialUnpacedBurst = 10;

}  // namespace

PacingSender::PacingSender()
    : sender_(nullptr),
      max_pacing_rate_(QuicBandwidth::Zero()),
      burst_tokens_(kInitialUnpacedBurst),
      ideal_next_packet_send_time_(QuicTime::Zero()),
      initial_burst_size_(kInitialUnpacedBurst),
      lumpy_tokens_(0),
      alarm_granularity_(QuicTime::Delta::FromMilliseconds(1)),
      pacing_limited_(false) {
  if (GetQuicReloadableFlag(quic_donot_reset_ideal_next_packet_send_time)) {
    QUIC_RELOADABLE_FLAG_COUNT(quic_donot_reset_ideal_next_packet_send_time);
  }
}

PacingSender::~PacingSender() {}

void PacingSender::set_sender(SendAlgorithmInterface* sender) {
  DCHECK(sender != nullptr);
  sender_ = sender;
}

void PacingSender::OnCongestionEvent(bool rtt_updated,
                                     QuicByteCount bytes_in_flight,
                                     QuicTime event_time,
                                     const AckedPacketVector& acked_packets,
                                     const LostPacketVector& lost_packets) {
  DCHECK(sender_ != nullptr);
  if (!lost_packets.empty()) {
    // Clear any burst tokens when entering recovery.
    burst_tokens_ = 0;
  }
  sender_->OnCongestionEvent(rtt_updated, bytes_in_flight, event_time,
                             acked_packets, lost_packets);
}

void PacingSender::OnPacketSent(
    QuicTime sent_time,
    QuicByteCount bytes_in_flight,
    QuicPacketNumber packet_number,
    QuicByteCount bytes,
    HasRetransmittableData has_retransmittable_data) {
  DCHECK(sender_ != nullptr);
  sender_->OnPacketSent(sent_time, bytes_in_flight, packet_number, bytes,
                        has_retransmittable_data);
  if (has_retransmittable_data != HAS_RETRANSMITTABLE_DATA) {
    return;
  }
  // If in recovery, the connection is not coming out of quiescence.
  if (bytes_in_flight == 0 && !sender_->InRecovery()) {
    // Add more burst tokens anytime the connection is leaving quiescence, but
    // limit it to the equivalent of a single bulk write, not exceeding the
    // current CWND in packets.
    burst_tokens_ = std::min(
        initial_burst_size_,
        static_cast<uint32_t>(sender_->GetCongestionWindow() / kDefaultTCPMSS));
  }
  if (burst_tokens_ > 0) {
    --burst_tokens_;
    if (!GetQuicReloadableFlag(quic_donot_reset_ideal_next_packet_send_time)) {
      ideal_next_packet_send_time_ = QuicTime::Zero();
    }
    pacing_limited_ = false;
    return;
  }
  // The next packet should be sent as soon as the current packet has been
  // transferred.  PacingRate is based on bytes in flight including this packet.
  QuicTime::Delta delay =
      PacingRate(bytes_in_flight + bytes).TransferTime(bytes);
  if (!pacing_limited_ || lumpy_tokens_ == 0) {
    // Reset lumpy_tokens_ if either application or cwnd throttles sending or
    // token runs out.
    lumpy_tokens_ = std::max(
        1u, std::min(static_cast<uint32_t>(
                         GetQuicFlag(FLAGS_quic_lumpy_pacing_size)),
                     static_cast<uint32_t>(
                         (sender_->GetCongestionWindow() *
                          GetQuicFlag(FLAGS_quic_lumpy_pacing_cwnd_fraction)) /
                         kDefaultTCPMSS)));
    if (GetQuicReloadableFlag(quic_no_lumpy_pacing_at_low_bw) &&
        sender_->BandwidthEstimate() <
            QuicBandwidth::FromKBitsPerSecond(1200)) {
      QUIC_RELOADABLE_FLAG_COUNT(quic_no_lumpy_pacing_at_low_bw);
      // Below 1.2Mbps, send 1 packet at once, because one full-sized packet
      // is about 10ms of queueing.
      lumpy_tokens_ = 1u;
    }
  }
  --lumpy_tokens_;
  if (pacing_limited_) {
    // Make up for lost time since pacing throttles the sending.
    ideal_next_packet_send_time_ = ideal_next_packet_send_time_ + delay;
  } else {
    ideal_next_packet_send_time_ =
        std::max(ideal_next_packet_send_time_ + delay, sent_time + delay);
  }
  // Stop making up for lost time if underlying sender prevents sending.
  pacing_limited_ = sender_->CanSend(bytes_in_flight + bytes);
}

void PacingSender::OnApplicationLimited() {
  // The send is application limited, stop making up for lost time.
  pacing_limited_ = false;
}

QuicTime::Delta PacingSender::TimeUntilSend(
    QuicTime now,
    QuicByteCount bytes_in_flight) const {
  DCHECK(sender_ != nullptr);

  if (!sender_->CanSend(bytes_in_flight)) {
    // The underlying sender prevents sending.
    return QuicTime::Delta::Infinite();
  }

  if (burst_tokens_ > 0 || bytes_in_flight == 0 || lumpy_tokens_ > 0) {
    // Don't pace if we have burst tokens available or leaving quiescence.
    return QuicTime::Delta::Zero();
  }

  // If the next send time is within the alarm granularity, send immediately.
  if (ideal_next_packet_send_time_ > now + alarm_granularity_) {
    QUIC_DVLOG(1) << "Delaying packet: "
                  << (ideal_next_packet_send_time_ - now).ToMicroseconds();
    return ideal_next_packet_send_time_ - now;
  }

  QUIC_DVLOG(1) << "Sending packet now. ideal_next_packet_send_time: "
                << ideal_next_packet_send_time_ << ", now: " << now;
  return QuicTime::Delta::Zero();
}

QuicBandwidth PacingSender::PacingRate(QuicByteCount bytes_in_flight) const {
  DCHECK(sender_ != nullptr);
  if (!max_pacing_rate_.IsZero()) {
    return QuicBandwidth::FromBitsPerSecond(
        std::min(max_pacing_rate_.ToBitsPerSecond(),
                 sender_->PacingRate(bytes_in_flight).ToBitsPerSecond()));
  }
  return sender_->PacingRate(bytes_in_flight);
}

}  // namespace quic
<|endoftext|>


<commit_before>#include <sstream> //std::stringstream
#include <ctime> //std::time
#include "request.h"
#include "lib/curl_wrapper.h"
#include "lib/exceptions.h"

using namespace bittrex;
using namespace bittrex::lib;

std::string Request::get(const std::string &key,
                         const std::string &secret,
                         const std::string &payloads,
                         const std::string &endpoint,
                         ApiType type) {

    std::string res;
    auto uri = BASE_URL + endpoint;
    CurlWrapper r;
    try {
        auto nonce = std::time(nullptr);
        if (type != ApiType::PUBLIC)
            uri += "apikey=" + key + "&nonce=" + std::to_string(nonce) + "&" + payloads;
        else
            uri += payloads;

        std::string apisign = "apisign:" + hmac_sha512(uri, secret);
        r.setOpt(curl::options::HttpHeader(apisign));
        r.setOpt(curl::options::WriteData(res));
        r.setOpt(curl::options::Url(uri));

        r.perform();
    }
    catch (fail &e) {
        std::cout << e.what() << std::endl;
    }
    return res;
}

<commit_msg>minor<commit_after>#include <sstream> //std::stringstream
#include <ctime> //std::time
#include "request.h"
#include "lib/curl_wrapper.h"
#include "lib/exceptions.h"

using namespace bittrex;
using namespace bittrex::lib;

std::string Request::get(const std::string &key,
                         const std::string &secret,
                         const std::string &payloads,
                         const std::string &endpoint,
                         ApiType type) {

    std::string res;
    auto uri = BASE_URL + endpoint;

    CurlWrapper r;
    try {
        auto nonce = std::time(nullptr);
        (type != ApiType::PUBLIC) ?
            uri += "apikey=" + key + "&nonce=" + std::to_string(nonce) + "&" + payloads :
            uri += payloads;

        std::string apisign = "apisign:" + hmac_sha512(uri, secret);
        r.setOpt(curl::options::HttpHeader(apisign));
        r.setOpt(curl::options::WriteData(res));
        r.setOpt(curl::options::Url(uri));

        r.perform();
    }
    catch (fail &e) {
        std::cout << e.what() << std::endl;
    }
    return res;
}

<|endoftext|>