text:
package com.digitalpetri.opcua.stack.server.handlers;

import java.io.IOException;
import java.net.URI;
import java.nio.ByteOrder;
import java.security.KeyPair;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;

import com.digitalpetri.opcua.stack.core.StatusCodes;
import com.digitalpetri.opcua.stack.core.UaException;
import com.digitalpetri.opcua.stack.core.application.CertificateManager;
import com.digitalpetri.opcua.stack.core.channel.ChannelSecurity;
import com.digitalpetri.opcua.stack.core.channel.ExceptionHandler;
import com.digitalpetri.opcua.stack.core.channel.SerializationQueue;
import com.digitalpetri.opcua.stack.core.channel.ServerSecureChannel;
import com.digitalpetri.opcua.stack.core.channel.headers.AsymmetricSecurityHeader;
import com.digitalpetri.opcua.stack.core.channel.headers.HeaderDecoder;
import com.digitalpetri.opcua.stack.core.channel.messages.ErrorMessage;
import com.digitalpetri.opcua.stack.core.channel.messages.MessageType;
import com.digitalpetri.opcua.stack.core.security.SecurityAlgorithm;
import com.digitalpetri.opcua.stack.core.security.SecurityPolicy;
import com.digitalpetri.opcua.stack.core.types.builtin.ByteString;
import com.digitalpetri.opcua.stack.core.types.builtin.DateTime;
import com.digitalpetri.opcua.stack.core.types.builtin.StatusCode;
import com.digitalpetri.opcua.stack.core.types.enumerated.SecurityTokenRequestType;
import com.digitalpetri.opcua.stack.core.types.structured.ChannelSecurityToken;
import com.digitalpetri.opcua.stack.core.types.structured.EndpointDescription;
import com.digitalpetri.opcua.stack.core.types.structured.OpenSecureChannelRequest;
import com.digitalpetri.opcua.stack.core.types.structured.OpenSecureChannelResponse;
import com.digitalpetri.opcua.stack.core.types.structured.ResponseHeader;
import com.digitalpetri.opcua.stack.core.util.BufferUtil;
import com.digitalpetri.opcua.stack.core.util.CertificateValidator;
import com.digitalpetri.opcua.stack.server.tcp.UaTcpStackServer;
import com.google.common.collect.Lists;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.digitalpetri.opcua.stack.core.types.builtin.unsigned.Unsigned.uint;
import static com.digitalpetri.opcua.stack.core.util.NonceUtil.generateNonce;
import static com.digitalpetri.opcua.stack.core.util.NonceUtil.getNonceLength;

public class UaTcpServerAsymmetricHandler extends ByteToMessageDecoder implements HeaderDecoder {

    private static final long SecureChannelLifetimeMin = 60000L * 60;
    private static final long SecureChannelLifetimeMax = 60000L * 60 * 24;

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private ServerSecureChannel secureChannel;
    private volatile boolean symmetricHandlerAdded = false;

    private List<ByteBuf> chunkBuffers = Lists.newArrayList();

    private final AtomicReference<AsymmetricSecurityHeader> headerRef = new AtomicReference<>();

    private final int maxChunkCount;
    private final int maxChunkSize;

    private final UaTcpStackServer server;
    private final SerializationQueue serializationQueue;

    public UaTcpServerAsymmetricHandler(UaTcpStackServer server, SerializationQueue serializationQueue) {
        this.server = server;
        this.serializationQueue = serializationQueue;

        maxChunkCount = serializationQueue.getParameters().getLocalMaxChunkCount();
        maxChunkSize = serializationQueue.getParameters().getLocalReceiveBufferSize();
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
        buffer = buffer.order(ByteOrder.LITTLE_ENDIAN);

        while (buffer.readableBytes() >= HeaderLength &&
                buffer.readableBytes() >= getMessageLength(buffer)) {

            int messageLength = getMessageLength(buffer);
            MessageType messageType = MessageType.fromMediumInt(buffer.getMedium(buffer.readerIndex()));

            switch (messageType) {
                case OpenSecureChannel:
                    onOpenSecureChannel(ctx, buffer.readSlice(messageLength));
                    break;

                case CloseSecureChannel:
                    logger.debug("Received CloseSecureChannelRequest");
                    if (secureChannel != null) {
                        server.closeSecureChannel(secureChannel);
                    }
                    buffer.skipBytes(messageLength);
                    break;

                default:
                    throw new UaException(StatusCodes.Bad_TcpMessageTypeInvalid,
                            "unexpected MessageType: " + messageType);
            }
        }
    }

    private void onOpenSecureChannel(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException {
        buffer.skipBytes(3); // Skip messageType

        char chunkType = (char) buffer.readByte();

        if (chunkType == 'A') {
            chunkBuffers.forEach(ByteBuf::release);
            chunkBuffers.clear();
            headerRef.set(null);
        } else {
            buffer.skipBytes(4); // Skip messageSize

            long secureChannelId = buffer.readUnsignedInt();
            AsymmetricSecurityHeader securityHeader = AsymmetricSecurityHeader.decode(buffer);

            if (secureChannelId == 0) {
                // Okay, this is the first OpenSecureChannelRequest... carry on.
                String endpointUrl = ctx.channel().attr(UaTcpServerHelloHandler.ENDPOINT_URL_KEY).get();
                String securityPolicyUri = securityHeader.getSecurityPolicyUri();

                EndpointDescription endpointDescription = Arrays.stream(server.getEndpointDescriptions())
                        .filter(e -> {
                            String s1 = pathOrUrl(endpointUrl);
                            String s2 = pathOrUrl(e.getEndpointUrl());
                            boolean uriMatch = s1.equals(s2);
                            boolean policyMatch = e.getSecurityPolicyUri().equals(securityPolicyUri);
                            return uriMatch && policyMatch;
                        }).findFirst().orElse(null);

                if (endpointDescription == null) {
                    throw new UaException(StatusCodes.Bad_SecurityChecksFailed, "SecurityPolicy URI did not match");
                }

                secureChannel = server.openSecureChannel();
                secureChannel.setEndpointDescription(endpointDescription);
            } else {
                secureChannel = server.getSecureChannel(secureChannelId);

                if (secureChannel == null) {
                    throw new UaException(StatusCodes.Bad_TcpSecureChannelUnknown,
                            "unknown secure channel id: " + secureChannelId);
                }

                if (!secureChannel.getRemoteCertificateBytes().equals(securityHeader.getSenderCertificate())) {
                    throw new UaException(StatusCodes.Bad_SecurityChecksFailed,
                            "certificate requesting renewal did not match existing certificate.");
                }

                Channel boundChannel = secureChannel.attr(UaTcpStackServer.BoundChannelKey).get();
                if (boundChannel != null && boundChannel != ctx.channel()) {
                    throw new UaException(StatusCodes.Bad_SecurityChecksFailed,
                            "received a renewal request from channel other than the bound channel.");
                }
            }

            if (!headerRef.compareAndSet(null, securityHeader)) {
                if (!securityHeader.equals(headerRef.get())) {
                    throw new UaException(StatusCodes.Bad_SecurityChecksFailed,
                            "subsequent AsymmetricSecurityHeader did not match");
                }
            }

            SecurityPolicy securityPolicy = SecurityPolicy.fromUri(securityHeader.getSecurityPolicyUri());
            secureChannel.setSecurityPolicy(securityPolicy);

            if (!securityHeader.getSenderCertificate().isNull() && securityPolicy != SecurityPolicy.None) {
                secureChannel.setRemoteCertificate(securityHeader.getSenderCertificate().bytes());

                CertificateValidator validator = new CertificateValidator(
                        server.getCertificateManager().getTrustList(),
                        server.getCertificateManager().getAuthorityList());

                try {
                    validator.validateTrustChain(
                            secureChannel.getRemoteCertificate(),
                            secureChannel.getRemoteCertificateChain());
                } catch (UaException e) {
                    try {
                        server.getCertificateManager().certificateRejected(secureChannel.getRemoteCertificate());

                        UaException cause = new UaException(e.getStatusCode(), "security checks failed");
                        ErrorMessage errorMessage = ExceptionHandler.sendErrorMessage(ctx, cause);

                        logger.debug("[remote={}] {}.",
                                ctx.channel().remoteAddress(), errorMessage.getReason(), cause);
                    } catch (Exception ignored) {
                    }
                }
            }

            if (!securityHeader.getReceiverThumbprint().isNull()) {
                CertificateManager certificateManager = server.getCertificateManager();

                Optional<X509Certificate> localCertificate = certificateManager
                        .getCertificate(securityHeader.getReceiverThumbprint());

                Optional<KeyPair> keyPair = certificateManager
                        .getKeyPair(securityHeader.getReceiverThumbprint());

                if (localCertificate.isPresent() && keyPair.isPresent()) {
                    secureChannel.setLocalCertificate(localCertificate.get());
                    secureChannel.setKeyPair(keyPair.get());
                } else {
                    throw new UaException(StatusCodes.Bad_SecurityChecksFailed,
                            "no certificate for provided thumbprint");
                }
            }

            int chunkSize = buffer.readerIndex(0).readableBytes();

            if (chunkSize > maxChunkSize) {
                throw new UaException(StatusCodes.Bad_TcpMessageTooLarge,
                        String.format("max chunk size exceeded (%s)", maxChunkSize));
            }

            chunkBuffers.add(buffer.retain());

            if (chunkBuffers.size() > maxChunkCount) {
                throw new UaException(StatusCodes.Bad_TcpMessageTooLarge,
                        String.format("max chunk count exceeded (%s)", maxChunkCount));
            }

            if (chunkType == 'F') {
                final List<ByteBuf> buffersToDecode = chunkBuffers;

                chunkBuffers = Lists.newArrayListWithCapacity(maxChunkCount);
                headerRef.set(null);

                serializationQueue.decode((binaryDecoder, chunkDecoder) -> {
                    ByteBuf messageBuffer = null;

                    try {
                        messageBuffer = chunkDecoder.decodeAsymmetric(
                                secureChannel,
                                MessageType.OpenSecureChannel,
                                buffersToDecode
                        );

                        OpenSecureChannelRequest request = binaryDecoder
                                .setBuffer(messageBuffer)
                                .decodeMessage(null);

                        logger.debug("Received OpenSecureChannelRequest ({}, id={}).",
                                request.getRequestType(), secureChannelId);

                        long requestId = chunkDecoder.getRequestId();
                        installSecurityToken(ctx, request, requestId);
                    } catch (UaException e) {
                        logger.error("Error decoding asymmetric message: {}", e.getMessage(), e);
                        ctx.close();
                    } finally {
                        if (messageBuffer != null) {
                            messageBuffer.release();
                        }
                        buffersToDecode.clear();
                    }
                });
            }
        }
    }

    private String pathOrUrl(String endpointUrl) {
        try {
            URI uri = URI.create(endpointUrl);
            return uri.getPath();
        } catch (Throwable t) {
            logger.warn("Endpoint URL '{}' is not a valid URI: {}", t.getMessage(), t);
            return endpointUrl;
        }
    }

    private void installSecurityToken(ChannelHandlerContext ctx,
                                      OpenSecureChannelRequest request,
                                      long requestId) throws UaException {

        SecurityTokenRequestType requestType = request.getRequestType();

        if (requestType == SecurityTokenRequestType.Issue) {
            secureChannel.setMessageSecurityMode(request.getSecurityMode());
        } else if (requestType == SecurityTokenRequestType.Renew &&
                secureChannel.getMessageSecurityMode() != request.getSecurityMode()) {

            throw new UaException(StatusCodes.Bad_SecurityChecksFailed,
                    "secure channel renewal requested a different MessageSecurityMode.");
        }

        long channelLifetime = request.getRequestedLifetime().longValue();
        channelLifetime = Math.min(SecureChannelLifetimeMax, channelLifetime);
        channelLifetime = Math.max(SecureChannelLifetimeMin, channelLifetime);

        ChannelSecurityToken newToken = new ChannelSecurityToken(
                uint(secureChannel.getChannelId()),
                uint(server.nextTokenId()),
                DateTime.now(),
                uint(channelLifetime)
        );

        ChannelSecurity.SecuritySecrets newKeys = null;

        if (secureChannel.isSymmetricSigningEnabled()) {
            SecurityAlgorithm algorithm = secureChannel.getSecurityPolicy().getSymmetricEncryptionAlgorithm();
            ByteString localNonce = generateNonce(getNonceLength(algorithm));

            secureChannel.setLocalNonce(localNonce);
            secureChannel.setRemoteNonce(request.getClientNonce());

            newKeys = ChannelSecurity.generateKeyPair(
                    secureChannel,
                    secureChannel.getRemoteNonce(),
                    secureChannel.getLocalNonce()
            );
        }

        ChannelSecurity oldSecrets = secureChannel.getChannelSecurity();
        ChannelSecurity.SecuritySecrets oldKeys = oldSecrets != null ? oldSecrets.getCurrentKeys() : null;
        ChannelSecurityToken oldToken = oldSecrets != null ? oldSecrets.getCurrentToken() : null;

        ChannelSecurity newSecrets = new ChannelSecurity(
                newKeys,
                newToken,
                oldKeys,
                oldToken
        );

        secureChannel.setChannelSecurity(newSecrets);

        ResponseHeader responseHeader = new ResponseHeader(
                DateTime.now(),
                request.getRequestHeader().getRequestHandle(),
                StatusCode.GOOD,
                null, null, null
        );

        OpenSecureChannelResponse response = new OpenSecureChannelResponse(
                responseHeader,
                uint(PROTOCOL_VERSION),
                newToken,
                secureChannel.getLocalNonce()
        );

        sendOpenSecureChannelResponse(ctx, requestId, response);
    }

    private void sendOpenSecureChannelResponse(ChannelHandlerContext ctx, long requestId, OpenSecureChannelResponse response) {
        serializationQueue.encode((binaryEncoder, chunkEncoder) -> {
            ByteBuf messageBuffer = BufferUtil.buffer();

            try {
                binaryEncoder.setBuffer(messageBuffer);
                binaryEncoder.encodeMessage(null, response);

                List<ByteBuf> chunks = chunkEncoder.encodeAsymmetric(
                        secureChannel,
                        MessageType.OpenSecureChannel,
                        messageBuffer
                );

                if (!symmetricHandlerAdded) {
                    ctx.pipeline().addFirst(new UaTcpServerSymmetricHandler(server, serializationQueue, secureChannel));
                    symmetricHandlerAdded = true;
                }

                chunks.forEach(c -> ctx.write(c, ctx.voidPromise()));
                ctx.flush();

                long lifetime = response.getSecurityToken().getRevisedLifetime().longValue();
                server.secureChannelIssuedOrRenewed(secureChannel, lifetime);

                logger.debug("Sent OpenSecureChannelResponse.");
            } catch (UaException e) {
                logger.error("Error encoding OpenSecureChannelResponse: {}", e.getMessage(), e);
                ctx.close();
            } finally {
                messageBuffer.release();
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        chunkBuffers.forEach(ByteBuf::release);
        chunkBuffers.clear();

        if (cause instanceof IOException) {
            ctx.close();
            logger.debug("[remote={}] IOException caught; channel closed");
        } else {
            ErrorMessage errorMessage = ExceptionHandler.sendErrorMessage(ctx, cause);

            if (cause instanceof UaException) {
                logger.debug("[remote={}] UaException caught; sent {}",
                        ctx.channel().remoteAddress(), errorMessage, cause);
            } else {
                logger.error("[remote={}] Exception caught; sent {}",
                        ctx.channel().remoteAddress(), errorMessage, cause);
            }
        }
    }

}


text:
These are the available I2C abstraction layers.  These are wrappers on the available [UD Library](https://labjack.com/support/software/installers/ud) and have the same platform restrictions as the available [UD library example code](https://labjack.com/support/software/examples/ud).

## Troubleshooting
If you are experiencing issues getting started with any of these wrappers you should start with the basic device examples found in these example code libraries.

## Supported Devices

## Device Datasheets
There is a lot of useful information in each of the devices datasheets relating to I2C.  The implemented I2C wrappers try to hide some of the complexities but in some cases it may be necessary to look for documentation about how I2C works on an individual LabJack device.
* [U3 Datasheet](https://labjack.com/support/datasheets/u3)
* [U6 Datasheet](https://labjack.com/support/datasheets/u6)
* [UE9 Datasheet](https://labjack.com/support/datasheets/ue9)

## I2C Related High-Level Driver Reference
There are some useful code snippits provided on on the devices I2C Serial Communication pages found in their datasheets.
* [U3 High-Level Driver Reference](https://labjack.com/support/datasheets/u3/high-level-driver/example-pseudocode/i2c)
* [U6 High-Level Driver Reference](https://labjack.com/support/datasheets/u6/high-level-driver/example-pseudocode/i2c)
* [UE9 High-Level Driver Reference](https://labjack.com/support/datasheets/ue9/high-level-driver/example-pseudocode/i2c)

## I2C Related Low-Level Functions
There are some useful code snippits provided on on the devices Low-Level Functions/I2C pages found in their datasheets.
* [U3 Low-Level Function Reference](https://labjack.com/support/datasheets/u3/low-level-function-reference/i2c)
* [U6 Low-Level Function Reference](https://labjack.com/support/datasheets/u6/low-level-function-reference/i2c)
* [UE9 Low-Level Function Reference](https://labjack.com/support/datasheets/ue9/low-level-function-reference/control-functions/i2c)

redpajama_set_name: RedPajamaGithub


text:
/****************************************************************************************/
/*                                                                                */
/*                                       Pegasus                                        */
/*                                                                                */
/****************************************************************************************/

//! \file   Application.h
//! \author David Worsham
//! \date   04th July 2013
//! \brief  Building block class for a Pegasus application.
//!         Manages access to the Pegasus runtime.

#ifndef PEGASUS_APP_APPLICATION_H
#define PEGASUS_APP_APPLICATION_H

#include "Pegasus/Application/Shared/ApplicationConfig.h"
#include "Pegasus/Core/IApplicationContext.h"
#include "Pegasus/AssetLib/RuntimeAssetObject.h"

// Forward declarations
namespace Pegasus {
    namespace App {
        class AppWindowManager;
        class AppWindowComponentFactory;
    }

    namespace Wnd {
        struct WindowConfig;
        class Window;
    }

    namespace Render {
        class IDevice;
        class Context;
    }

    namespace Shader {
        class ShaderManager;
    }

    namespace Texture {
        class TextureManager;
    }

    namespace Mesh {
        class MeshManager;
    }

    namespace BlockScript {
        class BlockScriptManager;
        class BlockLib;
    }

    namespace AssetLib {
        class AssetLib;
    }

    namespace RenderSystems {
        class RenderSystemManager;
    }
}

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

namespace Pegasus {
namespace App {

//! Building block class for a Pegasus application
//! Override Init, Shutdown, and Render to perform rendering.
//! \note To use this class, simply:
//! \note   1. instantiate it
//! \note   2. attach a window to it
//! \note   3. call Run to enter the application loop.
//! \todo Multi-application support
class Application : public Core::IApplicationContext
{
public:
    //! Constructor
    //! \param config Configuration struct for this Application.
    Application(const ApplicationConfig& config);

    //! Destructor
    virtual ~Application();

    //! Get the name of this app
    //! \return Application name.
    virtual const char* GetAppName() const = 0;

    //! Load the assets required to render the timeline blocks
    void Load();

    //! Unload the assets used by the timeline blocks
    void Unload();

    //! Updates the simulation / calls update on every block of this timeline.
    void Update();

    //! Attaches a new window to this app
    //! \param appWindowConfig Config structure for the window.
    //! \return The new window.
    //! \note Returns nullptr on failure.
    Wnd::Window* AttachWindow(const AppWindowConfig& appWindowConfig);

    //! Detaches a window from this app
    //! \param wnd The window to detach.
    void DetachWindow(Wnd::Window* wnd);

    //! Gets the application config.
    const ApplicationConfig& GetConfig() const { return mConfig; }

    // IWindowContext interface
    virtual Io::IOManager*                                  GetIOManager()               const { return mIoManager;               }
    virtual Graph::NodeManager*                             GetNodeManager()             const { return mNodeManager;             }
    virtual Texture::TextureManager*                        GetTextureManager()          const { return mTextureManager;          }
    virtual Mesh::MeshManager*                              GetMeshManager()             const { return mMeshManager;             }
    virtual Shader::ShaderManager*                          GetShaderManager()           const { return mShaderManager;           }
    virtual Timeline::TimelineManager*                      GetTimelineManager()         const { return mTimelineManager;         }
    virtual BlockScript::BlockScriptManager*                GetBlockScriptManager()      const { return mBlockScriptManager;      }
    virtual AssetLib::AssetLib*                             GetAssetLib()                const { return mAssetLib;                }
    virtual Pegasus::Application::RenderCollectionFactory*  GetRenderCollectionFactory() const { return mRenderCollectionFactory; }
    virtual PropertyGrid::PropertyGridManager*              GetPropertyGridManager()     const { return mPropertyGridManager;     }
    virtual RenderSystems::RenderSystemManager*             GetRenderSystemManager()     const { return mRenderSystemManager;     }
    virtual BlockScript::BlockLib*                          GetRenderBsApi()             const { return mRenderApiScript;         }
#if PEGASUS_ENABLE_BS_REFLECTION_INFO
    //! Returns the reflection information from blockscript.
    virtual App::AppBsReflectionInfo*                       GetBsReflectionInfo() const { return mBsReflectionInfo; }
#endif

    AppWindowManager*                                       GetWindowManager() const { return mWindowManager; }
protected:

    //! Custom initialization, done in the user application before the timeline triggers the loading of blocks and their assets
    virtual void InitializeApp() = 0;

    //! Custom shutdown, done in the user application
    virtual void ShutdownApp() = 0;

    //! Optional custom function, utilize this function to register any custom system that the app might want to register
    virtual void RegisterCustomRenderSystems(RenderSystems::RenderSystemManager* renderSystemManager) {}

private:
    // No copies allowed
    PG_DISABLE_COPY(Application);

    ApplicationConfig                               mConfig;                 //!< Cached config object
    Render::IDevice*                                mDevice;                 //!< Render device
    Render::Context*                                mRenderContext;          //!< Rendering context
    AppWindowManager*                               mWindowManager;          //!< Window manager
    Io::IOManager*                                  mIoManager;              //!< IO manager
    Graph::NodeManager*                             mNodeManager;            //!< Graph node manager
    Shader::ShaderManager*                          mShaderManager;          //!< Shader node manager
    Texture::TextureManager*                        mTextureManager;         //!< Texture node manager
    Mesh::MeshManager*                              mMeshManager;            //!< Mesh node manager
    Timeline::TimelineManager*                      mTimelineManager;        //!< Timeline manager
    BlockScript::BlockScriptManager*                mBlockScriptManager;     //!< BlockScriptManager manager.
    AssetLib::AssetLib*                             mAssetLib;               //!< AssetLib manager
    PropertyGrid::PropertyGridManager*              mPropertyGridManager;    //!< Property grid manager
    RenderSystems::RenderSystemManager*             mRenderSystemManager;    //!< Render systems manager. Used to instantiate custom systems.
    Pegasus::Application::RenderCollectionFactory*  mRenderCollectionFactory;//!< Render collection factory
#if PEGASUS_ENABLE_BS_REFLECTION_INFO
    App::AppBsReflectionInfo*                       mBsReflectionInfo; //!< Reflection and library info of blockscript libraries registered
#endif

    //Reference to the render api blockscript lib
    BlockScript::BlockLib* mRenderApiScript;
};

}   // namespace App
}   // namespace Pegasus

#endif  // PEGASUS_APP_APPLICATION_H


text:
@interface HGDIImplementation ()

@end

@implementation HGDIImplementation

@synthesize parameters = parameters_;
@synthesize serviceContainer = serviceContainer_;
@synthesize newInstanceSupported;

- (NSMutableDictionary *)parameters {
	if (!parameters_) {
		parameters_ = [[NSMutableDictionary alloc] init];
	}
	return parameters_;
}

- (id)instance {
	return nil;
}

- (id)newInstance {
	return nil;
}

- (void)setParameter:(id)parameter forKey:(NSString *)key {
	[self.parameters setObject:parameter forKey:key];
}

- (BOOL)isNewInstanceSupported {
	return NO;
}

@end


text:
package com.timgroup.stanislavski.magic.matchers;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.hamcrest.TypeSafeDiagnosingMatcher;

public class InstanceWithPropertiesMatcher<T> extends TypeSafeDiagnosingMatcher<T> {
    private final Class<T> targetClass;
    private final Iterable<Matcher<? super T>> propertyMatchers;

    public InstanceWithPropertiesMatcher(Class<T> targetClass, Iterable<Matcher<? super T>> propertyMatchers) {
        this.targetClass = targetClass;
        this.propertyMatchers = propertyMatchers;
    }

    @Override
    public void describeTo(Description description) {
        description.appendText("A ").appendText(targetClass.getSimpleName()).appendText(" ");
        boolean first = true;
        for (Matcher<? super T> propertyMatcher : propertyMatchers) {
            if (first) {
                first = false;
            } else {
                description.appendText(" and ");
            }
            propertyMatcher.describeTo(description);
        }
    }

    @Override
    protected boolean matchesSafely(T item, Description mismatchDescription) {
        if (item==null) {
            mismatchDescription.appendText("was null");
            return false;
        }

        if (!targetClass.isAssignableFrom(item.getClass())) {
            mismatchDescription.appendText("was not a ").appendValue(targetClass);
            return false;
        }

        if (Matchers.allOf(propertyMatchers).matches(item)) {
            return true;
        }

        mismatchDescription.appendText("was a ").appendText(targetClass.getSimpleName()).appendText(" ");
        boolean first = true;
        for (Matcher<? super T> propertyMatcher : propertyMatchers) {
            if (first) {
                first = false;
            } else {
                mismatchDescription.appendText(" and ");
            }
            propertyMatcher.describeMismatch(item, mismatchDescription);
        }
        return false;
    }
}


text:
PLUGINLIB_DECLARE_CLASS(
    mapviz_plugins,
    tf_frame,
    mapviz_plugins::TfFramePlugin,
    mapviz::MapvizPlugin);

namespace mapviz_plugins
{
  TfFramePlugin::TfFramePlugin() :
    config_widget_(new QWidget()),
    color_(Qt::green),
    draw_style_(LINES)
  {
    ui_.setupUi(config_widget_);

    // Set background white
    QPalette p(config_widget_->palette());
    p.setColor(QPalette::Background, Qt::white);
    config_widget_->setPalette(p);

    // Initialize color selector color
    ui_.selectcolor->setStyleSheet("background: " + color_.name() + ";");

    // Set status text red
    QPalette p3(ui_.status->palette());
    p3.setColor(QPalette::Text, Qt::red);
    ui_.status->setPalette(p3);

    QObject::connect(ui_.selectcolor, SIGNAL(clicked()), this, SLOT(SelectColor()));
    QObject::connect(ui_.selectframe, SIGNAL(clicked()), this, SLOT(SelectFrame()));
    QObject::connect(ui_.frame, SIGNAL(editingFinished()), this, SLOT(FrameEdited()));
    QObject::connect(ui_.positiontolerance, SIGNAL(valueChanged(double)), this, SLOT(PositionToleranceChanged(double)));
    QObject::connect(ui_.buffersize, SIGNAL(valueChanged(int)), this, SLOT(BufferSizeChanged(int)));
    QObject::connect(ui_.drawstyle, SIGNAL(activated(QString)), this, SLOT(SetDrawStyle(QString)));
  }

  TfFramePlugin::~TfFramePlugin()
  {
  }

  void TfFramePlugin::SelectFrame()
  {
    QDialog dialog;
    Ui::topicselect ui;
    ui.setupUi(&dialog);

    std::vector<std::string> frames;
    tf_->getFrameStrings(frames);

    for (unsigned int i = 0; i < frames.size(); i++)
    {
      ui.displaylist->addItem(frames[i].c_str());
    }
    ui.displaylist->setCurrentRow(0);

    dialog.exec();

    if (dialog.result() == QDialog::Accepted && ui.displaylist->selectedItems().count() == 1)
    {
      ui_.frame->setText(ui.displaylist->selectedItems().first()->text());
      FrameEdited();
    }
  }

  void TfFramePlugin::FrameEdited()
  {
    source_frame_ = ui_.frame->text().toStdString();
    PrintWarning("Waiting for transform.");

    ROS_INFO("Setting target frame to to %s", source_frame_.c_str());

    initialized_ = true;

    canvas_->update();
  }

  void TfFramePlugin::SetDrawStyle(QString style)
  {
    if (style == "lines")
    {
      draw_style_ = LINES;
    }
    else if (style == "points")
    {
      draw_style_ = POINTS;
    }
    else if (style == "arrows")
    {
      draw_style_ = ARROWS;
    }

    canvas_->update();
  }

  void TfFramePlugin::SelectColor()
  {
    QColorDialog dialog(color_, config_widget_);
    dialog.exec();

    if (dialog.result() == QDialog::Accepted)
    {
      color_ = dialog.selectedColor();
      ui_.selectcolor->setStyleSheet("background: " + color_.name() + ";");
      canvas_->update();
    }
  }

  void TfFramePlugin::PositionToleranceChanged(double value)
  {
    position_tolerance_ = value;
  }

  void TfFramePlugin::BufferSizeChanged(int value)
  {
    buffer_size_ = value;

    if (buffer_size_ > 0)
    {
      while (static_cast<int>(points_.size()) > buffer_size_)
      {
        points_.pop_front();
      }
    }

    canvas_->update();
  }

  void TfFramePlugin::TimerCallback(const ros::TimerEvent& event)
  {
    transform_util::Transform transform;
    if (GetTransform(ros::Time(), transform))
    {
      StampedPoint stamped_point;
      stamped_point.point = transform.GetOrigin();
      stamped_point.orientation = transform.GetOrientation();
      stamped_point.frame = target_frame_;
      stamped_point.stamp = transform.GetStamp();
      stamped_point.transformed = false;

      double distance = std::sqrt(
        std::pow(stamped_point.point.x() - points_.back().point.x(), 2) +
        std::pow(stamped_point.point.y() - points_.back().point.y(), 2));

      if (points_.empty() || distance >= position_tolerance_)
      {
        points_.push_back(stamped_point);
      }

      if (buffer_size_ > 0)
      {
        while (static_cast<int>(points_.size()) > buffer_size_)
        {
          points_.pop_front();
        }
      }

      cur_point_ = stamped_point;
    }
  }

  void TfFramePlugin::PrintError(const std::string& message)
  {
    if (message == ui_.status->text().toStdString())
      return;

    ROS_ERROR("Error: %s", message.c_str());
    QPalette p(ui_.status->palette());
    p.setColor(QPalette::Text, Qt::red);
    ui_.status->setPalette(p);
    ui_.status->setText(message.c_str());
  }

  void TfFramePlugin::PrintInfo(const std::string& message)
  {
    if (message == ui_.status->text().toStdString())
      return;

    ROS_INFO("%s", message.c_str());
    QPalette p(ui_.status->palette());
    p.setColor(QPalette::Text, Qt::green);
    ui_.status->setPalette(p);
    ui_.status->setText(message.c_str());
  }

  void TfFramePlugin::PrintWarning(const std::string& message)
  {
    if (message == ui_.status->text().toStdString())
      return;

    ROS_WARN("%s", message.c_str());
    QPalette p(ui_.status->palette());
    p.setColor(QPalette::Text, Qt::darkYellow);
    ui_.status->setPalette(p);
    ui_.status->setText(message.c_str());
  }

  QWidget* TfFramePlugin::GetConfigWidget(QWidget* parent)
  {
    config_widget_->setParent(parent);

    return config_widget_;
  }

  bool TfFramePlugin::Initialize(QGLWidget* canvas)
  {
    canvas_ = canvas;

    timer_ = node_.createTimer(ros::Duration(0.1), &TfFramePlugin::TimerCallback, this);

    return true;
  }

  void TfFramePlugin::Draw(double x, double y, double scale)
  {
    glColor4f(color_.redF(), color_.greenF(), color_.blueF(), 0.5);

    bool transformed = false;

    glColor4f(color_.redF(), color_.greenF(), color_.blueF(), 1.0);

    if (draw_style_ == ARROWS)
    {
      transformed = DrawArrows();
    }
    else
    {
      if (draw_style_ == LINES)
      {
        glLineWidth(3);
        glBegin(GL_LINE_STRIP);
      }
      else
      {
        glPointSize(6);
        glBegin(GL_POINTS);
      }

      std::list<StampedPoint>::iterator it = points_.begin();
      for (; it != points_.end(); ++it)
      {
        if (it->transformed)
        {
          glVertex2f(it->transformed_point.getX(), it->transformed_point.getY());

          transformed = true;
        }
      }

      if (cur_point_.transformed)
      {
        glVertex2f(
          cur_point_.transformed_point.getX(),
          cur_point_.transformed_point.getY());

        transformed = true;
      }

      glEnd();
    }

    if (transformed)
    {
      PrintInfo("OK");
    }
  }

  bool TfFramePlugin::DrawArrows()
  {
    bool transformed = false;
    glLineWidth(2);
    glBegin(GL_LINES);

    std::list<StampedPoint>::iterator it = points_.begin();
    for (; it != points_.end(); ++it)
    {
      if (it->transformed)
      {
        glVertex2f(it->transformed_point.getX(), it->transformed_point.getY());
        glVertex2f(it->transformed_arrow_point.getX(), it->transformed_arrow_point.getY());

        glVertex2f(it->transformed_arrow_point.getX(), it->transformed_arrow_point.getY());
        glVertex2f(it->transformed_arrow_left.getX(), it->transformed_arrow_left.getY());

        glVertex2f(it->transformed_arrow_point.getX(), it->transformed_arrow_point.getY());
        glVertex2f(it->transformed_arrow_right.getX(), it->transformed_arrow_right.getY());

        transformed = true;
      }
    }

    if (cur_point_.transformed)
    {
      glVertex2f(
        cur_point_.transformed_point.getX(),
        cur_point_.transformed_point.getY());
      glVertex2f(
        cur_point_.transformed_arrow_point.getX(),
        cur_point_.transformed_arrow_point.getY());

      glVertex2f(
        cur_point_.transformed_arrow_point.getX(),
        cur_point_.transformed_arrow_point.getY());
      glVertex2f(
        cur_point_.transformed_arrow_left.getX(),
        cur_point_.transformed_arrow_left.getY());

      glVertex2f(
        cur_point_.transformed_arrow_point.getX(),
        cur_point_.transformed_arrow_point.getY());
      glVertex2f(
        cur_point_.transformed_arrow_right.getX(),
        cur_point_.transformed_arrow_right.getY());

      transformed = true;
    }

    glEnd();

    return transformed;
  }

  bool TfFramePlugin::TransformPoint(StampedPoint& point)
  {
    transform_util::Transform transform;
    if (GetTransform(point.frame, point.stamp, transform))
    {
      point.transformed_point = transform * point.point;

      tf::Transform orientation(tf::Transform(transform.GetOrientation()) * point.orientation);
      point.transformed_arrow_point = point.transformed_point + orientation * tf::Point(1.0, 0.0, 0.0);
      point.transformed_arrow_left = point.transformed_point + orientation * tf::Point(0.75, -0.2, 0.0);
      point.transformed_arrow_right = point.transformed_point + orientation * tf::Point(0.75, 0.2, 0.0);

      point.transformed = true;
      return true;
    }

     point.transformed = false;
     return false;
  }

  void TfFramePlugin::Transform()
  {
    bool transformed = false;

    std::list<StampedPoint>::iterator points_it = points_.begin();
    for (; points_it != points_.end(); ++points_it)
    {
      transformed = transformed | TransformPoint(*points_it);
    }

    transformed = transformed | TransformPoint(cur_point_);

    if (!points_.empty() && !transformed)
    {
      PrintError("No transform error.");
    }
  }

  void TfFramePlugin::LoadConfig(const YAML::Node& node, const std::string& path)
  {
    node["frame"] >> source_frame_;
    ui_.frame->setText(source_frame_.c_str());

    std::string color;
    node["color"] >> color;
    color_ = QColor(color.c_str());
    ui_.selectcolor->setStyleSheet("background: " + color_.name() + ";");

    std::string draw_style;
    node["draw_style"] >> draw_style;

    if (draw_style == "lines")
    {
      draw_style_ = LINES;
      ui_.drawstyle->setCurrentIndex(0);
    }
    else if (draw_style == "points")
    {
      draw_style_ = POINTS;
      ui_.drawstyle->setCurrentIndex(1);
    }

    node["position_tolerance"] >> position_tolerance_;
    ui_.positiontolerance->setValue(position_tolerance_);

    node["buffer_size"] >> buffer_size_;
    ui_.buffersize->setValue(buffer_size_);

    FrameEdited();
  }

  void TfFramePlugin::SaveConfig(YAML::Emitter& emitter, const std::string& path)
  {
    emitter << YAML::Key << "frame" << YAML::Value << ui_.frame->text().toStdString();

    std::string color = color_.name().toStdString();
    emitter << YAML::Key << "color" << YAML::Value << color;

    std::string draw_style = ui_.drawstyle->currentText().toStdString();
    emitter << YAML::Key << "draw_style" << YAML::Value << draw_style;

    emitter << YAML::Key << "position_tolerance" << YAML::Value << position_tolerance_;

    emitter << YAML::Key << "buffer_size" << YAML::Value << buffer_size_;
  }
}


text:
layout:        quilt
title:         North and South
date:          2013-09-08 00:00:00

tags: frontpage

columnCSS:     "large-6 columns"
css:           "height: 370px; width: 100%;"

featuredImage:       https://lh3.googleusercontent.com/DmNm5pQo-WpkTm0CprAna8_eg35_1ZKc95KHCGInYbc=w470
featuredImageOnPage: https://lh3.googleusercontent.com/DmNm5pQo-WpkTm0CprAna8_eg35_1ZKc95KHCGInYbc=w1000

imagesOnPage: [
               'https://lh6.googleusercontent.com/7dWhd57ca2Vl_3mnfPiKRs_tfEmhT2PyceRIRWKZaD8=w303',
               'https://lh5.googleusercontent.com/iGS7aksrE4tM7d2qA_xOvE3IHA4xOrAOXQahBu5P7Jk=w303',
               'https://lh4.googleusercontent.com/0BnaZeO8iHXY9vkYEAwmCkfjJCf-oNCSjNvW6K9ckwk=w303',
               'https://lh5.googleusercontent.com/RQ9uMSMoXUrGDyVOQVQUN5wGsWyPpBzATuRwp6-lH0c=w303',
               'https://lh3.googleusercontent.com/Qmy-lGFMxtWGLfRJ0b91HS9GVSSSA7nIz3ei0qL87us=w303',
               'https://lh5.googleusercontent.com/-0Ya5kymO6c62lDXXhxiMO0NaLD33bqezm74S3YxFXw=w303',
               'https://lh5.googleusercontent.com/UaAgudiUN58cDMhRutK_npq9CQzl_mHkoI5CVKm_hwQ=w303',
               'https://lh5.googleusercontent.com/uFFbZhXkAuInfZwD0O1mXKBUDWIVNNWE6AxtcLEQ8RA=w303',
               'https://lh6.googleusercontent.com/o0TBmU63cq1p6ou4GSf2vJYmQ4gpISqTn06THhotGz0=w303'
              ]
---

### by Vickie Lopresti

About two years ago ... at the Valley Forge Homestead Quilt Guild Spring Retreat, a group of us got together and used the guild's die cutter to cut a bunch of our Civil War Reproduction fat quarters into tumbler pieces.  We each had to supply 25 fat quarters.  However, my quilt sort of had a mind of its own and I made it into a queen sized quilt.

I'm very pleased with the way Jackie quilted it.   We spoke at length about what design to use and which thread color.  She took her time, and explained everything.   Will keep going back!!!


text:
import uuid

import mock
import testtools
import webob

from nova.api.openstack.compute import evacuate as evacuate_v21
from nova.compute import api as compute_api
from nova.compute import vm_states
import nova.conf
from nova import exception
from nova import test
from nova.tests.unit.api.openstack import fakes
from nova.tests.unit import fake_instance

CONF = nova.conf.CONF

def fake_compute_api(*args, **kwargs):
    return True

def fake_compute_api_get(self, context, instance_id, want_objects=False,
                         **kwargs):
    # BAD_UUID is something that does not exist
    if instance_id == 'BAD_UUID':
        raise exception.InstanceNotFound(instance_id=instance_id)
    else:
        return fake_instance.fake_instance_obj(context, id=1, uuid=instance_id,
                                               task_state=None, host='host1',
                                               vm_state=vm_states.ACTIVE)

def fake_service_get_by_compute_host(self, context, host):
    if host == 'bad-host':
        raise exception.ComputeHostNotFound(host=host)
    else:
        return {
            'host_name': host,
            'service': 'compute',
            'zone': 'nova'
            }

class EvacuateTestV21(test.NoDBTestCase):
    validation_error = exception.ValidationError
    _methods = ('resize', 'evacuate')

    def setUp(self):
        super(EvacuateTestV21, self).setUp()
        self.stubs.Set(compute_api.API, 'get', fake_compute_api_get)
        self.stubs.Set(compute_api.HostAPI, 'service_get_by_compute_host',
                       fake_service_get_by_compute_host)
        self.UUID = uuid.uuid4()
        for _method in self._methods:
            self.stubs.Set(compute_api.API, _method, fake_compute_api)
        self._set_up_controller()
        self.admin_req = fakes.HTTPRequest.blank('', use_admin_context=True)
        self.req = fakes.HTTPRequest.blank('')

    def _set_up_controller(self):
        self.controller = evacuate_v21.EvacuateController()
        self.controller_no_ext = self.controller

    def _get_evacuate_response(self, json_load, uuid=None):
        base_json_load = {'evacuate': json_load}
        response = self.controller._evacuate(self.admin_req, uuid or self.UUID,
                                             body=base_json_load)

        return response

    def _check_evacuate_failure(self, exception, body, uuid=None,
                                controller=None):
        controller = controller or self.controller
        body = {'evacuate': body}
        self.assertRaises(exception,
                          controller._evacuate,
                          self.admin_req, uuid or self.UUID, body=body)

    def test_evacuate_with_valid_instance(self):
        admin_pass = 'MyNewPass'
        res = self._get_evacuate_response({'host': 'my-host',
                                           'onSharedStorage': 'False',
                                           'adminPass': admin_pass})

        self.assertEqual(admin_pass, res['adminPass'])

    def test_evacuate_with_invalid_instance(self):
        self._check_evacuate_failure(webob.exc.HTTPNotFound,
                                     {'host': 'my-host',
                                      'onSharedStorage': 'False',
                                      'adminPass': 'MyNewPass'},
                                     uuid='BAD_UUID')

    def test_evacuate_with_active_service(self):
        def fake_evacuate(*args, **kwargs):
            raise exception.ComputeServiceInUse("Service still in use")

        self.stubs.Set(compute_api.API, 'evacuate', fake_evacuate)
        self._check_evacuate_failure(webob.exc.HTTPBadRequest,
                                     {'host': 'my-host',
                                      'onSharedStorage': 'False',
                                      'adminPass': 'MyNewPass'})

    def test_evacuate_instance_with_no_target(self):
        admin_pass = 'MyNewPass'
        res = self._get_evacuate_response({'onSharedStorage': 'False',
                                           'adminPass': admin_pass})

        self.assertEqual(admin_pass, res['adminPass'])

    def test_evacuate_instance_without_on_shared_storage(self):
        self._check_evacuate_failure(self.validation_error,
                                     {'host': 'my-host',
                                      'adminPass': 'MyNewPass'})

    def test_evacuate_instance_with_invalid_characters_host(self):
        host = 'abc!#'
        self._check_evacuate_failure(self.validation_error,
                                     {'host': host,
                                      'onSharedStorage': 'False',
                                      'adminPass': 'MyNewPass'})

    def test_evacuate_instance_with_too_long_host(self):
        host = 'a' * 256
        self._check_evacuate_failure(self.validation_error,
                                     {'host': host,
                                      'onSharedStorage': 'False',
                                      'adminPass': 'MyNewPass'})

    def test_evacuate_instance_with_invalid_on_shared_storage(self):
        self._check_evacuate_failure(self.validation_error,
                                     {'host': 'my-host',
                                      'onSharedStorage': 'foo',
                                      'adminPass': 'MyNewPass'})

    def test_evacuate_instance_with_bad_target(self):
        self._check_evacuate_failure(webob.exc.HTTPNotFound,
                                     {'host': 'bad-host',
                                      'onSharedStorage': 'False',
                                      'adminPass': 'MyNewPass'})

    def test_evacuate_instance_with_target(self):
        admin_pass = 'MyNewPass'
        res = self._get_evacuate_response({'host': 'my-host',
                                           'onSharedStorage': 'False',
                                           'adminPass': admin_pass})

        self.assertEqual(admin_pass, res['adminPass'])

    @mock.patch('nova.objects.Instance.save')
    def test_evacuate_shared_and_pass(self, mock_save):
        self._check_evacuate_failure(webob.exc.HTTPBadRequest,
                                     {'host': 'bad-host',
                                      'onSharedStorage': 'True',
                                      'adminPass': 'MyNewPass'})

    @mock.patch('nova.objects.Instance.save')
    def test_evacuate_not_shared_pass_generated(self, mock_save):
        res = self._get_evacuate_response({'host': 'my-host',
                                           'onSharedStorage': 'False'})
        self.assertEqual(CONF.password_length, len(res['adminPass']))

    @mock.patch('nova.objects.Instance.save')
    def test_evacuate_shared(self, mock_save):
        self._get_evacuate_response({'host': 'my-host',
                                     'onSharedStorage': 'True'})

    def test_not_admin(self):
        body = {'evacuate': {'host': 'my-host',
                             'onSharedStorage': 'False'}}
        self.assertRaises(exception.PolicyNotAuthorized,
                          self.controller._evacuate,
                          self.req, self.UUID, body=body)

    def test_evacuate_to_same_host(self):
        self._check_evacuate_failure(webob.exc.HTTPBadRequest,
                                     {'host': 'host1',
                                      'onSharedStorage': 'False',
                                      'adminPass': 'MyNewPass'})

    def test_evacuate_instance_with_empty_host(self):
        self._check_evacuate_failure(self.validation_error,
                                     {'host': '',
                                      'onSharedStorage': 'False',
                                      'adminPass': 'MyNewPass'},
                                     controller=self.controller_no_ext)

    @mock.patch('nova.objects.Instance.save')
    def test_evacuate_instance_with_underscore_in_hostname(self, mock_save):
        admin_pass = 'MyNewPass'
        # NOTE: The hostname grammar in RFC952 does not allow for
        # underscores in hostnames. However, we should test that it
        # is supported because it sometimes occurs in real systems.
        res = self._get_evacuate_response({'host': 'underscore_hostname',
                                           'onSharedStorage': 'False',
                                           'adminPass': admin_pass})

        self.assertEqual(admin_pass, res['adminPass'])

    def test_evacuate_disable_password_return(self):
        self._test_evacuate_enable_instance_password_conf(False)

    def test_evacuate_enable_password_return(self):
        self._test_evacuate_enable_instance_password_conf(True)

    @mock.patch('nova.objects.Instance.save')
    def _test_evacuate_enable_instance_password_conf(self, mock_save,
                                                     enable_pass):
        self.flags(enable_instance_password=enable_pass)

        res = self._get_evacuate_response({'host': 'underscore_hostname',
                                           'onSharedStorage': 'False'})
        if enable_pass:
            self.assertIn('adminPass', res)
        else:
            self.assertIsNone(res.get('adminPass'))

class EvacuatePolicyEnforcementv21(test.NoDBTestCase):

    def setUp(self):
        super(EvacuatePolicyEnforcementv21, self).setUp()
        self.controller = evacuate_v21.EvacuateController()

    def test_evacuate_policy_failed(self):
        rule_name = "os_compute_api:os-evacuate"
        self.policy.set_rules({rule_name: "project:non_fake"})
        req = fakes.HTTPRequest.blank('')
        body = {'evacuate': {'host': 'my-host',
                             'onSharedStorage': 'False',
                             'adminPass': 'MyNewPass'
                             }}
        exc = self.assertRaises(
            exception.PolicyNotAuthorized,
            self.controller._evacuate, req, fakes.FAKE_UUID,
            body=body)
        self.assertEqual(
            "Policy doesn't allow %s to be performed." % rule_name,
            exc.format_message())

class EvacuateTestV214(EvacuateTestV21):
    def setUp(self):
        super(EvacuateTestV214, self).setUp()
        self.admin_req = fakes.HTTPRequest.blank('', use_admin_context=True,
                                                 version='2.14')
        self.req = fakes.HTTPRequest.blank('', version='2.14')

    def _get_evacuate_response(self, json_load, uuid=None):
        json_load.pop('onSharedStorage', None)
        base_json_load = {'evacuate': json_load}
        response = self.controller._evacuate(self.admin_req, uuid or self.UUID,
                                             body=base_json_load)

        return response

    def _check_evacuate_failure(self, exception, body, uuid=None,
                                controller=None):
        controller = controller or self.controller
        body.pop('onSharedStorage', None)
        body = {'evacuate': body}
        self.assertRaises(exception,
                          controller._evacuate,
                          self.admin_req, uuid or self.UUID, body=body)

    @mock.patch.object(compute_api.API, 'evacuate')
    def test_evacuate_instance(self, mock_evacuate):
        self._get_evacuate_response({})
        admin_pass = mock_evacuate.call_args_list[0][0][4]
        on_shared_storage = mock_evacuate.call_args_list[0][0][3]
        self.assertEqual(CONF.password_length, len(admin_pass))
        self.assertIsNone(on_shared_storage)

    def test_evacuate_with_valid_instance(self):
        admin_pass = 'MyNewPass'
        res = self._get_evacuate_response({'host': 'my-host',
                                           'adminPass': admin_pass})

        self.assertIsNone(res)

    @testtools.skip('Password is not returned from Microversion 2.14')
    def test_evacuate_disable_password_return(self):
        pass

    @testtools.skip('Password is not returned from Microversion 2.14')
    def test_evacuate_enable_password_return(self):
        pass

    @testtools.skip('onSharedStorage was removed from Microversion 2.14')
    def test_evacuate_instance_with_invalid_on_shared_storage(self):
        pass

    @testtools.skip('onSharedStorage was removed from Microversion 2.14')
    @mock.patch('nova.objects.Instance.save')
    def test_evacuate_not_shared_pass_generated(self, mock_save):
        pass

    @mock.patch.object(compute_api.API, 'evacuate')
    @mock.patch('nova.objects.Instance.save')
    def test_evacuate_pass_generated(self, mock_save, mock_evacuate):
        self._get_evacuate_response({'host': 'my-host'})
        self.assertEqual(CONF.password_length,
                         len(mock_evacuate.call_args_list[0][0][4]))

    def test_evacuate_instance_without_on_shared_storage(self):
        self._get_evacuate_response({'host': 'my-host',
                                     'adminPass': 'MyNewPass'})

    def test_evacuate_instance_with_no_target(self):
        admin_pass = 'MyNewPass'
        with mock.patch.object(compute_api.API, 'evacuate') as mock_evacuate:
            self._get_evacuate_response({'adminPass': admin_pass})
            self.assertEqual(admin_pass,
                             mock_evacuate.call_args_list[0][0][4])

    def test_not_admin(self):
        body = {'evacuate': {'host': 'my-host'}}
        self.assertRaises(exception.PolicyNotAuthorized,
                          self.controller._evacuate,
                          self.req, self.UUID, body=body)

    @testtools.skip('onSharedStorage was removed from Microversion 2.14')
    @mock.patch('nova.objects.Instance.save')
    def test_evacuate_shared_and_pass(self, mock_save):
        pass

    @testtools.skip('from Microversion 2.14 it is covered with '
                    'test_evacuate_pass_generated')
    def test_evacuate_instance_with_target(self):
        pass

    @mock.patch('nova.objects.Instance.save')
    def test_evacuate_instance_with_underscore_in_hostname(self, mock_save):
        # NOTE: The hostname grammar in RFC952 does not allow for
        # underscores in hostnames. However, we should test that it
        # is supported because it sometimes occurs in real systems.
        self._get_evacuate_response({'host': 'underscore_hostname'})


text:
package co.sabi11.items.interfaces;

public interface Veggies {
	public String toString();
}


text:
using System;
using System.Reactive;

namespace Avalonia.Layout
{
    /// <summary>
    /// Manages measuring and arranging of controls.
    /// </summary>
    public interface ILayoutManager
    {
        /// <summary>
        /// Notifies the layout manager that a control requires a measure.
        /// </summary>
        /// <param name="control">The control.</param>
        void InvalidateMeasure(ILayoutable control);

        /// <summary>
        /// Notifies the layout manager that a control requires an arrange.
        /// </summary>
        /// <param name="control">The control.</param>
        void InvalidateArrange(ILayoutable control);

        /// <summary>
        /// Executes a layout pass.
        /// </summary>
        /// <remarks>
        /// You should not usually need to call this method explictly, the layout manager will
        /// schedule layout passes itself.
        /// </remarks>
        void ExecuteLayoutPass();

        /// <summary>
        /// Executes the initial layout pass on a layout root.
        /// </summary>
        /// <param name="root">The control to lay out.</param>
        /// <remarks>
        /// You should not usually need to call this method explictly, the layout root will call
        /// it to carry out the initial layout of the control.
        /// </remarks>
        void ExecuteInitialLayoutPass(ILayoutRoot root);
    }
}


text:
package tc.oc.tracker.plugin;

import java.util.Map;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import tc.oc.tracker.DamageAPI;
import tc.oc.tracker.DamageInfo;
import tc.oc.tracker.damage.resolvers.DamageAPIResolver;
import tc.oc.tracker.event.EntityDamageEvent;

import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;

/**
 * Helper class for the {@link DamageAPI} and Tracker plugin to properly handle
 * damage inflicted through the API.
 *
 * Class is intended for internal use only. Methods are not guaranteed to
 * respect versioning contract.
 */
public final class DamageAPIHelper {
    /**
     * Gets the singleton DamageAPIHelper instance.
     *
     * @return DamageAPIHelper instance (never null)
     */
    public static @Nonnull DamageAPIHelper get() {
        return inst;
    }
    private static final @Nonnull DamageAPIHelper inst = new DamageAPIHelper();

    /**
     * Fetches the given {@link DamageInfo} object specified by
     * {@link DamageAPI#inflictDamage} so it can be fetched by the
     * {@link DamageAPIResolver} when plugins who listen to the Bukkit event
     * ask for it.
     *
     * @param event EntityDamageEvent to fetch the given damage for
     * @return Stored damage info or null if none is stored
     *
     * @throws NullPointerException if event is null
     */
    public @Nullable DamageInfo getEventDamageInfo(@Nonnull org.bukkit.event.entity.EntityDamageEvent event) {
        Preconditions.checkNotNull(event, "entity damage event");

        return this.eventDamageMapping.get(event);
    }

    /**
     * Sets the API damage info that corresponds to the specified event.
     *
     * Intended for internal use only, so this method is not guaranteed to stay
     * the same through stable version releases.
     *
     * @param event Specified event
     * @param damage Damage info that describes the damage or null to clear the
     *               store information
     * @return Previous damage info associated with the event
     *
     * @throws NullPointerException if event is null
     */
    public @Nullable DamageInfo setEventDamageInfo(@Nonnull org.bukkit.event.entity.EntityDamageEvent event, @Nullable DamageInfo info) {
        Preconditions.checkNotNull(event, "entity damage event");

        if(info != null) {
            return this.eventDamageMapping.put(event, info);
        } else {
            return this.eventDamageMapping.remove(event);
        }
    }

    private final @Nonnull Map<org.bukkit.event.entity.EntityDamageEvent, DamageInfo> eventDamageMapping = Maps.newHashMap();

    /**
     * Gets our version of the EntityDamageEvent so it can be called in
     * parallel to Bukkit's.
     *
     * @param bukkit Bukkit's version of the EntityDamageEvent
     * @return Our version of the event or null if there is none registered
     *
     * @throws NullPointerException if bukkit is null
     */
    public @Nullable EntityDamageEvent getOurEvent(@Nonnull org.bukkit.event.entity.EntityDamageEvent bukkit) {
        Preconditions.checkNotNull(bukkit, "entity damage event");

        return this.eventMapping.get(bukkit);
    }

    /**
     * Sets our version of the EntityDamageEvent so it can be called in
     * parallel with Bukkit's.
     *
     * @param bukkit Bukkit's version of the EntityDamageEvent
     * @param our Our version of the EntityDamageEvent or null to clear it
     * @return The previous association or null if none existed
     *
     * @throws NullPointerException if bukkit is null
     */
    public @Nullable EntityDamageEvent setOurEvent(@Nonnull org.bukkit.event.entity.EntityDamageEvent bukkit, @Nullable EntityDamageEvent our) {
        Preconditions.checkNotNull(bukkit, "entity damage event");

        if(our != null) {
            return this.eventMapping.put(bukkit, our);
        } else {
            return this.eventMapping.remove(bukkit);
        }
    }

    private final @Nonnull Map<org.bukkit.event.entity.EntityDamageEvent, EntityDamageEvent> eventMapping = Maps.newHashMap();
}


text:
package com.lynx.core;

public interface ExceptionListener {
    void onException(String error);
}


text:
package org.lilyproject.avro.repository;

import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;

import org.lilyproject.bytes.api.DataInput;
import org.lilyproject.bytes.api.DataOutput;
import org.lilyproject.bytes.impl.DataOutputImpl;
import org.lilyproject.repository.api.FieldTypes;
import org.lilyproject.repository.api.IdGenerator;
import org.lilyproject.repository.api.IdRecord;
import org.lilyproject.repository.api.IdentityRecordStack;
import org.lilyproject.repository.api.LRepository;
import org.lilyproject.repository.api.Metadata;
import org.lilyproject.repository.api.QName;
import org.lilyproject.repository.api.Record;
import org.lilyproject.repository.api.RecordException;
import org.lilyproject.repository.api.RepositoryException;
import org.lilyproject.repository.api.ResponseStatus;
import org.lilyproject.repository.api.SchemaId;
import org.lilyproject.repository.api.Scope;
import org.lilyproject.repository.api.TypeManager;
import org.lilyproject.repository.api.ValueType;
import org.lilyproject.repository.impl.IdRecordImpl;
import org.lilyproject.repository.impl.MetadataSerDeser;

/**
 * (De)serialization of Record objects from/to bytes.
 *
 *
TODO: idea for further improvement: the namespaces of the QName's could be stored just once
 * and mapped to a short prefix, giving some compression.

 */
public class RecordAsBytesConverter {
    private static final byte NULL_MARKER = 0;
    private static final byte NOT_NULL_MARKER = 1;
    private static final int VERSION_1 = 1;
    /** Version 2 adds metadata serialization. */
    private static final int VERSION_2 = 2;

    private RecordAsBytesConverter() {
    }

    public static final byte[] write(Record record, LRepository repository)
            throws RepositoryException, InterruptedException {
        DataOutput output = new DataOutputImpl();
        write(record, output, repository);
        return output.toByteArray();
    }

    public static final void write(Record record, DataOutput output, LRepository repository)
            throws RepositoryException, InterruptedException {
        // Write serialization format version
        output.writeShort(VERSION_2);

        // Write ID or null
        writeNullOrBytes(record.getId() != null ? record.getId().toBytes() : null, output);

        // Write version or null
        writeNullOrVLong(record.getVersion(), output);

        // Write record type info for each scope (all parts can be null)
        // This assumes the Scope enum stays stable!
        for (Scope scope : Scope.values()) {
            writeNullOrQName(record.getRecordTypeName(scope), output);
            writeNullOrVLong(record.getRecordTypeVersion(scope), output);
        }

        // Write the fields array
        FieldTypes fieldTypes = repository.getTypeManager().getFieldTypesSnapshot();
        output.writeVInt(record.getFields().size());
        for (Map.Entry<QName, Object> entry : record.getFields().entrySet()) {
            if (entry.getKey() == null) {
                throw new IllegalArgumentException("Record contains field with null key.");
            }
            if (entry.getValue() == null) {
                throw new IllegalArgumentException("Record contains field with null value.");
            }

            ValueType valueType = fieldTypes.getFieldType(entry.getKey()).getValueType();

            writeQName(entry.getKey(), output);
            output.writeUTF(valueType.getName());
            try {
                valueType.write(entry.getValue(), output, new IdentityRecordStack());
            } catch (Exception e) {
                throw new RecordException("Error serializing field " + entry.getKey(), e);
            }
        }

        // Write the fields to delete
        output.writeVInt(record.getFieldsToDelete().size());
        for (QName name : record.getFieldsToDelete()) {
            writeQName(name, output);
        }

        // Write transient attributes
        if (record.hasAttributes()) {
            output.writeVInt(record.getAttributes().size());
            for (String key : record.getAttributes().keySet()) {
                String value = record.getAttributes().get(key);
                output.writeUTF(key);
                output.writeUTF(value);
            }
        } else {
            output.writeVInt(0);
        }

        // Write response status or null
        writeNullOrVInt(record.getResponseStatus() != null ? record.getResponseStatus().ordinal() : null, output);

        // Write metadata
        Map<QName, Metadata> metadatas = record.getMetadataMap();
        if (metadatas.size() > 0) {
            output.writeVInt(metadatas.size());
            for (Map.Entry<QName, Metadata> entry : metadatas.entrySet()) {
                writeQName(entry.getKey(), output);
                MetadataSerDeser.write(entry.getValue(), output);
            }
        } else {
            output.writeVInt(0);
        }
    }

    public static final Record read(DataInput input, LRepository repository)
            throws RepositoryException, InterruptedException {
        // Read & check version
        int version = input.readShort();
        if (version != VERSION_1 && version != VERSION_2) {
            throw new RuntimeException("Unsupported record serialization version: " + version);
        }

        Record record = repository.getRecordFactory().newRecord();

        // Read ID
        byte[] idBytes = readNullOrBytes(input);
        if (idBytes != null) {
            record.setId(repository.getIdGenerator().fromBytes(idBytes));
        }

        // Read version
        record.setVersion(readNullOrVLong(input));

        // Read record types for each scope
        for (Scope scope : Scope.values()) {
            QName recordType = readNullOrQName(input);
            Long rtVersion = readNullOrVLong(input);
            record.setRecordType(scope, recordType, rtVersion);
        }

        // Read fields array
        TypeManager typeManager = repository.getTypeManager();
        int size = input.readVInt();
        for (int i = 0; i < size; i++) {
            QName name = readQName(input);
            String valueTypeName = input.readUTF();
            ValueType valueType = typeManager.getValueType(valueTypeName);
            Object value = valueType.read(input);
            record.setField(name, value);
        }

        // Read fields to delete
        size = input.readVInt();
        for (int i = 0; i < size; i++) {
            record.getFieldsToDelete().add(readQName(input));
        }

        // Read transient attributes
        size = input.readVInt();
        for (int i = 0; i < size; i++) {
            String key = input.readUTF();
            String value = input.readUTF();

            record.getAttributes().put(key, value);
        }

        // Read response status or null
        Integer responseStatusOrdinal = readNullOrVInt(input);
        if (responseStatusOrdinal != null) {
            record.setResponseStatus(ResponseStatus.values()[responseStatusOrdinal]);
        }

        // Read metadata
        if (version >= VERSION_2) {
            size = input.readVInt();
            for (int i = 0; i < size; i++) {
                QName fieldName = readQName(input);
                Metadata metadata = MetadataSerDeser.read(input);
                record.setMetadata(fieldName, metadata);
            }
        }

        return record;
    }

    public static final byte[] writeIdRecord(IdRecord record, LRepository repository)
            throws RepositoryException, InterruptedException {
        DataOutput output = new DataOutputImpl();
        writeIdRecord(record, output, repository);
        return output.toByteArray();
    }

    public static final void writeIdRecord(IdRecord record, DataOutput output, LRepository repository)
            throws RepositoryException, InterruptedException {
        write(record, output, repository);

        output.writeVInt(record.getFieldIdToNameMapping().size());
        for (Map.Entry<SchemaId, QName> entry : record.getFieldIdToNameMapping().entrySet()) {
            writeBytes(entry.getKey().getBytes(), output);
            writeQName(entry.getValue(), output);
        }

        for (Scope scope : Scope.values()) {
            SchemaId schemaId = record.getRecordTypeId(scope);
            writeNullOrBytes(schemaId != null ? schemaId.getBytes() : null, output);
        }
    }

    public static final IdRecord readIdRecord(DataInput input, LRepository repository)
            throws RepositoryException, InterruptedException {
        Record record = read(input, repository);

        IdGenerator idGenerator = repository.getIdGenerator();

        int size = input.readVInt();
        Map<SchemaId, QName> idToQNameMapping = new HashMap<SchemaId, QName>();
        for (int i = 0; i < size; i++) {
            byte[] schemaIdBytes = readBytes(input);
            QName name = readQName(input);

            SchemaId schemaId = idGenerator.getSchemaId(schemaIdBytes);
            idToQNameMapping.put(schemaId, name);
        }

        Map<Scope, SchemaId> recordTypeIds = new EnumMap(Scope.class);
        for (Scope scope : Scope.values()) {
            byte[] schemaIdBytes = readNullOrBytes(input);
            if (schemaIdBytes != null) {
                SchemaId schemaId = idGenerator.getSchemaId(schemaIdBytes);
                recordTypeIds.put(scope, schemaId);
            }
        }

        return new IdRecordImpl(record, idToQNameMapping, recordTypeIds);
    }

    private static void writeQName(QName name, DataOutput output) {
        output.writeUTF(name.getNamespace());
        output.writeUTF(name.getName());
    }

    private static QName readQName(DataInput input) {
        String namespace = input.readUTF();
        String name = input.readUTF();
        return new QName(namespace, name);
    }

    private static void writeNullOrQName(QName name, DataOutput output) {
        if (name == null) {
            output.writeByte(NULL_MARKER);
        } else {
            output.writeByte(NOT_NULL_MARKER);
            writeQName(name, output);
        }
    }

    private static QName readNullOrQName(DataInput input) {
        byte nullMarker = input.readByte();
        if (nullMarker == NULL_MARKER) {
            return null;
        } else {
            return readQName(input);
        }
    }

    private static void writeBytes(byte[] bytes, DataOutput output) {
        output.writeVInt(bytes.length);
        output.writeBytes(bytes);
    }

    private static byte[] readBytes(DataInput input) {
        int length = input.readVInt();
        return input.readBytes(length);
    }

    private static void writeNullOrBytes(byte[] bytes, DataOutput output) {
        if (bytes == null) {
            output.writeByte(NULL_MARKER);
        } else {
            output.writeByte(NOT_NULL_MARKER);
            writeBytes(bytes, output);
        }
    }

    private static byte[] readNullOrBytes(DataInput input) {
        byte nullMarker = input.readByte();
        if (nullMarker == NULL_MARKER) {
            return null;
        } else {
            return readBytes(input);
        }
    }

    private static void writeNullOrVLong(Long value, DataOutput output) {
        if (value == null) {
            output.writeByte(NULL_MARKER);
        } else {
            output.writeByte(NOT_NULL_MARKER);
            output.writeVLong(value);
        }
    }

    private static Long readNullOrVLong(DataInput input) {
        byte nullMarker = input.readByte();
        if (nullMarker == NULL_MARKER) {
            return null;
        } else {
            return input.readVLong();
        }
    }

    private static void writeNullOrVInt(Integer value, DataOutput output) {
        if (value == null) {
            output.writeByte(NULL_MARKER);
        } else {
            output.writeByte(NOT_NULL_MARKER);
            output.writeVInt(value);
        }
    }

    private static Integer readNullOrVInt(DataInput input) {
        byte nullMarker = input.readByte();
        if (nullMarker == NULL_MARKER) {
            return null;
        } else {
            return input.readVInt();
        }
    }

    private static void writeNullOrString(String value, DataOutput output) {
        if (value == null) {
            output.writeByte(NULL_MARKER);
        } else {
            output.writeByte(NOT_NULL_MARKER);
            output.writeUTF(value);
        }
    }

}


text:
<?php

namespace Magento\Braintree\Model\Report\ConditionAppliers;

/**
 * Braintree filter condition applier interface
 */
interface ApplierInterface
{
    const EQ = 'eq';
    const QTEQ = 'gteq';
    const LTEQ = 'lteq';
    const IN = 'in';
    const LIKE = 'like';

    /**
     * Apply filter condition
     *
     * @param object $field
     * @param string $condition
     * @param mixed $value
     * @return bool
     */
    public function apply($field, $condition, $value);
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>G3dLoader (libgdx API)</title>
<meta name="date" content="2013-05-14">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

				libgdx API

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.badlogic.gdx.graphics.g3d.loaders.g3d

Class G3dLoader

java.lang.Object

com.badlogic.gdx.graphics.g3d.loaders.g3d.G3dLoader

public class G3dLoader
extends java.lang.Object

Nested Class Summary

Nested Classes

Modifier and Type
Class and Description

static class
G3dLoader.G3dKeyframedModelLoader

static class
G3dLoader.G3dSkeletonModelLoader

static class
G3dLoader.G3dStillModelLoader

Constructor Summary

Constructors

Constructor and Description

G3dLoader()

Method Summary

Methods

Modifier and Type
Method and Description

static KeyframedModel
loadKeyframedModel(FileHandle handle)

static SkeletonModel
loadSkeletonModel(FileHandle handle)

static StillModel
loadStillModel(FileHandle handle)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

G3dLoader

public G3dLoader()

Method Detail

loadStillModel

public static StillModel loadStillModel(FileHandle handle)

loadKeyframedModel

public static KeyframedModel loadKeyframedModel(FileHandle handle)

loadSkeletonModel

public static SkeletonModel loadSkeletonModel(FileHandle handle)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

libgdx API

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

				Copyright © 2010-2013 Mario Zechner (contact@badlogicgames.com), Nathan Sweet (admin@esotericsoftware.com)


text:
extern "Java"
{
  namespace javax
  {
    namespace sound
    {
      namespace sampled
      {
          class BooleanControl$Type;
      }
    }
  }
}

class javax::sound::sampled::BooleanControl$Type : public ::javax::sound::sampled::Control$Type
{

public: // actually protected
  BooleanControl$Type(::java::lang::String *);
public:
  static ::javax::sound::sampled::BooleanControl$Type * APPLY_REVERB;
  static ::javax::sound::sampled::BooleanControl$Type * MUTE;
  static ::java::lang::Class class$;
};

#endif // __javax_sound_sampled_BooleanControl$Type__


text:
class PostDecorator < ApplicationDecorator
  def status
    published_status
  end

  def title_with_admin_link
    h.link_to title, h.admin_post_path(object)
  end

  def author
    text = "#{object.user.nombres} el #{I18n.l created_at, format: :short}"
    h.content_tag :div, text, class: "light"
  end

  def body
    GitHub::Markdown.render(object.body).html_safe
  end

  def comments_count
    text = h.pluralize comments.count, "comentario"
    h.content_tag :div, text, class: "light"
  end

  private

  # status
  def published_status
    if published?
      status_text = "publicada"
      status_class = "success"
    else
      status_text = "no publicada"
      status_class = "default"
    end
    h.content_tag :span, status_text, class: "label label-#{status_class}"
  end

  def navbar_status
    h.content_tag(:span, "en navbar", class: "label label-info") if navbar?
  end
end


text:
class FixPluralInNumberPicks < ActiveRecord::Migration
  def change
    remove_column :picks, :numbers, :string, null: false
    add_column :picks, :number, :string, null: false
  end
end


text:
package org.openntf.domino.nsfdata.structs;

/**
 * Specifies a cropping rectangle for display of graphical data. (editods.h)
 *
 */
public class CROPRECT extends AbstractStruct {

	public final Unsigned16 left = new Unsigned16();
	public final Unsigned16 top = new Unsigned16();
	public final Unsigned16 right = new Unsigned16();
	public final Unsigned16 bottom = new Unsigned16();

	@Override
	public String toString() {
		return "[" + getClass().getSimpleName() + ": Left=" + left.get() + ", Top=" + top.get() + ", Right=" + right.get() + ", Bottom="
				+ bottom.get() + "]";
	}
}


text:
package ca.ualberta.physics.cicstart.cml.command;

import static com.jayway.restassured.RestAssured.expect;
import static com.jayway.restassured.RestAssured.get;
import static com.jayway.restassured.RestAssured.given;

import java.io.File;
import java.io.FilenameFilter;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;

import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import ca.ualberta.physics.cicstart.cml.CMLLexer;
import ca.ualberta.physics.cicstart.cml.CMLParser;
import ca.ualberta.physics.cicstart.cml.ParsingAndBuildingTests;
import ca.ualberta.physics.cssdp.auth.service.AuthClient;
import ca.ualberta.physics.cssdp.configuration.InjectorHolder;
import ca.ualberta.physics.cssdp.configuration.ResourceUrls;
import ca.ualberta.physics.cssdp.domain.auth.User;
import ca.ualberta.physics.cssdp.domain.catalogue.CatalogueSearchRequest;
import ca.ualberta.physics.cssdp.domain.catalogue.CatalogueSearchResponse;
import ca.ualberta.physics.cssdp.domain.catalogue.DataProduct;
import ca.ualberta.physics.cssdp.domain.catalogue.Discriminator;
import ca.ualberta.physics.cssdp.domain.catalogue.MetadataParserConfig;
import ca.ualberta.physics.cssdp.domain.catalogue.Project;
import ca.ualberta.physics.cssdp.domain.file.Host;
import ca.ualberta.physics.cssdp.domain.file.Host.Protocol;
import ca.ualberta.physics.cssdp.domain.macro.Instance;
import ca.ualberta.physics.cssdp.model.Mnemonic;
import ca.ualberta.physics.cssdp.util.IntegrationTestScaffolding;
import ca.ualberta.physics.cssdp.vfs.configuration.VfsServer;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.io.Files;
import com.google.inject.Inject;
import com.jayway.restassured.http.ContentType;
import com.jayway.restassured.response.Response;

public class FullScriptTest extends IntegrationTestScaffolding {

	@Inject
	protected ObjectMapper mapper;

	@Inject
	protected AuthClient authClient;

	private String sessionToken;

	private User dataManager;

	public FullScriptTest() {
		InjectorHolder.inject(this);
	}

	@Override
	protected String getComponetContext() {
		return "unused";
	}

	@Before
	public void setupData() throws Exception {

		// Given a project definition
		Project apache = new Project();
		apache.setExternalKey(Mnemonic.of("APACHE3"));
		apache.setHost("sunsite.ualberta.ca");
		apache.setName("Apache data on sunsite at ualberta.ca");
		apache.setScanDirectories(Arrays.asList("/pub/Mirror/apache/commons"));

		Discriminator d = new Discriminator();
		d.setDescription("commons/daemon");
		d.setExternalKey(Mnemonic.of("COMMONS/DAEMON3"));
		d.setProject(apache);
		apache.getDiscriminators().add(d);

		DataProduct commonsDaemon = new DataProduct();
		commonsDaemon.setExternalKey(Mnemonic.of("COMMONS/DAEMON3"));
		commonsDaemon.setDescription("Apache Commons Daemon files");
		commonsDaemon.setDiscriminator(d);
		commonsDaemon.setProject(apache);

		MetadataParserConfig metadataParserConfig = new MetadataParserConfig();
		metadataParserConfig.setIncludesRegex(".*jar$");
		commonsDaemon.setMetadataParserConfig(metadataParserConfig);

		apache.getDataProducts().add(commonsDaemon);

		String apacheJSON = mapper.writeValueAsString(apache);

		Response findProjRes = get(ResourceUrls.PROJECT + "/APACHE3");
		if (findProjRes.getStatusCode() == 404) {
			given().body(apacheJSON).and().contentType("application/json")
					.expect().statusCode(201).when().post(ResourceUrls.PROJECT);
		}

		dataManager = setupDataManager();
		sessionToken = login(dataManager.getEmail(), "password");

		Host host = new Host();
		host.setHostname("sunsite.ualberta.ca");
		host.setProtocol(Protocol.ftp);
		host.setUsername("anonymous");
		host.setPassword("anonymous");

		Response findHostRes = get(ResourceUrls.HOST + "/sunsite.ualberta.ca");
		if (findHostRes.getStatusCode() == 404) {

			expect().statusCode(201).when().given().content(host).and()
					.contentType(ContentType.JSON).and()
					.headers("CICSTART.session", sessionToken)
					.post(ResourceUrls.HOST);
		}

		// WHEN the project host is fully scanned for files using the project's
		// metadata configuration
		Response res = given().header("CICSTART.session", sessionToken)
				.expect().statusCode(202).when()
				.put(ResourceUrls.PROJECT + "/APACHE3/scan");

		System.out.println(res.asString());

		CatalogueSearchRequest searchRequest = new CatalogueSearchRequest();
		searchRequest.setProjectKey(Mnemonic.of("APACHE3"));

		res = given().content(searchRequest).and()
				.contentType(ContentType.JSON)
				.post(ResourceUrls.PROJECT + "/find");

		// THEN a search request/response will contain a some files that we just
		// scanned
		CatalogueSearchResponse response = res
				.as(CatalogueSearchResponse.class);
		Assert.assertTrue(
				"There should be at least 1 apache jar on file on sunsite",
				response.getUris().size() > 0);
		Assert.assertTrue("Expecting any path to contain apache", response
				.getUris().get(0).getPath().contains("apache"));
		Assert.assertTrue("Expecting any path to contain jar", response
				.getUris().get(0).getPath().contains("jar"));

	}

	@Test
	public void testFullScriptRun() throws Exception {

		// cleanup left over cruft
		String vfsRoot = VfsServer.properties().getString("vfs_root");
		File extractedJarRoot = new File(new File(vfsRoot, dataManager.getId()
				.toString()), "testJob");

		if (extractedJarRoot.exists()) {
			for (File file : extractedJarRoot.listFiles()) {
				file.delete();
			}
		}

		String script = Files.toString(new File(ParsingAndBuildingTests.class
				.getResource("/test2.cml").toURI()), Charset.forName("UTF-8"));
		ANTLRInputStream input = new ANTLRInputStream(script);

		CMLLexer lexer = new CMLLexer(input);

		CommonTokenStream tokens = new CommonTokenStream(lexer);

		CMLParser parser = new CMLParser(tokens);

		ParseTreeWalker walker = new ParseTreeWalker();

		Macro macro = new Macro(script);

		ParseTree tree = parser.macro();

		walker.walk(macro, tree);

		CMLRuntime runtime = new CMLRuntime("testJob", sessionToken);
		runtime.run(macro.getCommands());

		new PutVFS(sessionToken, runtime.getRequestId(), "macro.log")
				.execute(runtime);

		vfsRoot = VfsServer.properties().getString("vfs_root");
		extractedJarRoot = new File(new File(vfsRoot, dataManager.getId()
				.toString()), "testJob");
		Assert.assertTrue(extractedJarRoot.listFiles().length > 0);
		Assert.assertEquals(1, extractedJarRoot.listFiles(new FilenameFilter() {

			@Override
			public boolean accept(File dir, String name) {
				return name.equals("macro.log");
			}
		}).length);

		for (File file : extractedJarRoot.listFiles()) {
			file.delete();
		}

	}

	@Test
	public void testStartVMAndRunStuffOnIt() throws Exception {

		String script = Files.toString(new File(ParsingAndBuildingTests.class
				.getResource("/test3.cml").toURI()), Charset.forName("UTF-8"));
		ANTLRInputStream input = new ANTLRInputStream(script);

		CMLLexer lexer = new CMLLexer(input);

		CommonTokenStream tokens = new CommonTokenStream(lexer);

		CMLParser parser = new CMLParser(tokens);

		ParseTreeWalker walker = new ParseTreeWalker();

		Macro macro = new Macro(script);

		ParseTree tree = parser.macro();

		walker.walk(macro, tree);

		CMLRuntime runtime = new CMLRuntime("testStartVMAndRunStuffOnIt",
				sessionToken);
		runtime.run(macro.getCommands());

		List<Instance> instances = runtime.getInstances();
		if (instances.size() > 0) {
			Instance instance = instances.get(0);

			// cleanup, stop the instance
			expect().statusCode(200).when().given().content(instance).and()
					.contentType(ContentType.JSON).and()
					.headers("CICSTART.session", sessionToken)
					.delete(ResourceUrls.MACRO + "/vm");
			// TODO release floating ips
		}

	}

}


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/*
 *
 * Date:    26 September 2003
 * SUMMARY: Regexp conformance test
 *
 * See http://bugzilla.mozilla.org/show_bug.cgi?id=220367
 *
 */
//-----------------------------------------------------------------------------
var UBound = 0;
var BUGNUMBER = 220367;
var summary = 'Regexp conformance test';
var status = '';
var statusitems = [];
var actual = '';
var actualvalues = [];
var expect= '';
var expectedvalues = [];

var re = /(a)|(b)/;

re.test('a');
status = inSection(1);
actual = RegExp.$1;
expect = 'a';
addThis();

status = inSection(2);
actual = RegExp.$2;
expect = '';
addThis();

re.test('b');
status = inSection(3);
actual = RegExp.$1;
expect = '';
addThis();

status = inSection(4);
actual = RegExp.$2;
expect = 'b';
addThis();

//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------

function addThis()
{
  statusitems[UBound] = status;
  actualvalues[UBound] = actual;
  expectedvalues[UBound] = expect;
  UBound++;
}

function test()
{
  enterFunc('test');
  printBugNumber(BUGNUMBER);
  printStatus(summary);

  for (var i=0; i<UBound; i++)
  {
    reportCompare(expectedvalues[i], actualvalues[i], statusitems[i]);
  }

  exitFunc ('test');
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StarshipSeven.GameInterfaces.Factories;
using StarshipSeven.GameInterfaces;
using StarshipSeven.GameInterfaces.Strategy;
using StarshipSeven.GameEntities.Factories.Helpers;
using System.Collections.ObjectModel;
using System.Collections.Specialized;

namespace StarshipSeven.GameEntities.Factories
{
    public class GameFactory : BaseGameFactory
    {
        private MapGenerator _mapGenerator = new MapGenerator();
        private Game _game = new Game();
        private NeutralPlayer _neutralPlayer;
        private Map _map;

        public GameFactory() : base(new PlayerFactory())
        {
            _neutralPlayer = PlayerFactory.CreateNeutralPlayer() as NeutralPlayer;
        }

        public override void GenerateMap()
        {
            _map = _mapGenerator.Generate(MapWidth, MapHeight, Players.OfType<Player>(), NeutralPlanetsNumber, _neutralPlayer);
            base.GenerateMap();
        }

        public override IMap CurrentMap
        {
            get { return _map; }
        }

        public override IGame Construct()
        {
            if (_map == null)
                GenerateMap();
            if (NeutralPlanetsNumber != 0)
                _game.AttachPlayer(_neutralPlayer);
            foreach (var player in Players.OfType<Player>())
                _game.AttachPlayer(player);
            _game.SetMap(_map);
            _game.BattleHandler = this.BattleHandler;
            _game.Initialize();
            return _game;
        }
    }
}