<commit_before>//   Copyright 2016-2020 Jean-Francois Poilpret
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

/*
 * Simple ranger example, using VL53L0X Time-of-flight range sensor I2C device.
 * This program uses FastArduino VL53L0X support API.
 *
 * Wiring:
 * - on ATmega328P based boards (including Arduino UNO):
 *   - A4 (PC4, SDA): connected to VL53L0X SDA pin
 *   - A5 (PC5, SCL): connected to VL53L0X SCL pin
 *   - direct USB access
 */

#include <fastarduino/time.h>
#include <fastarduino/uart.h>
#include <fastarduino/i2c_handler.h>
#include <fastarduino/i2c_debug.h>
#include <fastarduino/i2c_status.h>
#include <fastarduino/devices/vl53l0x.h>
#include <fastarduino/memory.h>

// #define DEBUG_I2C
// #define FORCE_SYNC

static constexpr const i2c::I2CMode MODE = i2c::I2CMode::FAST;
// static constexpr const i2c::I2CMode MODE = i2c::I2CMode::STANDARD;

static constexpr const board::USART UART = board::USART::USART0;
static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 128;
static char output_buffer[OUTPUT_BUFFER_SIZE];

REGISTER_UATX_ISR(0)

#ifdef DEBUG_I2C
static constexpr const uint8_t DEBUG_SIZE = 96;
#	if I2C_TRUE_ASYNC and not defined(FORCE_SYNC)
using DEBUGGER = i2c::debug::I2CDebugStatusRecorder<DEBUG_SIZE, DEBUG_SIZE>;
#define DEBUG(OUT) debugger.trace(OUT)
#define RESET_DEBUG() debugger.reset()
using MANAGER = i2c::I2CAsyncStatusDebugManager<MODE, i2c::I2CErrorPolicy::CLEAR_ALL_COMMANDS, DEBUGGER&, DEBUGGER&>;
static constexpr const uint8_t I2C_BUFFER_SIZE = 32;
static MANAGER::I2CCOMMAND i2c_buffer[I2C_BUFFER_SIZE];
#	else
using DEBUGGER = i2c::debug::I2CDebugStatusLiveLogger;
#define DEBUG(OUT)
#define RESET_DEBUG()
using MANAGER = i2c::I2CSyncStatusDebugManager<MODE, DEBUGGER&, DEBUGGER&>;
#	endif

#else

#	if I2C_TRUE_ASYNC and not defined(FORCE_SYNC)
using MANAGER = i2c::I2CAsyncManager<MODE, i2c::I2CErrorPolicy::CLEAR_ALL_COMMANDS>;
static constexpr const uint8_t I2C_BUFFER_SIZE = 32;
static MANAGER::I2CCOMMAND i2c_buffer[I2C_BUFFER_SIZE];
#	else
using MANAGER = i2c::I2CSyncManager<MODE>;
#	endif
#define DEBUG(OUT)
#define RESET_DEBUG()

#endif

#if I2C_TRUE_ASYNC and not defined(FORCE_SYNC)
REGISTER_I2C_ISR(MANAGER)
#endif

using streams::dec;
using streams::hex;
using streams::fixed;
using streams::endl;
using streams::flush;

using namespace devices::vl53l0x;
using TOF = VL53L0X<MANAGER>;

void display_memory(streams::ostream& out)
{
	out << F("free mem=") << dec << memory::free_mem() << endl;
}

int main() __attribute__((OS_main));
int main()
{
	board::init();
	sei();

	// open UART for traces
	serial::hard::UATX<UART> uart{output_buffer};
	streams::ostream out = uart.out();
	uart.begin(115200);
	out << streams::boolalpha;
	out << F("Start") << endl;

	// Initialize I2C async handler
#ifdef DEBUG_I2C
#	if I2C_TRUE_ASYNC and not defined(FORCE_SYNC)
	DEBUGGER debugger;
#	else
	DEBUGGER debugger{out};
#	endif
#endif

#if I2C_TRUE_ASYNC and not defined(FORCE_SYNC)
#	ifdef DEBUG_I2C
	MANAGER manager{i2c_buffer, debugger, debugger};
#	else
	MANAGER manager{i2c_buffer};
#	endif
#else
#	ifdef DEBUG_I2C
	MANAGER manager{debugger, debugger};
#	else
	MANAGER manager;
#	endif
#endif

	display_memory(out);

	out << F("Instantiate VL53L0X") << endl;
	TOF tof{manager};
	display_memory(out);

	out << F("Start I2C manager") << endl;
	manager.begin();
	display_memory(out);

	bool ok = false;

	{
	// constexpr SequenceSteps steps2 = SequenceSteps::create().tcc().pre_range().final_range();
	// out << F("steps2 = ") << hex << steps2.value() << endl;
	// ok = tof.set_sequence_steps(steps2);
	// out << F("tof.set_sequence_steps(status) = ") << ok << endl;
	// DEBUG(out);
	}

	{
		ok = tof.set_signal_rate_limit(0.5f);
		display_memory(out);
		out << F("tof.set_signal_rate_limit(0.5) = ") << ok << endl;
		DEBUG(out);
	}

	{
		// Call first initialization step
		out << F("Calling init_data_first()...") << endl;
		ok = tof.init_data_first();
		display_memory(out);
		out << F("tof.init_data_first() = ") << ok << endl;
		DEBUG(out);
	}

	{
		DeviceStatus status;
		ok = tof.get_range_status(status);
		display_memory(out);
		out << F("tof.get_range_status(status) = ") << ok
			<< F(", error = ") << dec << uint8_t(status.error())
			<< F(", data_ready = ") << status.data_ready() << endl;
		DEBUG(out);
	}

	{
		// Call second initialization step
		out << F("Calling init_static_second()...") << endl;
		ok = tof.init_static_second(GPIOSettings::sample_ready(), SequenceSteps::all().no_msrc().no_tcc());
		display_memory(out);
		out << F("tof.init_static_second() = ") << ok << endl;
		DEBUG(out);
	}

	{
		DeviceStatus status;
		ok = tof.get_range_status(status);
		display_memory(out);
		out << F("tof.get_range_status(status) = ") << ok
			<< F(", error = ") << dec << uint8_t(status.error())
			<< F(", data_ready = ") << status.data_ready() << endl;
		DEBUG(out);
	}

	// {
	// 	// Perform reference calibration
	// 	ok = tof.perform_ref_calibration();
	// 	display_memory(out);
	// 	out << F("tof.perform_ref_calibration() = ") << ok << endl;
	// 	DEBUG(out);
	// }

	// {
	// 	DeviceStatus status;
	// 	ok = tof.get_range_status(status);
	// 	display_memory(out);
	// 	out << F("tof.get_range_status(status) = ") << ok
	// 		<< F(", error = ") << dec << uint8_t(status.error())
	// 		<< F(", data_ready = ") << status.data_ready() << endl;
	// 	DEBUG(out);
	// }

	manager.end();
}
<commit_msg>Remove example obsolete code<commit_after>//   Copyright 2016-2020 Jean-Francois Poilpret
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

/*
 * Simple ranger example, using VL53L0X Time-of-flight range sensor I2C device.
 * This program uses FastArduino VL53L0X support API.
 *
 * Wiring:
 * - on ATmega328P based boards (including Arduino UNO):
 *   - A4 (PC4, SDA): connected to VL53L0X SDA pin
 *   - A5 (PC5, SCL): connected to VL53L0X SCL pin
 *   - direct USB access
 */

#include <fastarduino/time.h>
#include <fastarduino/uart.h>
#include <fastarduino/i2c_handler.h>
#include <fastarduino/i2c_debug.h>
#include <fastarduino/i2c_status.h>
#include <fastarduino/devices/vl53l0x.h>
#include <fastarduino/memory.h>

// #define DEBUG_I2C
// #define FORCE_SYNC

static constexpr const i2c::I2CMode MODE = i2c::I2CMode::FAST;
// static constexpr const i2c::I2CMode MODE = i2c::I2CMode::STANDARD;

static constexpr const board::USART UART = board::USART::USART0;
static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 128;
static char output_buffer[OUTPUT_BUFFER_SIZE];

REGISTER_UATX_ISR(0)

#ifdef DEBUG_I2C
static constexpr const uint8_t DEBUG_SIZE = 96;
#	if I2C_TRUE_ASYNC and not defined(FORCE_SYNC)
using DEBUGGER = i2c::debug::I2CDebugStatusRecorder<DEBUG_SIZE, DEBUG_SIZE>;
#define DEBUG(OUT) debugger.trace(OUT)
#define RESET_DEBUG() debugger.reset()
using MANAGER = i2c::I2CAsyncStatusDebugManager<MODE, i2c::I2CErrorPolicy::CLEAR_ALL_COMMANDS, DEBUGGER&, DEBUGGER&>;
static constexpr const uint8_t I2C_BUFFER_SIZE = 32;
static MANAGER::I2CCOMMAND i2c_buffer[I2C_BUFFER_SIZE];
#	else
using DEBUGGER = i2c::debug::I2CDebugStatusLiveLogger;
#define DEBUG(OUT)
#define RESET_DEBUG()
using MANAGER = i2c::I2CSyncStatusDebugManager<MODE, DEBUGGER&, DEBUGGER&>;
#	endif

#else

#	if I2C_TRUE_ASYNC and not defined(FORCE_SYNC)
using MANAGER = i2c::I2CAsyncManager<MODE, i2c::I2CErrorPolicy::CLEAR_ALL_COMMANDS>;
static constexpr const uint8_t I2C_BUFFER_SIZE = 32;
static MANAGER::I2CCOMMAND i2c_buffer[I2C_BUFFER_SIZE];
#	else
using MANAGER = i2c::I2CSyncManager<MODE>;
#	endif
#define DEBUG(OUT)
#define RESET_DEBUG()

#endif

#if I2C_TRUE_ASYNC and not defined(FORCE_SYNC)
REGISTER_I2C_ISR(MANAGER)
#endif

using streams::dec;
using streams::hex;
using streams::fixed;
using streams::endl;
using streams::flush;

using namespace devices::vl53l0x;
using TOF = VL53L0X<MANAGER>;

void display_memory(streams::ostream& out)
{
	out << F("free mem=") << dec << memory::free_mem() << endl;
}

int main() __attribute__((OS_main));
int main()
{
	board::init();
	sei();

	// open UART for traces
	serial::hard::UATX<UART> uart{output_buffer};
	streams::ostream out = uart.out();
	uart.begin(115200);
	out << streams::boolalpha;
	out << F("Start") << endl;

	// Initialize I2C async handler
#ifdef DEBUG_I2C
#	if I2C_TRUE_ASYNC and not defined(FORCE_SYNC)
	DEBUGGER debugger;
#	else
	DEBUGGER debugger{out};
#	endif
#endif

#if I2C_TRUE_ASYNC and not defined(FORCE_SYNC)
#	ifdef DEBUG_I2C
	MANAGER manager{i2c_buffer, debugger, debugger};
#	else
	MANAGER manager{i2c_buffer};
#	endif
#else
#	ifdef DEBUG_I2C
	MANAGER manager{debugger, debugger};
#	else
	MANAGER manager;
#	endif
#endif

	display_memory(out);

	out << F("Instantiate VL53L0X") << endl;
	TOF tof{manager};
	display_memory(out);

	out << F("Start I2C manager") << endl;
	manager.begin();
	display_memory(out);

	bool ok = false;

	{
		ok = tof.set_signal_rate_limit(0.5f);
		display_memory(out);
		out << F("tof.set_signal_rate_limit(0.5) = ") << ok << endl;
		DEBUG(out);
	}

	{
		// Call first initialization step
		out << F("Calling init_data_first()...") << endl;
		ok = tof.init_data_first();
		display_memory(out);
		out << F("tof.init_data_first() = ") << ok << endl;
		DEBUG(out);
	}

	{
		DeviceStatus status;
		ok = tof.get_range_status(status);
		display_memory(out);
		out << F("tof.get_range_status(status) = ") << ok
			<< F(", error = ") << dec << uint8_t(status.error())
			<< F(", data_ready = ") << status.data_ready() << endl;
		DEBUG(out);
	}

	{
		// Call second initialization step
		out << F("Calling init_static_second()...") << endl;
		ok = tof.init_static_second(GPIOSettings::sample_ready(), SequenceSteps::all().no_msrc().no_tcc());
		display_memory(out);
		out << F("tof.init_static_second() = ") << ok << endl;
		DEBUG(out);
	}

	{
		DeviceStatus status;
		ok = tof.get_range_status(status);
		display_memory(out);
		out << F("tof.get_range_status(status) = ") << ok
			<< F(", error = ") << dec << uint8_t(status.error())
			<< F(", data_ready = ") << status.data_ready() << endl;
		DEBUG(out);
	}

	// {
	// 	// Perform reference calibration
	// 	ok = tof.perform_ref_calibration();
	// 	display_memory(out);
	// 	out << F("tof.perform_ref_calibration() = ") << ok << endl;
	// 	DEBUG(out);
	// }

	// {
	// 	DeviceStatus status;
	// 	ok = tof.get_range_status(status);
	// 	display_memory(out);
	// 	out << F("tof.get_range_status(status) = ") << ok
	// 		<< F(", error = ") << dec << uint8_t(status.error())
	// 		<< F(", data_ready = ") << status.data_ready() << endl;
	// 	DEBUG(out);
	// }

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


<commit_before>/*
 OFX Switch plugin.
 Switch between inputs.

 Copyright (C) 2013 INRIA
 Author Frederic Devernay frederic.devernay@inria.fr

 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 INRIA
 Domaine de Voluceau
 Rocquencourt - B.P. 105
 78153 Le Chesnay Cedex - France

 The skeleton for this source file is from:
 OFX Basic Example plugin, a plugin that illustrates the use of the OFX Support library.

 Copyright (C) 2004-2005 The Open Effects Association Ltd
 Author Bruno Nicoletti bruno@thefoundry.co.uk

 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 The Open Effects Association Ltd, 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 The Open Effects Association Ltd
 1 Wardour St
 London W1D 6PA
 England

 */

#include "Switch.h"

#include <string>

#ifdef _WINDOWS
#include <windows.h>
#endif

#ifdef OFX_EXTENSIONS_NUKE
#include "nuke/fnOfxExtensions.h"
#endif

#define kSwitchPluginSourceClipCount 10
#define kSwitchPluginParamWhich "which"

////////////////////////////////////////////////////////////////////////////////
/** @brief The plugin that does our work */
class SwitchPlugin : public OFX::ImageEffect {
    protected :
    // do not need to delete these, the ImageEffect is managing them for us
    OFX::Clip *srcClip_[kSwitchPluginSourceClipCount];

    OFX::IntParam *which_;

    public :
    /** @brief ctor */
    SwitchPlugin(OfxImageEffectHandle handle);

    /* Override the render */
    virtual void render(const OFX::RenderArguments &args);

    /* override is identity */
    virtual bool isIdentity(const OFX::RenderArguments &args, OFX::Clip * &identityClip, double &identityTime);

#ifdef OFX_EXTENSIONS_NUKE
    /** @brief recover a transform matrix from an effect */
    virtual bool getTransform(const OFX::TransformArguments &args, OFX::Clip * &transformClip, double transformMatrix[9]);
#endif

    /** @brief called when a clip has just been changed in some way (a rewire maybe) */
    virtual void changedClip(const OFX::InstanceChangedArgs &args, const std::string &clipName);
};

SwitchPlugin::SwitchPlugin(OfxImageEffectHandle handle)
: ImageEffect(handle)
, which_(0)
{
    for (int i = 0; i < kSwitchPluginSourceClipCount; ++i) {
        std::stringstream s;
        s << i;
        srcClip_[i] = fetchClip(s.str());
    }
    which_  = fetchIntParam(kSwitchPluginParamWhich);
}

void
SwitchPlugin::render(const OFX::RenderArguments &args)
{
    // do nothing as this should never be called as isIdentity should always be trapped
}

// overridden is identity
bool
SwitchPlugin::isIdentity(const OFX::RenderArguments &args, OFX::Clip * &identityClip, double &identityTime)
{
    int input;
    which_->getValue(input);
    identityClip = srcClip_[input];
    return true;
}

#ifdef OFX_EXTENSIONS_NUKE
// overridden getTransform
bool SwitchPlugin::getTransform(const OFX::TransformArguments &args, OFX::Clip * &transformClip, double transformMatrix[9])
{
    int input;
    which_->getValue(input);
    transformClip = srcClip_[input];

    transformMatrix[0] = 1.;
    transformMatrix[1] = 0.;
    transformMatrix[2] = 0.;
    transformMatrix[3] = 0.;
    transformMatrix[4] = 1.;
    transformMatrix[5] = 0.;
    transformMatrix[6] = 0.;
    transformMatrix[7] = 0.;
    transformMatrix[8] = 1.;
    return true;
}
#endif

void
SwitchPlugin::changedClip(const OFX::InstanceChangedArgs &args, const std::string &clipName)
{
    int maxconnected = 1;
    for (int i = 2; i < kSwitchPluginSourceClipCount; ++i) {
        if (srcClip_[i]->isConnected()) {
            maxconnected = i;
        }
    }
    which_->setDisplayRange(0, maxconnected);
}

using namespace OFX;

void SwitchPluginFactory::describe(OFX::ImageEffectDescriptor &desc)
{
    // basic labels
    desc.setLabels("SwitchOFX", "SwitchOFX", "SwitchOFX");
    desc.setPluginGrouping("Merge");
    desc.setPluginDescription("Lets you switch between any number of inputs.");

    // add the supported contexts
    desc.addSupportedContext(eContextFilter);

    // add supported pixel depths
    desc.addSupportedBitDepth(eBitDepthUByte);
    desc.addSupportedBitDepth(eBitDepthUShort);
    desc.addSupportedBitDepth(eBitDepthFloat);

    // set a few flags
    desc.setSingleInstance(false);
    desc.setHostFrameThreading(true);
    desc.setSupportsMultiResolution(true);
    desc.setSupportsTiles(true);
    desc.setTemporalClipAccess(false);
    desc.setRenderTwiceAlways(false);
    desc.setSupportsMultipleClipPARs(false);
#ifdef OFX_EXTENSIONS_NUKE
    // Enable transform by the host.
    // It is only possible for transforms which can be represented as a 3x3 matrix.
    desc.setCanTransform(true);
#endif
}

void SwitchPluginFactory::describeInContext(OFX::ImageEffectDescriptor &desc, OFX::ContextEnum context)
{
    // Source clip only in the filter context
    // create the mandated source clip
    for (int i = 0; i < kSwitchPluginSourceClipCount; ++i) {
        std::stringstream s;
        s << i;
        ClipDescriptor *srcClip = desc.defineClip(s.str());
        srcClip->addSupportedComponent(ePixelComponentRGB);
        srcClip->addSupportedComponent(ePixelComponentRGBA);
        srcClip->addSupportedComponent(ePixelComponentAlpha);
        srcClip->setTemporalClipAccess(false);
        srcClip->setSupportsTiles(true);
        srcClip->setIsMask(false);
        if (i >= 2) {
            srcClip->setOptional(true);
        }
    }

    // create the mandated output clip
    ClipDescriptor *dstClip = desc.defineClip(kOfxImageEffectOutputClipName);
    dstClip->addSupportedComponent(ePixelComponentRGB);
    dstClip->addSupportedComponent(ePixelComponentRGBA);
    dstClip->addSupportedComponent(ePixelComponentAlpha);
    dstClip->setSupportsTiles(true);

    // make some pages and to things in
    PageParamDescriptor *page = desc.definePageParam("Controls");

    IntParamDescriptor *which = desc.defineIntParam(kSwitchPluginParamWhich);
    which->setLabels("which", "which", "which");
    which->setScriptName("which");
    which->setHint("The input to display. Each input is displayed at the value corresponding to the number of the input. For example, setting which to 4 displays the image from input 4.");
    which->setDefault(0);
    which->setRange(0, kSwitchPluginSourceClipCount);
    which->setDisplayRange(0, 1);
    which->setAnimates(true);

    page->addChild(*which);

#ifdef OFX_EXTENSIONS_NUKE
    // Enable transform by the host.
    // It is only possible for transforms which can be represented as a 3x3 matrix.
    desc.setCanTransform(true);
#endif
}

OFX::ImageEffect* SwitchPluginFactory::createInstance(OfxImageEffectHandle handle, OFX::ContextEnum context)
{
    return new SwitchPlugin(handle);
}

<commit_msg>Switch: also support the General context<commit_after>/*
 OFX Switch plugin.
 Switch between inputs.

 Copyright (C) 2013 INRIA
 Author Frederic Devernay frederic.devernay@inria.fr

 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 INRIA
 Domaine de Voluceau
 Rocquencourt - B.P. 105
 78153 Le Chesnay Cedex - France

 The skeleton for this source file is from:
 OFX Basic Example plugin, a plugin that illustrates the use of the OFX Support library.

 Copyright (C) 2004-2005 The Open Effects Association Ltd
 Author Bruno Nicoletti bruno@thefoundry.co.uk

 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 The Open Effects Association Ltd, 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 The Open Effects Association Ltd
 1 Wardour St
 London W1D 6PA
 England

 */

#include "Switch.h"

#include <string>

#ifdef _WINDOWS
#include <windows.h>
#endif

#ifdef OFX_EXTENSIONS_NUKE
#include "nuke/fnOfxExtensions.h"
#endif

#define kSwitchPluginSourceClipCount 10
#define kSwitchPluginParamWhich "which"

////////////////////////////////////////////////////////////////////////////////
/** @brief The plugin that does our work */
class SwitchPlugin : public OFX::ImageEffect {
    protected :
    // do not need to delete these, the ImageEffect is managing them for us
    OFX::Clip *srcClip_[kSwitchPluginSourceClipCount];

    OFX::IntParam *which_;

    public :
    /** @brief ctor */
    SwitchPlugin(OfxImageEffectHandle handle);

    /* Override the render */
    virtual void render(const OFX::RenderArguments &args);

    /* override is identity */
    virtual bool isIdentity(const OFX::RenderArguments &args, OFX::Clip * &identityClip, double &identityTime);

#ifdef OFX_EXTENSIONS_NUKE
    /** @brief recover a transform matrix from an effect */
    virtual bool getTransform(const OFX::TransformArguments &args, OFX::Clip * &transformClip, double transformMatrix[9]);
#endif

    /** @brief called when a clip has just been changed in some way (a rewire maybe) */
    virtual void changedClip(const OFX::InstanceChangedArgs &args, const std::string &clipName);
};

SwitchPlugin::SwitchPlugin(OfxImageEffectHandle handle)
: ImageEffect(handle)
, which_(0)
{
    for (int i = 0; i < kSwitchPluginSourceClipCount; ++i) {
        std::stringstream s;
        s << i;
        srcClip_[i] = fetchClip(s.str());
    }
    which_  = fetchIntParam(kSwitchPluginParamWhich);
}

void
SwitchPlugin::render(const OFX::RenderArguments &args)
{
    // do nothing as this should never be called as isIdentity should always be trapped
}

// overridden is identity
bool
SwitchPlugin::isIdentity(const OFX::RenderArguments &args, OFX::Clip * &identityClip, double &identityTime)
{
    int input;
    which_->getValue(input);
    identityClip = srcClip_[input];
    return true;
}

#ifdef OFX_EXTENSIONS_NUKE
// overridden getTransform
bool SwitchPlugin::getTransform(const OFX::TransformArguments &args, OFX::Clip * &transformClip, double transformMatrix[9])
{
    int input;
    which_->getValue(input);
    transformClip = srcClip_[input];

    transformMatrix[0] = 1.;
    transformMatrix[1] = 0.;
    transformMatrix[2] = 0.;
    transformMatrix[3] = 0.;
    transformMatrix[4] = 1.;
    transformMatrix[5] = 0.;
    transformMatrix[6] = 0.;
    transformMatrix[7] = 0.;
    transformMatrix[8] = 1.;
    return true;
}
#endif

void
SwitchPlugin::changedClip(const OFX::InstanceChangedArgs &args, const std::string &clipName)
{
    int maxconnected = 1;
    for (int i = 2; i < kSwitchPluginSourceClipCount; ++i) {
        if (srcClip_[i]->isConnected()) {
            maxconnected = i;
        }
    }
    which_->setDisplayRange(0, maxconnected);
}

using namespace OFX;

void SwitchPluginFactory::describe(OFX::ImageEffectDescriptor &desc)
{
    // basic labels
    desc.setLabels("SwitchOFX", "SwitchOFX", "SwitchOFX");
    desc.setPluginGrouping("Merge");
    desc.setPluginDescription("Lets you switch between any number of inputs.");

    // add the supported contexts
    desc.addSupportedContext(eContextGeneral);
    desc.addSupportedContext(eContextFilter);

    // add supported pixel depths
    desc.addSupportedBitDepth(eBitDepthUByte);
    desc.addSupportedBitDepth(eBitDepthUShort);
    desc.addSupportedBitDepth(eBitDepthFloat);

    // set a few flags
    desc.setSingleInstance(false);
    desc.setHostFrameThreading(true);
    desc.setSupportsMultiResolution(true);
    desc.setSupportsTiles(true);
    desc.setTemporalClipAccess(false);
    desc.setRenderTwiceAlways(false);
    desc.setSupportsMultipleClipPARs(false);
#ifdef OFX_EXTENSIONS_NUKE
    // Enable transform by the host.
    // It is only possible for transforms which can be represented as a 3x3 matrix.
    desc.setCanTransform(true);
#endif
}

void SwitchPluginFactory::describeInContext(OFX::ImageEffectDescriptor &desc, OFX::ContextEnum context)
{
    // Source clip only in the filter context
    // create the mandated source clip
    for (int i = 0; i < kSwitchPluginSourceClipCount; ++i) {
        std::stringstream s;
        s << i;
        ClipDescriptor *srcClip = desc.defineClip(s.str());
        srcClip->addSupportedComponent(ePixelComponentRGB);
        srcClip->addSupportedComponent(ePixelComponentRGBA);
        srcClip->addSupportedComponent(ePixelComponentAlpha);
        srcClip->setTemporalClipAccess(false);
        srcClip->setSupportsTiles(true);
        srcClip->setIsMask(false);
        if (i >= 2) {
            srcClip->setOptional(true);
        }
    }

    // create the mandated output clip
    ClipDescriptor *dstClip = desc.defineClip(kOfxImageEffectOutputClipName);
    dstClip->addSupportedComponent(ePixelComponentRGB);
    dstClip->addSupportedComponent(ePixelComponentRGBA);
    dstClip->addSupportedComponent(ePixelComponentAlpha);
    dstClip->setSupportsTiles(true);

    // make some pages and to things in
    PageParamDescriptor *page = desc.definePageParam("Controls");

    IntParamDescriptor *which = desc.defineIntParam(kSwitchPluginParamWhich);
    which->setLabels("which", "which", "which");
    which->setScriptName("which");
    which->setHint("The input to display. Each input is displayed at the value corresponding to the number of the input. For example, setting which to 4 displays the image from input 4.");
    which->setDefault(0);
    which->setRange(0, kSwitchPluginSourceClipCount);
    which->setDisplayRange(0, 1);
    which->setAnimates(true);

    page->addChild(*which);

#ifdef OFX_EXTENSIONS_NUKE
    // Enable transform by the host.
    // It is only possible for transforms which can be represented as a 3x3 matrix.
    desc.setCanTransform(true);
#endif
}

OFX::ImageEffect* SwitchPluginFactory::createInstance(OfxImageEffectHandle handle, OFX::ContextEnum context)
{
    return new SwitchPlugin(handle);
}

<|endoftext|>


<commit_before>#include "AliTPCExB.h"
#include "TMath.h"
#include "TTreeStream.h"

//
// Abstract class for ExB effect parameterization
//
//
//
// The ExB correction map is stored in the calib DB
// The lookup can be dumped to the tree:
/*

   //
  char *storage = "local://OCDBres"
  Int_t RunNumber=0;
  AliCDBManager::Instance()->SetDefaultStorage(storage);
  AliCDBManager::Instance()->SetRun(RunNumber)
  AliTPCExBFirst * exb = AliTPCcalibDB::Instance()->GetExB();
  //
  // See example macro $ALICE_ROOT/TPC/macros/AliTPCExBdraw.C
  //
  .L $ALICE_ROOT/TPC/macros/AliTPCExBdraw.C
  Draw0(0)

*/

AliTPCExB* AliTPCExB::fgInstance = 0;

ClassImp(AliTPCExB)

void AliTPCExB::TestExB(const char* fileName) {
  //
  // well, as the name sais...
  //
  TTreeSRedirector ts(fileName);
  Double_t x[3];
  for (x[0]=-250.;x[0]<=250.;x[0]+=10.)
    for (x[1]=-250.;x[1]<=250.;x[1]+=10.)
      for (x[2]=-250.;x[2]<=250.;x[2]+=10.) {
	Double_t d[3];
	Correct(x,d);
	Double_t r=TMath::Sqrt(x[0]*x[0]+x[1]*x[1]);
	Double_t rd=TMath::Sqrt(d[0]*d[0]+d[1]*d[1]);
	Double_t dr=r-rd;
	Double_t phi=TMath::ATan2(x[0],x[1]);
	Double_t phid=TMath::ATan2(d[0],d[1]);
	Double_t dphi=phi-phid;
	if (dphi<0.) dphi+=TMath::TwoPi();
	if (dphi>TMath::Pi()) dphi=TMath::TwoPi()-dphi;
	Double_t drphi=r*dphi;
	Double_t dx=x[0]-d[0];
	Double_t dy=x[1]-d[1];
	Double_t dz=x[2]-d[2];
	ts<<"positions"
	  <<"x0="<<x[0]
	  <<"x1="<<x[1]
	  <<"x2="<<x[2]
	  <<"dx="<<dx
	  <<"dy="<<dy
	  <<"dz="<<dz
	  <<"r="<<r
	  <<"phi="<<phi
	  <<"dr="<<dr
	  <<"drphi="<<drphi
	  <<"\n";
      }
}

Double_t AliTPCExB::GetDr(Double_t r, Double_t phi, Double_t z){
  //
  // Static function
  // Posibble to us it for visualization
  //
  //
  if (!fgInstance) return 0;
  Double_t pos0[3] = {r*TMath::Sin(phi), r*TMath::Cos(phi),z};
  Double_t pos1[3];
  fgInstance->Correct(pos0,pos1);
  Double_t dx=pos1[0]-pos0[0];
  Double_t dy=pos1[1]-pos0[1];
  //  Double_t dz=pos1[2]-pos0[2];
  return TMath::Sqrt(dx*dx+dy*dy);
}

Double_t AliTPCExB::GetDrphi(Double_t r, Double_t phi, Double_t z){
  //
  //
  //
  if (!fgInstance) return 0;
  Double_t pos0[3] = {r*TMath::Sin(phi), r*TMath::Cos(phi),z};
  Double_t pos1[3];
  fgInstance->Correct(pos0,pos1);
  Double_t dphi=TMath::ATan2(pos1[1],pos1[0])-TMath::ATan2(pos0[1],pos0[0]);
  return r*dphi;

}

Double_t AliTPCExB::GetDphi(Double_t r, Double_t phi, Double_t z){
  //
  //
  //
  if (!fgInstance) return 0;
  Double_t pos0[3] = {r*TMath::Sin(phi), r*TMath::Cos(phi),z};
  Double_t pos1[3];
  fgInstance->Correct(pos0,pos1);
  Double_t dphi=TMath::ATan2(pos1[1],pos1[0])-TMath::ATan2(pos0[1],pos0[0]);
  return dphi;

}

Double_t AliTPCExB::GetDz(Double_t r, Double_t phi, Double_t z){
  //
  //
  //
  if (!fgInstance) return 0;
  Double_t pos0[3] = {r*TMath::Sin(phi), r*TMath::Cos(phi),z};
  Double_t pos1[3];
  fgInstance->Correct(pos0,pos1);
  Double_t dz=pos1[2]-pos0[2];
  return dz;
}
<commit_msg>Updated documentation line - how to use the class  (Marian)<commit_after>#include "AliTPCExB.h"
#include "TMath.h"
#include "TTreeStream.h"

//
// Abstract class for ExB effect parameterization
//
//
//
// The ExB correction map is stored in the calib DB
// The lookup can be dumped to the tree:
/*

   //
  char *storage = "local://OCDBres"
  Int_t RunNumber=0;
  AliCDBManager::Instance()->SetDefaultStorage(storage);
  AliCDBManager::Instance()->SetRun(RunNumber)
  AliTPCExBFirst * exb = AliTPCcalibDB::Instance()->GetExB();
  //
  // See example macro $ALICE_ROOT/TPC/macros/AliTPCExBdraw.C
  //
  .L $ALICE_ROOT/TPC/macros/AliTPCExBdraw.C
  Draw(0)

*/

AliTPCExB* AliTPCExB::fgInstance = 0;

ClassImp(AliTPCExB)

void AliTPCExB::TestExB(const char* fileName) {
  //
  // well, as the name sais...
  //
  TTreeSRedirector ts(fileName);
  Double_t x[3];
  for (x[0]=-250.;x[0]<=250.;x[0]+=10.)
    for (x[1]=-250.;x[1]<=250.;x[1]+=10.)
      for (x[2]=-250.;x[2]<=250.;x[2]+=10.) {
	Double_t d[3];
	Correct(x,d);
	Double_t r=TMath::Sqrt(x[0]*x[0]+x[1]*x[1]);
	Double_t rd=TMath::Sqrt(d[0]*d[0]+d[1]*d[1]);
	Double_t dr=r-rd;
	Double_t phi=TMath::ATan2(x[0],x[1]);
	Double_t phid=TMath::ATan2(d[0],d[1]);
	Double_t dphi=phi-phid;
	if (dphi<0.) dphi+=TMath::TwoPi();
	if (dphi>TMath::Pi()) dphi=TMath::TwoPi()-dphi;
	Double_t drphi=r*dphi;
	Double_t dx=x[0]-d[0];
	Double_t dy=x[1]-d[1];
	Double_t dz=x[2]-d[2];
	ts<<"positions"
	  <<"x0="<<x[0]
	  <<"x1="<<x[1]
	  <<"x2="<<x[2]
	  <<"dx="<<dx
	  <<"dy="<<dy
	  <<"dz="<<dz
	  <<"r="<<r
	  <<"phi="<<phi
	  <<"dr="<<dr
	  <<"drphi="<<drphi
	  <<"\n";
      }
}

Double_t AliTPCExB::GetDr(Double_t r, Double_t phi, Double_t z){
  //
  // Static function
  // Posibble to us it for visualization
  //
  //
  if (!fgInstance) return 0;
  Double_t pos0[3] = {r*TMath::Sin(phi), r*TMath::Cos(phi),z};
  Double_t pos1[3];
  fgInstance->Correct(pos0,pos1);
  Double_t dx=pos1[0]-pos0[0];
  Double_t dy=pos1[1]-pos0[1];
  //  Double_t dz=pos1[2]-pos0[2];
  return TMath::Sqrt(dx*dx+dy*dy);
}

Double_t AliTPCExB::GetDrphi(Double_t r, Double_t phi, Double_t z){
  //
  //
  //
  if (!fgInstance) return 0;
  Double_t pos0[3] = {r*TMath::Sin(phi), r*TMath::Cos(phi),z};
  Double_t pos1[3];
  fgInstance->Correct(pos0,pos1);
  Double_t dphi=TMath::ATan2(pos1[1],pos1[0])-TMath::ATan2(pos0[1],pos0[0]);
  return r*dphi;

}

Double_t AliTPCExB::GetDphi(Double_t r, Double_t phi, Double_t z){
  //
  //
  //
  if (!fgInstance) return 0;
  Double_t pos0[3] = {r*TMath::Sin(phi), r*TMath::Cos(phi),z};
  Double_t pos1[3];
  fgInstance->Correct(pos0,pos1);
  Double_t dphi=TMath::ATan2(pos1[1],pos1[0])-TMath::ATan2(pos0[1],pos0[0]);
  return dphi;

}

Double_t AliTPCExB::GetDz(Double_t r, Double_t phi, Double_t z){
  //
  //
  //
  if (!fgInstance) return 0;
  Double_t pos0[3] = {r*TMath::Sin(phi), r*TMath::Cos(phi),z};
  Double_t pos1[3];
  fgInstance->Correct(pos0,pos1);
  Double_t dz=pos1[2]-pos0[2];
  return dz;
}
<|endoftext|>


<commit_before>/**
 * Copyright (C) 2012 by INdT
 *
 * This program 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
 * of the License, or (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * @author Rodrigo Goncalves de Oliveira <rodrigo.goncalves@openbossa.org>
 * @author Roger Felipe Zanoni da Silva <roger.zanoni@openbossa.org>
 */

#include "launcher.h"

#include <QtCore/qglobal.h>

#if QT_VERSION >= 0x050000
#include <QtGui/QGuiApplication>
#include <QtQml/QQmlContext>
#include <QtQml/QQmlEngine>
#include <QtQuick/QQuickView>
#else
#include <QtGui/QApplication>
#include <QtDeclarative/QDeclarativeContext>
#include <QtDeclarative/QDeclarativeView>
#include <QtDeclarative/QDeclarativeEngine>
#endif

#ifdef QT_OPENGL_LIB
#include <QtOpenGL/QGLWidget>
#endif

int main(int argc, char *argv[])
{
    QByteArray data = "1";
    qputenv("QML_IMPORT_TRACE", data);

#if QT_VERSION >= 0x050000
    QGuiApplication app(argc, argv);
    QQuickView view;
#else
    QApplication app(argc, argv);
    QDeclarativeView view;
#endif

    Launcher launcher;

    view.engine()->rootContext()->setContextProperty("launcher", &launcher);
    view.engine()->addImportPath("../../imports");

#if QT_VERSION >= 0x050000
    view.setSource(QUrl("qrc:/main-qt5.qml"));
#else
    view.setSource(QUrl("qrc:/main-qt4.qml"));
#endif

#ifdef QT_OPENGL_LIB
    view.setViewport(new QGLWidget);
#endif

    view.show();

    return app.exec();
}
<commit_msg>fixed import path in examples<commit_after>/**
 * Copyright (C) 2012 by INdT
 *
 * This program 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
 * of the License, or (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * @author Rodrigo Goncalves de Oliveira <rodrigo.goncalves@openbossa.org>
 * @author Roger Felipe Zanoni da Silva <roger.zanoni@openbossa.org>
 */

#include "launcher.h"

#include <QtCore/qglobal.h>

#if QT_VERSION >= 0x050000
#include <QtGui/QGuiApplication>
#include <QtQml/QQmlContext>
#include <QtQml/QQmlEngine>
#include <QtQuick/QQuickView>
#else
#include <QtGui/QApplication>
#include <QtDeclarative/QDeclarativeContext>
#include <QtDeclarative/QDeclarativeView>
#include <QtDeclarative/QDeclarativeEngine>
#endif

#ifdef QT_OPENGL_LIB
#include <QtOpenGL/QGLWidget>
#endif

int main(int argc, char *argv[])
{
    QByteArray data = "1";
    qputenv("QML_IMPORT_TRACE", data);

#if QT_VERSION >= 0x050000
    QGuiApplication app(argc, argv);
    QQuickView view;
#else
    QApplication app(argc, argv);
    QDeclarativeView view;
#endif

    Launcher launcher;

    view.engine()->rootContext()->setContextProperty("launcher", &launcher);
    view.engine()->addImportPath("../../src/imports");

#if QT_VERSION >= 0x050000
    view.setSource(QUrl("qrc:/main-qt5.qml"));
#else
    view.setSource(QUrl("qrc:/main-qt4.qml"));
#endif

#ifdef QT_OPENGL_LIB
    view.setViewport(new QGLWidget);
#endif

    view.show();

    return app.exec();
}
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2018.  All rights reserved
 */
//  TEST    Foundation::Containers::Mapping
//      STATUS  Alpha-Late
#include "Stroika/Foundation/StroikaPreComp.h"

#include <iostream>
#include <sstream>

#include "Stroika/Foundation/Containers/Collection.h"

#include "Stroika/Foundation/Containers/Concrete/Mapping_Array.h"
#include "Stroika/Foundation/Containers/Concrete/Mapping_LinkedList.h"
#include "Stroika/Foundation/Containers/Concrete/Mapping_stdmap.h"
#include "Stroika/Foundation/Containers/Concrete/SortedMapping_stdmap.h"
#include "Stroika/Foundation/Containers/Mapping.h"
#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Trace.h"

#include "../TestCommon/CommonTests_Mapping.h"
#include "../TestHarness/SimpleClass.h"
#include "../TestHarness/TestHarness.h"

using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Containers;

using Concrete::Mapping_Array;
using Concrete::Mapping_LinkedList;
using Concrete::Mapping_stdmap;

namespace {
    template <typename CONCRETE_CONTAINER>
    void DoTestForConcreteContainer_ ()
    {
        using namespace CommonTests::MappingTests;
        SimpleMappingTest_All_ (DEFAULT_TESTING_SCHEMA<CONCRETE_CONTAINER>{});
        SimpleMappingTest_WithDefaultEqCompaerer_ (DEFAULT_TESTING_SCHEMA<CONCRETE_CONTAINER>{});
    }
    template <typename CONCRETE_CONTAINER, typename FACTORY, typename VALUE_EQUALS_COMPARER_TYPE>
    void DoTestForConcreteContainer_ (FACTORY factory, VALUE_EQUALS_COMPARER_TYPE valueEqualsComparer)
    {
        using namespace CommonTests::MappingTests;
        auto testschema = DEFAULT_TESTING_SCHEMA<CONCRETE_CONTAINER, FACTORY, VALUE_EQUALS_COMPARER_TYPE>{factory, valueEqualsComparer};
        SimpleMappingTest_All_ (testschema);
    }
}

namespace {
    void Test2_SimpleBaseClassConversionTraitsConfusion_ ()
    {
        Debug::TraceContextBumper ctx{L"{}::Test2_SimpleBaseClassConversionTraitsConfusion_"};
        SortedMapping<int, float> xxxyy  = Concrete::SortedMapping_stdmap<int, float> ();
        Mapping<int, float>       xxxyy1 = Concrete::Mapping_stdmap<int, float> ();
    }
}

namespace {
    namespace Test4_MappingCTOROverloads_ {
        namespace xPrivate_ {
            struct A;
            struct B;
            struct A {
                A () {}
                A (const A&) {}
                A (const B&) {}
            };
            struct B {
                B () {}
                B (const A&) {}
                B (const B&) {}
            };

            using Common::KeyValuePair;
            using KEY_TYPE                = int;
            using VALUE_TYPE              = B;
            using CONTAINER_OF_PAIR_KEY_T = Mapping<int, A>;
            using T                       = KeyValuePair<KEY_TYPE, VALUE_TYPE>;
        }
        void DoIt ()
        {
            Debug::TraceContextBumper ctx{L"{}::Test4_MappingCTOROverloads_"};
            using namespace xPrivate_;
            Mapping<int, A> from;

            {
                using Common::KeyValuePair;
                static_assert (Configuration::IsIterableOfT<Mapping<int, A>, KeyValuePair<int, A>>::value);
                static_assert (Configuration::IsIterableOfT<Mapping<int, B>, KeyValuePair<int, B>>::value);
            }

            Mapping<int, B> to1;
            for (auto i : from) {
                to1.Add (i);
            }
            Mapping<int, B> to2 = from;
        }
    }
}

namespace {
    namespace ExampleCTORS_Test_5_ {
        void DoTest ()
        {
            Debug::TraceContextBumper ctx{L"{}::ExampleCTORS_Test_5_"};
            // From Mapping<> CTOR docs
            Collection<pair<int, int>> c;
            std::map<int, int>         m;

            Mapping<int, int> m1 = {pair<int, int>{1, 1}, pair<int, int>{2, 2}, pair<int, int>{3, 2}};
            Mapping<int, int> m2 = m1;
            Mapping<int, int> m3{m1};
            Mapping<int, int> m4{m1.begin (), m1.end ()};
            Mapping<int, int> m5{c};
            Mapping<int, int> m6{m};
            Mapping<int, int> m7{m.begin (), m.end ()};
            Mapping<int, int> m8{move (m1)};
        }
    }
}

namespace {
    namespace Where_Test_6_ {
        void DoAll ()
        {
            Mapping<int, int> m{KeyValuePair<int, int>{1, 3}, KeyValuePair<int, int>{2, 4}, KeyValuePair<int, int>{3, 5}, KeyValuePair<int, int>{4, 5}, KeyValuePair<int, int>{5, 7}};
            VerifyTestResult ((m.Where ([](const KeyValuePair<int, int>& value) { return Math::IsPrime (value.fKey); }) == Mapping<int, int>{KeyValuePair<int, int>{2, 4}, KeyValuePair<int, int>{3, 5}, KeyValuePair<int, int>{5, 7}}));
            VerifyTestResult ((m.Where ([](int key) { return Math::IsPrime (key); }) == Mapping<int, int>{KeyValuePair<int, int>{2, 4}, KeyValuePair<int, int>{3, 5}, KeyValuePair<int, int>{5, 7}}));
        }
    }
}

namespace {
    namespace WithKeys_Test_7_ {
        void DoAll ()
        {
            Mapping<int, int> m{KeyValuePair<int, int>{1, 3}, KeyValuePair<int, int>{2, 4}, KeyValuePair<int, int>{3, 5}, KeyValuePair<int, int>{4, 5}, KeyValuePair<int, int>{5, 7}};
            VerifyTestResult ((m.WithKeys (initializer_list<int>{2, 5}) == Mapping<int, int>{KeyValuePair<int, int>{2, 4}, KeyValuePair<int, int>{5, 7}}));
        }
    }
}

namespace {
    void DoRegressionTests_ ()
    {
        struct MySimpleClassWithoutComparisonOperators_ComparerWithEquals_ : Common::ComparisonRelationDeclaration<Common::ComparisonRelationType::eEquals> {
            using value_type = SimpleClassWithoutComparisonOperators;
            bool operator() (const value_type& v1, const value_type& v2) const
            {
                return v1.GetValue () == v2.GetValue ();
            }
        };

        DoTestForConcreteContainer_<Mapping<size_t, size_t>> ();
        DoTestForConcreteContainer_<Mapping<SimpleClass, SimpleClass>> ();
        DoTestForConcreteContainer_<Mapping<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators>> (
            []() { return Mapping<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators> (MySimpleClassWithoutComparisonOperators_ComparerWithEquals_{}); },
            MySimpleClassWithoutComparisonOperators_ComparerWithEquals_{});

        DoTestForConcreteContainer_<Mapping_Array<size_t, size_t>> ();
        DoTestForConcreteContainer_<Mapping_Array<SimpleClass, SimpleClass>> ();
        DoTestForConcreteContainer_<Mapping_Array<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators>> (
            []() { return Mapping_Array<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators> (MySimpleClassWithoutComparisonOperators_ComparerWithEquals_{}); },
            MySimpleClassWithoutComparisonOperators_ComparerWithEquals_{});

        DoTestForConcreteContainer_<Mapping_LinkedList<size_t, size_t>> ();
        DoTestForConcreteContainer_<Mapping_LinkedList<SimpleClass, SimpleClass>> ();
        // DoTestForConcreteContainer_AllTestsWhichDontRequireComparer_For_Type_<Mapping_LinkedList<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators_MappingTRAITS>> ();
        DoTestForConcreteContainer_<Mapping_LinkedList<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators>> (
            []() { return Mapping_LinkedList<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators> (MySimpleClassWithoutComparisonOperators_ComparerWithEquals_{}); },
            MySimpleClassWithoutComparisonOperators_ComparerWithEquals_{});

        DoTestForConcreteContainer_<Mapping_stdmap<size_t, size_t>> ();
        DoTestForConcreteContainer_<Mapping_stdmap<SimpleClass, SimpleClass>> ();
        {
            struct MySimpleClassWithoutComparisonOperators_ComparerWithLess_ : Common::ComparisonRelationDeclaration<Common::ComparisonRelationType::eStrictInOrder> {
                using value_type = SimpleClassWithoutComparisonOperators;
                bool operator() (const value_type& v1, const value_type& v2) const
                {
                    return v1.GetValue () < v2.GetValue ();
                }
            };
            DoTestForConcreteContainer_<Mapping_stdmap<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators>> (
                []() { return Mapping_stdmap<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators> (MySimpleClassWithoutComparisonOperators_ComparerWithLess_{}); },
                //Common::mkEqualsComparerAdapter (MySimpleClassWithoutComparisonOperators_ComparerWithLess_{})
                MySimpleClassWithoutComparisonOperators_ComparerWithEquals_{});
        }

        Test2_SimpleBaseClassConversionTraitsConfusion_ ();

        //Test3_SimpleMappingTest_WhichRequiresExplcitValueComparer ();

        Test4_MappingCTOROverloads_::DoIt ();

        ExampleCTORS_Test_5_::DoTest ();

        Where_Test_6_::DoAll ();
        WithKeys_Test_7_::DoAll ();
    }
}

int main ([[maybe_unused]] int argc, [[maybe_unused]] const char* argv[])
{
    Stroika::TestHarness::Setup ();
    return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
}
<commit_msg>Minor cosmetic cleanups for regression test which worked around problem with clang6 and libc++<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2018.  All rights reserved
 */
//  TEST    Foundation::Containers::Mapping
//      STATUS  Alpha-Late
#include "Stroika/Foundation/StroikaPreComp.h"

#include <iostream>
#include <sstream>

#include "Stroika/Foundation/Containers/Collection.h"

#include "Stroika/Foundation/Containers/Concrete/Mapping_Array.h"
#include "Stroika/Foundation/Containers/Concrete/Mapping_LinkedList.h"
#include "Stroika/Foundation/Containers/Concrete/Mapping_stdmap.h"
#include "Stroika/Foundation/Containers/Concrete/SortedMapping_stdmap.h"
#include "Stroika/Foundation/Containers/Mapping.h"
#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Trace.h"

#include "../TestCommon/CommonTests_Mapping.h"
#include "../TestHarness/SimpleClass.h"
#include "../TestHarness/TestHarness.h"

using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Containers;

using Concrete::Mapping_Array;
using Concrete::Mapping_LinkedList;
using Concrete::Mapping_stdmap;

namespace {
    template <typename CONCRETE_CONTAINER>
    void DoTestForConcreteContainer_ ()
    {
        using namespace CommonTests::MappingTests;
        SimpleMappingTest_All_ (DEFAULT_TESTING_SCHEMA<CONCRETE_CONTAINER>{});
        SimpleMappingTest_WithDefaultEqCompaerer_ (DEFAULT_TESTING_SCHEMA<CONCRETE_CONTAINER>{});
    }
    template <typename CONCRETE_CONTAINER, typename FACTORY, typename VALUE_EQUALS_COMPARER_TYPE>
    void DoTestForConcreteContainer_ (FACTORY factory, VALUE_EQUALS_COMPARER_TYPE valueEqualsComparer)
    {
        using namespace CommonTests::MappingTests;
        auto testschema = DEFAULT_TESTING_SCHEMA<CONCRETE_CONTAINER, FACTORY, VALUE_EQUALS_COMPARER_TYPE>{factory, valueEqualsComparer};
        SimpleMappingTest_All_ (testschema);
    }
}

namespace {
    void Test2_SimpleBaseClassConversionTraitsConfusion_ ()
    {
        Debug::TraceContextBumper ctx{L"{}::Test2_SimpleBaseClassConversionTraitsConfusion_"};
        SortedMapping<int, float> xxxyy  = Concrete::SortedMapping_stdmap<int, float> ();
        Mapping<int, float>       xxxyy1 = Concrete::Mapping_stdmap<int, float> ();
    }
}

namespace {
    namespace Test4_MappingCTOROverloads_ {
        namespace xPrivate_ {
            struct A;
            struct B;
            struct A {
                A () = default;
                A (const A&)= default;
                A (const B&) {}
            };
            struct B {
                B () = default;
                B (const A&) {}
                B (const B&) = default;
            };
            using Common::KeyValuePair;
            using KEY_TYPE                = int;
            using VALUE_TYPE              = B;
            using CONTAINER_OF_PAIR_KEY_T = Mapping<int, A>;
            using T                       = KeyValuePair<KEY_TYPE, VALUE_TYPE>;
        }
        void DoIt ()
        {
            Debug::TraceContextBumper ctx{L"{}::Test4_MappingCTOROverloads_"};
            using namespace xPrivate_;
            Mapping<int, A> from;

            static_assert (Configuration::IsIterableOfT<Mapping<int, A>, KeyValuePair<int, A>>::value);
            static_assert (Configuration::IsIterableOfT<Mapping<int, B>, KeyValuePair<int, B>>::value);

            Mapping<int, B> to1;
            for (auto i : from) {
                to1.Add (i);
            }
            Mapping<int, B> to2 = from;
        }
    }
}

namespace {
    namespace ExampleCTORS_Test_5_ {
        void DoTest ()
        {
            Debug::TraceContextBumper ctx{L"{}::ExampleCTORS_Test_5_"};
            // From Mapping<> CTOR docs
            Collection<pair<int, int>> c;
            std::map<int, int>         m;

            Mapping<int, int> m1 = {pair<int, int>{1, 1}, pair<int, int>{2, 2}, pair<int, int>{3, 2}};
            Mapping<int, int> m2 = m1;
            Mapping<int, int> m3{m1};
            Mapping<int, int> m4{m1.begin (), m1.end ()};
            Mapping<int, int> m5{c};
            Mapping<int, int> m6{m};
            Mapping<int, int> m7{m.begin (), m.end ()};
            Mapping<int, int> m8{move (m1)};
        }
    }
}

namespace {
    namespace Where_Test_6_ {
        void DoAll ()
        {
            Mapping<int, int> m{KeyValuePair<int, int>{1, 3}, KeyValuePair<int, int>{2, 4}, KeyValuePair<int, int>{3, 5}, KeyValuePair<int, int>{4, 5}, KeyValuePair<int, int>{5, 7}};
            VerifyTestResult ((m.Where ([](const KeyValuePair<int, int>& value) { return Math::IsPrime (value.fKey); }) == Mapping<int, int>{KeyValuePair<int, int>{2, 4}, KeyValuePair<int, int>{3, 5}, KeyValuePair<int, int>{5, 7}}));
            VerifyTestResult ((m.Where ([](int key) { return Math::IsPrime (key); }) == Mapping<int, int>{KeyValuePair<int, int>{2, 4}, KeyValuePair<int, int>{3, 5}, KeyValuePair<int, int>{5, 7}}));
        }
    }
}

namespace {
    namespace WithKeys_Test_7_ {
        void DoAll ()
        {
            Mapping<int, int> m{KeyValuePair<int, int>{1, 3}, KeyValuePair<int, int>{2, 4}, KeyValuePair<int, int>{3, 5}, KeyValuePair<int, int>{4, 5}, KeyValuePair<int, int>{5, 7}};
            VerifyTestResult ((m.WithKeys (initializer_list<int>{2, 5}) == Mapping<int, int>{KeyValuePair<int, int>{2, 4}, KeyValuePair<int, int>{5, 7}}));
        }
    }
}

namespace {
    void DoRegressionTests_ ()
    {
        struct MySimpleClassWithoutComparisonOperators_ComparerWithEquals_ : Common::ComparisonRelationDeclaration<Common::ComparisonRelationType::eEquals> {
            using value_type = SimpleClassWithoutComparisonOperators;
            bool operator() (const value_type& v1, const value_type& v2) const
            {
                return v1.GetValue () == v2.GetValue ();
            }
        };

        DoTestForConcreteContainer_<Mapping<size_t, size_t>> ();
        DoTestForConcreteContainer_<Mapping<SimpleClass, SimpleClass>> ();
        DoTestForConcreteContainer_<Mapping<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators>> (
            []() { return Mapping<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators> (MySimpleClassWithoutComparisonOperators_ComparerWithEquals_{}); },
            MySimpleClassWithoutComparisonOperators_ComparerWithEquals_{});

        DoTestForConcreteContainer_<Mapping_Array<size_t, size_t>> ();
        DoTestForConcreteContainer_<Mapping_Array<SimpleClass, SimpleClass>> ();
        DoTestForConcreteContainer_<Mapping_Array<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators>> (
            []() { return Mapping_Array<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators> (MySimpleClassWithoutComparisonOperators_ComparerWithEquals_{}); },
            MySimpleClassWithoutComparisonOperators_ComparerWithEquals_{});

        DoTestForConcreteContainer_<Mapping_LinkedList<size_t, size_t>> ();
        DoTestForConcreteContainer_<Mapping_LinkedList<SimpleClass, SimpleClass>> ();
        // DoTestForConcreteContainer_AllTestsWhichDontRequireComparer_For_Type_<Mapping_LinkedList<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators_MappingTRAITS>> ();
        DoTestForConcreteContainer_<Mapping_LinkedList<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators>> (
            []() { return Mapping_LinkedList<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators> (MySimpleClassWithoutComparisonOperators_ComparerWithEquals_{}); },
            MySimpleClassWithoutComparisonOperators_ComparerWithEquals_{});

        DoTestForConcreteContainer_<Mapping_stdmap<size_t, size_t>> ();
        DoTestForConcreteContainer_<Mapping_stdmap<SimpleClass, SimpleClass>> ();
        {
            struct MySimpleClassWithoutComparisonOperators_ComparerWithLess_ : Common::ComparisonRelationDeclaration<Common::ComparisonRelationType::eStrictInOrder> {
                using value_type = SimpleClassWithoutComparisonOperators;
                bool operator() (const value_type& v1, const value_type& v2) const
                {
                    return v1.GetValue () < v2.GetValue ();
                }
            };
            DoTestForConcreteContainer_<Mapping_stdmap<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators>> (
                []() { return Mapping_stdmap<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators> (MySimpleClassWithoutComparisonOperators_ComparerWithLess_{}); },
                //Common::mkEqualsComparerAdapter (MySimpleClassWithoutComparisonOperators_ComparerWithLess_{})
                MySimpleClassWithoutComparisonOperators_ComparerWithEquals_{});
        }

        Test2_SimpleBaseClassConversionTraitsConfusion_ ();

        //Test3_SimpleMappingTest_WhichRequiresExplcitValueComparer ();

        Test4_MappingCTOROverloads_::DoIt ();

        ExampleCTORS_Test_5_::DoTest ();

        Where_Test_6_::DoAll ();
        WithKeys_Test_7_::DoAll ();
    }
}

int main ([[maybe_unused]] int argc, [[maybe_unused]] const char* argv[])
{
    Stroika::TestHarness::Setup ();
    return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
}
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions Inc. 1990-2014.  All rights reserved
 */
//  TEST    Foundation::Memory
#include    "Stroika/Foundation/StroikaPreComp.h"

#include    "Stroika/Foundation/Containers/Mapping.h"
#include    "Stroika/Foundation/Debug/Assertions.h"
#include    "Stroika/Foundation/Debug/Trace.h"

#include    "Stroika/Foundation/Memory/AnyVariantValue.h"
#include    "Stroika/Foundation/Memory/Optional.h"
#include    "Stroika/Foundation/Memory/SharedByValue.h"
#include    "Stroika/Foundation/Memory/SharedPtr.h"

#include    "../TestHarness/SimpleClass.h"
#include    "../TestHarness/TestHarness.h"

using   namespace   Stroika;
using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::Memory;

//TODO: DOES IT EVEN NEED TO BE SAID? THese tests are a bit sparse ;-)

namespace   {
    void    Test1_Optional ()
    {
        {
            Optional<int>   x;
            VerifyTestResult (x.IsMissing ());
            x = 1;
            VerifyTestResult (not x.IsMissing ());
            VerifyTestResult (x.IsPresent ());
            VerifyTestResult (*x == 1);
        }
        {
            // Careful about self-assignment
            Optional<int>   x;
            x = 3;
            x = max (*x, 1);
            VerifyTestResult (x == 3);
        }
        auto testOptionalOfThingNotCopyable = [] () {
            struct NotCopyable {
                NotCopyable () {}
                NotCopyable (const NotCopyable&&) {}    // but is moveable!
                NotCopyable (const NotCopyable&) = delete;
                const NotCopyable& operator= (const NotCopyable&) = delete;
            };
            Optional<NotCopyable>   n1;
            VerifyTestResult (n1.IsMissing ());
            Optional<NotCopyable>   n2 (std::move (NotCopyable ()));    // use r-value reference to move
            VerifyTestResult (n2.IsPresent ());
        };
        testOptionalOfThingNotCopyable ();
    }
    void    Test2_SharedByValue ()
    {
    }
    void    Test_4_Optional_Of_Mapping_Copy_Problem_ ()
    {
        using   namespace   Stroika::Foundation::Memory;
        using   namespace   Stroika::Foundation::Containers;
        Mapping<int, float>  ml1, ml2;
        ml1 = ml2;

        Optional<Mapping<int, float>>  ol1, ol2;
        if (ol2.IsPresent ()) {
            ml1 = *ol2;
        }
        ol1 = ml1;
        Optional<Mapping<int, float>>  xxxx2 (ml1);

        // fails to compile prior to 2013-09-09
        Optional<Mapping<int, float>>  xxxx1 (ol1);
        // fails to compile prior to 2013-09-09
        ol1 = ol2;
    }
    void    Test_5_AnyVariantValue_ ()
    {
        {
            VerifyTestResult (AnyVariantValue ().empty ());
            VerifyTestResult (not AnyVariantValue (1).empty ());
            VerifyTestResult (not AnyVariantValue ("1").empty ());
            //VerifyTestResult (AnyVariantValue ("1").GetType () == typeid ("1"));  // not sure why this fails but not worthy worrying about yet
            VerifyTestResult (AnyVariantValue (1).As<int> () == 1);
        }
        {
            AnyVariantValue v;
            VerifyTestResult (v.empty ());
            v = AnyVariantValue (1);
            VerifyTestResult (not v.empty ());
            VerifyTestResult (v.GetType () == typeid (1));
            VerifyTestResult (v.As<int> () == 1);
            v = AnyVariantValue (L"a");
            //VerifyTestResult (v.GetType () == typeid (L"a")); // not sure why this fails but not worthy worrying about yet
            VerifyTestResult (not v.empty ());
            v.clear ();
            VerifyTestResult (v.empty ());
            VerifyTestResult (v.GetType () == typeid (void));
        }
        {
            struct JIM {
                int a;
            };
            AnyVariantValue v;
            VerifyTestResult (v.empty ());
            v = AnyVariantValue (JIM ());
            VerifyTestResult (v.GetType () == typeid (JIM));
        }
        {
            AnyVariantValue v;
            VerifyTestResult (v.empty ());
            v = AnyVariantValue (1);
            v = v;
            VerifyTestResult (v.GetType () == typeid (1));
            VerifyTestResult (v.As<int> () == 1);
            v = AnyVariantValue (v);
            VerifyTestResult (v.GetType () == typeid (1));
            VerifyTestResult (v.As<int> () == 1);
        }
        {
            static int nCopies = 0;
            struct Copyable {
                Copyable ()
                {
                    ++nCopies;
                }
                Copyable (const Copyable&)
                {
                    ++nCopies;
                }
                ~Copyable ()
                {
                    --nCopies;
                }
                const Copyable& operator= (const Copyable&) = delete;
            };
            {
                AnyVariantValue v;
                VerifyTestResult (v.empty ());
                v = AnyVariantValue (Copyable ());
                v = v;
                v = AnyVariantValue (AnyVariantValue (v));
                v = AnyVariantValue (AnyVariantValue (Copyable ()));
                VerifyTestResult (v.GetType () == typeid (Copyable));
            }
            VerifyTestResult (0 == nCopies);
        }
    }

    void    Test_6_SharedPtr ()
    {
        {
            SharedPtr<int> p (new int (3));
            VerifyTestResult (p.use_count () == 1);
            VerifyTestResult (p.unique ());
            VerifyTestResult (*p == 3);
        }
        {
            static int nCreates = 0;
            static int nDestroys = 0;
            struct COUNTED_OBJ {
                COUNTED_OBJ ()
                {
                    ++nCreates;
                }
                COUNTED_OBJ (const COUNTED_OBJ&)
                {
                    ++nCreates;
                }
                ~COUNTED_OBJ ()
                {
                    ++nDestroys;
                }
                const COUNTED_OBJ& operator= (const COUNTED_OBJ&) = delete;
            };
            struct CNT2 : COUNTED_OBJ {
            };
            {
                SharedPtr<COUNTED_OBJ> p (new COUNTED_OBJ ());
            }
            VerifyTestResult (nCreates == nDestroys);
            {
                SharedPtr<COUNTED_OBJ> p (SharedPtr<CNT2> (new CNT2 ()));
                VerifyTestResult (nCreates == nDestroys + 1);
            }
            VerifyTestResult (nCreates == nDestroys);
        }
    }
}

namespace   {

    void    DoRegressionTests_ ()
    {
        Test1_Optional ();
        Test2_SharedByValue ();
        Test_4_Optional_Of_Mapping_Copy_Problem_ ();
        Test_5_AnyVariantValue_ ();
        Test_6_SharedPtr ();
    }
}

int main (int argc, const char* argv[])
{
    Stroika::TestHarness::Setup ();
    Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
    return EXIT_SUCCESS;
}

<commit_msg>Started writing SharedPtr<> enable_shared_from_this test code (not working)<commit_after>/*
 * Copyright(c) Sophist Solutions Inc. 1990-2014.  All rights reserved
 */
//  TEST    Foundation::Memory
#include    "Stroika/Foundation/StroikaPreComp.h"

#include    "Stroika/Foundation/Containers/Mapping.h"
#include    "Stroika/Foundation/Debug/Assertions.h"
#include    "Stroika/Foundation/Debug/Trace.h"

#include    "Stroika/Foundation/Memory/AnyVariantValue.h"
#include    "Stroika/Foundation/Memory/Optional.h"
#include    "Stroika/Foundation/Memory/SharedByValue.h"
#include    "Stroika/Foundation/Memory/SharedPtr.h"

#include    "../TestHarness/SimpleClass.h"
#include    "../TestHarness/TestHarness.h"

using   namespace   Stroika;
using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::Memory;

//TODO: DOES IT EVEN NEED TO BE SAID? THese tests are a bit sparse ;-)

namespace   {
    void    Test1_Optional ()
    {
        {
            Optional<int>   x;
            VerifyTestResult (x.IsMissing ());
            x = 1;
            VerifyTestResult (not x.IsMissing ());
            VerifyTestResult (x.IsPresent ());
            VerifyTestResult (*x == 1);
        }
        {
            // Careful about self-assignment
            Optional<int>   x;
            x = 3;
            x = max (*x, 1);
            VerifyTestResult (x == 3);
        }
        auto testOptionalOfThingNotCopyable = [] () {
            struct NotCopyable {
                NotCopyable () {}
                NotCopyable (const NotCopyable&&) {}    // but is moveable!
                NotCopyable (const NotCopyable&) = delete;
                const NotCopyable& operator= (const NotCopyable&) = delete;
            };
            Optional<NotCopyable>   n1;
            VerifyTestResult (n1.IsMissing ());
            Optional<NotCopyable>   n2 (std::move (NotCopyable ()));    // use r-value reference to move
            VerifyTestResult (n2.IsPresent ());
        };
        testOptionalOfThingNotCopyable ();
    }
    void    Test2_SharedByValue ()
    {
    }
    void    Test_4_Optional_Of_Mapping_Copy_Problem_ ()
    {
        using   namespace   Stroika::Foundation::Memory;
        using   namespace   Stroika::Foundation::Containers;
        Mapping<int, float>  ml1, ml2;
        ml1 = ml2;

        Optional<Mapping<int, float>>  ol1, ol2;
        if (ol2.IsPresent ()) {
            ml1 = *ol2;
        }
        ol1 = ml1;
        Optional<Mapping<int, float>>  xxxx2 (ml1);

        // fails to compile prior to 2013-09-09
        Optional<Mapping<int, float>>  xxxx1 (ol1);
        // fails to compile prior to 2013-09-09
        ol1 = ol2;
    }
    void    Test_5_AnyVariantValue_ ()
    {
        {
            VerifyTestResult (AnyVariantValue ().empty ());
            VerifyTestResult (not AnyVariantValue (1).empty ());
            VerifyTestResult (not AnyVariantValue ("1").empty ());
            //VerifyTestResult (AnyVariantValue ("1").GetType () == typeid ("1"));  // not sure why this fails but not worthy worrying about yet
            VerifyTestResult (AnyVariantValue (1).As<int> () == 1);
        }
        {
            AnyVariantValue v;
            VerifyTestResult (v.empty ());
            v = AnyVariantValue (1);
            VerifyTestResult (not v.empty ());
            VerifyTestResult (v.GetType () == typeid (1));
            VerifyTestResult (v.As<int> () == 1);
            v = AnyVariantValue (L"a");
            //VerifyTestResult (v.GetType () == typeid (L"a")); // not sure why this fails but not worthy worrying about yet
            VerifyTestResult (not v.empty ());
            v.clear ();
            VerifyTestResult (v.empty ());
            VerifyTestResult (v.GetType () == typeid (void));
        }
        {
            struct JIM {
                int a;
            };
            AnyVariantValue v;
            VerifyTestResult (v.empty ());
            v = AnyVariantValue (JIM ());
            VerifyTestResult (v.GetType () == typeid (JIM));
        }
        {
            AnyVariantValue v;
            VerifyTestResult (v.empty ());
            v = AnyVariantValue (1);
            v = v;
            VerifyTestResult (v.GetType () == typeid (1));
            VerifyTestResult (v.As<int> () == 1);
            v = AnyVariantValue (v);
            VerifyTestResult (v.GetType () == typeid (1));
            VerifyTestResult (v.As<int> () == 1);
        }
        {
            static int nCopies = 0;
            struct Copyable {
                Copyable ()
                {
                    ++nCopies;
                }
                Copyable (const Copyable&)
                {
                    ++nCopies;
                }
                ~Copyable ()
                {
                    --nCopies;
                }
                const Copyable& operator= (const Copyable&) = delete;
            };
            {
                AnyVariantValue v;
                VerifyTestResult (v.empty ());
                v = AnyVariantValue (Copyable ());
                v = v;
                v = AnyVariantValue (AnyVariantValue (v));
                v = AnyVariantValue (AnyVariantValue (Copyable ()));
                VerifyTestResult (v.GetType () == typeid (Copyable));
            }
            VerifyTestResult (0 == nCopies);
        }
    }

    // temporarily put this out here to avoid MSVC compiler bug -- LGP 2014-02-26
#if 1
    struct jim : std::enable_shared_from_this<jim> {
        int field = 1;
        shared_ptr<jim> doIt ()
        {
            return shared_from_this ();
        }
    };
#else
    struct jim : Memory::enable_shared_from_this<jim> {
        int field = 1;
        SharedPtr<jim>  doIt ()
        {
            return shared_from_this ();
        }
    };
#endif

    void    Test_6_SharedPtr ()
    {
        {
            SharedPtr<int> p (new int (3));
            VerifyTestResult (p.use_count () == 1);
            VerifyTestResult (p.unique ());
            VerifyTestResult (*p == 3);
        }
        {
            static int nCreates = 0;
            static int nDestroys = 0;
            struct COUNTED_OBJ {
                COUNTED_OBJ ()
                {
                    ++nCreates;
                }
                COUNTED_OBJ (const COUNTED_OBJ&)
                {
                    ++nCreates;
                }
                ~COUNTED_OBJ ()
                {
                    ++nDestroys;
                }
                const COUNTED_OBJ& operator= (const COUNTED_OBJ&) = delete;
            };
            struct CNT2 : COUNTED_OBJ {
            };
            {
                SharedPtr<COUNTED_OBJ> p (new COUNTED_OBJ ());
            }
            VerifyTestResult (nCreates == nDestroys);
            {
                SharedPtr<COUNTED_OBJ> p (SharedPtr<CNT2> (new CNT2 ()));
                VerifyTestResult (nCreates == nDestroys + 1);
            }
            VerifyTestResult (nCreates == nDestroys);
        }
        {
#if 1
            shared_ptr<jim> x (new jim ());
            shared_ptr<jim> y = x->doIt ();
            VerifyTestResult (x == y);
#else
            SharedPtr<jim> x (new jim ());
            SharedPtr<jim> y = x->doIt ();
            VerifyTestResult (x == y);
#endif
        }
    }
}

namespace   {

    void    DoRegressionTests_ ()
    {
        Test1_Optional ();
        Test2_SharedByValue ();
        Test_4_Optional_Of_Mapping_Copy_Problem_ ();
        Test_5_AnyVariantValue_ ();
        Test_6_SharedPtr ();
    }
}

int main (int argc, const char* argv[])
{
    Stroika::TestHarness::Setup ();
    Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
    return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>#include "../../include/frame/WeightFunction.h"
#include <stdexcept>
#include <gsl/gsl_math.h>

namespace shapelens {

  WeightFunction::WeightFunction() : n(0), type(0) {
    fptr = &WeightFunction::Flat;
  }
  WeightFunction::WeightFunction(data_t scale_, const Point<data_t>& centroid_):
    scale(scale_), C(centroid_), n(0), type(1) {
    sigma2 = scale*scale;
    fptr = &WeightFunction::Gauss;
  }
  data_t  WeightFunction::Gauss(const Point<data_t>& P) const {
    data_t r = sqrt(gsl_pow_2(P(0)-C(0)) + gsl_pow_2(P(1)-C(1)));
    return Gauss(r);
  }
  data_t  WeightFunction::Gauss_(const Point<data_t>& P) const {
    data_t r = sqrt(gsl_pow_2(P(0)-C(0)) + gsl_pow_2(P(1)-C(1)));
    return Gauss(r)*(-r/sigma2);
  }
  data_t  WeightFunction::Gauss__(const Point<data_t>& P) const {
    data_t r = sqrt(gsl_pow_2(P(0)-C(0)) + gsl_pow_2(P(1)-C(1)));
    return Gauss(r)*(gsl_pow_2(r/sigma2) - 1./sigma2);
  }
  data_t  WeightFunction::Gauss___(const Point<data_t>& P) const {
    data_t r = sqrt(gsl_pow_2(P(0)-C(0)) + gsl_pow_2(P(1)-C(1)));
    return Gauss(r)*(gsl_pow_3(-r/sigma2) + 3*r/(sigma2*sigma2));
  }
  data_t  WeightFunction::Gauss_2(const Point<data_t>& P) const {
    data_t r = sqrt(gsl_pow_2(P(0)-C(0)) + gsl_pow_2(P(1)-C(1)));
    return -Gauss(r)/(2*sigma2);
  }
  data_t  WeightFunction::Gauss__2(const Point<data_t>& P) const {
    data_t r = sqrt(gsl_pow_2(P(0)-C(0)) + gsl_pow_2(P(1)-C(1)));
    return Gauss(r)/gsl_pow_2(2*sigma2);
  }
  data_t  WeightFunction::Gauss___2(const Point<data_t>& P) const {
    data_t r = sqrt(gsl_pow_2(P(0)-C(0)) + gsl_pow_2(P(1)-C(1)));
    return Gauss(r)/gsl_pow_3(2*sigma2);
  }
  data_t  WeightFunction::Gauss(data_t r) const {
    return exp(-r*r/(2*sigma2));
  }
  data_t  WeightFunction::Flat(const Point<data_t>& P) const {
    return 1;
  }
  data_t  WeightFunction::Flat_(const Point<data_t>& P) const {
    return 0;
  }

  void WeightFunction::setType(int type_) {
    if (type_ != type) {
      type = type_;
      setDerivative(n);
    }
  }
  int WeightFunction::getType() const {
    return type;
  }

  void WeightFunction::setDerivative(int n_) {
    n = n_;
    switch (type) {
    case 1:
      switch (n) {
      case 0: fptr = &WeightFunction::Gauss; break;
      case 1: fptr = &WeightFunction::Gauss_; break;
      case -1: fptr = &WeightFunction::Gauss_2; break;
      case 2: fptr = &WeightFunction::Gauss__; break;
      case -2: fptr = &WeightFunction::Gauss__2; break;
      case 3: fptr = &WeightFunction::Gauss___; break;
      case -3: fptr = &WeightFunction::Gauss___2; break;
      default: throw std::invalid_argument("WeightFunction: derivative of Gaussian invalid");
      } break;
    default:
      if (n==0)
	fptr = &WeightFunction::Flat;
      else
	fptr = &WeightFunction::Flat_;
    }
  }
  int WeightFunction::getDerivative() const {
    return n;
  }

  data_t WeightFunction::getScale() const {
    return scale;
  }
  void WeightFunction::setScale(data_t scale_) {
    scale = scale_;
    sigma2 = scale*scale;
  }
}
<commit_msg>bugfix in 3rd derivative of WeightFunction<commit_after>#include "../../include/frame/WeightFunction.h"
#include <stdexcept>
#include <gsl/gsl_math.h>

namespace shapelens {

  WeightFunction::WeightFunction() : n(0), type(0) {
    fptr = &WeightFunction::Flat;
  }
  WeightFunction::WeightFunction(data_t scale_, const Point<data_t>& centroid_):
    scale(scale_), C(centroid_), n(0), type(1) {
    sigma2 = scale*scale;
    fptr = &WeightFunction::Gauss;
  }
  data_t  WeightFunction::Gauss(const Point<data_t>& P) const {
    data_t r = sqrt(gsl_pow_2(P(0)-C(0)) + gsl_pow_2(P(1)-C(1)));
    return Gauss(r);
  }
  data_t  WeightFunction::Gauss_(const Point<data_t>& P) const {
    data_t r = sqrt(gsl_pow_2(P(0)-C(0)) + gsl_pow_2(P(1)-C(1)));
    return Gauss(r)*(-r/sigma2);
  }
  data_t  WeightFunction::Gauss__(const Point<data_t>& P) const {
    data_t r = sqrt(gsl_pow_2(P(0)-C(0)) + gsl_pow_2(P(1)-C(1)));
    return Gauss(r)*(gsl_pow_2(r/sigma2) - 1./sigma2);
  }
  data_t  WeightFunction::Gauss___(const Point<data_t>& P) const {
    data_t r = sqrt(gsl_pow_2(P(0)-C(0)) + gsl_pow_2(P(1)-C(1)));
    return Gauss(r)*(gsl_pow_3(-r/sigma2) + 3*r/(sigma2*sigma2));
  }
  data_t  WeightFunction::Gauss_2(const Point<data_t>& P) const {
    data_t r = sqrt(gsl_pow_2(P(0)-C(0)) + gsl_pow_2(P(1)-C(1)));
    return -Gauss(r)/(2*sigma2);
  }
  data_t  WeightFunction::Gauss__2(const Point<data_t>& P) const {
    data_t r = sqrt(gsl_pow_2(P(0)-C(0)) + gsl_pow_2(P(1)-C(1)));
    return Gauss(r)/gsl_pow_2(2*sigma2);
  }
  data_t  WeightFunction::Gauss___2(const Point<data_t>& P) const {
    data_t r = sqrt(gsl_pow_2(P(0)-C(0)) + gsl_pow_2(P(1)-C(1)));
    return -Gauss(r)/gsl_pow_3(2*sigma2);
  }
  data_t  WeightFunction::Gauss(data_t r) const {
    return exp(-r*r/(2*sigma2));
  }
  data_t  WeightFunction::Flat(const Point<data_t>& P) const {
    return 1;
  }
  data_t  WeightFunction::Flat_(const Point<data_t>& P) const {
    return 0;
  }

  void WeightFunction::setType(int type_) {
    if (type_ != type) {
      type = type_;
      setDerivative(n);
    }
  }
  int WeightFunction::getType() const {
    return type;
  }

  void WeightFunction::setDerivative(int n_) {
    n = n_;
    switch (type) {
    case 1:
      switch (n) {
      case 0: fptr = &WeightFunction::Gauss; break;
      case 1: fptr = &WeightFunction::Gauss_; break;
      case -1: fptr = &WeightFunction::Gauss_2; break;
      case 2: fptr = &WeightFunction::Gauss__; break;
      case -2: fptr = &WeightFunction::Gauss__2; break;
      case 3: fptr = &WeightFunction::Gauss___; break;
      case -3: fptr = &WeightFunction::Gauss___2; break;
      default: throw std::invalid_argument("WeightFunction: derivative of Gaussian invalid");
      } break;
    default:
      if (n==0)
	fptr = &WeightFunction::Flat;
      else
	fptr = &WeightFunction::Flat_;
    }
  }
  int WeightFunction::getDerivative() const {
    return n;
  }

  data_t WeightFunction::getScale() const {
    return scale;
  }
  void WeightFunction::setScale(data_t scale_) {
    scale = scale_;
    sigma2 = scale*scale;
  }
}
<|endoftext|>


<commit_before>#include <bits/stdc++.h>
using namespace std;

int v, e; //v = cantidad de nodos, e = cantidad de aristas
const int MAX = 5000; // Máxima cantidad de nodos
vector<int> ady[MAX]; //Lista de Adyacencia del grafo

int main() {
	int origen, destino,i;

    //Al iniciar cada caso de prueba
    cin >> v >> e;

    while( e > 0 ){
      cin >> origen >> destino;

      ady[origen].push_back(destino);
      ady[destino].push_back(origen);
      e--;
	}

	//Imprime la lista de adyacencia
	for(int i=1;i<=v;i++){
		cout<<i<<"\n";
		for(int j=0;j<ady[i].size();j++){
			cout<<ady[i][j]<<" ";
		}
		cout<<"\n";
	}

	return 0;
}
<commit_msg>Update AdjacencyList.cpp<commit_after>#include <bits/stdc++.h>
using namespace std;

int v, e; //v = cantidad de nodos, e = cantidad de aristas
const int MAX = 5000; // Máxima cantidad de nodos
vector<int> ady[MAX]; //Lista de Adyacencia del grafo

int main() {
    int origen, destino,i;

    //Al iniciar cada caso de prueba
    cin >> v >> e;

    while( e > 0 ){
      cin >> origen >> destino;

      ady[origen].push_back(destino);
      ady[destino].push_back(origen);
      e--;
    }

    //Imprime la lista de adyacencia
    for(int i=1;i<=v;i++){
	cout<<i<<"\n";
	for(int j=0;j<ady[i].size();j++){
		cout<<ady[i][j]<<" ";
	}
	cout<<"\n";
     }
     return 0;
}
<|endoftext|>