<commit_before>// #include guards
#ifndef ICEFIELD_H
#define ICEFIELD_H

// Used for overloading << operator with an ostream
#include <iostream>

/* A class representing an ice rink that, like in Pac-Man and
 * Final Fantasy, has wraparound geography and finite dimensions.
 */
class IceField {
public:

    /* Creates a new IceField object
     * PARAMS
     **** rows: number of rows on the IceField
     **** cols: number of columns on the IceField
     **** startRow: initial row number of the zamboni, zero-indexed
     **** startCol: initial column number of the zamboni, zero-indexed
     **** numMoves: number of time the zamboni moves and changes color
     * RETURN
     **** IceField object created with the given parameters
     */
    IceField(int rows, int cols, int startRow, int startCol, int numMoves);

    /* Safely destroys the IceField object.
     */
    ~IceField();

    /* Cleans the ice according to the Pac-Man algorithm:
     * stepSize := 1
     * loop numMoves times
     *     Move stepSize steps in the current direction
     *     Rotate the direction of the zamboni 90 degrees clockwise
     *     Switch to the next color
     *     stepSize := stepSize + 1
     * end loop
     * The zamboni starts by facing up.
     */
    clean();

    /* Outputs a visual representation of the ice field, with
     * the letters A-Z representing the different colors, the
     * character '.' representing white ice, and the character
     * '@' representing the current location of the Zamboni.
     */
    friend std::ostream& operator<<(std::ostream& o, const IceField ice);

private:

    /* The number of colors the zamboni can paint. Since each
     * letter of the alphabet represents a different color,
     * there are 26 possible colors.
     */
    static const int NUMBER_OF_COLORS = 26;

    /* The character that represents the first color the zamboni
     * will paint. This is used to the field currentColor into
     * a character, since the expressions ZERO_COLOR + 0,
     * ZERO_COLOR + 1, and ZERO_COLOR + 2 will have the values
     * 'A', 'B', and 'C', respectively, and so on.
     */
    static const char ZERO_COLOR = 'A';

    /* Constants that represent the four directions in which the
     * zamboni can move.
     */
    static const int NORTH = 0;
    static const int EAST = 1;
    static const int SOUTH = 2;
    static const int WEST = 3;

    /* Number of rows in the ice field.
     */
    int rows;

    /* Number of columns in the ice field
     */
    int cols;

    /* Initial row number of the zamboni, zero-indexed
     */
    int startRow;

    /* Initial column number of the zamboni, zero-indexed
     */
    int startCol;

    /* Number of times the zamboni moves and changes color.
     */
    int numMoves;

    /* Distance the zamboni should move in the next direction.
     */
    int stepSize;

    /* A 2D array that contains the colors of every square on the
     * ice field, with '.' representing white, A-Z representing colors,
     * and '@' representing the current location of the zamboni.
     */
    char** grid;

    /* An integer representing the color the zamboni is painting.
     * Always meets the condition 0 <= currentColor < NUMBER_OF_COLORS.
     * To guarantee this, it should always be modded by NUMBER_OF_COLORS
     * after incrementing.
     */
    int currentColor = 0;

    /* An integer representing the direction in which the zamboni is
     * moving. It should always have the value NORTH, EAST, SOUTH, or
     * WEST.
     */
    int currentDirection;

    /* Moves the zamboni in its current direction, coloring every square
     * it passes over, including the square it starts from, and not
     * including the square it finishes on. If it moves across one edge,
     * it wraps around to the opposite edge.
     */
    void moveZamboni(int distance);

    /* Turns the zamboni clockwise.
     */
    void turnZamboni();
};

// Closes #include guard.
#endif<commit_msg>Fixed #include guard to match the header file name<commit_after>// #include guards
#ifndef ICEFIELD_HPP
#define ICEFIELD_HPP

// Used for overloading << operator with an ostream
#include <iostream>

/* A class representing an ice rink that, like in Pac-Man and
 * Final Fantasy, has wraparound geography and finite dimensions.
 */
class IceField {
public:

    /* Creates a new IceField object
     * PARAMS
     **** rows: number of rows on the IceField
     **** cols: number of columns on the IceField
     **** startRow: initial row number of the zamboni, zero-indexed
     **** startCol: initial column number of the zamboni, zero-indexed
     **** numMoves: number of time the zamboni moves and changes color
     * RETURN
     **** IceField object created with the given parameters
     */
    IceField(int rows, int cols, int startRow, int startCol, int numMoves);

    /* Safely destroys the IceField object.
     */
    ~IceField();

    /* Cleans the ice according to the Pac-Man algorithm:
     * stepSize := 1
     * loop numMoves times
     *     Move stepSize steps in the current direction
     *     Rotate the direction of the zamboni 90 degrees clockwise
     *     Switch to the next color
     *     stepSize := stepSize + 1
     * end loop
     * The zamboni starts by facing up.
     */
    clean();

    /* Outputs a visual representation of the ice field, with
     * the letters A-Z representing the different colors, the
     * character '.' representing white ice, and the character
     * '@' representing the current location of the Zamboni.
     */
    friend std::ostream& operator<<(std::ostream& o, const IceField ice);

private:

    /* The number of colors the zamboni can paint. Since each
     * letter of the alphabet represents a different color,
     * there are 26 possible colors.
     */
    static const int NUMBER_OF_COLORS = 26;

    /* The character that represents the first color the zamboni
     * will paint. This is used to the field currentColor into
     * a character, since the expressions ZERO_COLOR + 0,
     * ZERO_COLOR + 1, and ZERO_COLOR + 2 will have the values
     * 'A', 'B', and 'C', respectively, and so on.
     */
    static const char ZERO_COLOR = 'A';

    /* Constants that represent the four directions in which the
     * zamboni can move.
     */
    static const int NORTH = 0;
    static const int EAST = 1;
    static const int SOUTH = 2;
    static const int WEST = 3;

    /* Number of rows in the ice field.
     */
    int rows;

    /* Number of columns in the ice field
     */
    int cols;

    /* Initial row number of the zamboni, zero-indexed
     */
    int startRow;

    /* Initial column number of the zamboni, zero-indexed
     */
    int startCol;

    /* Number of times the zamboni moves and changes color.
     */
    int numMoves;

    /* Distance the zamboni should move in the next direction.
     */
    int stepSize;

    /* A 2D array that contains the colors of every square on the
     * ice field, with '.' representing white, A-Z representing colors,
     * and '@' representing the current location of the zamboni.
     */
    char** grid;

    /* An integer representing the color the zamboni is painting.
     * Always meets the condition 0 <= currentColor < NUMBER_OF_COLORS.
     * To guarantee this, it should always be modded by NUMBER_OF_COLORS
     * after incrementing.
     */
    int currentColor = 0;

    /* An integer representing the direction in which the zamboni is
     * moving. It should always have the value NORTH, EAST, SOUTH, or
     * WEST.
     */
    int currentDirection;

    /* Moves the zamboni in its current direction, coloring every square
     * it passes over, including the square it starts from, and not
     * including the square it finishes on. If it moves across one edge,
     * it wraps around to the opposite edge.
     */
    void moveZamboni(int distance);

    /* Turns the zamboni clockwise.
     */
    void turnZamboni();
};

// Closes #include guard.
#endif<|endoftext|>


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

#include <Urho3D/Core/CoreEvents.h>
#include <Urho3D/Core/ProcessUtils.h>
#include <Urho3D/Input/Input.h>
#include <Urho3D/UI/Font.h>
#include <Urho3D/UI/Text.h>
#include <Urho3D/UI/UI.h>

#include "HelloWorld.h"

#include <Urho3D/DebugNew.h>

// Expands to this example's entry-point
URHO3D_DEFINE_APPLICATION_MAIN(HelloWorld)

HelloWorld::HelloWorld(Context* context) :
    Sample(context)
{
}

void HelloWorld::Start()
{
    // Execute base class startup
    Sample::Start();

    // Create "Hello World" Text
    CreateText();

    // Finally subscribe to the update event. Note that by subscribing events at this point we have already missed some events
    // like the ScreenMode event sent by the Graphics subsystem when opening the application window. To catch those as well we
    // could subscribe in the constructor instead.
    SubscribeToEvents();

    // Set the mouse mode to use in the sample
    Sample::InitMouseMode(MM_FREE);
}

void HelloWorld::CreateText()
{
    ResourceCache* cache = GetSubsystem<ResourceCache>();

    // Construct new Text object
    SharedPtr<Text> helloText(new Text(context_));

    // Set String to display
    helloText->SetText("Hello World from Urho3D!");

    // Set font and text color
    helloText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 30);
    helloText->SetColor(Color(0.0f, 1.0f, 0.0f));

    // Align Text center-screen
    helloText->SetHorizontalAlignment(HA_CENTER);
    helloText->SetVerticalAlignment(VA_CENTER);

    // Add Text instance to the UI root element
    GetSubsystem<UI>()->GetRoot()->AddChild(helloText);
}

void HelloWorld::SubscribeToEvents()
{
    // Subscribe HandleUpdate() function for processing update events
    SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(HelloWorld, HandleUpdate));
}

void HelloWorld::HandleUpdate(StringHash eventType, VariantMap& eventData)
{
    // Do nothing for now, could be extended to eg. animate the display
}
<commit_msg>Temporarily add serialization test code.<commit_after>//
// Copyright (c) 2008-2017 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

#include <Urho3D/Core/CoreEvents.h>
#include <Urho3D/Core/ProcessUtils.h>
#include <Urho3D/Input/Input.h>
#include <Urho3D/UI/Font.h>
#include <Urho3D/UI/Text.h>
#include <Urho3D/UI/UI.h>
#include <Urho3D/IO/VectorBuffer.h> // TO BE REMOVED

#include "HelloWorld.h"

#include <Urho3D/DebugNew.h>

// Expands to this example's entry-point
URHO3D_DEFINE_APPLICATION_MAIN(HelloWorld)

// TO BE REMOVED
// @{
static const char* enumNames[] =
{
    "Enum1",
    "Enum2",
    "Enum3"
};

enum class TestEnum
{
    Enum1,
    Enum2,
    Enum3,
};

class TestSerializable : public Serializable
{
    URHO3D_OBJECT(TestSerializable, Serializable);

public:
    TestSerializable(Context* context) : Serializable(context) { }

    static void RegisterObject(Context* context)
    {
        context->RegisterFactory<TestSerializable>();
        URHO3D_ATTRIBUTE("attribute", String, attribute_, "attribute", AM_DEFAULT);
        URHO3D_ATTRIBUTE_EX("attributeEx", String, attributeEx_, OnAttributeExSet, "attributeEx", AM_DEFAULT);
        URHO3D_ENUM_ATTRIBUTE("enumAttribute", enumAttribute_, enumNames, TestEnum::Enum2, AM_DEFAULT);
        URHO3D_ENUM_ATTRIBUTE_EX("enumAttributeEx", enumAttributeEx_, OnEnumAttributeExSet, enumNames, TestEnum::Enum2, AM_DEFAULT);
        URHO3D_ACCESSOR_ATTRIBUTE("accessorAttribute", GetAccessorAttribute, SetAccessorAttribute, String, "accessorAttribute", AM_DEFAULT);
        URHO3D_ENUM_ACCESSOR_ATTRIBUTE("enumAccessorAttribute", GetEnumAccessorAttribute, SetEnumAccessorAttribute, TestEnum, enumNames, TestEnum::Enum3, AM_DEFAULT);
        URHO3D_MIXED_ACCESSOR_ATTRIBUTE("mixedAccessorAttribute", GetMixedAccessorAttribute, SetMixedAccessorAttribute, String, "mixedAccessorAttribute", AM_DEFAULT);

        {
            String suffix = "_temp";
            auto getter = [=](const TestSerializable& self, Variant& value)
            {
                value = self.customAttribute_ + suffix;
            };
            auto setter = [=](TestSerializable& self, const Variant& value)
            {
                self.customAttribute_ = value.GetString() + suffix;
            };
            URHO3D_CUSTOM_ATTRIBUTE("customAttribute", getter, setter, String, "customAttribute", AM_DEFAULT);
        }

        {
            auto getter = [=](const TestSerializable& self, Variant& value)
            {
                value = static_cast<int>(self.customEnumAttribute_);
            };
            auto setter = [=](TestSerializable& self, const Variant& value)
            {
                self.customEnumAttribute_ = static_cast<TestEnum>(value.GetInt());
            };
            URHO3D_CUSTOM_ENUM_ATTRIBUTE("customAttribute", getter, setter, enumNames, TestEnum::Enum1, AM_DEFAULT);
        }
    }

    String attribute_;
    String attributeEx_;
    void OnAttributeExSet()
    {
        attributeEx_ = attributeEx_.ToUpper();
    }
    TestEnum enumAttribute_ = TestEnum::Enum1;
    TestEnum enumAttributeEx_ = TestEnum::Enum1;
    void OnEnumAttributeExSet()
    {
        enumAttributeEx_ = static_cast<TestEnum>(static_cast<int>(enumAttributeEx_) + 1);
    }

    String accessorAttribute_;
    const String& GetAccessorAttribute() const { return accessorAttribute_; }
    void SetAccessorAttribute(const String& value) { accessorAttribute_ = value; }

    TestEnum enumAccessorAttribute_ = TestEnum::Enum1;
    TestEnum GetEnumAccessorAttribute() const { return enumAccessorAttribute_; }
    void SetEnumAccessorAttribute(TestEnum value) { enumAccessorAttribute_ = value; }

    String mixedAccessorAttribute_;
    String GetMixedAccessorAttribute() const { return mixedAccessorAttribute_; }
    void SetMixedAccessorAttribute(const String& value) { mixedAccessorAttribute_ = value; }

    String customAttribute_;
    TestEnum customEnumAttribute_ = TestEnum::Enum1;
};
// @}

HelloWorld::HelloWorld(Context* context) :
    Sample(context)
{
    // TO BE REMOVED
    // @{
    TestSerializable::RegisterObject(context);
    auto obj = MakeShared<TestSerializable>(context_);
    obj->ResetToDefault();

    VectorBuffer buf;
    XMLFile xml(context_);
    obj->SaveXML(xml.CreateRoot("test"));
    xml.Save(buf);
    String text;
    text.Append(reinterpret_cast<const char*>(buf.GetData()), buf.GetSize());
    obj.Reset();
    // @}
}

void HelloWorld::Start()
{
    // Execute base class startup
    Sample::Start();

    // Create "Hello World" Text
    CreateText();

    // Finally subscribe to the update event. Note that by subscribing events at this point we have already missed some events
    // like the ScreenMode event sent by the Graphics subsystem when opening the application window. To catch those as well we
    // could subscribe in the constructor instead.
    SubscribeToEvents();

    // Set the mouse mode to use in the sample
    Sample::InitMouseMode(MM_FREE);
}

void HelloWorld::CreateText()
{
    ResourceCache* cache = GetSubsystem<ResourceCache>();

    // Construct new Text object
    SharedPtr<Text> helloText(new Text(context_));

    // Set String to display
    helloText->SetText("Hello World from Urho3D!");

    // Set font and text color
    helloText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 30);
    helloText->SetColor(Color(0.0f, 1.0f, 0.0f));

    // Align Text center-screen
    helloText->SetHorizontalAlignment(HA_CENTER);
    helloText->SetVerticalAlignment(VA_CENTER);

    // Add Text instance to the UI root element
    GetSubsystem<UI>()->GetRoot()->AddChild(helloText);
}

void HelloWorld::SubscribeToEvents()
{
    // Subscribe HandleUpdate() function for processing update events
    SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(HelloWorld, HandleUpdate));
}

void HelloWorld::HandleUpdate(StringHash eventType, VariantMap& eventData)
{
    // Do nothing for now, could be extended to eg. animate the display
}
<|endoftext|>


<commit_before>// 837 Studios - 2016 - Michael Gaskin (teak421) -- MIT License

#include "SmoothZoomPrivatePCH.h"
#include "SmoothZoom.h"
#include "AC_SmoothZoom.h"

DEFINE_LOG_CATEGORY(ZoomLog);

UAC_SmoothZoom::UAC_SmoothZoom()
{
	PrimaryComponentTick.bCanEverTick = true;
	// Default Values
	CurrentVersion = 1.3f;
	MinTargetLength = 150.0f;
	MaxTargetLength = 1500.0f;
	ZoomUnits = 125.0f;
	ZoomSmoothness = 9.0f;
}

void UAC_SmoothZoom::BeginPlay() { 	Super::BeginPlay(); }

void UAC_SmoothZoom::TickComponent( float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction )
{
	Super::TickComponent(DeltaTime, TickType, ThisTickFunction);

	// Only call when need to, saves ms's
	if (SpringArm->TargetArmLength != DesiredArmLength)
	{
		SpringArm->TargetArmLength = FMath::FInterpTo(SpringArm->TargetArmLength, DesiredArmLength, DeltaTime, ZoomSmoothness);
	}
}

// Assigns the SpringArm component
void UAC_SmoothZoom::SetSpringArmComponent(UPARAM(ref)USpringArmComponent* AssignedSpringArm)
{
	DesiredArmLength = AssignedSpringArm->TargetArmLength;
	SpringArm = AssignedSpringArm;
}

// Sets the DesiredArmLength
void UAC_SmoothZoom::SmoothCameraZoom(bool bZoomOut)
{
	DesiredArmLength = bZoomOut ? SpringArm->TargetArmLength + ZoomUnits
		: SpringArm->TargetArmLength + (ZoomUnits * -1);
	if (DesiredArmLength > MaxTargetLength || DesiredArmLength < MinTargetLength)
	{
		DesiredArmLength = FMath::Min<float>(FMath::Max<float>(DesiredArmLength, MinTargetLength), MaxTargetLength);
	}

	if (bDebug) { SmoothZoomLog(); }
}

void UAC_SmoothZoom::SmoothZoomLog()
{
	UE_LOG(ZoomLog, Log, TEXT("ArmLength: %f, Min: %f Max: %f, ZUnits: %f, Smoothness: %f"),
		DesiredArmLength, MinTargetLength, MaxTargetLength, ZoomUnits, ZoomSmoothness)
}

<commit_msg>Improvement in how checking occurs in the tick function.  Will reduce calls.  Thanks to dc5ala.<commit_after>// 837 Studios - 2016 - Michael Gaskin (teak421) -- MIT License

#include "SmoothZoomPrivatePCH.h"
#include "SmoothZoom.h"
#include "AC_SmoothZoom.h"

DEFINE_LOG_CATEGORY(ZoomLog);

UAC_SmoothZoom::UAC_SmoothZoom()
{
	PrimaryComponentTick.bCanEverTick = true;
	// Default Values
	CurrentVersion = 1.31f;
	MinTargetLength = 150.0f;
	MaxTargetLength = 1500.0f;
	ZoomUnits = 125.0f;
	ZoomSmoothness = 9.0f;
}

void UAC_SmoothZoom::BeginPlay() { 	Super::BeginPlay(); }

void UAC_SmoothZoom::TickComponent( float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction )
{
	Super::TickComponent(DeltaTime, TickType, ThisTickFunction);

	// Only call when need to, saves ms's
	if (!FMath::IsNearlyEqual(SpringArm->TargetArmLength, DesiredArmLength, 0.5f))
	{
		SpringArm->TargetArmLength = FMath::FInterpTo(SpringArm->TargetArmLength, DesiredArmLength, DeltaTime, ZoomSmoothness);
	}
}

// Assigns the SpringArm component
void UAC_SmoothZoom::SetSpringArmComponent(UPARAM(ref)USpringArmComponent* AssignedSpringArm)
{
	DesiredArmLength = AssignedSpringArm->TargetArmLength;
	SpringArm = AssignedSpringArm;
}

// Sets the DesiredArmLength
void UAC_SmoothZoom::SmoothCameraZoom(bool bZoomOut)
{
	DesiredArmLength = bZoomOut ? SpringArm->TargetArmLength + ZoomUnits
		: SpringArm->TargetArmLength + (ZoomUnits * -1);
	if (DesiredArmLength > MaxTargetLength || DesiredArmLength < MinTargetLength)
	{
		DesiredArmLength = FMath::Min<float>(FMath::Max<float>(DesiredArmLength, MinTargetLength), MaxTargetLength);
	}

	if (bDebug) { SmoothZoomLog(); }
}

void UAC_SmoothZoom::SmoothZoomLog()
{
	UE_LOG(ZoomLog, Log, TEXT("ArmLength: %f, Min: %f Max: %f, ZUnits: %f, Smoothness: %f"),
		DesiredArmLength, MinTargetLength, MaxTargetLength, ZoomUnits, ZoomSmoothness)
}

<|endoftext|>


<commit_before>/**
 * This file is part of TelepathyQt4
 *
 * @copyright Copyright (C) 2011 Collabora Ltd. <http://www.collabora.co.uk/>
 * @copyright Copyright (C) 2011 Nokia Corporation
 * @license LGPL 2.1
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "TelepathyQt4/simple-stream-tube-handler.h"

#include "TelepathyQt4/_gen/simple-stream-tube-handler.moc.hpp"

#include "TelepathyQt4/debug-internal.h"

#include <TelepathyQt4/Account>
#include <TelepathyQt4/ChannelClassSpec>
#include <TelepathyQt4/PendingComposite>
#include <TelepathyQt4/PendingReady>
#include <TelepathyQt4/StreamTubeChannel>

namespace Tp
{

namespace
{
    ChannelClassSpecList buildFilter(const QStringList &p2pServices,
            const QStringList &roomServices, bool requested)
    {
        ChannelClassSpecList filter;

        foreach (const QString &service, p2pServices)
        {
            filter.append(requested ?
                    ChannelClassSpec::outgoingStreamTube(service) :
                    ChannelClassSpec::incomingStreamTube(service));
        }

        foreach (const QString &service, roomServices)
        {
            filter.append(requested ?
                    ChannelClassSpec::outgoingRoomStreamTube(service) :
                    ChannelClassSpec::incomingRoomStreamTube(service));
        }

        return filter;
    }
}

SharedPtr<SimpleStreamTubeHandler> SimpleStreamTubeHandler::create(
        const QStringList &p2pServices,
        const QStringList &roomServices,
        bool requested,
        bool monitorConnections,
        bool bypassApproval)
{
    return SharedPtr<SimpleStreamTubeHandler>(
            new SimpleStreamTubeHandler(
                p2pServices,
                roomServices,
                requested,
                monitorConnections,
                bypassApproval));
}

SimpleStreamTubeHandler::SimpleStreamTubeHandler(
        const QStringList &p2pServices,
        const QStringList &roomServices,
        bool requested,
        bool monitorConnections,
        bool bypassApproval)
    : AbstractClient(),
    AbstractClientHandler(buildFilter(p2pServices, roomServices, requested)),
    mMonitorConnections(monitorConnections),
    mBypassApproval(bypassApproval)
{
}

SimpleStreamTubeHandler::~SimpleStreamTubeHandler()
{
    if (!mTubes.empty()) {
        debug() << "~SSTubeHandler(): Closing" << mTubes.size() << "leftover tubes";

        foreach (const StreamTubeChannelPtr &tube, mTubes.keys()) {
            tube->requestClose();
        }
    }
}

void SimpleStreamTubeHandler::handleChannels(
        const MethodInvocationContextPtr<> &context,
        const AccountPtr &account,
        const ConnectionPtr &connection,
        const QList<ChannelPtr> &channels,
        const QList<ChannelRequestPtr> &requestsSatisfied,
        const QDateTime &userActionTime,
        const HandlerInfo &handlerInfo)
{
    debug() << "SimpleStreamTubeHandler::handleChannels() invoked for " <<
        channels.size() << "channels on account" << account->objectPath();

    SharedPtr<InvocationData> invocation(new InvocationData());
    QList<PendingOperation *> readyOps;

    foreach (const ChannelPtr &chan, channels) {
        StreamTubeChannelPtr tube = StreamTubeChannelPtr::qObjectCast(chan);

        if (!tube) {
            // TODO: if Channel ever starts utilizing its immutable props for the immutable
            // accessors, use Channel::channelType() here
            const QString channelType =
                chan->immutableProperties()[QLatin1String(
                        TELEPATHY_INTERFACE_CHANNEL ".ChannelType")].toString();

            if (channelType != TP_QT4_IFACE_CHANNEL_TYPE_STREAM_TUBE) {
                debug() << "We got a non-StreamTube channel" << chan->objectPath() <<
                    "of type" << channelType << ", ignoring";
            } else {
                warning() << "The channel factory used for a simple StreamTube handler must" <<
                    "construct StreamTubeChannel subclasses for stream tubes";
            }
            continue;
        }

        Features features = StreamTubeChannel::FeatureStreamTube;
        if (mMonitorConnections) {
            features.insert(StreamTubeChannel::FeatureConnectionMonitoring);
        }
        readyOps.append(tube->becomeReady(features));

        invocation->tubes.append(tube);
    }

    invocation->ctx = context;
    invocation->acc = account;
    invocation->time = userActionTime;

    if (!requestsSatisfied.isEmpty()) {
        invocation->hints = requestsSatisfied.first()->hints();
    }

    mInvocations.append(invocation);

    if (invocation->tubes.isEmpty()) {
        warning() << "SSTH::HandleChannels got no suitable channels, admitting we're Confused";
        invocation->readyOp = 0;
        invocation->error = TP_QT4_ERROR_CONFUSED;
        invocation->message = QLatin1String("Got no suitable channels");
        onReadyOpFinished(0);
    } else {
        invocation->readyOp = new PendingComposite(readyOps, SharedPtr<SimpleStreamTubeHandler>(this));
        connect(invocation->readyOp,
                SIGNAL(finished(Tp::PendingOperation*)),
                SLOT(onReadyOpFinished(Tp::PendingOperation*)));
    }
}

void SimpleStreamTubeHandler::onReadyOpFinished(Tp::PendingOperation *op)
{
    Q_ASSERT(!mInvocations.isEmpty());
    Q_ASSERT(!op || op->isFinished());

    for (QLinkedList<SharedPtr<InvocationData> >::iterator i = mInvocations.begin();
            op != 0 && i != mInvocations.end(); ++i) {
        if ((*i)->readyOp != op) {
            continue;
        }

        (*i)->readyOp = 0;

        if (op->isError()) {
            warning() << "Preparing proxies for SSTubeHandler failed with" << op->errorName()
                << op->errorMessage();
            (*i)->error = op->errorName();
            (*i)->message = op->errorMessage();
        }

        break;
    }

    while (!mInvocations.isEmpty() && !mInvocations.first()->readyOp) {
        SharedPtr<InvocationData> invocation = mInvocations.takeFirst();

        if (!invocation->error.isEmpty()) {
            // We guarantee that the proxies were ready - so we can't invoke the client if they
            // weren't made ready successfully. Fix the introspection code if this happens :)
            invocation->ctx->setFinishedWithError(invocation->error, invocation->message);
            continue;
        }

        debug() << "Emitting SSTubeHandler::invokedForTube for" << invocation->tubes.size()
            << "tubes";

        foreach (const StreamTubeChannelPtr &tube, invocation->tubes) {
            if (!tube->isValid()) {
                debug() << "Skipping already invalidated tube" << tube->objectPath();
                continue;
            }

            if (!mTubes.contains(tube)) {
                connect(tube.data(),
                        SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),
                        SLOT(onTubeInvalidated(Tp::DBusProxy*,QString,QString)));

                mTubes.insert(tube, invocation->acc);
            }

            emit invokedForTube(
                    invocation->acc,
                    tube,
                    invocation->time,
                    invocation->hints);
        }

        invocation->ctx->setFinished();
    }
}

void SimpleStreamTubeHandler::onTubeInvalidated(DBusProxy *proxy,
        const QString &errorName, const QString &errorMessage)
{
    StreamTubeChannelPtr tube(qobject_cast<StreamTubeChannel *>(proxy));

    Q_ASSERT(!tube.isNull());
    Q_ASSERT(mTubes.contains(tube));

    debug() << "Tube" << tube->objectPath() << "invalidated - " << errorName << ':' << errorMessage;

    AccountPtr acc = mTubes.value(tube);
    mTubes.remove(tube);

    emit tubeInvalidated(
            acc,
            tube,
            errorName,
            errorMessage);
}

} // Tp
<commit_msg>SimpleStreamTubeHandler: Weed out duplicate services when building filter<commit_after>/**
 * This file is part of TelepathyQt4
 *
 * @copyright Copyright (C) 2011 Collabora Ltd. <http://www.collabora.co.uk/>
 * @copyright Copyright (C) 2011 Nokia Corporation
 * @license LGPL 2.1
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "TelepathyQt4/simple-stream-tube-handler.h"

#include "TelepathyQt4/_gen/simple-stream-tube-handler.moc.hpp"

#include "TelepathyQt4/debug-internal.h"

#include <TelepathyQt4/Account>
#include <TelepathyQt4/ChannelClassSpec>
#include <TelepathyQt4/PendingComposite>
#include <TelepathyQt4/PendingReady>
#include <TelepathyQt4/StreamTubeChannel>

namespace Tp
{

namespace
{
    ChannelClassSpecList buildFilter(const QStringList &p2pServices,
            const QStringList &roomServices, bool requested)
    {
        ChannelClassSpecList filter;

        // Convert to QSet to weed out duplicates
        foreach (const QString &service, p2pServices.toSet())
        {
            filter.append(requested ?
                    ChannelClassSpec::outgoingStreamTube(service) :
                    ChannelClassSpec::incomingStreamTube(service));
        }

        // Convert to QSet to weed out duplicates
        foreach (const QString &service, roomServices.toSet())
        {
            filter.append(requested ?
                    ChannelClassSpec::outgoingRoomStreamTube(service) :
                    ChannelClassSpec::incomingRoomStreamTube(service));
        }

        return filter;
    }
}

SharedPtr<SimpleStreamTubeHandler> SimpleStreamTubeHandler::create(
        const QStringList &p2pServices,
        const QStringList &roomServices,
        bool requested,
        bool monitorConnections,
        bool bypassApproval)
{
    return SharedPtr<SimpleStreamTubeHandler>(
            new SimpleStreamTubeHandler(
                p2pServices,
                roomServices,
                requested,
                monitorConnections,
                bypassApproval));
}

SimpleStreamTubeHandler::SimpleStreamTubeHandler(
        const QStringList &p2pServices,
        const QStringList &roomServices,
        bool requested,
        bool monitorConnections,
        bool bypassApproval)
    : AbstractClient(),
    AbstractClientHandler(buildFilter(p2pServices, roomServices, requested)),
    mMonitorConnections(monitorConnections),
    mBypassApproval(bypassApproval)
{
}

SimpleStreamTubeHandler::~SimpleStreamTubeHandler()
{
    if (!mTubes.empty()) {
        debug() << "~SSTubeHandler(): Closing" << mTubes.size() << "leftover tubes";

        foreach (const StreamTubeChannelPtr &tube, mTubes.keys()) {
            tube->requestClose();
        }
    }
}

void SimpleStreamTubeHandler::handleChannels(
        const MethodInvocationContextPtr<> &context,
        const AccountPtr &account,
        const ConnectionPtr &connection,
        const QList<ChannelPtr> &channels,
        const QList<ChannelRequestPtr> &requestsSatisfied,
        const QDateTime &userActionTime,
        const HandlerInfo &handlerInfo)
{
    debug() << "SimpleStreamTubeHandler::handleChannels() invoked for " <<
        channels.size() << "channels on account" << account->objectPath();

    SharedPtr<InvocationData> invocation(new InvocationData());
    QList<PendingOperation *> readyOps;

    foreach (const ChannelPtr &chan, channels) {
        StreamTubeChannelPtr tube = StreamTubeChannelPtr::qObjectCast(chan);

        if (!tube) {
            // TODO: if Channel ever starts utilizing its immutable props for the immutable
            // accessors, use Channel::channelType() here
            const QString channelType =
                chan->immutableProperties()[QLatin1String(
                        TELEPATHY_INTERFACE_CHANNEL ".ChannelType")].toString();

            if (channelType != TP_QT4_IFACE_CHANNEL_TYPE_STREAM_TUBE) {
                debug() << "We got a non-StreamTube channel" << chan->objectPath() <<
                    "of type" << channelType << ", ignoring";
            } else {
                warning() << "The channel factory used for a simple StreamTube handler must" <<
                    "construct StreamTubeChannel subclasses for stream tubes";
            }
            continue;
        }

        Features features = StreamTubeChannel::FeatureStreamTube;
        if (mMonitorConnections) {
            features.insert(StreamTubeChannel::FeatureConnectionMonitoring);
        }
        readyOps.append(tube->becomeReady(features));

        invocation->tubes.append(tube);
    }

    invocation->ctx = context;
    invocation->acc = account;
    invocation->time = userActionTime;

    if (!requestsSatisfied.isEmpty()) {
        invocation->hints = requestsSatisfied.first()->hints();
    }

    mInvocations.append(invocation);

    if (invocation->tubes.isEmpty()) {
        warning() << "SSTH::HandleChannels got no suitable channels, admitting we're Confused";
        invocation->readyOp = 0;
        invocation->error = TP_QT4_ERROR_CONFUSED;
        invocation->message = QLatin1String("Got no suitable channels");
        onReadyOpFinished(0);
    } else {
        invocation->readyOp = new PendingComposite(readyOps, SharedPtr<SimpleStreamTubeHandler>(this));
        connect(invocation->readyOp,
                SIGNAL(finished(Tp::PendingOperation*)),
                SLOT(onReadyOpFinished(Tp::PendingOperation*)));
    }
}

void SimpleStreamTubeHandler::onReadyOpFinished(Tp::PendingOperation *op)
{
    Q_ASSERT(!mInvocations.isEmpty());
    Q_ASSERT(!op || op->isFinished());

    for (QLinkedList<SharedPtr<InvocationData> >::iterator i = mInvocations.begin();
            op != 0 && i != mInvocations.end(); ++i) {
        if ((*i)->readyOp != op) {
            continue;
        }

        (*i)->readyOp = 0;

        if (op->isError()) {
            warning() << "Preparing proxies for SSTubeHandler failed with" << op->errorName()
                << op->errorMessage();
            (*i)->error = op->errorName();
            (*i)->message = op->errorMessage();
        }

        break;
    }

    while (!mInvocations.isEmpty() && !mInvocations.first()->readyOp) {
        SharedPtr<InvocationData> invocation = mInvocations.takeFirst();

        if (!invocation->error.isEmpty()) {
            // We guarantee that the proxies were ready - so we can't invoke the client if they
            // weren't made ready successfully. Fix the introspection code if this happens :)
            invocation->ctx->setFinishedWithError(invocation->error, invocation->message);
            continue;
        }

        debug() << "Emitting SSTubeHandler::invokedForTube for" << invocation->tubes.size()
            << "tubes";

        foreach (const StreamTubeChannelPtr &tube, invocation->tubes) {
            if (!tube->isValid()) {
                debug() << "Skipping already invalidated tube" << tube->objectPath();
                continue;
            }

            if (!mTubes.contains(tube)) {
                connect(tube.data(),
                        SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),
                        SLOT(onTubeInvalidated(Tp::DBusProxy*,QString,QString)));

                mTubes.insert(tube, invocation->acc);
            }

            emit invokedForTube(
                    invocation->acc,
                    tube,
                    invocation->time,
                    invocation->hints);
        }

        invocation->ctx->setFinished();
    }
}

void SimpleStreamTubeHandler::onTubeInvalidated(DBusProxy *proxy,
        const QString &errorName, const QString &errorMessage)
{
    StreamTubeChannelPtr tube(qobject_cast<StreamTubeChannel *>(proxy));

    Q_ASSERT(!tube.isNull());
    Q_ASSERT(mTubes.contains(tube));

    debug() << "Tube" << tube->objectPath() << "invalidated - " << errorName << ':' << errorMessage;

    AccountPtr acc = mTubes.value(tube);
    mTubes.remove(tube);

    emit tubeInvalidated(
            acc,
            tube,
            errorName,
            errorMessage);
}

} // Tp
<|endoftext|>


<commit_before>//
// Name: UtilDlg.cpp
//
// Copyright (c) 2002-2006 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#ifdef __GNUG__
	#pragma implementation "UtilDlg.cpp"
#endif

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#include "vtlib/vtlib.h"
#include "vtlib/core/Route.h"
#include "UtilDlg.h"
#include "EnviroGUI.h"

// WDR: class implementations

//----------------------------------------------------------------------------
// UtilDlg
//----------------------------------------------------------------------------

// WDR: event table for UtilDlg

BEGIN_EVENT_TABLE(UtilDlg,AutoDialog)
	EVT_INIT_DIALOG (UtilDlg::OnInitDialog)
	EVT_CHOICE( ID_STRUCTTYPE, UtilDlg::OnStructType )
END_EVENT_TABLE()

UtilDlg::UtilDlg( wxWindow *parent, wxWindowID id, const wxString &title,
	const wxPoint &position, const wxSize& size, long style ) :
	AutoDialog( parent, id, title, position, size, style )
{
	UtilDialogFunc( this, TRUE );

	m_pChoice = GetStructtype();
	m_iType = 0;

	AddValidator(ID_STRUCTTYPE, &m_iType);
}

// WDR: handler implementations for UtilDlg

void UtilDlg::OnStructType( wxCommandEvent &event )
{
	TransferDataFromWindow();
	wxString val = m_pChoice->GetStringSelection();
	g_App.SetRouteOptions((const char *) val.mb_str(wxConvUTF8));
	g_App.start_new_fence();
}

void UtilDlg::OnInitDialog(wxInitDialogEvent& event)
{
	vtContentManager &mng = vtGetContent();

	m_pChoice->Clear();
	for (unsigned int i = 0; i < mng.NumItems(); i++)
	{
		vtString str;
		vtItem *item = mng.GetItem(i);
		if (item->GetValueString("type", str))
		{
			if (str == "utility pole")
				m_pChoice->Append(wxString::FromAscii(item->m_name));
		}
	}
	TransferDataToWindow();

	wxString val = m_pChoice->GetStringSelection();
	g_App.SetRouteOptions((const char *) val.mb_str(wxConvUTF8));
}

<commit_msg>added logging<commit_after>//
// Name: UtilDlg.cpp
//
// Copyright (c) 2002-2008 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#ifdef __GNUG__
	#pragma implementation "UtilDlg.cpp"
#endif

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#include "vtlib/vtlib.h"
#include "vtlib/core/Route.h"
#include "UtilDlg.h"
#include "EnviroGUI.h"
#include "vtdata/vtLog.h"

// WDR: class implementations

//----------------------------------------------------------------------------
// UtilDlg
//----------------------------------------------------------------------------

// WDR: event table for UtilDlg

BEGIN_EVENT_TABLE(UtilDlg,AutoDialog)
	EVT_INIT_DIALOG (UtilDlg::OnInitDialog)
	EVT_CHOICE( ID_STRUCTTYPE, UtilDlg::OnStructType )
END_EVENT_TABLE()

UtilDlg::UtilDlg( wxWindow *parent, wxWindowID id, const wxString &title,
	const wxPoint &position, const wxSize& size, long style ) :
	AutoDialog( parent, id, title, position, size, style )
{
	UtilDialogFunc( this, TRUE );

	m_pChoice = GetStructtype();
	m_iType = 0;

	AddValidator(ID_STRUCTTYPE, &m_iType);
}

// WDR: handler implementations for UtilDlg

void UtilDlg::OnStructType( wxCommandEvent &event )
{
	TransferDataFromWindow();
	wxString val = m_pChoice->GetStringSelection();
	g_App.SetRouteOptions((const char *) val.mb_str(wxConvUTF8));
	g_App.start_new_fence();
}

void UtilDlg::OnInitDialog(wxInitDialogEvent& event)
{
	VTLOG("UtilDlg looking for items of type utility pole.\n");
	vtContentManager &mng = vtGetContent();

	int found = 0;
	m_pChoice->Clear();
	for (unsigned int i = 0; i < mng.NumItems(); i++)
	{
		vtString str;
		vtItem *item = mng.GetItem(i);
		if (item->GetValueString("type", str))
		{
			if (str == "utility pole")
			{
				m_pChoice->Append(wxString::FromAscii(item->m_name));
				found++;
			}
		}
	}
	TransferDataToWindow();

	VTLOG("\t%d items, %d found.\n", mng.NumItems(), found);

	wxString val = m_pChoice->GetStringSelection();
	g_App.SetRouteOptions((const char *) val.mb_str(wxConvUTF8));
}

<|endoftext|>


<commit_before>#include <stdio.h>
#include <ctype.h>
#include <metaImage.h>

int testMetaImage(int argc, char *argv[])
  {

  MetaImage tIm(8, 8, 1, 2, MET_CHAR);

  int i;
  for(i=0; i<64; i++)
    tIm.ElementData(i, i);

  for(i=0; i<64; i++)
    {
    if(i != tIm.ElementData(i))
      {
      std::cout << "Assigned Element Values Maintained: FAIL" << std::endl;
      return 1;
      }
    }

  tIm.Write("test.mha");
  tIm.PrintInfo();

  MetaImage tIm2("test.mha");
  tIm2.PrintInfo();
  for(i=0; i<64; i++)
    {
    if(i != tIm.ElementData(i))
      {
      std::cout << "Read Element Values: FAIL" << std::endl;
      return 1;
      }
    }

  return 0;
  }
<commit_msg>STYLE: Added end of test<commit_after>#include <stdio.h>
#include <ctype.h>
#include <metaImage.h>

int testMetaImage(int argc, char *argv[])
  {

  MetaImage tIm(8, 8, 1, 2, MET_CHAR);

  int i;
  for(i=0; i<64; i++)
    tIm.ElementData(i, i);

  for(i=0; i<64; i++)
    {
    if(i != tIm.ElementData(i))
      {
      std::cout << "Assigned Element Values Maintained: FAIL" << std::endl;
      return 1;
      }
    }

  tIm.Write("test.mha");
  tIm.PrintInfo();

  MetaImage tIm2("test.mha");
  tIm2.PrintInfo();
  for(i=0; i<64; i++)
    {
    if(i != tIm.ElementData(i))
      {
      std::cout << "Read Element Values: FAIL" << std::endl;
      return 1;
      }
    }

  std::cout << "[DONE]" << std::endl;
  return 0;
  }
<|endoftext|>


<commit_before>/*
 * FstAligner.cpp
 *
 * align hypothesis fst to reference fst, produce WER
 *
 *  Created on: 2010-12-6
 *      Author: freqyifan@gmail.com
 */

#include "FstAligner.h"

#include <iostream>
#include <fstream>
#include <fst/fstlib.h>
#include <fst/script/draw.h>

FstAligner::FstAligner() {
	// TODO Auto-generated constructor stub

}

FstAligner::~FstAligner() {
	// TODO Auto-generated destructor stub
}

void drawFstToFile(fst::StdVectorFst &fstToDraw, const fst::SymbolTable &symbol, const std::string &name) {
	std::ofstream stream(name.c_str());
	if (stream.is_open()) {
		fst::script::FstClass object(&fstToDraw);
		fst::script::DrawFst(object, &symbol, &symbol, 0, false,
							name, 8.5, 11, false, false, 0.40, 0.25, 14, 5,
							false, &stream, name);
	}
	stream.close();
}

void FstAligner::align(const FstAlignOption & option,
		const FstLoader &refLoader, const FstLoader &hypLoader,
		FstAlignResult &result) {
	fst::SymbolTable symbol("symbol");

	symbol.AddSymbol(option.symEps);
	symbol.AddSymbol(option.symOov);
	symbol.AddSymbol(option.symIns);
	symbol.AddSymbol(option.symDel);
	symbol.AddSymbol(option.symSub);

	refLoader.addToSymbolTable(symbol);
	hypLoader.addToSymbolTable(symbol);
	fst::StdVectorFst refFst = refLoader.convertToFst(symbol);
	fst::StdVectorFst hypFst = hypLoader.convertToFst(symbol);

	symbol.WriteText("symbol");

	assert(refFst.NumStates() > 1);
	assert(hypFst.NumStates() > 1);

	// add possible insertion/deletion/substitution to reference
	int nstate = refFst.NumStates();

	if (option.bForceEnterAndExit == false) {
		refFst.AddArc(0, fst::StdArc(symbol.Find(option.symOov), symbol.Find(option.symIns),
										option.insCost, 0));
		refFst.AddArc(nstate-1, fst::StdArc(symbol.Find(option.symOov), symbol.Find(option.symIns),
										option.insCost, nstate-1));
	}
	else {
		nstate --;
	}

	for (int i=1; i<nstate; i++) {
		refFst.AddArc(i-1, fst::StdArc(symbol.Find(option.symEps), symbol.Find(refLoader.getToken(i-1)),
										option.delCost, i));
		refFst.AddArc(i-1, fst::StdArc(symbol.Find(option.symOov), symbol.Find(refLoader.getToken(i-1)),
										option.subCost, i));
	}

	fst::ArcSort(&hypFst, fst::StdOLabelCompare());
	fst::ArcSort(&refFst, fst::StdILabelCompare());

	typedef fst::SigmaMatcher< fst::SortedMatcher<fst::StdFst> >RM;
	fst::ComposeFstOptions<fst::StdArc, RM> opts;
	opts.gc_limit = 0;
	opts.matcher1 = new RM(hypFst, fst::MATCH_NONE, fst::kNoLabel);
	opts.matcher2 = new RM(refFst, fst::MATCH_INPUT, symbol.Find(option.symOov));

	fst::StdComposeFst cFst(hypFst, refFst, opts);
	fst::StdVectorFst composedFst(cFst);

	if (option.saveCompositionDot != "")
		drawFstToFile(composedFst, symbol, option.saveCompositionDot);

	fst::StdVectorFst pathFst;
	fst::ShortestPath(composedFst, &pathFst);
	if (option.saveShortestPathDot != "")
		drawFstToFile(pathFst, symbol, option.saveShortestPathDot);

	fst::StdVectorFst::StateId state = pathFst.Start();
	while (state > 0) {
		fst::ArcIterator<fst::StdVectorFst> aiter(pathFst, state);
		const fst::StdArc &arc = aiter.Value();
		result.alignment.push_back(std::make_pair(symbol.Find(arc.ilabel), symbol.Find(arc.olabel)));
		state = arc.nextstate;
	}

	result.update(option);
}
<commit_msg>/ bugfix: added missing insertions on all reference states<commit_after>/*
 * FstAligner.cpp
 *
 * align hypothesis fst to reference fst, produce WER
 *
 *  Created on: 2010-12-6
 *      Author: freqyifan@gmail.com
 */

#include "FstAligner.h"

#include <iostream>
#include <fstream>
#include <fst/fstlib.h>
#include <fst/script/draw.h>

FstAligner::FstAligner() {
	// TODO Auto-generated constructor stub

}

FstAligner::~FstAligner() {
	// TODO Auto-generated destructor stub
}

void drawFstToFile(fst::StdVectorFst &fstToDraw, const fst::SymbolTable &symbol, const std::string &name) {
	std::ofstream stream(name.c_str());
	if (stream.is_open()) {
		fst::script::FstClass object(&fstToDraw);
		fst::script::DrawFst(object, &symbol, &symbol, 0, false,
							name, 8.5, 11, false, false, 0.40, 0.25, 14, 5,
							false, &stream, name);
	}
	stream.close();
}

void FstAligner::align(const FstAlignOption & option,
		const FstLoader &refLoader, const FstLoader &hypLoader,
		FstAlignResult &result) {
	fst::SymbolTable symbol("symbol");

	symbol.AddSymbol(option.symEps);
	symbol.AddSymbol(option.symOov);
	symbol.AddSymbol(option.symIns);
	symbol.AddSymbol(option.symDel);
	symbol.AddSymbol(option.symSub);

	refLoader.addToSymbolTable(symbol);
	hypLoader.addToSymbolTable(symbol);
	fst::StdVectorFst refFst = refLoader.convertToFst(symbol);
	fst::StdVectorFst hypFst = hypLoader.convertToFst(symbol);

	symbol.WriteText("symbol");

	assert(refFst.NumStates() > 1);
	assert(hypFst.NumStates() > 1);

	// add possible insertion/deletion/substitution to reference
	int nstate = refFst.NumStates();

	if (option.bForceEnterAndExit == false) {
		refFst.AddArc(0, fst::StdArc(symbol.Find(option.symOov), symbol.Find(option.symIns),
										option.insCost, 0));
		refFst.AddArc(nstate-1, fst::StdArc(symbol.Find(option.symOov), symbol.Find(option.symIns),
										option.insCost, nstate-1));
	}
	else {
		nstate --;
	}

	for (int i=1; i<nstate; i++) {
		refFst.AddArc(i-1, fst::StdArc(symbol.Find(option.symEps), symbol.Find(refLoader.getToken(i-1)),
										option.delCost, i));
		refFst.AddArc(i-1, fst::StdArc(symbol.Find(option.symOov), symbol.Find(refLoader.getToken(i-1)),
										option.subCost, i));
		refFst.AddArc(i, fst::StdArc(symbol.Find(option.symOov), symbol.Find(option.symIns),
										option.insCost, i));
	}

	fst::ArcSort(&hypFst, fst::StdOLabelCompare());
	fst::ArcSort(&refFst, fst::StdILabelCompare());

	typedef fst::SigmaMatcher< fst::SortedMatcher<fst::StdFst> >RM;
	fst::ComposeFstOptions<fst::StdArc, RM> opts;
	opts.gc_limit = 0;
	opts.matcher1 = new RM(hypFst, fst::MATCH_NONE, fst::kNoLabel);
	opts.matcher2 = new RM(refFst, fst::MATCH_INPUT, symbol.Find(option.symOov));

	fst::StdComposeFst cFst(hypFst, refFst, opts);
	fst::StdVectorFst composedFst(cFst);

	if (option.saveCompositionDot != "")
		drawFstToFile(composedFst, symbol, option.saveCompositionDot);

	fst::StdVectorFst pathFst;
	fst::ShortestPath(composedFst, &pathFst);
	if (option.saveShortestPathDot != "")
		drawFstToFile(pathFst, symbol, option.saveShortestPathDot);

	fst::StdVectorFst::StateId state = pathFst.Start();
	while (state > 0) {
		fst::ArcIterator<fst::StdVectorFst> aiter(pathFst, state);
		const fst::StdArc &arc = aiter.Value();
		result.alignment.push_back(std::make_pair(symbol.Find(arc.ilabel), symbol.Find(arc.olabel)));
		state = arc.nextstate;
	}

	result.update(option);
}
<|endoftext|>


<commit_before>#include "GPS.h"
#include "Battery.h"

char* parse_token(char* data, char* dest)
{
    int i = 0;
    while(data[i] != ',' && data[i] != 0)
        ++i;
    if( dest != NULL)
        strncpy(dest, data, i);
    if(data[i])
        ++i;
    return data + i;
}

void GPSTracker::localize()
{
    //Read data from GPS
    LGPS.getData(&gps_info);
    char* data = (char*)gps_info.GPGGA;
    Serial.println(data);
    char buff[20];
    data = parse_token(data, NULL); // $GPGGA
    data = parse_token(data, buff); // Time
    gps_data[cache_gps].date_time = atof(buff);

    data = parse_token(data, buff);   // Latitude
    double tmp = atof(buff);
    gps_data[cache_gps].latitude = ((int)tmp) / 100;
    tmp -= (gps_data[cache_gps].latitude * 100);
    tmp /= 60.0;
    gps_data[cache_gps].latitude += tmp;

    data = parse_token(data, buff);   // North/South
    if(buff[0] == 'S' || buff[0] == 's')
        gps_data[cache_gps].latitude *= -1;

    data = parse_token(data, buff);   // Longitude
    tmp = atof(buff);
    gps_data[cache_gps].longitude = ((int)tmp) / 100;
    tmp -= (gps_data[cache_gps].longitude * 100);
    tmp /= 60.0;
    gps_data[cache_gps].longitude += tmp;

    data = parse_token(data, buff);   // West/East
    if(buff[0] == 'W' || buff[0] == 'w')
        gps_data[cache_gps].longitude *= -1;

    data = parse_token(data, buff);     // Fix bit
    if(buff[0] != '0')
    {
        data = parse_token(data, buff);
        gps_data[cache_gps].num_satelites = (int)atof(buff);
    }
    else
    {
        data = parse_token(data, NULL); // flush the empty number of satelites
        gps_data[cache_gps].num_satelites = 0;
    }
    data = parse_token(data, NULL); // flush the horizontal dilutoion of position
    data = parse_token(data, buff); // get the Altitude
    gps_data[cache_gps].altitude = atof(buff);
    data = parse_token(data, NULL); // flush the measurment system of altitude
    data = parse_token(data, buff); // get the height of geoid
    gps_data[cache_gps].altitude -= atof(buff);
    Serial.println("The location was localized");
    Serial.print(gps_data[cache_gps].latitude, 6);
    Serial.print(" ");
    Serial.print(gps_data[cache_gps].longitude, 6);
    Serial.print(" #sats ");
    Serial.println(gps_data[cache_gps].num_satelites);

}

void GPSTracker::submitToServer()
{
    int i;
    for (i = 0; i < 3; ++i)
    {
        if (client.connect(site_url, site_port))
        {
            break;
        }
    }
    if (i == 3)
    {
        return;
    }
    char buff[256];
    client.println("GET / HTTP/1.1");
    client.print("Host: ");
    client.print(site_url);
    client.print(":");
    client.println(site_port);
    client.print("Latitude: ");
    sprintf(buff, "%.6f", gps_data[cache_gps].latitude);
    client.println(buff);
    client.print("Longitude: ");
    sprintf(buff, "%.6f", gps_data[cache_gps].longitude);
    client.println(buff);
    client.print("Altitude: ");
    client.println(gps_data[cache_gps].altitude);
    client.print("Satelites_Count: ");
    client.println(gps_data[cache_gps].num_satelites);
    client.print("Localization_Time: ");
    client.println(gps_data[cache_gps].date_time);
    client.print("Battery_Rate: ");
    client.println(get_battery_rate());
    client.println();

    // get the response
    int response;
    while (client.available())
    {
        response = client.read(); // TODO: Read the response on larger batches, not byte by byte
        if (response < 0)
            break;
    }
    Serial.println("Data is submitted to server");
}

void GPSTracker::updateTimeInterval()
{
    if (haveWeMoved())
    {
        if (time_interval > 32000)
            time_interval /= 4;
        else if (time_interval > LOWER_TIME_LIMIT)
            time_interval /= 2;
        time_interval = max(time_interval, LOWER_TIME_LIMIT);
    }
    else
    {
        if (time_interval < 32000)
            time_interval *= 4;
        else if (time_interval < UPPER_TIME_LIMIT)
            time_interval *= 2;
        time_interval = min(time_interval, UPPER_TIME_LIMIT);
    }
}

void GPSTracker::setUrl(const char* new_url)
{
    strncpy(site_url, new_url, SITE_URL_LENGTH - 1);
}

GPSTracker::GPSTracker()
{
    client = LGPRSClient();
    time_interval = (UPPER_TIME_LIMIT + LOWER_TIME_LIMIT) / 16;
    setUrl(""); // TODO: Enter valid URL/IP
    site_port = 80;
    lastRun = millis();
    Wifi_enabled = false;
    GPS_enabled = false;
    cache_gps = 0;
    Serial.println("GPS_Tracker is init");
}

void GPSTracker::initModules()
{
    Serial.println("In initModules");
    startGps();
    startGPRS();
    for(int i = 0; i < CACHE_COUNT; ++i)
        gps_data[i].longitude = gps_data[i].latitude = 0.0;
}

void GPSTracker::startGps()
{
    LGPS.powerOn();
    delay(1000);
    GPS_enabled = true;
    Serial.println("GPS is started");
}

void GPSTracker::stopGps()
{
    LGPS.powerOff();
    GPS_enabled = false;
    Serial.println("GPS is stopped");
}

void GPSTracker::startGPRS()
{
    while (!LGPRS.attachGPRS("telenorbg", "telenor", "")) // TODO: Enter valid values for your telecom operator.
    {
        delay(2000);
    }
    Serial.println("GSM/GPRS is started");
}

void GPSTracker::disableModules()
{
    stopGps();
}

void GPSTracker::run()
{
    unsigned long current_lapsed_time;
    int tries = 0;
    current_lapsed_time = millis();
    if (current_lapsed_time - lastRun > time_interval)
    {
        Serial.println("Start another instance of the MaiN LOOP");
        // here we have to get the location and submit it
        // also update lastRun, check the movement in the last positions
        // the sum of the coordinates devided by the number of points
        // give us the center of gravity
        // if we were stationary, then the distance between all points will be very small
        // if we start to move, then tha last point will move the center of gravity
        // enough, that it will get away from most of the points
        if(GPS_enabled == false)
            startGps();
        tries = 0;
        do
        {
            localize();
            ++tries;
        }while(gps_data[cache_gps].num_satelites < 4 && tries < 16);
        if(tries < 16 )
        {
            submitToServer();
            updateTimeInterval();
            if (Wifi_enabled)
            {
                // submit localization to WI-FI module
                this->serve_on_wifi();
            }
            // increase cache_gps
            cache_gps = (cache_gps+1) % CACHE_COUNT;
        }
        lastRun = millis();
        if (time_interval > 32000)
            stopGps();
    }
    delay(time_interval);
}

bool GPSTracker::haveWeMoved() const
{
    double longi=0.0f, lati=0.0f;
    for (int i = 0; i < CACHE_COUNT; ++i)
    {
        longi += gps_data[i].longitude;
        lati += gps_data[i].latitude;
    }
    longi /= CACHE_COUNT;
    lati /= CACHE_COUNT;
    if( abs(longi - gps_data[cache_gps].longitude) +
        abs(lati - gps_data[cache_gps].latitude) < MOVEMENT_TRESHHOLD)
        return false;
    return true;
}

void GPSTracker::serve_on_wifi() const
{
    LWiFi.begin();
    LWiFi.connect("GPS_Tracker");
    LWiFiClient client;
    client.connect("server", 80);

    char buff[256];
    sprintf(buff, "%.6f", gps_data[cache_gps].latitude);
    client.print(buff);
    client.print(" ");
    sprintf(buff, "%.6f", gps_data[cache_gps].longitude);
    client.print(buff);
    client.println();

    LWiFi.end();
}
<commit_msg>Fix reading number of satelites Add some delay between consequent invokes of 'localize' Add some debug logs Move delay in run method<commit_after>#include "GPS.h"
#include "Battery.h"

char* parse_token(char* data, char* dest)
{
    int i = 0;
    while(data[i] != ',' && data[i] != 0)
        ++i;
    if (dest != NULL)
    {
        strncpy(dest, data, i);
        dest[i] = '\0';
    }
    if(data[i])
        ++i;
    return data + i;
}

void GPSTracker::localize()
{
    //Read data from GPS
    LGPS.getData(&gps_info);
    char* data = (char*)gps_info.GPGGA;
    Serial.println(data);
    char buff[20];
    data = parse_token(data, NULL); // $GPGGA
    data = parse_token(data, buff); // Time
    gps_data[cache_gps].date_time = atof(buff);

    data = parse_token(data, buff);   // Latitude
    double tmp = atof(buff);
    gps_data[cache_gps].latitude = ((int)tmp) / 100;
    tmp -= (gps_data[cache_gps].latitude * 100);
    tmp /= 60.0;
    gps_data[cache_gps].latitude += tmp;

    data = parse_token(data, buff);   // North/South
    if(buff[0] == 'S' || buff[0] == 's')
        gps_data[cache_gps].latitude *= -1;

    data = parse_token(data, buff);   // Longitude
    tmp = atof(buff);
    gps_data[cache_gps].longitude = ((int)tmp) / 100;
    tmp -= (gps_data[cache_gps].longitude * 100);
    tmp /= 60.0;
    gps_data[cache_gps].longitude += tmp;

    data = parse_token(data, buff);   // West/East
    if(buff[0] == 'W' || buff[0] == 'w')
        gps_data[cache_gps].longitude *= -1;

    data = parse_token(data, buff);     // Fix bit
    if(buff[0] != '0')
    {
        data = parse_token(data, buff);
        gps_data[cache_gps].num_satelites = atoi(buff);
    }
    else
    {
        data = parse_token(data, NULL); // flush the empty number of satelites
        gps_data[cache_gps].num_satelites = 0;
    }
    data = parse_token(data, NULL); // flush the horizontal dilutoion of position
    data = parse_token(data, buff); // get the Altitude
    gps_data[cache_gps].altitude = atof(buff);
    data = parse_token(data, NULL); // flush the measurment system of altitude
    data = parse_token(data, buff); // get the height of geoid
    gps_data[cache_gps].altitude -= atof(buff);
    Serial.println("The location was localized");
    Serial.print(gps_data[cache_gps].latitude, 6);
    Serial.print(" ");
    Serial.print(gps_data[cache_gps].longitude, 6);
    Serial.print(" #sats ");
    Serial.println(gps_data[cache_gps].num_satelites);
    delay(1000);

}

void GPSTracker::submitToServer()
{
    Serial.println("In submitToServer");
    int i;
    for (i = 0; i < 3; ++i)
    {
        Serial.print("connect to server, attempt <-- ");
        Serial.println(i + 1);
        if (client.connect(site_url, site_port))
        {
            break;
        }
    }
    if (i == 3)
    {
        Serial.println("Failed to connecto to site_url");
        return;
    }
    char buff[256];
    client.println("GET / HTTP/1.1");
    client.print("Host: ");
    client.print(site_url);
    client.print(":");
    client.println(site_port);
    client.print("Latitude: ");
    sprintf(buff, "%.6f", gps_data[cache_gps].latitude);
    client.println(buff);
    client.print("Longitude: ");
    sprintf(buff, "%.6f", gps_data[cache_gps].longitude);
    client.println(buff);
    client.print("Altitude: ");
    client.println(gps_data[cache_gps].altitude);
    client.print("Satelites_Count: ");
    client.println(gps_data[cache_gps].num_satelites);
    client.print("Localization_Time: ");
    client.println(gps_data[cache_gps].date_time);
    client.print("Battery_Rate: ");
    client.println(get_battery_rate());
    client.println();

    Serial.println("The data is sent to server, now gets the response");
    // get the response
    int response;
    while (client.available())
    {
        response = client.read(); // TODO: Read the response on larger batches, not byte by byte
        if (response < 0)
            break;
    }
    Serial.println("Response arrived");
}

void GPSTracker::updateTimeInterval()
{
    if (haveWeMoved())
    {
        if (time_interval > 32000)
            time_interval /= 4;
        else if (time_interval > LOWER_TIME_LIMIT)
            time_interval /= 2;
        time_interval = max(time_interval, LOWER_TIME_LIMIT);
    }
    else
    {
        if (time_interval < 32000)
            time_interval *= 4;
        else if (time_interval < UPPER_TIME_LIMIT)
            time_interval *= 2;
        time_interval = min(time_interval, UPPER_TIME_LIMIT);
    }
}

void GPSTracker::setUrl(const char* new_url)
{
    strncpy(site_url, new_url, SITE_URL_LENGTH - 1);
}

GPSTracker::GPSTracker()
{
    client = LGPRSClient();
    time_interval = (UPPER_TIME_LIMIT + LOWER_TIME_LIMIT) / 16;
    setUrl("", SET_URL_COMPILE_ERROR); // TODO: Enter valid URL/IP
    site_port = 80;
    lastRun = millis();
    Wifi_enabled = false;
    GPS_enabled = false;
    cache_gps = 0;
    Serial.println("GPS_Tracker is init");
}

void GPSTracker::initModules()
{
    Serial.println("In initModules");
    startGps();
    startGPRS();
    for(int i = 0; i < CACHE_COUNT; ++i)
        gps_data[i].longitude = gps_data[i].latitude = 0.0;
}

void GPSTracker::startGps()
{
    LGPS.powerOn();
    delay(1000);
    GPS_enabled = true;
    Serial.println("GPS is started");
}

void GPSTracker::stopGps()
{
    LGPS.powerOff();
    GPS_enabled = false;
    Serial.println("GPS is stopped");
}

void GPSTracker::startGPRS()
{
    while (!LGPRS.attachGPRS("telenorbg", "telenor", "")) // TODO: Enter valid values for your telecom operator.
    {
        delay(2000);
    }
    Serial.println("GSM/GPRS is started");
}

void GPSTracker::disableModules()
{
    stopGps();
}

void GPSTracker::run()
{
    unsigned long current_lapsed_time;
    int tries = 0;
    current_lapsed_time = millis();
    if (current_lapsed_time - lastRun > time_interval)
    {
        Serial.println("Start another instance of the MaiN LOOP");
        // here we have to get the location and submit it
        // also update lastRun, check the movement in the last positions
        // the sum of the coordinates devided by the number of points
        // give us the center of gravity
        // if we were stationary, then the distance between all points will be very small
        // if we start to move, then tha last point will move the center of gravity
        // enough, that it will get away from most of the points
        if(GPS_enabled == false)
            startGps();
        tries = 0;
        do
        {
            Serial.println("In do-while loop");
            localize();
            ++tries;
        }while(gps_data[cache_gps].num_satelites < 4 && tries < 16);
        Serial.println("Out of do-while loop");
        Serial.print("attempts= ");
        Serial.println(tries);
        if(tries < 16 )
        {
            submitToServer();
            updateTimeInterval();
            if (Wifi_enabled)
            {
                // submit localization to WI-FI module
                this->serve_on_wifi();
            }
            // increase cache_gps
            cache_gps = (cache_gps+1) % CACHE_COUNT;
        }
        lastRun = millis();
        if (time_interval > 32000)
            stopGps();
        delay(time_interval);
    }
}

bool GPSTracker::haveWeMoved() const
{
    double longi=0.0f, lati=0.0f;
    for (int i = 0; i < CACHE_COUNT; ++i)
    {
        longi += gps_data[i].longitude;
        lati += gps_data[i].latitude;
    }
    longi /= CACHE_COUNT;
    lati /= CACHE_COUNT;
    if( abs(longi - gps_data[cache_gps].longitude) +
        abs(lati - gps_data[cache_gps].latitude) < MOVEMENT_TRESHHOLD)
        return false;
    return true;
}

void GPSTracker::serve_on_wifi() const
{
    LWiFi.begin();
    LWiFi.connect("GPS_Tracker");
    LWiFiClient client;
    client.connect("server", 80);

    char buff[256];
    sprintf(buff, "%.6f", gps_data[cache_gps].latitude);
    client.print(buff);
    client.print(" ");
    sprintf(buff, "%.6f", gps_data[cache_gps].longitude);
    client.print(buff);
    client.println();

    LWiFi.end();
}
<|endoftext|>


<commit_before>/*
 * Copyright 2010 MQWeb - Franky Braem
 *
 * Licensed under the EUPL, Version 1.1 or – as soon they
 * will be approved by the European Commission - subsequent
 * versions of the EUPL (the "Licence");
 * You may not use this work except in compliance with the
 * Licence.
 * You may obtain a copy of the Licence at:
 *
 * http://joinup.ec.europa.eu/software/page/eupl
 *
 * Unless required by applicable law or agreed to in
 * writing, software distributed under the Licence is
 * distributed on an "AS IS" basis,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied.
 * See the Licence for the specific language governing
 * permissions and limitations under the Licence.
 */
#include <string.h> // For memcpy
#include <cmqc.h>

#include "Poco/DateTimeParser.h"
#include "MQ/PCF.h"

namespace MQ
{

PCF::PCF(bool zos)
	: Message()
	, _zos(zos)
{
}

PCF::PCF(int cmd, bool zos)
	: Message()
	, _zos(zos)
{
	setFormat(MQFMT_ADMIN);
	setType(MQMT_REQUEST);
	setPersistence(MQPER_NOT_PERSISTENT);
	buffer().resize(MQCFH_STRUC_LENGTH);
	MQCFH* header = (MQCFH*)(MQBYTE*) &buffer()[0];
	header->StrucLength    = MQCFH_STRUC_LENGTH;
	if ( _zos )
	{
		header->Type    = MQCFT_COMMAND_XR;
		header->Version = MQCFH_VERSION_3;
	}
	else
	{
		header->Type       = (MQLONG) MQCFT_COMMAND;
		header->Version    = MQCFH_VERSION_1;
	}
	header->Command        = cmd;
	header->MsgSeqNumber   = MQCFC_LAST;
	header->Control        = MQCFC_LAST;
	header->ParameterCount = 0;
}

PCF::~PCF()
{
}

void PCF::init()
{
	MQCFH* header = (MQCFH*)(MQBYTE*) &(buffer()[0]);
	int pos = MQCFH_STRUC_LENGTH;
	for(int i = 0; i < header->ParameterCount; i++)
	{
		MQLONG *pcfType = (MQLONG*) &buffer()[pos];
		_pointers[pcfType[2]] = pos;
		pos += pcfType[1];
	}
}

std::string PCF::getParameterString(MQLONG parameter) const
{
	MQCFH* header = (MQCFH*)(MQBYTE*) &(buffer()[0]);
	std::map<MQLONG, int>::const_iterator it = _pointers.find(parameter);
	if ( it == _pointers.end() )
		throw Poco::NotFoundException(parameter);

	MQLONG *pcfType = (MQLONG*) &buffer()[it->second];
	if ( *pcfType == MQCFT_STRING )
	{
		MQCFST* pcfParam = (MQCFST*) &buffer()[it->second];
		std::string result(pcfParam->String, pcfParam->StringLength);
		return Poco::trimRightInPlace(result);
	}
	else if ( *pcfType == MQCFT_BYTE_STRING )
	{
		MQCFBS* pcfParam = (MQCFBS*) &buffer()[it->second];
		return Message::getBufferAsHex(pcfParam->String, pcfParam->StringLength);
	}

	throw Poco::BadCastException(parameter);
}

BufferPtr PCF::getParameterByteString(MQLONG parameter) const
{
	MQCFH* header = (MQCFH*)(MQBYTE*) &(buffer()[0]);
	std::map<MQLONG, int>::const_iterator it = _pointers.find(parameter);
	if ( it == _pointers.end() )
		throw Poco::NotFoundException(parameter);

	MQLONG *pcfType = (MQLONG*) &buffer()[it->second];
	if ( *pcfType == MQCFT_BYTE_STRING )
	{
		MQCFBS* pcfParam = (MQCFBS*) &buffer()[it->second];
		return new Buffer(pcfParam->String, pcfParam->StringLength);
	}

	throw Poco::BadCastException(parameter);
}

std::string PCF::optParameterString(MQLONG parameter, const std::string& def) const
{
	std::string result = def;

	try
	{
		result = getParameterString(parameter);
	}
	catch(...)
	{
	}

	return result;
}

Poco::DateTime PCF::getParameterDate(MQLONG dateParameter, MQLONG timeParameter) const
{
	std::string dateValue = getParameterString(dateParameter);
	Poco::trimRightInPlace(dateValue);
	std::string timeValue = getParameterString(timeParameter);
	Poco::trimRightInPlace(timeValue);
	dateValue += timeValue;
	if ( ! dateValue.empty() )
	{
		Poco::DateTime dateTime;
		int timeZone;
		Poco::DateTimeParser::parse("%Y%n%e%H%M%S", dateValue, dateTime, timeZone);
		return dateTime;
	}
	return Poco::DateTime();
}

MQLONG PCF::getParameterNum(MQLONG parameter) const
{
	std::map<MQLONG, int>::const_iterator it = _pointers.find(parameter);
	if ( it == _pointers.end() )
		throw Poco::NotFoundException(parameter);

	MQLONG *pcfType = (MQLONG*) &buffer()[it->second];
	if ( *pcfType == MQCFT_INTEGER )
	{
		MQCFIN* pcfParam = (MQCFIN*) &buffer()[it->second];
		return pcfParam->Value;
	}

	throw Poco::BadCastException(parameter);
}

std::vector<MQLONG> PCF::getParameterNumList(MQLONG parameter) const
{
	std::map<MQLONG, int>::const_iterator it = _pointers.find(parameter);
	if ( it == _pointers.end() )
		throw Poco::NotFoundException(parameter);

	MQLONG *pcfType = (MQLONG*) &buffer()[it->second];
	if ( *pcfType == MQCFT_INTEGER_LIST )
	{
		std::vector<MQLONG> list;
		MQCFIL* pcfParam = (MQCFIL*) &buffer()[it->second];
		for(int i = 0; i < pcfParam->Count; ++i)
		{
			list.push_back(pcfParam->Values[i]);
		}
		return list;
	}

	throw Poco::BadCastException(parameter);
}

std::vector<std::string> PCF::getParameterStringList(MQLONG parameter) const
{
	std::map<MQLONG, int>::const_iterator it = _pointers.find(parameter);
	if ( it == _pointers.end() )
		throw Poco::NotFoundException(parameter);

	MQLONG *pcfType = (MQLONG*) &buffer()[it->second];
	if ( *pcfType == MQCFT_STRING_LIST )
	{
		std::vector<std::string> list;
		MQCFSL* pcfParam = (MQCFSL*) &buffer()[it->second];
		for(int i = 0; i < pcfParam->Count; ++i)
		{
			std::string result(pcfParam->Strings, i * pcfParam->StringLength, pcfParam->StringLength);
			Poco::trimRightInPlace(result);
			list.push_back(result);
		}
		return list;
	}

	throw Poco::BadCastException(parameter);
}

MQLONG PCF::optParameterNum(MQLONG parameter, MQLONG def) const
{
	MQLONG result = def;
	try
	{
		result = getParameterNum(parameter);
	}
	catch(...)
	{
	}
	return result;
}

void PCF::addParameter(MQLONG parameter, const std::string& value)
{
	MQLONG structLength = ((MQCFST_STRUC_LENGTH_FIXED + value.length()) / 4 + 1) * 4;
	_pointers[parameter] = buffer().size();
	buffer().resize(buffer().size() + structLength);
	MQCFST* pcfParam = (MQCFST*) &buffer()[_pointers[parameter]];
	pcfParam->Type           = MQCFT_STRING;
	pcfParam->StrucLength    = structLength;
	pcfParam->Parameter      = parameter;
	pcfParam->CodedCharSetId = MQCCSI_DEFAULT;
	pcfParam->StringLength   = value.length();
	memcpy(pcfParam->String, value.c_str(), pcfParam->StringLength);
	MQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];
	header->ParameterCount++;
}

void PCF::addParameter(MQLONG parameter, MQLONG value)
{
	_pointers[parameter] = buffer().size();
	buffer().resize(buffer().size() + MQCFIN_STRUC_LENGTH);
	MQCFIN* pcfParam = (MQCFIN*) &buffer()[_pointers[parameter]];
	pcfParam->Type        = MQCFT_INTEGER;
	pcfParam->StrucLength = MQCFIN_STRUC_LENGTH;
	pcfParam->Parameter   = parameter;
	pcfParam->Value       = value;
	MQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];
	header->ParameterCount++;
}

void PCF::addParameter(MQLONG parameter, BufferPtr value)
{
	MQLONG structLength = ((MQCFST_STRUC_LENGTH_FIXED + value->sizeBytes()) / 4 + 1) * 4;
	_pointers[parameter] = buffer().size();
	buffer().resize(buffer().size() + structLength);
	MQCFBS* pcfParam = (MQCFBS*) &buffer()[_pointers[parameter]];
	pcfParam->Type           = MQCFT_BYTE_STRING;
	pcfParam->StrucLength    = structLength;
	pcfParam->Parameter      = parameter;
	pcfParam->StringLength   = value->sizeBytes();
	memcpy(pcfParam->String, value->begin(), pcfParam->StringLength);
	MQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];
	header->ParameterCount++;
}

void PCF::addParameterList(MQLONG parameter, MQLONG *values)
{
	int count = (sizeof values / sizeof values[0]);
	int strucLength = MQCFIL_STRUC_LENGTH_FIXED + count * 4;
	_pointers[parameter] = buffer().size();
	buffer().resize(buffer().size() + strucLength);
	MQCFIL *pcfIntegerList = (MQCFIL *) &buffer()[_pointers[parameter]];
	pcfIntegerList->Count       = count;
	pcfIntegerList->Type        = MQCFT_INTEGER_LIST;
	pcfIntegerList->StrucLength = strucLength;
	pcfIntegerList->Parameter   = parameter;
	pcfIntegerList->Values[0]   = *values;
	MQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];
	header->ParameterCount++;
}

void PCF::addFilter(MQLONG parameter, MQLONG op, const std::string& value)
{
	MQLONG strucLength = ((MQCFSF_STRUC_LENGTH_FIXED + value.length()) / 4 + 1) * 4;
	_pointers[parameter] = buffer().size();
	buffer().resize(buffer().size() + strucLength);
	MQCFSF* pcfFilter = (MQCFSF*) &buffer()[_pointers[parameter]];
	pcfFilter->Type              = MQCFT_STRING_FILTER;
	pcfFilter->StrucLength       = strucLength;
	pcfFilter->Parameter         = parameter;
	pcfFilter->Operator          = op;
	pcfFilter->CodedCharSetId    = MQCCSI_DEFAULT;
	pcfFilter->FilterValueLength = value.length();
	memcpy(pcfFilter->FilterValue, value.c_str(), pcfFilter->FilterValueLength);
	MQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];
	header->ParameterCount++;
}

void PCF::addFilter(MQLONG parameter, MQLONG op, MQLONG value)
{
	_pointers[parameter] = buffer().size();
	buffer().resize(buffer().size() + MQCFIF_STRUC_LENGTH);
	MQCFIF* pcfFilter = (MQCFIF*) &buffer()[_pointers[parameter]];
	pcfFilter->Type              = MQCFT_INTEGER_FILTER;
	pcfFilter->StrucLength       = MQCFIF_STRUC_LENGTH;
	pcfFilter->Parameter         = parameter;
	pcfFilter->Operator          = op;
	pcfFilter->FilterValue       = value;
	MQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];
	header->ParameterCount++;
}

std::vector<MQLONG> PCF::getParameters() const
{
	std::vector<MQLONG> parameters;
	for(std::map<MQLONG, int>::const_iterator it = _pointers.begin(); it != _pointers.end(); it++)
	{
		MQLONG *pcfType = (MQLONG*) &buffer()[it->second];
		parameters.push_back(pcfType[2]);
	}
	return parameters;
}

} // Namespace MQ
<commit_msg>Add count argument to addParameterList<commit_after>/*
 * Copyright 2010 MQWeb - Franky Braem
 *
 * Licensed under the EUPL, Version 1.1 or – as soon they
 * will be approved by the European Commission - subsequent
 * versions of the EUPL (the "Licence");
 * You may not use this work except in compliance with the
 * Licence.
 * You may obtain a copy of the Licence at:
 *
 * http://joinup.ec.europa.eu/software/page/eupl
 *
 * Unless required by applicable law or agreed to in
 * writing, software distributed under the Licence is
 * distributed on an "AS IS" basis,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied.
 * See the Licence for the specific language governing
 * permissions and limitations under the Licence.
 */
#include <string.h> // For memcpy
#include <cmqc.h>

#include "Poco/DateTimeParser.h"
#include "MQ/PCF.h"

namespace MQ
{

PCF::PCF(bool zos)
	: Message()
	, _zos(zos)
{
}

PCF::PCF(int cmd, bool zos)
	: Message()
	, _zos(zos)
{
	setFormat(MQFMT_ADMIN);
	setType(MQMT_REQUEST);
	setPersistence(MQPER_NOT_PERSISTENT);
	buffer().resize(MQCFH_STRUC_LENGTH);
	MQCFH* header = (MQCFH*)(MQBYTE*) &buffer()[0];
	header->StrucLength    = MQCFH_STRUC_LENGTH;
	if ( _zos )
	{
		header->Type    = MQCFT_COMMAND_XR;
		header->Version = MQCFH_VERSION_3;
	}
	else
	{
		header->Type       = (MQLONG) MQCFT_COMMAND;
		header->Version    = MQCFH_VERSION_1;
	}
	header->Command        = cmd;
	header->MsgSeqNumber   = MQCFC_LAST;
	header->Control        = MQCFC_LAST;
	header->ParameterCount = 0;
}

PCF::~PCF()
{
}

void PCF::init()
{
	MQCFH* header = (MQCFH*)(MQBYTE*) &(buffer()[0]);
	int pos = MQCFH_STRUC_LENGTH;
	for(int i = 0; i < header->ParameterCount; i++)
	{
		MQLONG *pcfType = (MQLONG*) &buffer()[pos];
		_pointers[pcfType[2]] = pos;
		pos += pcfType[1];
	}
}

std::string PCF::getParameterString(MQLONG parameter) const
{
	MQCFH* header = (MQCFH*)(MQBYTE*) &(buffer()[0]);
	std::map<MQLONG, int>::const_iterator it = _pointers.find(parameter);
	if ( it == _pointers.end() )
		throw Poco::NotFoundException(parameter);

	MQLONG *pcfType = (MQLONG*) &buffer()[it->second];
	if ( *pcfType == MQCFT_STRING )
	{
		MQCFST* pcfParam = (MQCFST*) &buffer()[it->second];
		std::string result(pcfParam->String, pcfParam->StringLength);
		return Poco::trimRightInPlace(result);
	}
	else if ( *pcfType == MQCFT_BYTE_STRING )
	{
		MQCFBS* pcfParam = (MQCFBS*) &buffer()[it->second];
		return Message::getBufferAsHex(pcfParam->String, pcfParam->StringLength);
	}

	throw Poco::BadCastException(parameter);
}

BufferPtr PCF::getParameterByteString(MQLONG parameter) const
{
	MQCFH* header = (MQCFH*)(MQBYTE*) &(buffer()[0]);
	std::map<MQLONG, int>::const_iterator it = _pointers.find(parameter);
	if ( it == _pointers.end() )
		throw Poco::NotFoundException(parameter);

	MQLONG *pcfType = (MQLONG*) &buffer()[it->second];
	if ( *pcfType == MQCFT_BYTE_STRING )
	{
		MQCFBS* pcfParam = (MQCFBS*) &buffer()[it->second];
		return new Buffer(pcfParam->String, pcfParam->StringLength);
	}

	throw Poco::BadCastException(parameter);
}

std::string PCF::optParameterString(MQLONG parameter, const std::string& def) const
{
	std::string result = def;

	try
	{
		result = getParameterString(parameter);
	}
	catch(...)
	{
	}

	return result;
}

Poco::DateTime PCF::getParameterDate(MQLONG dateParameter, MQLONG timeParameter) const
{
	std::string dateValue = getParameterString(dateParameter);
	Poco::trimRightInPlace(dateValue);
	std::string timeValue = getParameterString(timeParameter);
	Poco::trimRightInPlace(timeValue);
	dateValue += timeValue;
	if ( ! dateValue.empty() )
	{
		Poco::DateTime dateTime;
		int timeZone;
		Poco::DateTimeParser::parse("%Y%n%e%H%M%S", dateValue, dateTime, timeZone);
		return dateTime;
	}
	return Poco::DateTime();
}

MQLONG PCF::getParameterNum(MQLONG parameter) const
{
	std::map<MQLONG, int>::const_iterator it = _pointers.find(parameter);
	if ( it == _pointers.end() )
		throw Poco::NotFoundException(parameter);

	MQLONG *pcfType = (MQLONG*) &buffer()[it->second];
	if ( *pcfType == MQCFT_INTEGER )
	{
		MQCFIN* pcfParam = (MQCFIN*) &buffer()[it->second];
		return pcfParam->Value;
	}

	throw Poco::BadCastException(parameter);
}

std::vector<MQLONG> PCF::getParameterNumList(MQLONG parameter) const
{
	std::map<MQLONG, int>::const_iterator it = _pointers.find(parameter);
	if ( it == _pointers.end() )
		throw Poco::NotFoundException(parameter);

	MQLONG *pcfType = (MQLONG*) &buffer()[it->second];
	if ( *pcfType == MQCFT_INTEGER_LIST )
	{
		std::vector<MQLONG> list;
		MQCFIL* pcfParam = (MQCFIL*) &buffer()[it->second];
		for(int i = 0; i < pcfParam->Count; ++i)
		{
			list.push_back(pcfParam->Values[i]);
		}
		return list;
	}

	throw Poco::BadCastException(parameter);
}

std::vector<std::string> PCF::getParameterStringList(MQLONG parameter) const
{
	std::map<MQLONG, int>::const_iterator it = _pointers.find(parameter);
	if ( it == _pointers.end() )
		throw Poco::NotFoundException(parameter);

	MQLONG *pcfType = (MQLONG*) &buffer()[it->second];
	if ( *pcfType == MQCFT_STRING_LIST )
	{
		std::vector<std::string> list;
		MQCFSL* pcfParam = (MQCFSL*) &buffer()[it->second];
		for(int i = 0; i < pcfParam->Count; ++i)
		{
			std::string result(pcfParam->Strings, i * pcfParam->StringLength, pcfParam->StringLength);
			Poco::trimRightInPlace(result);
			list.push_back(result);
		}
		return list;
	}

	throw Poco::BadCastException(parameter);
}

MQLONG PCF::optParameterNum(MQLONG parameter, MQLONG def) const
{
	MQLONG result = def;
	try
	{
		result = getParameterNum(parameter);
	}
	catch(...)
	{
	}
	return result;
}

void PCF::addParameter(MQLONG parameter, const std::string& value)
{
	MQLONG structLength = ((MQCFST_STRUC_LENGTH_FIXED + value.length()) / 4 + 1) * 4;
	_pointers[parameter] = buffer().size();
	buffer().resize(buffer().size() + structLength);
	MQCFST* pcfParam = (MQCFST*) &buffer()[_pointers[parameter]];
	pcfParam->Type           = MQCFT_STRING;
	pcfParam->StrucLength    = structLength;
	pcfParam->Parameter      = parameter;
	pcfParam->CodedCharSetId = MQCCSI_DEFAULT;
	pcfParam->StringLength   = value.length();
	memcpy(pcfParam->String, value.c_str(), pcfParam->StringLength);
	MQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];
	header->ParameterCount++;
}

void PCF::addParameter(MQLONG parameter, MQLONG value)
{
	_pointers[parameter] = buffer().size();
	buffer().resize(buffer().size() + MQCFIN_STRUC_LENGTH);
	MQCFIN* pcfParam = (MQCFIN*) &buffer()[_pointers[parameter]];
	pcfParam->Type        = MQCFT_INTEGER;
	pcfParam->StrucLength = MQCFIN_STRUC_LENGTH;
	pcfParam->Parameter   = parameter;
	pcfParam->Value       = value;
	MQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];
	header->ParameterCount++;
}

void PCF::addParameter(MQLONG parameter, BufferPtr value)
{
	MQLONG structLength = ((MQCFST_STRUC_LENGTH_FIXED + value->sizeBytes()) / 4 + 1) * 4;
	_pointers[parameter] = buffer().size();
	buffer().resize(buffer().size() + structLength);
	MQCFBS* pcfParam = (MQCFBS*) &buffer()[_pointers[parameter]];
	pcfParam->Type           = MQCFT_BYTE_STRING;
	pcfParam->StrucLength    = structLength;
	pcfParam->Parameter      = parameter;
	pcfParam->StringLength   = value->sizeBytes();
	memcpy(pcfParam->String, value->begin(), pcfParam->StringLength);
	MQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];
	header->ParameterCount++;
}

void PCF::addParameterList(MQLONG parameter, MQLONG *values, unsigned int count)
{
	int strucLength = MQCFIL_STRUC_LENGTH_FIXED + count * sizeof(MQLONG);
	_pointers[parameter] = buffer().size();
	buffer().resize(buffer().size() + strucLength);
	MQCFIL *pcfIntegerList = (MQCFIL *) &buffer()[_pointers[parameter]];
	pcfIntegerList->Count       = count;
	pcfIntegerList->Type        = MQCFT_INTEGER_LIST;
	pcfIntegerList->StrucLength = strucLength;
	pcfIntegerList->Parameter   = parameter;
	for(int i = 0; i < count; ++i) pcfIntegerList->Values[i] = values[i];
	MQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];
	header->ParameterCount++;
}

void PCF::addFilter(MQLONG parameter, MQLONG op, const std::string& value)
{
	MQLONG strucLength = ((MQCFSF_STRUC_LENGTH_FIXED + value.length()) / 4 + 1) * 4;
	_pointers[parameter] = buffer().size();
	buffer().resize(buffer().size() + strucLength);
	MQCFSF* pcfFilter = (MQCFSF*) &buffer()[_pointers[parameter]];
	pcfFilter->Type              = MQCFT_STRING_FILTER;
	pcfFilter->StrucLength       = strucLength;
	pcfFilter->Parameter         = parameter;
	pcfFilter->Operator          = op;
	pcfFilter->CodedCharSetId    = MQCCSI_DEFAULT;
	pcfFilter->FilterValueLength = value.length();
	memcpy(pcfFilter->FilterValue, value.c_str(), pcfFilter->FilterValueLength);
	MQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];
	header->ParameterCount++;
}

void PCF::addFilter(MQLONG parameter, MQLONG op, MQLONG value)
{
	_pointers[parameter] = buffer().size();
	buffer().resize(buffer().size() + MQCFIF_STRUC_LENGTH);
	MQCFIF* pcfFilter = (MQCFIF*) &buffer()[_pointers[parameter]];
	pcfFilter->Type              = MQCFT_INTEGER_FILTER;
	pcfFilter->StrucLength       = MQCFIF_STRUC_LENGTH;
	pcfFilter->Parameter         = parameter;
	pcfFilter->Operator          = op;
	pcfFilter->FilterValue       = value;
	MQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];
	header->ParameterCount++;
}

std::vector<MQLONG> PCF::getParameters() const
{
	std::vector<MQLONG> parameters;
	for(std::map<MQLONG, int>::const_iterator it = _pointers.begin(); it != _pointers.end(); it++)
	{
		MQLONG *pcfType = (MQLONG*) &buffer()[it->second];
		parameters.push_back(pcfType[2]);
	}
	return parameters;
}

} // Namespace MQ
<|endoftext|>