text:
describe ("Cookie Tests",function() {
    var cookieName = "myCookie";

    /*
       NOTE:

       These tests can only run in a client-server setup with a properly
       configured FQDN for the server.

       Please read:
         RFC 2109 (https://www.ietf.org/rfc/rfc2109.txt)
       and this thread on the chromium bugtracker:
         https://code.google.com/p/chromium/issues/detail?id=535

       In your development environment please configure your localhost with a fully
       qualified domain name locally:

       In a UNIX/Mac/Linux environment you can add a name for 127.0.0.1 to
       your /etc/hosts such as:
         127.0.0.1	www.example.org  www

       You can do the same under windows, however the path to the file is a
       little different:

       Valid for Windown Vista/7/2008/2012: C:\Windows\System32\drivers\etc\hosts

       We (as in the boomerang team) are not responsible for any accidental or
       direct damages and or damage claims. See LICENSE for further information.
    */

    if (window.location.protocol === "file:")
	return;

    describe("getCookie Tests",function() {
	it("Should have an exisiting BOOMR.utils.getCookie function",function() {
	    assert.isFunction(BOOMR.utils.getCookie);
	});

	it("Should return null when calling getCookie() with empty arguments",function() {
	    assert.isNull(BOOMR.utils.getCookie());
	});

	it("Should return null when calling getCookie with empty String",function(){
	    assert.isNull(BOOMR.utils.getCookie(""));
	});
	it("Should return null when calling with null as first argument",function(){
	    assert.isNull(BOOMR.utils.getCookie(null));
	});

	it("Should return null when calling with not existing cookie",function() {
	    assert.isNull(BOOMR.utils.getCookie("some-none-existing-cooke"));
	});
    });

    describe("setCookie Tests",function() {
	it("Should have an exisiting BOOMR.utils.setCookie function",function(){
	    assert.isFunction(BOOMR.utils.setCookie);
	});

	it("Should return false if no name was passed as first argument to setCookie()",function()  {
	    assert.isFalse(BOOMR.utils.setCookie());
	});

	it("Should return false when setting only Cookie name",function() {
	    assert.isFalse(BOOMR.utils.setCookie(cookieName));
	});

	it("Should return true when setting Cookie with value",function(){
	    assert.isTrue(BOOMR.utils.setCookie(cookieName,"value"));
	});

	it("Should return false when removing previously set Cookie",function(){
	    assert.isTrue(BOOMR.utils.removeCookie(cookieName));
	});

	it("Should return the cookie value string that we've set previously", function() {
	    var value = "value";
	    BOOMR.utils.setCookie(cookieName,value);

	    assert.equal(BOOMR.utils.getCookie(cookieName),value);
	    BOOMR.utils.removeCookie(cookieName);
	});

	it("Should return the EXACT value string that we've set previously",function () {
	    var value = "1";
	    var value_strict_false = 1;

	    BOOMR.utils.setCookie(cookieName,value);
	    assert.strictEqual(BOOMR.utils.getCookie(cookieName),value);
	    assert.notStrictEqual(BOOMR.utils.getCookie(cookieName),value_strict_false);
	    BOOMR.utils.removeCookie(cookieName);
	});

	it("Should return false when trying to set a cookie bigger than 500 characters",function() {
	    var value = "";
	    for (var index = 0; index <= 500;index++) {
		value += "1";
	    }
	    assert.isFalse(BOOMR.utils.setCookie("failCookie",value));

	});
    });

    describe("getSubCookies",function() {

	it("Should have an exisiting BOOMR.utils.getSubCookies function",function() {
	    assert.isFunction(BOOMR.utils.getSubCookies);
	});

	it("Should return null when calling getSubCookies() with empty arguments",function() {
	    assert.isNull(BOOMR.utils.getSubCookies());
	});

	it("Should return null when calling getSubCookies with empty String",function(){
	    assert.isNull(BOOMR.utils.getSubCookies(""));
	});
	it("Should return null when calling with null as first argument",function(){
	    assert.isNull(BOOMR.utils.getSubCookies(null));
	});

	it("Should return null when calling with a non-string object",function() {
	    assert.isNull(BOOMR.utils.getSubCookies({key: "value"}));
	});

	it("Should return the value that we've set previously",function () {
	    var value = {value : { subValue: "value" }};
	    BOOMR.utils.setCookie(cookieName,value);
	    assert.deepEqual(BOOMR.utils.getSubCookies("subValue"),{subValue: "value"});
	});

	it("Should return null when requesting the subCookie '&'",function() {
	    assert.isNull(BOOMR.utils.getSubCookies("&"));
	});

	it("Should return null when requesting the subCookie '=&='",function(){
	    assert.isNull(BOOMR.utils.getSubCookies("=&="));
	});

	it("Should return null when requesting a value instead of a key for a subCookie i.e. '=someValue'",function(){
	    assert.isNull(BOOMR.utils.getSubCookies("=someValue"));
	});

	it("Should return null when requesting a subCookie named '='",function() {
	    assert.isNull(BOOMR.utils.getSubCookies("="));
	});
    });
});


text:
package com.github.platan.bamboo.sputnik;

import static com.atlassian.bamboo.repository.ReflectionRepositoryAccessor.StashRepositoryAccessor.getApplicationLink;
import static com.atlassian.bamboo.repository.ReflectionRepositoryAccessor.StashRepositoryAccessor.getStashProjectKey;
import static com.atlassian.bamboo.repository.ReflectionRepositoryAccessor.StashRepositoryAccessor.getStashRepositorySlug;
import static com.atlassian.bamboo.repository.ReflectionRepositoryAccessor.StashRepositoryAccessor.isStashRepository;

import com.atlassian.applinks.api.ApplicationLink;
import com.atlassian.bamboo.process.EnvironmentVariableAccessor;
import com.atlassian.bamboo.repository.Repository;
import com.atlassian.bamboo.repository.RepositoryDefinition;
import com.atlassian.bamboo.task.TaskContext;
import com.atlassian.bamboo.task.TaskException;
import com.atlassian.bamboo.v2.build.BuildContext;
import org.jetbrains.annotations.NotNull;

import java.net.URI;
import java.util.List;

public class StashRepositoryDetailsLoader {

    private final EnvironmentVariableAccessor environmentVariableAccessor;

    public StashRepositoryDetailsLoader(EnvironmentVariableAccessor environmentVariableAccessor) {
        this.environmentVariableAccessor = environmentVariableAccessor;
    }

    @NotNull
    public StashRepositoryDetails getRepositoryDetails(TaskContext taskContext) throws TaskException {
        RepositoryDefinition repositoryDefinition = getMainStashRepository(taskContext);
        Repository repository = repositoryDefinition.getRepository();
        ApplicationLink applicationLink = getApplicationLink(repository);
        if (applicationLink == null) {
            throw new TaskException(String.format("Application link for '%s' repository is empty", repository.getName()));
        }
        URI stashUrl = applicationLink.getDisplayUrl();
        String stashProjectKey = getStashProjectKey(repository);
        String stashRepositorySlug = getStashRepositorySlug(repository);
        String branchName = getBranchName(taskContext, repositoryDefinition);
        String checkoutLocation = taskContext.getBuildContext().getCheckoutLocation().get(repositoryDefinition.getId());
        return new StashRepositoryDetails(stashUrl, stashProjectKey, stashRepositorySlug, branchName, checkoutLocation);
    }

    private String getBranchName(TaskContext taskContext, RepositoryDefinition repositoryDefinition) {
        int position = repositoryDefinition.getPosition() + 1;
        String variableKey = String.format("bamboo_planRepository_%d_branch", position);
        return environmentVariableAccessor.getEnvironment(taskContext).get(variableKey);
    }

    private RepositoryDefinition getMainStashRepository(TaskContext taskContext) throws TaskException {
        BuildContext buildContext = taskContext.getBuildContext();
        List<RepositoryDefinition> repositoryDefinitions = buildContext.getRepositoryDefinitions();

        if (repositoryDefinitions.isEmpty()) {
            throw new TaskException("No Stash repository is defined!");
        }
        RepositoryDefinition repositoryDefinition = repositoryDefinitions.get(0);
        if (!isStashRepository(repositoryDefinition.getRepository())) {
            throw new TaskException(String.format("'%s' is not a Stash repository!", repositoryDefinition.getName()));
        }
        if (!buildContext.getCheckoutLocation().containsKey(repositoryDefinition.getId())) {
            throw new TaskException(String.format("Repository '%s' is not checked out!", repositoryDefinition.getName()));
        }
        return repositoryDefinition;
    }

}

redpajama_set_name: RedPajamaGithub


text:
apt-get install dirmngr -y -qq
echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu xenial main" | tee /etc/apt/sources.list.d/webupd8team-java.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu xenial main" | tee -a /etc/apt/sources.list.d/webupd8team-java.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
gpg --keyserver hkp://keyserver.ubuntu.com:80 --recv C2518248EEA14886
gpg --export --armor 9BDB3D89CE49EC21 | apt-key add -
apt-get update
apt-get install oracle-java8-set-default -y -qq


text:
package org.apache.deltaspike.security.impl.authorization;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Annotated;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.interceptor.InvocationContext;

import org.apache.deltaspike.core.util.metadata.builder.ParameterValueRedefiner;
import org.apache.deltaspike.security.api.authorization.SecuredReturn;
import org.apache.deltaspike.security.api.authorization.SecurityParameterBinding;

/**
 * Responsible for supplying requested method invocation values to the security binding method.
 */
public class SecurityParameterValueRedefiner implements ParameterValueRedefiner
{
    private CreationalContext<?> creationalContext;
    private InvocationContext invocation;
    private Object result;

    public SecurityParameterValueRedefiner(CreationalContext<?> creationalContext,
                                           InvocationContext invocation,
                                           Object result)
    {
        this.creationalContext = creationalContext;
        this.invocation = invocation;
        this.result = result;
    }

    @Override
    public Object redefineParameterValue(ParameterValue value)
    {

        InjectionPoint injectionPoint = value.getInjectionPoint();
        if (injectionPoint != null)
        {
            if (value.getInjectionPoint().getAnnotated().getBaseType().equals(InvocationContext.class))
            {
                return invocation;
            }
            else if (value.getInjectionPoint().getAnnotated().isAnnotationPresent(SecuredReturn.class))
            {
                return result;
            }
            else
            {
                Annotated securingParameterAnnotatedType = injectionPoint.getAnnotated();
                Set<Annotation> securingParameterAnnotations = securingParameterAnnotatedType.getAnnotations();

                Set<Annotation> requiredBindingAnnotations = new HashSet<Annotation>();
                for (Annotation annotation : securingParameterAnnotations)
                {
                    if (annotation.annotationType().isAnnotationPresent(SecurityParameterBinding.class))
                    {
                        requiredBindingAnnotations.add(annotation);
                    }
                }

                if (!requiredBindingAnnotations.isEmpty())
                {
                    Method method = invocation.getMethod();
                    Annotation[][] businessMethodParameterAnnotations = method.getParameterAnnotations();
                    for (int i = 0; i < businessMethodParameterAnnotations.length; i++)
                    {
                        List<Annotation> businessParameterAnnotations = Arrays
                                    .asList(businessMethodParameterAnnotations[i]);
                        for (Annotation annotation : requiredBindingAnnotations)
                        {
                            if (businessParameterAnnotations.contains(annotation))
                            {
                                return invocation.getParameters()[i];
                            }
                        }
                    }

                    throw new IllegalStateException("Missing required security parameter binding "
                                + requiredBindingAnnotations + " on method invocation ["
                                + method.getDeclaringClass().getName() + "." + method.getName()
                                + Arrays.asList(method.getParameterTypes()).toString().replaceFirst("\\[", "(")
                                            .replaceFirst("\\]$", ")") + "]");

                }
            }
        }

        return value.getDefaultValue(creationalContext);
    }
}


text:
import onnx
import torch
import numpy as np
from typing import Any
from onnx import helper
from onnx import onnx_pb as onnx_proto
from distutils.version import LooseVersion
from torch.onnx import register_custom_op_symbolic

from ._utils import ONNXModelUtils
from ._base import CustomFunction, ProcessingTracedModule, is_processing_module
from ._onnx_ops import ox as _ox, schema as _schema
from ._onnx_ops import ONNXElementContainer, make_model_ex
from .._ortapi2 import OrtPyFunction, get_opset_version_from_ort

def _is_numpy_object(x):
    return isinstance(x, (np.ndarray, np.generic))

def _is_numpy_string_type(arr):
    return arr.dtype.kind in {'U', 'S'}

def _is_string_type(x):
    if isinstance(x, list):
        return any(_is_string_type(e) for e in x)
    elif isinstance(x, torch.Tensor):
        return False
    elif not _is_numpy_object(x):
        x = np.array(x)
    return _is_numpy_string_type(x)

def _to_onnx_type(dtype):
    ty_dict = {torch.bool: onnx_proto.TensorProto.BOOL,
               torch.float32: onnx_proto.TensorProto.FLOAT,
               torch.float64: onnx_proto.TensorProto.DOUBLE,
               torch.long: onnx_proto.TensorProto.INT64,
               torch.int32: onnx_proto.TensorProto.INT32}
    # ...
    return ty_dict.get(dtype, onnx_proto.TensorProto.STRING)

class OnnxOpFunction(CustomFunction):
    @classmethod
    def get_next_id_name(cls, name_base):
        name = 'cls' if name_base is None else name_base
        _cid = getattr(cls, '_cid', 1)
        cls._cid = _cid + 1
        return "{}_{}".format(name, _cid)

    @staticmethod
    def jvp(ctx: Any, *grad_inputs: Any) -> Any:
        pass

    @staticmethod
    def backward(ctx: Any, *grad_outputs: Any) -> Any:
        return grad_outputs

    @classmethod
    def build_model(cls, opset_version, *args):
        # build the one node graph
        if isinstance(args[0], list):
            args = [np.asarray(_i) for _i in args]
        ec = ONNXElementContainer(get_opset_version_from_ort() if opset_version is None else opset_version)
        attrs = cls.attrs
        vi_inputs = [helper.make_tensor_value_info(
            'it_' + str(id(_arg)), _to_onnx_type(_arg.dtype), list(_arg.shape))
            for _arg in args]
        inputs = [_vi.name for _vi in vi_inputs]
        if hasattr(cls.opb_func, 'outputs') and len(cls.opb_func.outputs) > 0:
            vi_outputs = [helper.make_tensor_value_info(
                cls.get_next_id_name('ot'), *_schm) for _schm in cls.opb_func.outputs]
        else:
            vi_outputs = [helper.make_tensor_value_info(
                cls.get_next_id_name('ot'), onnx_proto.TensorProto.FLOAT, []
            )]
        outputs = [_vi.name for _vi in vi_outputs]
        # build the node
        opfunc = cls.opb_func
        opfunc(inputs, outputs, ec, None, **attrs)
        g = helper.make_graph(ec.nodes, cls.get_next_id_name('g'), vi_inputs, vi_outputs)
        m = make_model_ex(g, ec.node_domain_version_pair_sets, ec.target_opset)
        return m

    @classmethod
    @torch.jit.unused
    def _onnx_call(cls, ctx, *args) -> Any:
        m = cls.build_model(None, *args)
        try:
            f = OrtPyFunction.from_model(m)
            result = f(*list(_i.numpy() if isinstance(_i, torch.Tensor) else _i for _i in args))
        except Exception as e:
            onnx.save_model(m, '_temp_debugging.onnx')
            raise e

        results = result if isinstance(result, tuple) else [result]
        return tuple([torch.from_numpy(_o) for _o in results]) if len(results) > 1 else torch.from_numpy(results[0])

    @classmethod
    def forward(cls, ctx: Any, *args: Any, **kwargs: Any) -> Any:
        return cls._onnx_call(ctx, *args, **kwargs)

    @classmethod
    def symbolic(cls, g, *args):
        return g.op(cls.op_type, *args)

def create_op_function(op_type: str, func, **attrs):
    if _ox.is_raw(func):
        func = _schema(func.__func__)
    cls = type(_ox.get_unique_operator_type_name(op_type), (OnnxOpFunction,),
               dict(
                   op_type=op_type,
                   opb_func=func,
                   attrs=attrs
               ))
    return cls.apply  # noqa

onnx_pad = create_op_function('Pad', _ox.pad)
onnx_where = create_op_function('Where', _ox.where)
onnx_greater = create_op_function('Greater', _ox.greater)

class _OnnxModelFunction:
    id_object_map = {}  # cannot use the string directly since jit.script doesn't support the data type
    id_function_map = {}
    str_model_function_id = '_model_function_id'
    str_model_id = '_model_id'
    str_model_attached = '_model_attached'

@torch.jit.ignore
def _invoke_onnx_model(model_id: int, *args, **kwargs):
    func = _OnnxModelFunction.id_function_map.get(model_id, None)
    if not func:
        model_or_path = _OnnxModelFunction.id_object_map.get(model_id)
        if model_or_path is None:
            raise ValueError("cannot find id={} registered!".format(model_id))
        func = OrtPyFunction.from_model(model_or_path)
        _OnnxModelFunction.id_function_map[model_id] = func
    results = func(*list(_i.numpy() if isinstance(_i, torch.Tensor) else _i for _i in args), **kwargs)
    return tuple(
        [torch.from_numpy(_o) for _o in results]) if isinstance(results, tuple) else torch.from_numpy(results)

@torch.jit.ignore
def invoke_onnx_model1(model_id: int, arg0):
    return _invoke_onnx_model(model_id, arg0)

@torch.jit.ignore
def invoke_onnx_model2(model_id: int, arg0, arg1):
    return _invoke_onnx_model(model_id, arg0, arg1)

@torch.jit.ignore
def invoke_onnx_model3(model_id: int, arg0, arg1, arg2):
    return _invoke_onnx_model(model_id, arg0, arg1, arg2)

class _OnnxTracedFunction(CustomFunction):
    @classmethod
    def forward(cls, ctx: Any, *args: Any, **kwargs: Any) -> Any:
        return _invoke_onnx_model(args[0].item(), *args[1:], **kwargs)

    @classmethod
    def symbolic(cls, g, *args):
        ret = g.op('ai.onnx.contrib::_ModelFunctionCall', *args)
        model_id = torch.onnx.symbolic_helper._maybe_get_scalar(args[0])  # noqa
        if not model_id:
            return ret

        func = _OnnxModelFunction.id_function_map.get(model_id.item(), None)
        if not func or len(func.outputs) <= 1:
            return ret

        outputs = [ret]
        for _ in range(len(func.outputs) - 1):
            outputs.append(ret.node().addOutput())

        return tuple(outputs)

def create_model_function(model_or_path):
    _id = id(model_or_path)
    assert _id != 0, "internal error: the id of a Python object is 0."
    _OnnxModelFunction.id_object_map[_id] = model_or_path
    return _id

def get_id_models():
    return _OnnxModelFunction.id_object_map

class OnnxTracedModelFunction:
    def __init__(self, onnx_model):
        self.func_id = create_model_function(onnx_model)

    def __call__(self, *args, **kwargs):
        return _OnnxTracedFunction.apply(torch.tensor(self.func_id), *args, **kwargs)

class _OnnxModelModule(torch.nn.Module):
    def __init__(self, mdl):
        super(_OnnxModelModule, self).__init__()
        self.function = OnnxTracedModelFunction(mdl)

    def forward(self, *args):
        return self.function(*args)

def _symbolic_pythonop(g: torch._C.Graph, n: torch._C.Node, *args, **kwargs):
    name = kwargs["name"]
    if name.startswith(invoke_onnx_model1.__name__[:-1]):
        # NB: if you want to get the value of the first argument, i.e. the model id,
        # you can get it by torch.onnx.symbolic_helper._maybe_get_scalar(args[0]).item()
        ret = g.op("ai.onnx.contrib::_ModelFunctionCall", *args)
    else:
        # Logs a warning and returns None
        import warnings
        return warnings.warn("prim::PythonOp", "unknown node kind: " + name)
    # Copy type and shape from original node.
    ret.setType(n.output().type())
    return ret

if LooseVersion(torch.__version__) >= LooseVersion("1.11"):
    register_custom_op_symbolic("prim::PythonOp", _symbolic_pythonop, 1)

class SequentialProcessingModule(ProcessingTracedModule):
    def __init__(self, *models):
        super(SequentialProcessingModule, self).__init__()
        self.model_list = torch.nn.ModuleList()
        for mdl_ in models:
            if isinstance(mdl_, onnx.ModelProto):
                self.model_list.append(_OnnxModelModule(mdl_))
            elif is_processing_module(mdl_):
                self.model_list.append(mdl_)
            else:
                assert callable(mdl_), "the model type is not recognizable."
                self.model_list.append(ProcessingTracedModule(mdl_))

    def forward(self, *args):
        outputs = args
        with torch.no_grad():
            for idx_, mdl_ in enumerate(self.model_list):
                if not isinstance(outputs, tuple):
                    outputs = (outputs,)
                outputs = mdl_(*outputs)

        return outputs

    def export(self, *args, **kwargs):
        prefix_m = None
        core_m = self
        raw_input_flag = any(_is_string_type(x_) for x_ in args)
        if raw_input_flag:
            # NB: torch.onnx.export doesn't support exporting a module accepting string type input,
            # So, in this case, the module will be separated into two parts to use the customized export.
            m0 = self.model_list[0]
            new_args = m0(*args)
            if not isinstance(new_args, tuple):
                new_args = (new_args, )
            prefix_m = m0.export(*args, **kwargs)
            args = new_args
            core_m = SequentialProcessingModule(*self.model_list[1:])
        if prefix_m is None:
            return super().export(*args, **kwargs)
        else:
            oxml = core_m.export(*args, **kwargs)
            model = ONNXModelUtils.join_models(prefix_m, oxml)

            # Rename the input/output node names if the user has provided any substitutions!
            # Ref: https://github.com/onnx/onnx/issues/2052
            # Known issue: This logic doesn't deal with subgraphs.
            if (('input_names' in kwargs) or ('output_names' in kwargs)) and \
              (kwargs['input_names'] or kwargs['output_names']):
                swaps = {}
                if 'input_names' in kwargs and kwargs['input_names']:
                    assert len(model.graph.input) == len(kwargs['input_names']), \
                      "Expecting {} input names but got {}".format(
                        len(model.graph.input), len(kwargs['input_names']))
                    for n, new_name in zip(model.graph.input, kwargs['input_names']):
                        swaps[n.name] = new_name
                        n.name = new_name

                if 'output_names' in kwargs and kwargs['output_names']:
                    assert len(model.graph.output) == len(kwargs['output_names']), \
                      "Expecting {} output names but got {}".format(
                        len(model.graph.output), len(kwargs['output_names']))
                    for n, new_name in zip(model.graph.output, kwargs['output_names']):
                        swaps[n.name] = new_name
                        n.name = new_name

                if swaps:
                    for n in model.graph.node:
                        for j in range(len(n.input)):
                            n.input[j] = swaps.get(n.input[j], n.input[j])

                        for j in range(len(n.output)):
                            n.output[j] = swaps.get(n.output[j], n.output[j])

                    for n in model.graph.initializer:
                        n.name = swaps.get(n.name, n.name)

            return model


text:
export const REQUEST_PLUGINS = 'REQUEST_PLUGINS'
export const RECEIVE_PLUGINS = 'RECEIVE_PLUGINS'


text:
#ifndef SPIRE_RENDER_BMFONT_HPP
#define SPIRE_RENDER_BMFONT_HPP

#include <es-log/trace-log.h>
#include <cstdint>
#include <cstddef>
#include <vector>
#include <string>
#include <map>
#include <spire/scishare.h>

// Forward declare a class that we need for parsing BMFont files.
namespace spire {
class BSerialize;
}

namespace ren {

/// \note The texture names are stored in the page block.

/// Loads a BMFont file from memory and stores relevant BMFont blocks.
class SCISHARE BMFont
{
public:
  BMFont();
  virtual ~BMFont();

  void clear();

  void loadFromBuffer(uint8_t* buffer, size_t bytesRead);

  /// Returns the text width in pixels.
  int32_t getASCIITextWidth(const char* text) const;

  /// Returns the line height in pixels.
  int32_t getLineHeight() const;

  /// Returns the kerning pair adjustment for the two characters given,
  /// in pixels.
  int32_t getKerningAdjustment(uint32_t firstCharID, uint32_t secondCharID) const;

  // Block types that can be loaded from BMFont file.
  enum BLOCK_TYPES
  {
    BLOCK_INFO    = 1,
    BLOCK_COMMON  = 2,
    BLOCK_PAGES   = 3,
    BLOCK_CHARS   = 4,
    BLOCK_KERN    = 5
  };

  /// The following structures represent the data as loaded in from a BMFont
  /// file.
  struct InfoBlock
  {
    int16_t   fontSize;
    uint8_t   bitField;
    uint8_t   charSet;
    uint16_t  stretchH;
    uint8_t   aa;
    uint8_t   paddingUp;
    uint8_t   paddingRight;
    uint8_t   paddingDown;
    uint8_t   paddingLeft;
    uint8_t   spacingHoriz;
    uint8_t   spacingVert;
    uint8_t   outline;
    std::string fontName;
  };

  struct CommonBlock
  {
    uint16_t lineHeight;  ///< Distance, in pixels, between each line of text.
    uint16_t base;        ///< The number of pixels from the absolute top of the line to the base
                          ///< of the characters. http://www.angelcode.com/products/bmfont/doc/render_text.html
    uint16_t scaleW;      ///< Width of the texture. Normally used to scale x pos of the char image.
    uint16_t scaleH;      ///< Height of the texture. Normalled used to scale y pos of the char image.
    uint16_t pages;       ///< Number of texture pages included in the font.
    uint8_t bitField;     ///< Contains the packed bit. If packed is set, then monochrome characters have
                          ///< been packed into each of the texture channels. In this case alphaChannel
                          ///< describes what is stored in each channel.

    /// Set to 0 if the channel holds the glyph data, 1 if it holds the outline,
    /// 2 if it holds the outline and the glyph, 3 if it is set to zero, 4 if it
    /// is set to one.
    /// @{
    uint8_t alphaChannel;
    uint8_t redChannel;
    uint8_t greenChannel;
    uint8_t blueChannel;
    /// @}
  };

  struct PageBlock
  {
    // The id of each page is the zero-based index of the string name.
    // So it is the index into this page block.
    std::vector<std::string> pages;
  };

  // Character info struct. Read from the BLOCK_CHARS.
  struct CharInfo
  {
    uint32_t id;        ///< Character id (unicode id).

    /// For the absolute meaning of all of these values, please consult
    /// http://www.angelcode.com/products/bmfont/doc/render_text.html.
    /// @{
    uint16_t x;         ///< The left position of the character image in the texture.
    uint16_t y;         ///< The top position of the character image in the texture.
    uint16_t width;     ///< The width of the character image in the texture.
    uint16_t height;    ///< The height of the character image in the texture.
    int16_t xoffset;    ///< How much the current cursor position should be offset.
    int16_t yoffset;
    int16_t xadvance;   ///< How much the current position should be advanced after drawing the character.
    /// @}
    uint8_t page;
    uint8_t channel;    ///< Texture channel where the character is found.
  };

  // Kerning information struct. The multipmap is based off of the first
  // element in the kern info structure.
  struct KernInfo
  {
    uint32_t firstID;
    uint32_t secondID;
    int16_t amount;
  };

  /// Returns the character info for the given character ID. Returns nullptr
  /// if the character ID is not present in the system.
  const CharInfo* getCharInfo(uint32_t charID) const;

  // Block accessors.
  const InfoBlock&    getInfoBlock()    const {return mInfoBlock;}
  const CommonBlock&  getCommonBlock()  const {return mCommonBlock;}
  const PageBlock&    getPageBlock()    const {return mPageBlock;}
  const std::map<uint32_t, CharInfo>&       getCharMap()  const {return mCharMap;}
  const std::multimap<uint32_t, KernInfo>&  getKernMap()  const {return mKernMultiMap;}

private:

  /// Various functions to read blocks inside of the BMFont file.
  /// @{
  void readInfoBlock(spire::BSerialize& s);
  void readCommonBlock(spire::BSerialize& s);
  void readPageBlock(spire::BSerialize& s, size_t blockSize);
  void readCharBlock(spire::BSerialize& s, size_t blockSize);
  void readKernBlock(spire::BSerialize& s, size_t blockSize);
  /// @}

  InfoBlock   mInfoBlock;
  CommonBlock mCommonBlock;
  PageBlock   mPageBlock;

  // Since the only time we will be accessing these structures is when we
  // are constructing the text to be displayed, cache locality doesn't
  // matter as much. We save more memory by skipping over the characters that
  // aren't represented in the 0 - 255 range. Additionally, we can represent
  // unicode characters which are much larger in range.
  std::map<uint32_t, CharInfo>      mCharMap;
  std::multimap<uint32_t, KernInfo> mKernMultiMap;
};

} // namespace ren

#endif


text:
package com.neustar.ultraservice.schema.v01;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for PrioritizedRecordsList complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="PrioritizedRecordsList">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="prioritizedRecord" type="{http://schema.ultraservice.neustar.com/v01/}AlertPrioritizedRecord" maxOccurs="unbounded"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PrioritizedRecordsList", propOrder = {
    "prioritizedRecord"
})
public class PrioritizedRecordsList {

    @XmlElement(required = true)
    protected List<AlertPrioritizedRecord> prioritizedRecord;

    /**
     * Gets the value of the prioritizedRecord property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the prioritizedRecord property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getPrioritizedRecord().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link AlertPrioritizedRecord }
     *
     *
     */
    public List<AlertPrioritizedRecord> getPrioritizedRecord() {
        if (prioritizedRecord == null) {
            prioritizedRecord = new ArrayList<AlertPrioritizedRecord>();
        }
        return this.prioritizedRecord;
    }

}


text:
using Microsoft.AspNetCore.Components.RenderTree;
using Microsoft.Extensions.Logging;

namespace Microsoft.AspNetCore.Components.Infrastructure;

/// <summary>
/// Manages the persistent state of components in an application.
/// </summary>
public class ComponentStatePersistenceManager
{
    private bool _stateIsPersisted;
    private readonly List<Func<Task>> _pauseCallbacks = new();
    private readonly Dictionary<string, byte[]> _currentState = new(StringComparer.Ordinal);
    private readonly ILogger<ComponentStatePersistenceManager> _logger;

    /// <summary>
    /// Initializes a new instance of <see cref="ComponentStatePersistenceManager"/>.
    /// </summary>
    public ComponentStatePersistenceManager(ILogger<ComponentStatePersistenceManager> logger)
    {
        State = new PersistentComponentState(_currentState, _pauseCallbacks);
        _logger = logger;
    }

    /// <summary>
    /// Gets the <see cref="ComponentStatePersistenceManager"/> associated with the <see cref="ComponentStatePersistenceManager"/>.
    /// </summary>
    public PersistentComponentState State { get; }

    /// <summary>
    /// Restores the component application state from the given <see cref="IPersistentComponentStateStore"/>.
    /// </summary>
    /// <param name="store">The <see cref="IPersistentComponentStateStore"/> to restore the application state from.</param>
    /// <returns>A <see cref="Task"/> that will complete when the state has been restored.</returns>
    public async Task RestoreStateAsync(IPersistentComponentStateStore store)
    {
        var data = await store.GetPersistedStateAsync();
        State.InitializeExistingState(data);
    }

    /// <summary>
    /// Persists the component application state into the given <see cref="IPersistentComponentStateStore"/>.
    /// </summary>
    /// <param name="store">The <see cref="IPersistentComponentStateStore"/> to restore the application state from.</param>
    /// <param name="renderer">The <see cref="Renderer"/> that components are being rendered.</param>
    /// <returns>A <see cref="Task"/> that will complete when the state has been restored.</returns>
    public Task PersistStateAsync(IPersistentComponentStateStore store, Renderer renderer)
    {
        if (_stateIsPersisted)
        {
            throw new InvalidOperationException("State already persisted.");
        }

        _stateIsPersisted = true;

        return renderer.Dispatcher.InvokeAsync(PauseAndPersistState);

        async Task PauseAndPersistState()
        {
            State.PersistingState = true;
            await PauseAsync();
            State.PersistingState = false;

            await store.PersistStateAsync(_currentState);
        }
    }

    internal Task PauseAsync()
    {
        List<Task>? pendingCallbackTasks = null;

        for (var i = 0; i < _pauseCallbacks.Count; i++)
        {
            var callback = _pauseCallbacks[i];
            var result = ExecuteCallback(callback, _logger);
            if (!result.IsCompletedSuccessfully)
            {
                pendingCallbackTasks ??= new();
                pendingCallbackTasks.Add(result);
            }
        }

        if (pendingCallbackTasks != null)
        {
            return Task.WhenAll(pendingCallbackTasks);
        }
        else
        {
            return Task.CompletedTask;
        }

        static Task ExecuteCallback(Func<Task> callback, ILogger<ComponentStatePersistenceManager> logger)
        {
            try
            {
                var current = callback();
                if (current.IsCompletedSuccessfully)
                {
                    return current;
                }
                else
                {
                    return Awaited(current, logger);
                }
            }
            catch (Exception ex)
            {
                logger.LogError(new EventId(1000, "PersistenceCallbackError"), ex, "There was an error executing a callback while pausing the application.");
                return Task.CompletedTask;
            }

            static async Task Awaited(Task task, ILogger<ComponentStatePersistenceManager> logger)
            {
                try
                {
                    await task;
                }
                catch (Exception ex)
                {
                    logger.LogError(new EventId(1000, "PersistenceCallbackError"), ex, "There was an error executing a callback while pausing the application.");
                    return;
                }
            }
        }
    }
}


text:
title: "Worker Model patterns"
weight: 3
---

In CDS you can use worker model on any platform, distribution and arch you want. To permit that you need to indicate what will be executed on the worker vm or image before the execution of the worker binary itself. For example, before launching the worker binary you need to download that binary with curl or wget or anything else, depends on which OS you are.

To not copy/paste each time the same script for each worker model on the same OS and also to give the ability for a no CDS administrator to create their own worker model you can create worker model patterns. A pattern is only created by administrator and is linked to a worker model type (OpenStack, Docker, vSphere, ...). For example you can have different patterns for type vSphere and for different OS like Windows, Linux, macOS, ...

CDS give you some variables to use in your patterns: [click here]({{< relref "/docs/concepts/worker-model/variables.md" >}}).

To create a pattern in the UI (only for CDS administrator) go to the navbar admin menu:

![Worker Model Patterns menu](/images/worker_model_patterns_menu.png)

And then you can add/create/delete patterns with this kind of view:

![Worker Model Patterns menu](/images/worker_model_patterns_add.png)


text:
package org.sagebionetworks.bridge.services;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.sagebionetworks.bridge.TestConstants.TEST_STUDY;

import java.util.List;

import javax.annotation.Resource;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.sagebionetworks.bridge.BridgeUtils;
import org.sagebionetworks.bridge.TestUtils;
import org.sagebionetworks.bridge.dynamodb.DynamoStudy;
import org.sagebionetworks.bridge.json.BridgeObjectMapper;
import org.sagebionetworks.bridge.models.schedules.ABTestScheduleStrategy;
import org.sagebionetworks.bridge.models.schedules.Activity;
import org.sagebionetworks.bridge.models.schedules.Schedule;
import org.sagebionetworks.bridge.models.schedules.ABTestGroup;
import org.sagebionetworks.bridge.models.schedules.SchedulePlan;
import org.sagebionetworks.bridge.models.studies.Study;
import org.sagebionetworks.bridge.models.studies.StudyIdentifierImpl;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

@ContextConfiguration("classpath:test-context.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class SchedulePlanServiceTest {

    @Resource
    SchedulePlanService schedulePlanService;

    private Study study;

    @Before
    public void before() {
        study = new DynamoStudy();
        study.setIdentifier("test-study");
        study.setTaskIdentifiers(Sets.newHashSet("AAA", "BBB", "CCC"));
    }

    @Test
    public void canSaveSchedulePlan() throws Exception {
        SchedulePlan savedPlan = null;
        try {
            SchedulePlan plan = TestUtils.getABTestSchedulePlan(study);
            plan.setGuid(null);
            plan.setVersion(null);
            savedPlan = schedulePlanService.createSchedulePlan(study, plan);
            assertNotNull(savedPlan.getGuid());
            assertNotNull(savedPlan.getVersion());
        } finally {
            schedulePlanService.deleteSchedulePlanPermanently(new StudyIdentifierImpl(savedPlan.getStudyKey()), savedPlan.getGuid());
        }
    }

    @Test
    public void canRoundTripSchedulePlan() throws Exception {
        SchedulePlan plan = TestUtils.getABTestSchedulePlan(TEST_STUDY);

        String json = BridgeObjectMapper.get().writeValueAsString(plan);

        SchedulePlan retrieved = BridgeObjectMapper.get().readValue(json, SchedulePlan.class);
        assertEquals("Test A/B Schedule", retrieved.getLabel());

        // Walk down the object graph and verify that data is there.
        ABTestScheduleStrategy strategy = (ABTestScheduleStrategy)retrieved.getStrategy();
        ABTestGroup group = strategy.getScheduleGroups().get(0);
        Activity activity = group.getSchedule().getActivities().get(0);
        assertEquals("Do AAA task", activity.getLabel());
    }

    // Two behaviors here: an activity with no GUID will get one, and an activity with an
    // unknown GUID (not currently saved) will also be assigned a GUID, to prevent spoofing
    // or just accidentally breaking the system by assigning a non-unique GUID.
    @Test
    public void updateOfSchedulePlanSetsGuids() {
        SchedulePlan plan = TestUtils.getSimpleSchedulePlan(TEST_STUDY);
        plan.setLabel(plan.getLabel() + " more");

        List<Activity> activities = Lists.newArrayList(taskActivity("AAA"), taskActivity("BBB"));
        getSchedule(plan).setActivities(activities);

        SchedulePlan asSaved = schedulePlanService.createSchedulePlan(study, plan);

        // Existing activity, change the GUID to be invalid
        Activity act2 = getSchedule(asSaved).getActivities().get(1);
        act2 = new Activity.Builder().withActivity(act2).withGuid("BAD_GUID").build();

        // New activity, has no GUID
        Activity act3 = new Activity.Builder().withActivity(taskActivity("CCC")).withGuid(null).build();

        // Add these back to the collection;
        activities.set(1, act2);
        activities.add(act3);

        SchedulePlan asUpdated = schedulePlanService.updateSchedulePlan(study, plan);

        assertNotEquals("BAD_GUID", getSchedule(asUpdated).getActivities().get(1).getGuid());
        assertNotNull(getSchedule(asUpdated).getActivities().get(2).getGuid());

        schedulePlanService.deleteSchedulePlanPermanently(study, asUpdated.getGuid());
    }

    private Activity taskActivity(String identifier) {
        return new Activity.Builder().withGuid(BridgeUtils.generateGuid()).withLabel("Activity"+identifier)
                .withTask(identifier).build();
    }

    private Schedule getSchedule(SchedulePlan plan) {
        return plan.getStrategy().getAllPossibleSchedules().get(0);
    }

}


text:
dbm.registerClass("dbm.flow.nodes.curves.CreateWedgeInBoxCurveNode", "dbm.core.FlowBaseObject", function(objectFunctions, staticFunctions, ClassReference) {
	//console.log("dbm.flow.nodes.curves.CreateWedgeInBoxCurveNode");

	//Self reference
	var CreateWedgeInBoxCurveNode = dbm.importClass("dbm.flow.nodes.curves.CreateWedgeInBoxCurveNode");

	//Error report

	//Dependencies
	var Point = dbm.importClass("dbm.core.data.points.Point");

	//Utils
	var LineIntersection2d = dbm.importClass("dbm.utils.math.LineIntersection2d");

	//Constants

	/**
	 * Constructor
	 */
	objectFunctions._init = function() {
		//console.log("dbm.flow.nodes.curves.CreateWedgeInBoxCurveNode::_init");

		this.superCall();

		this._lineIntersection = (new LineIntersection2d()).init();

		this._x = this.createProperty("x", 0);
		this._y = this.createProperty("y", 0);
		this._pivotX = this.createProperty("pivotX", 0.5);
		this._pivotY = this.createProperty("pivotY", 0.5);
		this._startAngle = this.createProperty("startAngle", 0);
		this._endAngle = this.createProperty("endAngle", 0);
		this._width = this.createProperty("width", 1);
		this._height = this.createProperty("height", 1);
		this._outputCurve = this.createProperty("outputCurve", null).setAlwaysUpdateFlow(true);

		this.createUpdateFunction("default", this._update, [this._x, this._y, this._pivotX, this._pivotY, this._startAngle, this._endAngle, this._width, this._height], [this._outputCurve]);

		return this;
	};

	objectFunctions._update = function(aFlowUpdateNumber) {
		//console.log("dbm.flow.nodes.curves.CreateWedgeInBoxCurveNode::_update");
		//console.log(this);

		var x = this._x.getValueWithoutFlow();
		var y = this._y.getValueWithoutFlow();
		var pivotX = this._pivotX.getValueWithoutFlow();
		var pivotY = this._pivotY.getValueWithoutFlow();
		var width = this._width.getValueWithoutFlow();
		var height = this._height.getValueWithoutFlow();

		var startAngle = this._startAngle.getValueWithoutFlow();
		var endAngle = this._endAngle.getValueWithoutFlow();

		var centerPointX = x+pivotX*width;
		var centerPointY = y+pivotY*height;

		var returnCurve = dbm.singletons.dbmCurveCreator.createRectangle(x, y, width, height);

		var centerPoint = Point.create(centerPointX, centerPointY);

		var startVector = Point.create(Math.cos(startAngle), Math.sin(startAngle));
		var endVector = Point.create(Math.cos(endAngle), Math.sin(endAngle));
		var tempVector2 = Point.create(0, 0);

		var startIndex = -1;
		var endIndex = -1;
		var startEdgePoint = Point.create();
		var endEdgePoint = Point.create();

		var currentArray = returnCurve.pointsArray;
		var currentArrayLength = currentArray.length-1;
		for(var i = 0; i < currentArrayLength; i++) { //MENOTE: last point is same as first point
			var currentPoint = currentArray[i];
			var nextPoint = currentArray[i+1];
			tempVector2.x = nextPoint.x-currentPoint.x;
			tempVector2.y = nextPoint.y-currentPoint.y;

			if(startIndex === -1) {
				var theResult = this._lineIntersection.findLineIntersection(centerPoint, startVector, currentPoint, tempVector2);

				if(theResult && this._lineIntersection.parameter2 >= 0 && this._lineIntersection.parameter2 <= 1 && this._lineIntersection.parameter1 >= 0) {
					startIndex = i;
					startEdgePoint.x = this._lineIntersection.x;
					startEdgePoint.y = this._lineIntersection.y;
				}
			}
			if(endIndex === -1) {
				var theResult = this._lineIntersection.findLineIntersection(centerPoint, endVector, currentPoint, tempVector2);

				if(theResult && this._lineIntersection.parameter2 >= 0 && this._lineIntersection.parameter2 <= 1 && this._lineIntersection.parameter1 >= 0) {
					endIndex = i;
					endEdgePoint.x = this._lineIntersection.x;
					endEdgePoint.y = this._lineIntersection.y;
				}
			}
		}

		var newPointsArray = new Array();
		newPointsArray.push(centerPoint);
		newPointsArray.push(startEdgePoint);
		if(startAngle > endAngle) {
			if(startIndex < endIndex) {
				startIndex += 4;
			}
			var currentArray = returnCurve.pointsArray;
			for(var i = startIndex; i > endIndex; i--) {
				newPointsArray.push(currentArray[i%4]);
			}
		}
		else if(startAngle < endAngle) {
			if(startIndex > endIndex) {
				endIndex += 4;
			}
			var currentArray = returnCurve.pointsArray;
			for(var i = startIndex+1; i <= endIndex; i++) {
				newPointsArray.push(currentArray[i%4]);
			}
		}

		newPointsArray.push(endEdgePoint);
		newPointsArray.push(centerPoint.duplicate());

		returnCurve.pointsArray = newPointsArray;

		this._outputCurve.setValueWithFlow(returnCurve, aFlowUpdateNumber);
	};

	objectFunctions.setAllReferencesToNull = function() {

		this._x = null;
		this._y = null;
		this._pivotX = null;
		this._pivotY = null;
		this._startAngle = null;
		this._endAngle = null;
		this._width = null;
		this._height = null;
		this._outputCurve = null;

		this.superCall();
	};

	staticFunctions.create = function(aX, aY, aPivotX, aPivotY, aStartAngle, aEndAngle, aWidth, aHeight) {
		//console.log("dbm.flow.nodes.curves.CreateWedgeInBoxCurveNode::create");
		//console.log(aInputPoints, aIsRound);
		var newNode = (new ClassReference()).init();
		newNode.setPropertyInputWithoutNull("x", aX);
		newNode.setPropertyInputWithoutNull("y", aY);
		newNode.setPropertyInputWithoutNull("pivotX", aPivotY);
		newNode.setPropertyInputWithoutNull("pivotY", aPivotY);
		newNode.setPropertyInputWithoutNull("startAngle", aStartAngle);
		newNode.setPropertyInputWithoutNull("endAngle", aEndAngle);
		newNode.setPropertyInputWithoutNull("width", aWidth);
		newNode.setPropertyInputWithoutNull("height", aHeight);
		return newNode;
	};
});


text:
/**
 * @file aws_auth_v4_test.cc
 * @brief Unit tests for functions implementing S3 auth version 4
 */

#include <string.h>
#include <openssl/hmac.h>   /* EVP_MAX_MD_SIZE */
#define CATCH_CONFIG_MAIN   /* include main function */
#include <catch.hpp>        /* catch unit-test framework */
#include "../aws_auth_v4.h" /* S3 auth v4 utility */

/* uriEncode() ***************************************************************************************************************** */

TEST_CASE("uriEncode(): encode empty input", "[AWS][auth][utility]")
{
  String in("");
  String encoded = uriEncode(in, /* isObjectName */ false);
  CHECK(0 == encoded.length()); /* 0 encoded because of the invalid input */
}

TEST_CASE("uriEncode(): encode unreserved chars", "[s3_auth]")
{
  const String in = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                    "abcdefghijklmnopqrstuvwxyz"
                    "0123456789"
                    "-._~";
  String encoded = uriEncode(in, /* isObjectName */ false);

  CHECK(in.length() == encoded.length());
  CHECK_FALSE(encoded.compare("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                              "abcdefghijklmnopqrstuvwxyz"
                              "0123456789"
                              "-._~"));
}

TEST_CASE("uriEncode(): encode reserved chars in a name which is not object name", "[AWS][auth][utility]")
{
  const String in = " /!\"#$%&'()*+,:;<=>?@[\\]^`{|}"; /* some printable but reserved chars */
  String encoded  = uriEncode(in, /* isObjectName */ false);

  CHECK(3 * in.length() == encoded.length()); /* size of "%NN" = 3 */
  CHECK_FALSE(encoded.compare("%20%2F%21%22%23%24%25%26%27%28%29%2A%2B%2C%3A%3B%3C%3D%3E%3F%40%5B%5C%5D%5E%60%7B%7C%7D"));
}

TEST_CASE("uriEncode(): encode reserved chars in an object name", "[AWS][auth][utility]")
{
  const String in = " /!\"#$%&'()*+,:;<=>?@[\\]^`{|}"; /* some printable but reserved chars */
  String encoded  = uriEncode(in, /* isObjectName */ true);

  CHECK(3 * in.length() - 2 == encoded.length()); /* size of "%NN" = 3, '/' is not encoded */
  CHECK_FALSE(encoded.compare("%20/%21%22%23%24%25%26%27%28%29%2A%2B%2C%3A%3B%3C%3D%3E%3F%40%5B%5C%5D%5E%60%7B%7C%7D"));
}

TEST_CASE("uriDecode(): decode empty input", "[AWS][auth][utility]")
{
  String encoded("");
  String decoded = uriDecode(encoded);
  CHECK(0 == decoded.length()); /* 0 encoded because of the invalid input */
}

TEST_CASE("uriDecode(): decode unreserved chars", "[AWS][auth][utility]")
{
  const String encoded = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                         "abcdefghijklmnopqrstuvwxyz"
                         "0123456789"
                         "-._~";
  String decoded = uriDecode(encoded);

  CHECK(encoded.length() == encoded.length());
  CHECK_FALSE(decoded.compare("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                              "abcdefghijklmnopqrstuvwxyz"
                              "0123456789"
                              "-._~"));
}

TEST_CASE("uriDecode(): decode reserved chars", "[AWS][auth][utility]")
{
  const String encoded =
    "%20%2F%21%22%23%24%25%26%27%28%29%2A%2B%2C%3A%3B%3C%3D%3E%3F%40%5B%5C%5D%5E%60%7B%7C%7D"; /* some printable but
                                                                                reserved chars */
  String decoded = uriDecode(encoded);

  CHECK(3 * decoded.length() == encoded.length()); /* size of "%NN" = 3 */
  CHECK_FALSE(decoded.compare(" /!\"#$%&'()*+,:;<=>?@[\\]^`{|}"));
}

/* base16Encode() ************************************************************************************************************** */

TEST_CASE("base16Encode(): base16 encode empty string", "[utility]")
{
  const char *in = nullptr;
  size_t inLen   = 0;
  String encoded = base16Encode(in, inLen);

  CHECK(0 == encoded.length());
}

TEST_CASE("base16Encode(): base16 encode RFC4648 test vectors", "[utility]")
{
  /* use the test vectors from RFC4648: https://tools.ietf.org/html/rfc4648#section-10 (just convert to lower case) */
  const char *bench[] = {"",       "",     "f",        "66",    "fo",         "666f",   "foo",
                         "666f6f", "foob", "666f6f62", "fooba", "666f6f6261", "foobar", "666f6f626172"};

  for (size_t i = 0; i < sizeof(bench) / sizeof(char *); i += 2) {
    const char *in = bench[i];
    size_t inLen   = strlen(in);
    String encoded = base16Encode(in, inLen);

    CHECK(inLen * 2 == encoded.length());
    CHECK_FALSE(encoded.compare(bench[i + 1]));
  }
}

/* trimWhiteSpaces() ******************************************************************************************************** */

TEST_CASE("trimWhiteSpaces(): trim invalid arguments, check pointers", "[utility]")
{
  const char *in = nullptr;
  size_t inLen   = 0;
  size_t outLen  = 0;

  const char *start = trimWhiteSpaces(in, inLen, outLen);

  CHECK(in == start);
}

TEST_CASE("trimWhiteSpaces(): trim empty input, check pointers", "[utility]")
{
  const char *in = "";
  size_t inLen   = 0;
  size_t outLen  = 0;

  const char *start = trimWhiteSpaces(in, inLen, outLen);

  CHECK(in == start);
}

TEST_CASE("trimWhiteSpaces(): trim nothing to trim, check pointers", "[utility]")
{
  const char in[] = "Important Message";
  size_t inLen    = strlen(in);
  size_t newLen   = 0;

  const char *start = trimWhiteSpaces(in, inLen, newLen);

  CHECK(in == start);
  CHECK(inLen == newLen);
}

TEST_CASE("trimWhiteSpaces(): trim beginning, check pointers", "[utility]")
{
  const char in[] = " \t\nImportant Message";
  size_t inLen    = strlen(in);
  size_t newLen   = 0;

  const char *start = trimWhiteSpaces(in, inLen, newLen);

  CHECK(in + 3 == start);
  CHECK(inLen - 3 == newLen);
}

TEST_CASE("trimWhiteSpaces(): trim end, check pointers", "[utility]")
{
  const char in[] = "Important Message \t\n";
  size_t inLen    = strlen(in);
  size_t newLen   = 0;

  const char *start = trimWhiteSpaces(in, inLen, newLen);

  CHECK(in == start);
  CHECK(inLen - 3 == newLen);
}

TEST_CASE("trimWhiteSpaces(): trim both ends, check pointers", "[utility]")
{
  const char in[] = "\v\t\n Important Message \t\n";
  size_t inLen    = strlen(in);
  size_t newLen   = 0;

  const char *start = trimWhiteSpaces(in, inLen, newLen);

  CHECK(in + 4 == start);
  CHECK(inLen - 7 == newLen);
}

TEST_CASE("trimWhiteSpaces(): trim both, check string", "[utility]")
{
  String in      = "\v\t\n Important Message \t\n";
  String trimmed = trimWhiteSpaces(in);

  CHECK_FALSE(trimmed.compare("Important Message"));
  CHECK(in.length() - 7 == trimmed.length());
}

TEST_CASE("trimWhiteSpaces(): trim right, check string", "[utility]")
{
  String in      = "Important Message \t\n";
  String trimmed = trimWhiteSpaces(in);

  CHECK_FALSE(trimmed.compare("Important Message"));
  CHECK(in.length() - 3 == trimmed.length());
}

TEST_CASE("trimWhiteSpaces(): trim left, check string", "[utility]")
{
  String in      = "\v\t\n Important Message";
  String trimmed = trimWhiteSpaces(in);

  CHECK_FALSE(trimmed.compare("Important Message"));
  CHECK(in.length() - 4 == trimmed.length());
}

TEST_CASE("trimWhiteSpaces(): trim empty, check string", "[utility]")
{
  String in      = "\v\t\n  \t\n";
  String trimmed = trimWhiteSpaces(in);

  CHECK(trimmed.empty());
  CHECK(0 == trimmed.length());
}

/* AWS Regions ***************************************************************************************************** */

TEST_CASE("AWSRegions: get region empty input", "[AWS][auth][utility]")
{
  const char *host = "";
  String s         = getRegion(defaultDefaultRegionMap, host, strlen(host));
  CHECK_FALSE(s.compare("us-east-1"));
}

TEST_CASE("AWSRegions: get region by providing no bucket name", "[AWS][auth][utility]")
{
  const char *host = "s3.eu-west-2.amazonaws.com";
  String s         = getRegion(defaultDefaultRegionMap, host, strlen(host));
  CHECK_FALSE(s.compare("eu-west-2"));
}

TEST_CASE("AWSRegions: get region by providing bucket name having single label", "[AWS][auth][utility]")
{
  const char *host = "label1.label2.s3.eu-west-2.amazonaws.com";
  String s         = getRegion(defaultDefaultRegionMap, host, strlen(host));
  CHECK_FALSE(s.compare("eu-west-2"));
}

TEST_CASE("AWSRegions: get region by providing bucket name having multiple labels", "[AWS][auth][utility]")
{
  const char *host = "label1.label2.s3.eu-west-2.amazonaws.com";
  String s         = getRegion(defaultDefaultRegionMap, host, strlen(host));
  CHECK_FALSE(s.compare("eu-west-2"));
}

TEST_CASE("AWSRegions: get region by providing bucket name having single label not matching any entry point",
          "[AWS][auth][utility]")
{
  const char *host = "THIS_NEVER_MATCHES.eu-west-2.amazonaws.com";
  String s         = getRegion(defaultDefaultRegionMap, host, strlen(host));
  CHECK_FALSE(s.compare("us-east-1"));
}

TEST_CASE("AWSRegions: get region by providing bucket name having multiple labels not matching any entry point",
          "[AWS][auth][utility]")
{
  const char *host = "label1.label2.THIS_NEVER_MATCHES.eu-west-2.amazonaws.com";
  String s         = getRegion(defaultDefaultRegionMap, host, strlen(host));
  CHECK_FALSE(s.compare("us-east-1"));
}

/* AWS spec tests/example ****************************************************************************************** */

/* Test from docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html
 * User id, secret and time */
const char *awsSecretAccessKey = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY";
const char *awsAccessKeyId     = "AKIAIOSFODNN7EXAMPLE";
const char *awsService         = "s3";

void
ValidateBench(TsInterface &api, bool signPayload, time_t *now, const char *bench[], const StringSet &includedHeaders,
              const StringSet &excludedHeaders)
{
  /* Test the main entry point for calculation of the Authorization header content */
  AwsAuthV4 util(api, now, signPayload, awsAccessKeyId, strlen(awsAccessKeyId), awsSecretAccessKey, strlen(awsSecretAccessKey),
                 awsService, strlen(awsService), includedHeaders, excludedHeaders, defaultDefaultRegionMap);
  String authorizationHeader = util.getAuthorizationHeader();
  CAPTURE(authorizationHeader);
  CHECK_FALSE(authorizationHeader.compare(bench[0]));

  /* Test payload hash */
  String payloadHash = util.getPayloadHash();
  CAPTURE(payloadHash);
  CHECK_FALSE(payloadHash.compare(bench[5]));

  /* Test the date time header content */
  size_t dateLen   = 0;
  const char *date = util.getDateTime(&dateLen);
  CAPTURE(String(date, dateLen));
  CHECK_FALSE(String(date, dateLen).compare(bench[2]));

  /* Now test particular test points to pinpoint problems easier in case of regression */

  /* test the canonization of the request */
  String signedHeaders;
  String canonicalReq = getCanonicalRequestSha256Hash(api, signPayload, includedHeaders, excludedHeaders, signedHeaders);
  CAPTURE(canonicalReq);
  CHECK_FALSE(canonicalReq.compare(bench[1]));
  CAPTURE(signedHeaders);
  CHECK_FALSE(signedHeaders.compare(bench[6]));

  /* Test the formating of the date and time */
  char dateTime[sizeof("20170428T010203Z")];
  size_t dateTimeLen = getIso8601Time(now, dateTime, sizeof(dateTime));
  CAPTURE(String(dateTime, dateTimeLen));
  CHECK_FALSE(String(dateTime, dateTimeLen).compare(bench[2]));

  /* Test the region name */
  int hostLen      = 0;
  const char *host = api.getHost(&hostLen);
  String awsRegion = getRegion(defaultDefaultRegionMap, host, hostLen);

  /* Test string to sign calculation */
  String stringToSign = getStringToSign(host, hostLen, dateTime, dateTimeLen, awsRegion.c_str(), awsRegion.length(), awsService,
                                        strlen(awsService), canonicalReq.c_str(), canonicalReq.length());
  CAPTURE(stringToSign);
  CHECK_FALSE(stringToSign.compare(bench[3]));

  /* Test the signature calculation */
  char signature[EVP_MAX_MD_SIZE];
  size_t signatureLen =
    getSignature(awsSecretAccessKey, strlen(awsSecretAccessKey), awsRegion.c_str(), awsRegion.length(), awsService,
                 strlen(awsService), dateTime, 8, stringToSign.c_str(), stringToSign.length(), signature, EVP_MAX_MD_SIZE);
  String base16Signature = base16Encode(signature, signatureLen);
  CAPTURE(base16Signature);
  CHECK_FALSE(base16Signature.compare(bench[4]));
}

/**
 * Test from docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html
 * Example: GET Object
 */
TEST_CASE("AWSAuthSpecByExample: GET Object", "[AWS][auth][SpecByExample]")
{
  time_t now = 1369353600; /* 5/24/2013 00:00:00 GMT */

  /* Define the HTTP request elements */
  MockTsInterface api;
  api._method.assign("GET");
  api._host.assign("examplebucket.s3.amazonaws.com");
  api._path.assign("test.txt");
  api._query.assign("");
  api._headers["Host"]                 = "examplebucket.s3.amazonaws.com";
  api._headers["Range"]                = "bytes=0-9";
  api._headers["x-amz-content-sha256"] = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
  api._headers["x-amz-date"]           = "20130524T000000Z";

  const char *bench[] = {
    /* Authorization Header */
    "AWS4-HMAC-SHA256 "
    "Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request,"
    "SignedHeaders=host;range;x-amz-content-sha256;x-amz-date,"
    "Signature=f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41",
    /* Canonical Request sha256 */
    "7344ae5b7ee6c3e7e6b0fe0640412a37625d1fbfff95c48bbb2dc43964946972",
    /* Date and time*/
    "20130524T000000Z",
    /* String to sign */
    "AWS4-HMAC-SHA256\n"
    "20130524T000000Z\n"
    "20130524/us-east-1/s3/aws4_request\n"
    "7344ae5b7ee6c3e7e6b0fe0640412a37625d1fbfff95c48bbb2dc43964946972",
    /* Signature */
    "f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41",
    /* Payload hash */
    "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
    /* Signed Headers */
    "host;range;x-amz-content-sha256;x-amz-date",
  };

  ValidateBench(api, /*signePayload */ true, &now, bench, defaultIncludeHeaders, defaultExcludeHeaders);
}

/**
 * Test from docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html
 * Example: GET Bucket Lifecycle
 */
TEST_CASE("AWSAuthSpecByExample: GET Bucket Lifecycle", "[AWS][auth][SpecByExample]")
{
  time_t now = 1369353600; /* 5/24/2013 00:00:00 GMT */

  /* Define the HTTP request elements */
  MockTsInterface api;
  api._method.assign("GET");
  api._host.assign("examplebucket.s3.amazonaws.com");
  api._path.assign("");
  api._query.assign("lifecycle");
  api._headers["Host"]                 = "examplebucket.s3.amazonaws.com";
  api._headers["x-amz-content-sha256"] = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
  api._headers["x-amz-date"]           = "20130524T000000Z";

  const char *bench[] = {
    /* Authorization Header */
    "AWS4-HMAC-SHA256 "
    "Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request,"
    "SignedHeaders=host;x-amz-content-sha256;x-amz-date,"
    "Signature=fea454ca298b7da1c68078a5d1bdbfbbe0d65c699e0f91ac7a200a0136783543",
    /* Canonical Request sha256 */
    "9766c798316ff2757b517bc739a67f6213b4ab36dd5da2f94eaebf79c77395ca",
    /* Date and time*/
    "20130524T000000Z",
    /* String to sign */
    "AWS4-HMAC-SHA256\n"
    "20130524T000000Z\n"
    "20130524/us-east-1/s3/aws4_request\n"
    "9766c798316ff2757b517bc739a67f6213b4ab36dd5da2f94eaebf79c77395ca",
    /* Signature */
    "fea454ca298b7da1c68078a5d1bdbfbbe0d65c699e0f91ac7a200a0136783543",
    /* Payload hash */
    "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
    /* Signed Headers */
    "host;x-amz-content-sha256;x-amz-date",
  };

  ValidateBench(api, /*signePayload */ true, &now, bench, defaultIncludeHeaders, defaultExcludeHeaders);
}

/**
 * Test from docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html
 * Example: Get Bucket (List Objects)
 */
TEST_CASE("AWSAuthSpecByExample: Get Bucket List Objects", "[AWS][auth][SpecByExample]")
{
  time_t now = 1369353600; /* 5/24/2013 00:00:00 GMT */

  /* Define the HTTP request elements */
  MockTsInterface api;
  api._method.assign("GET");
  api._host.assign("examplebucket.s3.amazonaws.com");
  api._path.assign("");
  api._query.assign("max-keys=2&prefix=J");
  api._headers["Host"]                 = "examplebucket.s3.amazonaws.com";
  api._headers["x-amz-content-sha256"] = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
  api._headers["x-amz-date"]           = "20130524T000000Z";

  const char *bench[] = {
    /* Authorization Header */
    "AWS4-HMAC-SHA256 "
    "Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request,"
    "SignedHeaders=host;x-amz-content-sha256;x-amz-date,"
    "Signature=34b48302e7b5fa45bde8084f4b7868a86f0a534bc59db6670ed5711ef69dc6f7",
    /* Canonical Request sha256 */
    "df57d21db20da04d7fa30298dd4488ba3a2b47ca3a489c74750e0f1e7df1b9b7",
    /* Date and time*/
    "20130524T000000Z",
    /* String to sign */
    "AWS4-HMAC-SHA256\n"
    "20130524T000000Z\n"
    "20130524/us-east-1/s3/aws4_request\n"
    "df57d21db20da04d7fa30298dd4488ba3a2b47ca3a489c74750e0f1e7df1b9b7",
    /* Signature */
    "34b48302e7b5fa45bde8084f4b7868a86f0a534bc59db6670ed5711ef69dc6f7",
    /* Payload hash */
    "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
    /* Signed Headers */
    "host;x-amz-content-sha256;x-amz-date",
  };

  ValidateBench(api, /*signePayload */ true, &now, bench, defaultIncludeHeaders, defaultExcludeHeaders);
}

/**
 * Test based on docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html
 * but this time don't sign the payload to test "UNSIGNED-PAYLOAD" feature.
 * Example: Get Bucket (List Objects)
 */
TEST_CASE("AWSAuthSpecByExample: GET Bucket List Objects, unsigned pay-load", "[AWS][auth][SpecByExample]")
{
  time_t now = 1369353600; /* 5/24/2013 00:00:00 GMT */

  /* Define the HTTP request elements */
  MockTsInterface api;
  api._method.assign("GET");
  api._host.assign("examplebucket.s3.amazonaws.com");
  api._path.assign("");
  api._query.assign("max-keys=2&prefix=J");
  api._headers["Host"]                 = "examplebucket.s3.amazonaws.com";
  api._headers["x-amz-content-sha256"] = "UNSIGNED-PAYLOAD";
  api._headers["x-amz-date"]           = "20130524T000000Z";

  const char *bench[] = {
    /* Authorization Header */
    "AWS4-HMAC-SHA256 "
    "Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request,"
    "SignedHeaders=host;x-amz-content-sha256;x-amz-date,"
    "Signature=b1a076428fa68c2c42202ee5a5718b8207f725e451e2157d6b1c393e01fc2e68",
    /* Canonical Request sha256 */
    "528623330c85041d6fb82795b6f8d5771825d3568b9f0bc1faa8a49e1f5f9cfc",
    /* Date and time*/
    "20130524T000000Z",
    /* String to sign */
    "AWS4-HMAC-SHA256\n"
    "20130524T000000Z\n"
    "20130524/us-east-1/s3/aws4_request\n"
    "528623330c85041d6fb82795b6f8d5771825d3568b9f0bc1faa8a49e1f5f9cfc",
    /* Signature */
    "b1a076428fa68c2c42202ee5a5718b8207f725e451e2157d6b1c393e01fc2e68",
    /* Payload hash */
    "UNSIGNED-PAYLOAD",
    /* Signed Headers */
    "host;x-amz-content-sha256;x-amz-date",
  };

  ValidateBench(api, /*signePayload */ false, &now, bench, defaultIncludeHeaders, defaultExcludeHeaders);
}

/**
 * Test based on docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html
 * but this time don't sign the payload to test "UNSIGNED-PAYLOAD" feature and
 * have extra headers to be excluded from the signature (internal and changing headers)
 * Example: Get Bucket (List Objects)
 */
TEST_CASE("AWSAuthSpecByExample: GET Bucket List Objects, unsigned pay-load, exclude internal and changing headers", "[AWS][auth]")
{
  time_t now = 1369353600; /* 5/24/2013 00:00:00 GMT */

  /* Define the HTTP request elements */
  MockTsInterface api;
  api._method.assign("GET");
  api._host.assign("examplebucket.s3.amazonaws.com");
  api._path.assign("");
  api._query.assign("max-keys=2&prefix=J");
  api._headers["Host"]                 = "examplebucket.s3.amazonaws.com";
  api._headers["x-amz-content-sha256"] = "UNSIGNED-PAYLOAD";
  api._headers["x-amz-date"]           = "20130524T000000Z";
  api._headers["@internal"]            = "internal value";
  api._headers["x-forwarded-for"]      = "192.168.7.1";
  api._headers["via"] = "http/1.1 tcp ipv4 ats_dev[7e67ac60-c204-450d-90be-a426dd3b569f] (ApacheTrafficServer/7.2.0)";

  const char *bench[] = {
    /* Authorization Header */
    "AWS4-HMAC-SHA256 "
    "Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request,"
    "SignedHeaders=host;x-amz-content-sha256;x-amz-date,"
    "Signature=b1a076428fa68c2c42202ee5a5718b8207f725e451e2157d6b1c393e01fc2e68",
    /* Canonical Request sha256 */
    "528623330c85041d6fb82795b6f8d5771825d3568b9f0bc1faa8a49e1f5f9cfc",
    /* Date and time*/
    "20130524T000000Z",
    /* String to sign */
    "AWS4-HMAC-SHA256\n"
    "20130524T000000Z\n"
    "20130524/us-east-1/s3/aws4_request\n"
    "528623330c85041d6fb82795b6f8d5771825d3568b9f0bc1faa8a49e1f5f9cfc",
    /* Signature */
    "b1a076428fa68c2c42202ee5a5718b8207f725e451e2157d6b1c393e01fc2e68",
    /* Payload hash */
    "UNSIGNED-PAYLOAD",
    /* Signed Headers */
    "host;x-amz-content-sha256;x-amz-date",
  };

  ValidateBench(api, /*signePayload */ false, &now, bench, defaultIncludeHeaders, defaultExcludeHeaders);
}

/**
 * Test based on docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html
 * but this time query param value is already encoded, it should not URI encode it twice
 * according to AWS real behavior undocumented in the specification.
 */
TEST_CASE("AWSAuthSpecByExample: GET Bucket List Objects, query param value already URI encoded", "[AWS][auth]")
{
  time_t now = 1369353600; /* 5/24/2013 00:00:00 GMT */

  /* Define the HTTP request elements */
  MockTsInterface api;
  api._method.assign("GET");
  api._host.assign("examplebucket.s3.amazonaws.com");
  api._path.assign("");
  api._query.assign("key=TEST==");
  api._headers["Host"]                 = "examplebucket.s3.amazonaws.com";
  api._headers["x-amz-content-sha256"] = "UNSIGNED-PAYLOAD";
  api._headers["x-amz-date"]           = "20130524T000000Z";

  const char *bench[] = {
    /* Authorization Header */
    "AWS4-HMAC-SHA256 "
    "Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request,"
    "SignedHeaders=host;x-amz-content-sha256;x-amz-date,"
    "Signature=60b410f6a0ffe09b91c2aef1f179945916b45ea215278e6b8f6cfb8d461e3706",
    /* Canonical Request sha256 */
    "1035b1d75dad9e94fa99fa6edc2cf7d489f38796109a132721621977737a41cc",
    /* Date and time*/
    "20130524T000000Z",
    /* String to sign */
    "AWS4-HMAC-SHA256\n"
    "20130524T000000Z\n"
    "20130524/us-east-1/s3/aws4_request\n"
    "1035b1d75dad9e94fa99fa6edc2cf7d489f38796109a132721621977737a41cc",
    /* Signature */
    "60b410f6a0ffe09b91c2aef1f179945916b45ea215278e6b8f6cfb8d461e3706",
    /* Payload hash */
    "UNSIGNED-PAYLOAD",
    /* Signed Headers */
    "host;x-amz-content-sha256;x-amz-date",
  };

  ValidateBench(api, /*signePayload */ false, &now, bench, defaultIncludeHeaders, defaultExcludeHeaders);

  /* Now make query param value encoded beforehand and expect the same result,
   * it should not URI encode it twice according to AWS real behavior undocumented in the specification.*/
  api._query.assign("key=TEST%3D%3D");
  ValidateBench(api, /*signePayload */ false, &now, bench, defaultIncludeHeaders, defaultExcludeHeaders);
}

/* Utility parameters related tests ******************************************************************************** */

void
ValidateBenchCanonicalRequest(TsInterface &api, bool signPayload, time_t *now, const char *bench[],
                              const StringSet &includedHeaders, const StringSet &excludedHeaders)
{
  /* Test the main entry point for calculation of the Authorization header content */
  AwsAuthV4 util(api, now, signPayload, awsAccessKeyId, strlen(awsAccessKeyId), awsSecretAccessKey, strlen(awsSecretAccessKey),
                 awsService, strlen(awsService), includedHeaders, excludedHeaders, defaultDefaultRegionMap);

  /* test the canonization of the request */
  String signedHeaders;
  String canonicalReq = getCanonicalRequestSha256Hash(api, signPayload, includedHeaders, excludedHeaders, signedHeaders);
  CHECK_FALSE(signedHeaders.compare(bench[0]));
  CHECK_FALSE(canonicalReq.compare(bench[1]));
}

TEST_CASE("S3AuthV4UtilParams: include all headers by default", "[AWS][auth][utility]")
{
  time_t now = 1369353600; /* 5/24/2013 00:00:00 GMT */

  /* Define the HTTP request elements */
  MockTsInterface api;
  api._method.assign("GET");
  api._host.assign("examplebucket.s3.amazonaws.com");
  api._path.assign("");
  api._query.assign("max-keys=2&prefix=J");
  api._headers["Host"]                 = "examplebucket.s3.amazonaws.com";
  api._headers["Content-Type"]         = "gzip";
  api._headers["x-amz-content-sha256"] = "UNSIGNED-PAYLOAD";
  api._headers["x-amz-date"]           = "20130524T000000Z";
  api._headers["HeaderA"]              = "HeaderAValue";
  api._headers["HeaderB"]              = "HeaderBValue";
  api._headers["HeaderC"]              = "HeaderCValue";
  api._headers["HeaderD"]              = "HeaderDValue";
  api._headers["HeaderE"]              = "HeaderEValue";
  api._headers["HeaderF"]              = "HeaderFValue";

  StringSet include = defaultIncludeHeaders;
  StringSet exclude = defaultExcludeHeaders;

  const char *bench[] = {
    /* Signed Headers */
    "content-type;headera;headerb;headerc;headerd;headere;headerf;host;x-amz-content-sha256;x-amz-date",
    /* Canonical Request sha256 */
    "819a275bbd601fd6f6ba39190ee8299d34fcb0f5e0a4c0d8017c35e79a026579",
  };

  ValidateBenchCanonicalRequest(api, /*signePayload */ false, &now, bench, include, exclude);
}

TEST_CASE("S3AuthV4UtilParams: include all headers explicit", "[AWS][auth][SpecByExample]")
{
  time_t now = 1369353600; /* 5/24/2013 00:00:00 GMT */

  /* Define the HTTP request elements */
  MockTsInterface api;
  api._method.assign("GET");
  api._host.assign("examplebucket.s3.amazonaws.com");
  api._path.assign("");
  api._query.assign("max-keys=2&prefix=J");
  api._headers["Host"]                 = "examplebucket.s3.amazonaws.com";
  api._headers["Content-Type"]         = "gzip";
  api._headers["x-amz-content-sha256"] = "UNSIGNED-PAYLOAD";
  api._headers["x-amz-date"]           = "20130524T000000Z";
  api._headers["HeaderA"]              = "HeaderAValue";
  api._headers["HeaderB"]              = "HeaderBValue";
  api._headers["HeaderC"]              = "HeaderCValue";
  api._headers["HeaderD"]              = "HeaderDValue";
  api._headers["HeaderE"]              = "HeaderEValue";
  api._headers["HeaderF"]              = "HeaderFValue";

  StringSet include;
  commaSeparateString<StringSet>(include, "HeaderA,HeaderB,HeaderC,HeaderD,HeaderE,HeaderF");
  StringSet exclude = defaultExcludeHeaders;

  const char *bench[] = {
    /* Signed Headers */
    "content-type;headera;headerb;headerc;headerd;headere;headerf;host;x-amz-content-sha256;x-amz-date",
    /* Canonical Request sha256 */
    "819a275bbd601fd6f6ba39190ee8299d34fcb0f5e0a4c0d8017c35e79a026579",
  };

  ValidateBenchCanonicalRequest(api, /*signePayload */ false, &now, bench, include, exclude);
}

TEST_CASE("S3AuthV4UtilParams: exclude all headers explicit", "[AWS][auth][utility]")
{
  time_t now = 1369353600; /* 5/24/2013 00:00:00 GMT */

  /* Define the HTTP request elements */
  MockTsInterface api;
  api._method.assign("GET");
  api._host.assign("examplebucket.s3.amazonaws.com");
  api._path.assign("");
  api._query.assign("max-keys=2&prefix=J");
  api._headers["Host"]                 = "examplebucket.s3.amazonaws.com";
  api._headers["Content-Type"]         = "gzip";
  api._headers["x-amz-content-sha256"] = "UNSIGNED-PAYLOAD";
  api._headers["x-amz-date"]           = "20130524T000000Z";
  api._headers["HeaderA"]              = "HeaderAValue";
  api._headers["HeaderB"]              = "HeaderBValue";
  api._headers["HeaderC"]              = "HeaderCValue";
  api._headers["HeaderD"]              = "HeaderDValue";
  api._headers["HeaderE"]              = "HeaderEValue";
  api._headers["HeaderF"]              = "HeaderFValue";

  StringSet include = defaultIncludeHeaders;
  StringSet exclude;
  commaSeparateString<StringSet>(exclude, "HeaderA,HeaderB,HeaderC,HeaderD,HeaderE,HeaderF");

  const char *bench[] = {
    /* Signed Headers */
    "content-type;host;x-amz-content-sha256;x-amz-date",
    /* Canonical Request sha256 */
    "ef3088997c69bc860e0bb36f97a8335f38863339e7fd01f2cd17b5391da575fb",
  };

  ValidateBenchCanonicalRequest(api, /*signePayload */ false, &now, bench, include, exclude);
}

TEST_CASE("S3AuthV4UtilParams: include/exclude non overlapping headers", "[AWS][auth][utility]")
{
  time_t now = 1369353600; /* 5/24/2013 00:00:00 GMT */

  /* Define the HTTP request elements */
  MockTsInterface api;
  api._method.assign("GET");
  api._host.assign("examplebucket.s3.amazonaws.com");
  api._path.assign("");
  api._query.assign("max-keys=2&prefix=J");
  api._headers["Host"]                 = "examplebucket.s3.amazonaws.com";
  api._headers["Content-Type"]         = "gzip";
  api._headers["x-amz-content-sha256"] = "UNSIGNED-PAYLOAD";
  api._headers["x-amz-date"]           = "20130524T000000Z";
  api._headers["HeaderA"]              = "HeaderAValue";
  api._headers["HeaderB"]              = "HeaderBValue";
  api._headers["HeaderC"]              = "HeaderCValue";
  api._headers["HeaderD"]              = "HeaderDValue";
  api._headers["HeaderE"]              = "HeaderEValue";
  api._headers["HeaderF"]              = "HeaderFValue";

  StringSet include, exclude;
  commaSeparateString<StringSet>(include, "HeaderA,HeaderB,HeaderC");
  commaSeparateString<StringSet>(exclude, "HeaderD,HeaderE,HeaderF");

  const char *bench[] = {
    /* Signed Headers */
    "content-type;headera;headerb;headerc;host;x-amz-content-sha256;x-amz-date",
    /* Canonical Request sha256 */
    "c1c7fb808eefdb712192efeed168fdecef0f8d95e8df5a2569d127068c425209",
  };

  ValidateBenchCanonicalRequest(api, /*signePayload */ false, &now, bench, include, exclude);
}

TEST_CASE("S3AuthV4UtilParams: include/exclude overlapping headers", "[AWS][auth][utility]")
{
  time_t now = 1369353600; /* 5/24/2013 00:00:00 GMT */

  /* Define the HTTP request elements */
  MockTsInterface api;
  api._method.assign("GET");
  api._host.assign("examplebucket.s3.amazonaws.com");
  api._path.assign("");
  api._query.assign("max-keys=2&prefix=J");
  api._headers["Host"]                 = "examplebucket.s3.amazonaws.com";
  api._headers["Content-Type"]         = "gzip";
  api._headers["x-amz-content-sha256"] = "UNSIGNED-PAYLOAD";
  api._headers["x-amz-date"]           = "20130524T000000Z";
  api._headers["HeaderA"]              = "HeaderAValue";
  api._headers["HeaderB"]              = "HeaderBValue";
  api._headers["HeaderC"]              = "HeaderCValue";
  api._headers["HeaderD"]              = "HeaderDValue";
  api._headers["HeaderE"]              = "HeaderEValue";
  api._headers["HeaderF"]              = "HeaderFValue";

  StringSet include, exclude;
  commaSeparateString<StringSet>(include, "HeaderA,HeaderB,HeaderC");
  commaSeparateString<StringSet>(exclude, "HeaderC,HeaderD,HeaderE,HeaderF");

  const char *bench[] = {
    /* Signed Headers */
    "content-type;headera;headerb;host;x-amz-content-sha256;x-amz-date",
    /* Canonical Request sha256 */
    "0ac0bd67e304b3c25ec51f01b86c824f7439cdb0a5bc16acdebab73f34e12a57",
  };

  ValidateBenchCanonicalRequest(api, /*signePayload */ false, &now, bench, include, exclude);
}

TEST_CASE("S3AuthV4UtilParams: include/exclude overlapping headers missing include", "[AWS][auth][utility]")
{
  time_t now = 1369353600; /* 5/24/2013 00:00:00 GMT */

  /* Define the HTTP request elements */
  MockTsInterface api;
  api._method.assign("GET");
  api._host.assign("examplebucket.s3.amazonaws.com");
  api._path.assign("");
  api._query.assign("max-keys=2&prefix=J");
  api._headers["Host"]                 = "examplebucket.s3.amazonaws.com";
  api._headers["Content-Type"]         = "gzip";
  api._headers["x-amz-content-sha256"] = "UNSIGNED-PAYLOAD";
  api._headers["x-amz-date"]           = "20130524T000000Z";
  api._headers["HeaderA"]              = "HeaderAValue";
  api._headers["HeaderB"]              = "HeaderBValue";
  api._headers["HeaderC"]              = "HeaderCValue";
  api._headers["HeaderD"]              = "HeaderDValue";
  api._headers["HeaderE"]              = "HeaderEValue";
  api._headers["HeaderF"]              = "HeaderFValue";

  StringSet include, exclude;
  commaSeparateString<StringSet>(include, "HeaderA,HeaderC");
  commaSeparateString<StringSet>(exclude, "HeaderC,HeaderD,HeaderE,HeaderF");

  const char *bench[] = {
    /* Signed Headers */
    "content-type;headera;host;x-amz-content-sha256;x-amz-date",
    /* Canonical Request sha256 */
    "5b5bef63c923fed685230feb91d8059fe8d56c80d21ba6922ee335ff3fcc45bf",
  };

  ValidateBenchCanonicalRequest(api, /*signePayload */ false, &now, bench, include, exclude);
}

TEST_CASE("S3AuthV4UtilParams: include/exclude overlapping headers missing exclude", "[AWS][auth][utility]")
{
  time_t now = 1369353600; /* 5/24/2013 00:00:00 GMT */

  /* Define the HTTP request elements */
  MockTsInterface api;
  api._method.assign("GET");
  api._host.assign("examplebucket.s3.amazonaws.com");
  api._path.assign("");
  api._query.assign("max-keys=2&prefix=J");
  api._headers["Host"]                 = "examplebucket.s3.amazonaws.com";
  api._headers["Content-Type"]         = "gzip";
  api._headers["x-amz-content-sha256"] = "UNSIGNED-PAYLOAD";
  api._headers["x-amz-date"]           = "20130524T000000Z";
  api._headers["HeaderA"]              = "HeaderAValue";
  api._headers["HeaderB"]              = "HeaderBValue";
  api._headers["HeaderC"]              = "HeaderCValue";
  api._headers["HeaderD"]              = "HeaderDValue";
  api._headers["HeaderE"]              = "HeaderEValue";
  api._headers["HeaderF"]              = "HeaderFValue";

  StringSet include, exclude;
  commaSeparateString<StringSet>(include, "HeaderA,HeaderB,HeaderC");
  commaSeparateString<StringSet>(exclude, "HeaderC,HeaderD,HeaderF");

  const char *bench[] = {
    /* Signed Headers */
    "content-type;headera;headerb;host;x-amz-content-sha256;x-amz-date",
    /* Canonical Request sha256 */
    "0ac0bd67e304b3c25ec51f01b86c824f7439cdb0a5bc16acdebab73f34e12a57",
  };

  ValidateBenchCanonicalRequest(api, /*signePayload */ false, &now, bench, include, exclude);
}

/*
 * Mandatory headers Host, x-amz-* and Content-Type will must be included even if the user asked to exclude them.
 */
TEST_CASE("S3AuthV4UtilParams: include content type", "[AWS][auth][utility]")
{
  time_t now = 1369353600; /* 5/24/2013 00:00:00 GMT */

  /* Define the HTTP request elements */
  MockTsInterface api;
  api._method.assign("GET");
  api._host.assign("examplebucket.s3.amazonaws.com");
  api._path.assign("");
  api._query.assign("max-keys=2&prefix=J");
  api._headers["Host"]                 = "examplebucket.s3.amazonaws.com";
  api._headers["Content-Type"]         = "gzip";
  api._headers["x-amz-content-sha256"] = "UNSIGNED-PAYLOAD";
  api._headers["x-amz-date"]           = "20130524T000000Z";

  StringSet include = defaultIncludeHeaders;
  StringSet exclude;
  commaSeparateString<StringSet>(exclude, "Content-Type,x-amz-content-sha256,x-amz-date");

  const char *bench[] = {
    /* Signed Headers */
    "content-type;host;x-amz-content-sha256;x-amz-date",
    /* Canonical Request sha256 */
    "ef3088997c69bc860e0bb36f97a8335f38863339e7fd01f2cd17b5391da575fb",
  };

  ValidateBenchCanonicalRequest(api, /*signePayload */ false, &now, bench, include, exclude);
}

/*
 * Mandatory headers Host, x-amz-* and Content-Type will must be included even if the user asked to exclude them.
 * Content-type should not be signed if missing from the HTTP request.
 */
TEST_CASE("S3AuthV4UtilParams: include missing content type", "[AWS][auth][utility]")
{
  time_t now = 1369353600; /* 5/24/2013 00:00:00 GMT */

  /* Define the HTTP request elements */
  MockTsInterface api;
  api._method.assign("GET");
  api._host.assign("examplebucket.s3.amazonaws.com");
  api._path.assign("");
  api._query.assign("max-keys=2&prefix=J");
  api._headers["Host"]                 = "examplebucket.s3.amazonaws.com";
  api._headers["x-amz-content-sha256"] = "UNSIGNED-PAYLOAD";
  api._headers["x-amz-date"]           = "20130524T000000Z";

  StringSet include = defaultIncludeHeaders;
  StringSet exclude;
  commaSeparateString<StringSet>(exclude, "Content-Type,x-amz-content-sha256,x-amz-date");

  const char *bench[] = {
    /* Signed Headers */
    "host;x-amz-content-sha256;x-amz-date",
    /* Canonical Request sha256 */
    "528623330c85041d6fb82795b6f8d5771825d3568b9f0bc1faa8a49e1f5f9cfc",
  };

  ValidateBenchCanonicalRequest(api, /*signePayload */ false, &now, bench, include, exclude);
}


text:
Django Tumblog
=============================

A sort of, almost, maybe clone of Tumblr.


text:
///original version written by Erwin Coumans, October 2013

#ifndef BT_PATH_SOLVER_H
#define BT_PATH_SOLVER_H

//#define BT_USE_PATH
#ifdef BT_USE_PATH

extern "C"
{
#include "PATH/SimpleLCP.h"
#include "PATH/License.h"
#include "PATH/Error_Interface.h"
};
void __stdcall MyError(Void *data, Char *msg)
{
	printf("Path Error: %s\n", msg);
}
void __stdcall MyWarning(Void *data, Char *msg)
{
	printf("Path Warning: %s\n", msg);
}

Error_Interface e;

#include "btMLCPSolverInterface.h"
#include "Dantzig/lcp.h"

class btPathSolver : public btMLCPSolverInterface
{
public:
	btPathSolver()
	{
		License_SetString("2069810742&Courtesy_License&&&USR&2013&14_12_2011&1000&PATH&GEN&31_12_2013&0_0_0&0&0_0");
		e.error_data = 0;
		e.warning = MyWarning;
		e.error = MyError;
		Error_SetInterface(&e);
	}

	virtual bool solveMLCP(const btMatrixXu &A, const btVectorXu &b, btVectorXu &x, const btVectorXu &lo, const btVectorXu &hi, const btAlignedObjectArray<int> &limitDependency, int numIterations, bool useSparsity = true)
	{
		MCP_Termination status;

		int numVariables = b.rows();
		if (0 == numVariables)
			return true;

		/*	 - variables - the number of variables in the problem
			- m_nnz - the number of nonzeros in the M matrix
			- m_i - a vector of size m_nnz containing the row indices for M
			- m_j - a vector of size m_nnz containing the column indices for M
			- m_ij - a vector of size m_nnz containing the data for M
			- q - a vector of size variables
			- lb - a vector of size variables containing the lower bounds on x
			- ub - a vector of size variables containing the upper bounds on x
			*/
		btAlignedObjectArray<double> values;
		btAlignedObjectArray<int> rowIndices;
		btAlignedObjectArray<int> colIndices;

		for (int i = 0; i < A.rows(); i++)
		{
			for (int j = 0; j < A.cols(); j++)
			{
				if (A(i, j) != 0.f)
				{
					//add 1, because Path starts at 1, instead of 0
					rowIndices.push_back(i + 1);
					colIndices.push_back(j + 1);
					values.push_back(A(i, j));
				}
			}
		}
		int numNonZero = rowIndices.size();
		btAlignedObjectArray<double> zResult;
		zResult.resize(numVariables);
		btAlignedObjectArray<double> rhs;
		btAlignedObjectArray<double> upperBounds;
		btAlignedObjectArray<double> lowerBounds;
		for (int i = 0; i < numVariables; i++)
		{
			upperBounds.push_back(hi[i]);
			lowerBounds.push_back(lo[i]);
			rhs.push_back(-b[i]);
		}

		SimpleLCP(numVariables, numNonZero, &rowIndices[0], &colIndices[0], &values[0], &rhs[0], &lowerBounds[0], &upperBounds[0], &status, &zResult[0]);

		if (status != MCP_Solved)
		{
			static const char *gReturnMsgs[] = {
				"Invalid return",
				"MCP_Solved: The problem was solved",
				"MCP_NoProgress: A stationary point was found",
				"MCP_MajorIterationLimit: Major iteration limit met",
				"MCP_MinorIterationLimit: Cumulative minor iteration limit met",
				"MCP_TimeLimit: Ran out of time",
				"MCP_UserInterrupt: Control-C, typically",
				"MCP_BoundError: Problem has a bound error",
				"MCP_DomainError: Could not find starting point",
				"MCP_Infeasible: Problem has no solution",
				"MCP_Error: An error occurred within the code",
				"MCP_LicenseError: License could not be found",
				"MCP_OK"};

			printf("ERROR: The PATH MCP solver failed: %s\n", gReturnMsgs[(unsigned int)status]);  // << std::endl;
			printf("using Projected Gauss Seidel fallback\n");

			return false;
		}
		else
		{
			for (int i = 0; i < numVariables; i++)
			{
				x[i] = zResult[i];
				//check for #NAN
				if (x[i] != zResult[i])
					return false;
			}
			return true;
		}
	}
};

#endif  //BT_USE_PATH

#endif  //BT_PATH_SOLVER_H


text:
<?php
/**
 * Checkout Form
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/checkout/form-checkout.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see        https://docs.woocommerce.com/document/template-structure/
 * @author        WooThemes
 * @package    WooCommerce/Templates
 * @version     2.3.0
 */
if (!defined('ABSPATH')) {
    exit;
}
?>

    <?php
    /**
     * woocommerce_before_main_content hook.
     *
     * @hooked woocommerce_breadcrumb - 20
     */
    do_action('woocommerce_before_main_content');
    ?>

            <?php
            wc_print_notices();
            do_action('woocommerce_before_checkout_form', $checkout);
            // If checkout registration is disabled and not logged in, the user cannot checkout
            if (!$checkout->enable_signup && !$checkout->enable_guest_checkout && !is_user_logged_in()) {
                echo apply_filters('woocommerce_checkout_must_be_logged_in_message', __('You must be logged in to checkout.', 'woocommerce'));
                return;
            }
            ?>

                <?php do_action('woocommerce_checkout_before_customer_details'); ?>
                <form name="checkout" method="post" class="checkout woocommerce-checkout"
                      action="<?php echo esc_url(wc_get_checkout_url()); ?>" enctype="multipart/form-data">

                    <?php if (sizeof($checkout->checkout_fields) > 0) : ?>

                            <?php if (wc_ship_to_billing_address_only() && WC()->cart->needs_shipping()) : ?>

                                <?php _e('Billing & Shipping', 'woocommerce'); ?>

                            <?php else : ?>

                                <?php _e('Billing Details', 'woocommerce'); ?>

                            <?php endif; ?>

                            <?php do_action('woocommerce_checkout_billing'); ?>
                            <?php do_action('woocommerce_checkout_shipping'); ?>
                            <?php do_action('woocommerce_checkout_after_customer_details'); ?>

                    <?php endif; ?>

                        <?php _e('Your order', 'woocommerce'); ?>

                        <?php do_action('woocommerce_checkout_before_order_review'); ?>

                            <?php do_action('woocommerce_checkout_order_review'); ?>

                    <?php do_action('woocommerce_checkout_after_order_review'); ?>

                </form>

            <?php do_action('woocommerce_after_checkout_form', $checkout); ?>

Your Checkout Progress

1.
                    <?php if (wc_ship_to_billing_address_only() && WC()->cart->needs_shipping()) : ?>

                        <?php _e('Billing & Shipping', 'woocommerce'); ?>

                    <?php else : ?>

                        <?php _e('Billing Details', 'woocommerce'); ?>

                    <?php endif; ?>

2.   <?php _e('Your order', 'woocommerce'); ?>

Custom CMS block displayed below the one page checkout progress block. Put your own content here.

                    hot
                    -40% Valentine
 Underwear Sale
                    Lorem ipsum dolor sitamet, conse adipisc sed do eiusmod tempor.


text:
require File.expand_path('../test_helper', __FILE__)

describe "AsNewSan", ActiveRecord::TestCase do
  include DBSetupAndTeardownHelper

  it "should really create a record for a `new' object with `as_new' set to `true'" do
    assert_difference('BaconFlavour.count_including_new_records', +1) { BaconFlavour.as_new(:name => 'chunky') }
    BaconFlavour.find_including_new_records(:first, :conditions => { :name => 'chunky' }).as_new.should.be true
  end

  it "should garbage collect any record which has been in the db for a specific period" do
    old_record = BaconFlavour.as_new(:name => 'banana', :created_at => (Time.now - 1.week - 1))
    new_record = BaconFlavour.as_new(:name => 'smoked')

    assert_difference('BaconFlavour.count_including_new_records', -1) { BaconFlavour.collect_garbage! }
  end

  it "should be possible to do a `find' including `as_new' records" do
    as_new_record = BaconFlavour.as_new(:name => 'smells as new')
    not_as_new_record = BaconFlavour.create(:name => 'does not smell at all')

    BaconFlavour.find_including_new_records(:all).should == [as_new_record, not_as_new_record]
    BaconFlavour.find(:all).should == [not_as_new_record]
  end

  it "should set `as_new' records to `false' on update" do
    record = BaconFlavour.as_new(:name => 'ice cream')
    record.as_new_record?.should.be true
    record.update_attribute(:name, 'that is right, bacon ice cream')
    record.as_new_record?.should.be false
  end

  it "should define a named scope to exclude as_new records" do
    as_new_record = BaconFlavour.as_new(:name => 'good as new')
    BaconFlavour.exclude_as_new.find_including_new_records(:first, :conditions => { :name => 'good as new' }).should.be.nil
  end
end


text:
/*
 * Created on 31-Mar-2005
 *
 */
package br.unicamp.ic.sed.mobilemedia.album.spec.dt;

/**
 * @author tyoung
 *
 * This class contains all constants used by the MobileMedia application.
 * It is the central location to store any static string data.
 */
public class Constants {

	public static final String ALBUMLIST_SCREEN = "AlbumListScreen";
	public static final String IMAGE_SCREEN = "ImageScreen";
	public static final String IMAGELIST_SCREEN = "ImageListScreen";

	public static final String NEWALBUM_SCREEN = "NewAlbumScreen";
	public static final String CONFIRMDELETEALBUM_SCREEN = "ConfirmDeleteAlbumScreen";
	public static final String ADDPHOTOTOALBUM_SCREEN = "AddPhotoToAlbum";

	public static final String NEWLABEL_SCREEN = "NewLabelScreen";

	//#ifdef device_screen_176x205

    /** Screen Size*/
	public static final int SCREEN_WIDTH  = 176;
	public static final int SCREEN_HEIGHT = 205;

	//#elifdef device_screen_128x149
	//#
	//# /** Screen Size*/
	//# public static final int SCREEN_WIDTH  = 128;
	//# public static final int SCREEN_HEIGHT = 149;
	//#
	//#elifdef device_screen_132x176
	//#
	//# /** Screen Size*/
	//# public static final int SCREEN_WIDTH  = 132;
	//# public static final int SCREEN_HEIGHT = 176;
	//#
	//#endif

}


text:
require 'spree_core'
require 'spree_power_reviews/engine'