text:
/**
 * The instance API is the thing that is returned when oboe() is called.
 * it allows:
 *
 *    - listeners for various events to be added and removed
 *    - the http response header/headers to be read
 */
function instanceApi(oboeBus, contentSource){

  var oboeApi,
      fullyQualifiedNamePattern = /^(node|path):./,
      rootNodeFinishedEvent = oboeBus(ROOT_NODE_FOUND),
      emitNodeDrop = oboeBus(NODE_DROP).emit,
      emitNodeSwap = oboeBus(NODE_SWAP).emit,

      /**
       * Add any kind of listener that the instance api exposes
       */
      addListener = varArgs(function( eventId, parameters ){

        if( oboeApi[eventId] ) {

          // for events added as .on(event, callback), if there is a
          // .event() equivalent with special behaviour , pass through
          // to that:
          apply(parameters, oboeApi[eventId]);
        } else {

          // we have a standard Node.js EventEmitter 2-argument call.
          // The first parameter is the listener.
          var event = oboeBus(eventId),
              listener = parameters[0];

          if( fullyQualifiedNamePattern.test(eventId) ) {

            // allow fully-qualified node/path listeners
            // to be added
            addForgettableCallback(event, listener);
          } else  {

            // the event has no special handling, pass through
            // directly onto the event bus:
            event.on( listener);
          }
        }

        return oboeApi; // chaining
      }),

      /**
       * Remove any kind of listener that the instance api exposes
       */
      removeListener = function( eventId, p2, p3 ){

        if( eventId == 'done' ) {

          rootNodeFinishedEvent.un(p2);

        } else if( eventId == 'node' || eventId == 'path' ) {

          // allow removal of node and path
          oboeBus.un(eventId + ':' + p2, p3);
        } else {

          // we have a standard Node.js EventEmitter 2-argument call.
          // The second parameter is the listener. This may be a call
          // to remove a fully-qualified node/path listener but requires
          // no special handling
          var listener = p2;

          oboeBus(eventId).un(listener);
        }

        return oboeApi; // chaining
      };

  /**
   * Add a callback, wrapped in a try/catch so as to not break the
   * execution of Oboe if an exception is thrown (fail events are
   * fired instead)
   *
   * The callback is used as the listener id so that it can later be
   * removed using .un(callback)
   */
  function addProtectedCallback(eventName, callback) {
    oboeBus(eventName).on(protectedCallback(callback), callback);
    return oboeApi; // chaining
  }

  /**
   * Add a callback where, if .forget() is called during the callback's
   * execution, the callback will be de-registered
   */
  function addForgettableCallback(event, callback, listenerId) {

    // listenerId is optional and if not given, the original
    // callback will be used
    listenerId = listenerId || callback;

    var safeCallback = protectedCallback(callback);

    event.on( function() {

      var discard = false;

      oboeApi.forget = function(){
        discard = true;
      };

      apply( arguments, safeCallback );

      delete oboeApi.forget;

      if( discard ) {
        event.un(listenerId);
      }
    }, listenerId);

    return oboeApi; // chaining
  }

  /**
   *  wrap a callback so that if it throws, Oboe.js doesn't crash but instead
   *  throw the error in another event loop
   */
  function protectedCallback( callback ) {
    return function() {
      try{
        return callback.apply(oboeApi, arguments);
      }catch(e)  {
        setTimeout(function() {
          throw new Error(e.message);
        });
      }
    }
  }

  /**
   * Return the fully qualified event for when a pattern matches
   * either a node or a path
   *
   * @param type {String} either 'node' or 'path'
   */
  function fullyQualifiedPatternMatchEvent(type, pattern) {
    return oboeBus(type + ':' + pattern);
  }

  function wrapCallbackToSwapNodeIfSomethingReturned( callback ) {
    return function() {
      var returnValueFromCallback = callback.apply(this, arguments);

      if( defined(returnValueFromCallback) ) {

        if( returnValueFromCallback == oboe.drop ) {
          emitNodeDrop();
        } else {
          emitNodeSwap(returnValueFromCallback);
        }
      }
    }
  }

  function addSingleNodeOrPathListener(eventId, pattern, callback) {

    var effectiveCallback;

    if( eventId == 'node' ) {
      effectiveCallback = wrapCallbackToSwapNodeIfSomethingReturned(callback);
    } else {
      effectiveCallback = callback;
    }

    addForgettableCallback(
      fullyQualifiedPatternMatchEvent(eventId, pattern),
      effectiveCallback,
      callback
    );
  }

  /**
   * Add several listeners at a time, from a map
   */
  function addMultipleNodeOrPathListeners(eventId, listenerMap) {

    for( var pattern in listenerMap ) {
      addSingleNodeOrPathListener(eventId, pattern, listenerMap[pattern]);
    }
  }

  /**
   * implementation behind .onPath() and .onNode()
   */
  function addNodeOrPathListenerApi( eventId, jsonPathOrListenerMap, callback ){

    if( isString(jsonPathOrListenerMap) ) {
      addSingleNodeOrPathListener(eventId, jsonPathOrListenerMap, callback);

    } else {
      addMultipleNodeOrPathListeners(eventId, jsonPathOrListenerMap);
    }

    return oboeApi; // chaining
  }

  // some interface methods are only filled in after we receive
  // values and are noops before that:
  oboeBus(ROOT_PATH_FOUND).on( function(rootNode) {
    oboeApi.root = functor(rootNode);
  });

  /**
   * When content starts make the headers readable through the
   * instance API
   */
  oboeBus(HTTP_START).on( function(_statusCode, headers) {

    oboeApi.header =  function(name) {
      return name ? headers[name]
        : headers
      ;
    }
  });

  /**
   * Construct and return the public API of the Oboe instance to be
   * returned to the calling application
   */
  return oboeApi = {
    on             : addListener,
    addListener    : addListener,
    removeListener : removeListener,
    emit           : oboeBus.emit,

    node           : partialComplete(addNodeOrPathListenerApi, 'node'),
    path           : partialComplete(addNodeOrPathListenerApi, 'path'),

    done           : partialComplete(addForgettableCallback, rootNodeFinishedEvent),
    start          : partialComplete(addProtectedCallback, HTTP_START ),

    // fail doesn't use protectedCallback because
    // could lead to non-terminating loops
    fail           : oboeBus(FAIL_EVENT).on,

    // public api calling abort fires the ABORTING event
    abort          : oboeBus(ABORTING).emit,

    // initially return nothing for header and root
    header         : noop,
    root           : noop,

    source         : contentSource
  };
}


text:
#include "device.hpp"
#include "context.hpp"
#include "global_managers_init.hpp"
#include "texture_decoder.hpp"
#include "memory_mapped_texture.hpp"
#include "math.hpp"
#include "muglm/muglm_impl.hpp"
#include "thread_group.hpp"
#include <random>

#ifdef HAVE_ASTC_DECODER
#include "astcenc.h"
#endif

using namespace Granite;
using namespace Vulkan;

static BufferHandle readback_image(CommandBuffer &cmd, const Image &image)
{
	BufferCreateInfo readback_info;
	readback_info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT;
	readback_info.domain = BufferDomain::CachedHost;
	readback_info.size = image.get_width() * image.get_height() *
	                     TextureFormatLayout::format_block_size(image.get_format(),
	                                                            VK_IMAGE_ASPECT_COLOR_BIT);
	auto readback_buffer = cmd.get_device().create_buffer(readback_info);

	cmd.copy_image_to_buffer(*readback_buffer, image, 0,
	                         {}, { image.get_width(), image.get_height(), 1 },
	                         0, 0,
	                         { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 });

	cmd.barrier(VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT,
	            VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_HOST_READ_BIT);
	return readback_buffer;
}

static bool compare_r8(Device &device,
                       const Buffer &reference, const Buffer &decoded,
                       unsigned width, unsigned height, int max_diff)
{
	auto *mapped_reference = static_cast<const uint8_t *>(device.map_host_buffer(reference, MEMORY_ACCESS_READ_BIT));
	auto *mapped_decoded = static_cast<const uint8_t *>(device.map_host_buffer(decoded, MEMORY_ACCESS_READ_BIT));

	for (unsigned y = 0; y < height; y++)
	{
		for (unsigned x = 0; x < width; x++)
		{
			auto &ref = mapped_reference[y * width + x];
			auto &dec = mapped_decoded[y * width + x];

			int diff_r = muglm::abs(int(ref) - int(dec));

			if (diff_r > max_diff)
			{
				LOGE("(%u, %u): Reference (%u) != (%u).\n",
				     x, y, ref, dec);
				return false;
			}
		}
	}

	return true;
}

static bool compare_r16f(Device &device,
                         const Buffer &reference, const Buffer &decoded,
                         unsigned width, unsigned height)
{
	auto *mapped_reference = static_cast<const uint16_t *>(device.map_host_buffer(reference, MEMORY_ACCESS_READ_BIT));
	auto *mapped_decoded = static_cast<const uint16_t *>(device.map_host_buffer(decoded, MEMORY_ACCESS_READ_BIT));

	for (unsigned y = 0; y < height; y++)
	{
		for (unsigned x = 0; x < width; x++)
		{
			auto &ref = mapped_reference[y * width + x];
			auto &dec = mapped_decoded[y * width + x];

			int diff_r = muglm::abs(int(ref) - int(dec));

			if (diff_r)
			{
				LOGE("(%u, %u): Reference (%u) != (%u).\n",
				     x, y, ref, dec);
				return false;
			}
		}
	}

	return true;
}

static bool compare_rg8(Device &device,
                          const Buffer &reference, const Buffer &decoded,
                          unsigned width, unsigned height, int max_diff)
{
	auto *mapped_reference = static_cast<const u8vec2 *>(device.map_host_buffer(reference, MEMORY_ACCESS_READ_BIT));
	auto *mapped_decoded = static_cast<const u8vec2 *>(device.map_host_buffer(decoded, MEMORY_ACCESS_READ_BIT));

	for (unsigned y = 0; y < height; y++)
	{
		for (unsigned x = 0; x < width; x++)
		{
			auto &ref = mapped_reference[y * width + x];
			auto &dec = mapped_decoded[y * width + x];

			int diff_r = muglm::abs(int(ref.x) - int(dec.x));
			int diff_g = muglm::abs(int(ref.y) - int(dec.y));
			int diff_max = muglm::max(diff_r, diff_g);

			if (diff_max > max_diff)
			{
				LOGE("(%u, %u): Reference (%u, %u) != (%u, %u).\n",
				     x, y,
				     ref.x, ref.y, dec.x, dec.y);
				return false;
			}
		}
	}

	return true;
}

static bool compare_rg16f(Device &device,
                          const Buffer &reference, const Buffer &decoded,
                          unsigned width, unsigned height)
{
	auto *mapped_reference = static_cast<const u16vec2 *>(device.map_host_buffer(reference, MEMORY_ACCESS_READ_BIT));
	auto *mapped_decoded = static_cast<const u16vec2 *>(device.map_host_buffer(decoded, MEMORY_ACCESS_READ_BIT));

	for (unsigned y = 0; y < height; y++)
	{
		for (unsigned x = 0; x < width; x++)
		{
			auto &ref = mapped_reference[y * width + x];
			auto &dec = mapped_decoded[y * width + x];

			int diff_r = muglm::abs(int(ref.x) - int(dec.x));
			int diff_g = muglm::abs(int(ref.y) - int(dec.y));
			int diff_max = muglm::max(diff_r, diff_g);

			if (diff_max)
			{
				LOGE("(%u, %u): Reference (%u, %u) != (%u, %u).\n",
				     x, y,
				     ref.x, ref.y, dec.x, dec.y);
				return false;
			}
		}
	}

	return true;
}

static bool compare_rgba8(Device &device,
                          const Buffer &reference, const Buffer &decoded,
                          unsigned width, unsigned height, int max_diff)
{
	auto *mapped_reference = static_cast<const u8vec4 *>(device.map_host_buffer(reference, MEMORY_ACCESS_READ_BIT));
	auto *mapped_decoded = static_cast<const u8vec4 *>(device.map_host_buffer(decoded, MEMORY_ACCESS_READ_BIT));

	for (unsigned y = 0; y < height; y++)
	{
		for (unsigned x = 0; x < width; x++)
		{
			auto &ref = mapped_reference[y * width + x];
			auto &dec = mapped_decoded[y * width + x];

			int diff_r = muglm::abs(int(ref.x) - int(dec.x));
			int diff_g = muglm::abs(int(ref.y) - int(dec.y));
			int diff_b = muglm::abs(int(ref.z) - int(dec.z));
			int diff_a = muglm::abs(int(ref.w) - int(dec.w));
			int diff_max = muglm::max(muglm::max(diff_r, diff_g), muglm::max(diff_b, diff_a));

			if (diff_max > max_diff)
			{
				LOGE("(%u, %u): Reference (%u, %u, %u, %u) != (%u, %u, %u, %u).\n",
				     x, y,
				     ref.x, ref.y, ref.z, ref.w,
				     dec.x, dec.y, dec.z, dec.w);
				return false;
			}
		}
	}

	return true;
}

static bool compare_rgba16f(Device &device,
                            const Buffer &reference, const Buffer &decoded,
                            unsigned width, unsigned height)
{
	auto *mapped_reference = static_cast<const u16vec4 *>(device.map_host_buffer(reference, MEMORY_ACCESS_READ_BIT));
	auto *mapped_decoded = static_cast<const u16vec4 *>(device.map_host_buffer(decoded, MEMORY_ACCESS_READ_BIT));

	for (unsigned y = 0; y < height; y++)
	{
		for (unsigned x = 0; x < width; x++)
		{
			auto ref = mapped_reference[y * width + x];
			auto dec = mapped_decoded[y * width + x];

			int diff_r = muglm::abs(int(ref.x) - int(dec.x));
			int diff_g = muglm::abs(int(ref.y) - int(dec.y));
			int diff_b = muglm::abs(int(ref.z) - int(dec.z));
			int diff_a = muglm::abs(int(ref.w) - int(dec.w));
			int diff_max = muglm::max(muglm::max(diff_r, diff_g), muglm::max(diff_b, diff_a));

			if (diff_max)
			{
				LOGE("(%u, %u): Reference (%u, %u, %u, %u) != (%u, %u, %u, %u).\n",
				     x, y,
				     ref.x, ref.y, ref.z, ref.w,
				     dec.x, dec.y, dec.z, dec.w);
				return false;
			}
		}
	}

	return true;
}

#ifdef HAVE_ASTC_DECODER
static BufferHandle decode_astc_cpu(Device &device, const TextureFormatLayout &layout, VkFormat readback_format)
{
	astcenc_config config = {};
	uint32_t block_width, block_height;
	TextureFormatLayout::format_block_dim(layout.get_format(), block_width, block_height);
	bool hdr = readback_format == VK_FORMAT_R16G16B16A16_SFLOAT;
	astcenc_config_init(hdr ? ASTCENC_PRF_HDR : ASTCENC_PRF_LDR_SRGB,
	                    block_width, block_height, 1,
	                    ASTCENC_PRE_FAST, 0, &config);

	astcenc_context *ctx = nullptr;
	if (astcenc_context_alloc(&config, 1, &ctx) != ASTCENC_SUCCESS)
		return {};

	astcenc_image image = {};
	image.dim_x = layout.get_width();
	image.dim_y = layout.get_height();
	image.dim_z = 1;

	Vulkan::BufferCreateInfo buffer_info = {};
	buffer_info.size = layout.get_width() * layout.get_height() * (hdr ? 8 : 4);
	buffer_info.domain = BufferDomain::CachedHost;
	buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
	auto buffer = device.create_buffer(buffer_info);

	void *slice = nullptr;

	if (!hdr)
	{
		slice = static_cast<uint8_t *>(device.map_host_buffer(*buffer, MEMORY_ACCESS_WRITE_BIT));
		image.data = &slice;
		image.data_type = ASTCENC_TYPE_U8;
	}
	else
	{
		slice = static_cast<uint16_t *>(device.map_host_buffer(*buffer, MEMORY_ACCESS_WRITE_BIT));
		image.data = &slice;
		image.data_type = ASTCENC_TYPE_F16;
	}

	astcenc_swizzle swz = { ASTCENC_SWZ_R, ASTCENC_SWZ_G, ASTCENC_SWZ_B, ASTCENC_SWZ_A };
	if (astcenc_decompress_image(ctx, static_cast<const uint8_t *>(layout.data()),
	                             layout.get_layer_size(0), &image, &swz, 0) != ASTCENC_SUCCESS)
	{
		buffer.reset();
	}
	astcenc_context_free(ctx);
	return buffer;
}
#endif

static BufferHandle decode_gpu(CommandBuffer &cmd, const TextureFormatLayout &layout, VkFormat format)
{
#ifdef HAVE_ASTC_DECODER
	if (Vulkan::format_compression_type(layout.get_format()) == Vulkan::FormatCompressionType::ASTC)
		return decode_astc_cpu(cmd.get_device(), layout, format);
#endif

	auto &device = cmd.get_device();
	auto uploaded_info = ImageCreateInfo::immutable_image(layout);
	uploaded_info.initial_layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
	uploaded_info.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
	auto uploaded_staging = device.create_image_staging_buffer(layout);
	auto uploaded_tex = device.create_image_from_staging_buffer(uploaded_info, &uploaded_staging);

	auto rt_info = ImageCreateInfo::render_target(layout.get_width(), layout.get_height(), format);
	rt_info.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
	rt_info.initial_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
	auto rt = device.create_image(rt_info);

	cmd.blit_image(*rt, *uploaded_tex,
	               {}, { int(layout.get_width()), int(layout.get_height()), 1 },
	               {}, { int(layout.get_width()), int(layout.get_height()), 1 },
	               0, 0,
	               0, 0, 1, VK_FILTER_NEAREST);

	cmd.image_barrier(*rt, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
	                  VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT,
	                  VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT);

	return readback_image(cmd, *rt);
}

static BufferHandle decode_compute(CommandBuffer &cmd, const TextureFormatLayout &layout,
                                   VkFormat preferred_readback_format)
{
	auto compressed = decode_compressed_image(cmd, layout, preferred_readback_format);
	if (!compressed)
		return {};
	cmd.image_barrier(*compressed, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
	                  VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0,
	                  VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT);
	return readback_image(cmd, *compressed);
}

template <bool dual_plane>
static bool test_astc_weights(Device &device, VkFormat format, VkFormat readback_format)
{
	auto cmd = device.request_command_buffer();
	std::mt19937 rnd(1337);
	Vulkan::MemoryMappedTexture tex;
	unsigned width = 2048;
	unsigned height = 2048;

	unsigned block_width, block_height;
	Vulkan::TextureFormatLayout::format_block_dim(format, block_width, block_height);

	unsigned blocks_x = (width + block_width - 1) / block_width;
	unsigned blocks_y = (height + block_height - 1) / block_height;
	unsigned num_blocks = blocks_x * blocks_y;
	tex.set_2d(format, width, height);
	if (!tex.map_write_scratch())
		return false;

	auto &layout = tex.get_layout();
	auto *d = static_cast<uint32_t *>(layout.data_opaque(0, 0, 0, 0));

	// Expose all possible weight encoding formats.
	for (unsigned i = 0; i < num_blocks; i++, d += 4)
	{
		d[0] = 0;
		d[1] = 0;
		d[2] = 0;
		d[3] = 0;

		d[0] |= uint32_t(dual_plane) << 10;

		unsigned weight_bits = i & 15;
		while ((weight_bits & 6) == 0)
			weight_bits++;

		d[0] |= ((weight_bits >> 3) & 1) << 9;
		d[0] |= ((weight_bits >> 2) & 1) << 1;
		d[0] |= ((weight_bits >> 1) & 1) << 0;
		d[0] |= ((weight_bits >> 0) & 1) << 4;

		// Endpoint type
		d[0] |= 0 << 13;

		// 4x4 weight grid.
		d[0] |= 0 << 7;
		d[0] |= 2 << 5;

		// Randomize endpoint and weights.
		d[0] |= uint32_t(rnd()) << 17;
		d[1] = uint32_t(rnd());
		d[2] = uint32_t(rnd());
		d[3] = uint32_t(rnd());
	}

	auto readback_reference = decode_gpu(*cmd, layout, readback_format);
	auto readback_decoded = decode_compute(*cmd, layout, readback_format);
	if (!readback_decoded)
	{
		device.submit_discard(cmd);
		return false;
	}

	Fence fence;
	device.submit(cmd, &fence);
	fence->wait();

	if (readback_format == VK_FORMAT_R16G16B16A16_SFLOAT)
		return compare_rgba16f(device, *readback_reference, *readback_decoded, width, height);
	else if (readback_format == VK_FORMAT_R8G8B8A8_SRGB || readback_format == VK_FORMAT_R8G8B8A8_UNORM)
		return compare_rgba8(device, *readback_reference, *readback_decoded, width, height, 0);
	else
		return false;
}

static bool test_astc_endpoint_formats(Device &device, VkFormat format, VkFormat readback_format)
{
	auto cmd = device.request_command_buffer();
	std::mt19937 rnd(1337);
	Vulkan::MemoryMappedTexture tex;
	unsigned width = 8092;
	unsigned height = 8092;

	unsigned block_width, block_height;
	Vulkan::TextureFormatLayout::format_block_dim(format, block_width, block_height);

	unsigned blocks_x = (width + block_width - 1) / block_width;
	unsigned blocks_y = (height + block_height - 1) / block_height;
	unsigned num_blocks = blocks_x * blocks_y;
	tex.set_2d(format, width, height);
	if (!tex.map_write_scratch())
		return false;

	auto &layout = tex.get_layout();
	auto *d = static_cast<uint32_t *>(layout.data_opaque(0, 0, 0, 0));

	// Expose all possible weight encoding formats.
	for (unsigned i = 0; i < num_blocks; i++, d += 4)
	{
		d[0] = 0;
		d[1] = 0;
		d[2] = 0;
		d[3] = 0;

		unsigned weight_bits = (i >> 4) & 15;
		while ((weight_bits & 6) == 0)
			weight_bits++;

		d[0] |= ((weight_bits >> 3) & 1) << 9;
		d[0] |= ((weight_bits >> 2) & 1) << 1;
		d[0] |= ((weight_bits >> 1) & 1) << 0;
		d[0] |= ((weight_bits >> 0) & 1) << 4;

		// Endpoint type
		d[0] |= (i & 15) << 13;

		// 4x4 weight grid.
		d[0] |= 0 << 7;
		d[0] |= 2 << 5;

		// Randomize endpoint and weights.
		d[0] |= uint32_t(rnd()) << 17;
		d[1] = uint32_t(rnd());
		d[2] = uint32_t(rnd());
		d[3] = uint32_t(rnd());
	}

	auto readback_reference = decode_gpu(*cmd, layout, readback_format);
	auto readback_decoded = decode_compute(*cmd, layout, readback_format);
	if (!readback_decoded)
	{
		device.submit_discard(cmd);
		return false;
	}

	Fence fence;
	device.submit(cmd, &fence);
	fence->wait();

	if (readback_format == VK_FORMAT_R16G16B16A16_SFLOAT)
		return compare_rgba16f(device, *readback_reference, *readback_decoded, width, height);
	else if (readback_format == VK_FORMAT_R8G8B8A8_SRGB || readback_format == VK_FORMAT_R8G8B8A8_UNORM)
		return compare_rgba8(device, *readback_reference, *readback_decoded, width, height, 0);
	else
		return false;
}

template <bool dual_plane>
static bool test_astc_partitions(Device &device, VkFormat format, VkFormat readback_format)
{
	auto cmd = device.request_command_buffer();
	std::mt19937 rnd(1339);
	Vulkan::MemoryMappedTexture tex;
	unsigned width = 2048;
	unsigned height = 2048;

	unsigned block_width, block_height;
	Vulkan::TextureFormatLayout::format_block_dim(format, block_width, block_height);

	unsigned blocks_x = (width + block_width - 1) / block_width;
	unsigned blocks_y = (height + block_height - 1) / block_height;
	unsigned num_blocks = blocks_x * blocks_y;
	tex.set_2d(format, width, height);
	if (!tex.map_write_scratch())
		return false;

	auto &layout = tex.get_layout();
	auto *d = static_cast<uint32_t *>(layout.data_opaque(0, 0, 0, 0));

	// Expose all possible weight encoding formats.
	for (unsigned i = 0; i < num_blocks; i++, d += 4)
	{
		d[0] = 0;
		d[1] = 0;
		d[2] = 0;
		d[3] = 0;

		d[0] |= uint32_t(dual_plane) << 10;

		unsigned weight_bits = 5;
		d[0] |= ((weight_bits >> 3) & 1) << 9;
		d[0] |= ((weight_bits >> 2) & 1) << 1;
		d[0] |= ((weight_bits >> 1) & 1) << 0;
		d[0] |= ((weight_bits >> 0) & 1) << 4;

		// 4x4 weight grid.
		d[0] |= 0 << 7;
		d[0] |= 2 << 5;

		unsigned seed = i & 1023;
		unsigned num_partitions_1 = (i >> 10) & 3;

		d[0] |= num_partitions_1 << 11;
		d[0] |= seed << 13;

		// Constant CEM, variable endpoint type.
		d[0] |= ((i >> 12) & 0xf) << 25;

		// Randomize endpoint and weights.
		d[0] |= uint32_t(rnd()) << 29;
		d[1] = uint32_t(rnd());
		d[2] = uint32_t(rnd());
		d[3] = uint32_t(rnd());
	}

	auto readback_reference = decode_gpu(*cmd, layout, readback_format);
	auto readback_decoded = decode_compute(*cmd, layout, readback_format);
	if (!readback_decoded)
	{
		device.submit_discard(cmd);
		return false;
	}

	Fence fence;
	device.submit(cmd, &fence);
	fence->wait();

	if (readback_format == VK_FORMAT_R16G16B16A16_SFLOAT)
		return compare_rgba16f(device, *readback_reference, *readback_decoded, width, height);
	else if (readback_format == VK_FORMAT_R8G8B8A8_SRGB || readback_format == VK_FORMAT_R8G8B8A8_UNORM)
		return compare_rgba8(device, *readback_reference, *readback_decoded, width, height, 0);
	else
		return false;
}

template <bool dual_plane>
static bool test_astc_partitions_complex(Device &device, VkFormat format, VkFormat readback_format)
{
	auto cmd = device.request_command_buffer();
	std::mt19937 rnd(1338);
	Vulkan::MemoryMappedTexture tex;
	unsigned width = 2048;
	unsigned height = 2048;

	unsigned block_width, block_height;
	Vulkan::TextureFormatLayout::format_block_dim(format, block_width, block_height);

	unsigned blocks_x = (width + block_width - 1) / block_width;
	unsigned blocks_y = (height + block_height - 1) / block_height;
	unsigned num_blocks = blocks_x * blocks_y;
	tex.set_2d(format, width, height);
	if (!tex.map_write_scratch())
		return false;

	auto &layout = tex.get_layout();
	auto *d = static_cast<uint32_t *>(layout.data_opaque(0, 0, 0, 0));

	// Expose all possible weight encoding formats.
	for (unsigned i = 0; i < num_blocks; i++, d += 4)
	{
		d[0] = 0;
		d[1] = 0;
		d[2] = 0;
		d[3] = 0;

		d[0] |= uint32_t(dual_plane) << 10;

		constexpr unsigned weight_bits = dual_plane ? 2 : 5;
		d[0] |= ((weight_bits >> 3) & 1) << 9;
		d[0] |= ((weight_bits >> 2) & 1) << 1;
		d[0] |= ((weight_bits >> 1) & 1) << 0;
		d[0] |= ((weight_bits >> 0) & 1) << 4;

		// 4x4 weight grid.
		d[0] |= 0 << 7;
		d[0] |= 2 << 5;

		unsigned seed = i & 1023;
		unsigned num_partitions_1 = (i >> 10) & 3;

		d[0] |= num_partitions_1 << 11;
		d[0] |= seed << 13;

		d[0] |= ((i >> 12) & 0x3f) << 23;

		// Randomize endpoint and weights.
		d[0] |= uint32_t(rnd()) << 29;
		d[1] = uint32_t(rnd());
		d[2] = uint32_t(rnd());
		d[3] = uint32_t(rnd());
	}

	auto readback_reference = decode_gpu(*cmd, layout, readback_format);
	auto readback_decoded = decode_compute(*cmd, layout, readback_format);
	if (!readback_decoded)
	{
		device.submit_discard(cmd);
		return false;
	}

	Fence fence;
	device.submit(cmd, &fence);
	fence->wait();

	if (readback_format == VK_FORMAT_R16G16B16A16_SFLOAT)
		return compare_rgba16f(device, *readback_reference, *readback_decoded, width, height);
	else if (readback_format == VK_FORMAT_R8G8B8A8_SRGB || readback_format == VK_FORMAT_R8G8B8A8_UNORM)
		return compare_rgba8(device, *readback_reference, *readback_decoded, width, height, 0);
	else
		return false;
}

static bool test_astc_void_extent(Device &device, VkFormat format, VkFormat readback_format)
{
	auto cmd = device.request_command_buffer();
	std::mt19937 rnd(1338);
	Vulkan::MemoryMappedTexture tex;
	unsigned width = 2048;
	unsigned height = 2048;

	unsigned block_width, block_height;
	Vulkan::TextureFormatLayout::format_block_dim(format, block_width, block_height);

	unsigned blocks_x = (width + block_width - 1) / block_width;
	unsigned blocks_y = (height + block_height - 1) / block_height;
	unsigned num_blocks = blocks_x * blocks_y;
	tex.set_2d(format, width, height);
	if (!tex.map_write_scratch())
		return false;

	auto &layout = tex.get_layout();
	auto *d = static_cast<uint32_t *>(layout.data_opaque(0, 0, 0, 0));

	// Expose all possible weight encoding formats.
	for (unsigned i = 0; i < num_blocks; i++, d += 4)
	{
		d[0] = 0;
		d[1] = 0;
		d[2] = 0;
		d[3] = 0;

		d[0] |= 0x1fc;

		// HDR vs LDR selector.
		bool HDR = (i & 1) != 0;
		d[0] |= uint32_t(HDR) << 9;

		// Reserved bits must be 1.
		d[0] |= 3 << 10;

		// All 1s for S coord.
		if (i & 2)
		{
			d[0] |= ~0u << 12;
			d[1] |= (1 << 6) - 1;
		}

		// All 1s for T coord
		if (i & 4)
			d[1] = ~0u << 6;

		d[0] |= uint32_t(rnd()) << 12;
		d[1] |= uint32_t(rnd());

		if (HDR)
		{
			// Inputs must be finite, or we get undefined behavior.
			auto r = uint16_t(rnd());
			auto g = uint16_t(rnd());
			auto b = uint16_t(rnd());
			auto a = uint16_t(rnd());
			const auto fixup = [](uint16_t &v) { if (((v & 0x7fff) >> 10) >= 0x1f) v = 0; };
			fixup(r);
			fixup(g);
			fixup(b);
			fixup(a);
			d[2] |= uint32_t(r);
			d[2] |= uint32_t(g) << 16;
			d[3] |= uint32_t(b);
			d[3] |= uint32_t(a) << 16;
		}
		else
		{
			d[2] = uint32_t(rnd());
			d[3] = uint32_t(rnd());
		}
	}

	auto readback_reference = decode_gpu(*cmd, layout, readback_format);
	auto readback_decoded = decode_compute(*cmd, layout, readback_format);
	if (!readback_decoded)
	{
		device.submit_discard(cmd);
		return false;
	}

	Fence fence;
	device.submit(cmd, &fence);
	fence->wait();

	if (readback_format == VK_FORMAT_R16G16B16A16_SFLOAT)
		return compare_rgba16f(device, *readback_reference, *readback_decoded, width, height);
	else if (readback_format == VK_FORMAT_R8G8B8A8_SRGB || readback_format == VK_FORMAT_R8G8B8A8_UNORM)
		return compare_rgba8(device, *readback_reference, *readback_decoded, width, height, 0);
	else
		return false;
}

static bool test_astc_block_mode(Device &device, VkFormat format, VkFormat readback_format)
{
	auto cmd = device.request_command_buffer();
	std::mt19937 rnd(1338);
	Vulkan::MemoryMappedTexture tex;
	unsigned width = 8092;
	unsigned height = 8092;

	unsigned block_width, block_height;
	Vulkan::TextureFormatLayout::format_block_dim(format, block_width, block_height);

	unsigned blocks_x = (width + block_width - 1) / block_width;
	unsigned blocks_y = (height + block_height - 1) / block_height;
	unsigned num_blocks = blocks_x * blocks_y;
	tex.set_2d(format, width, height);
	if (!tex.map_write_scratch())
		return false;

	auto &layout = tex.get_layout();
	auto *d = static_cast<uint32_t *>(layout.data_opaque(0, 0, 0, 0));

	// Expose all possible weight encoding formats.
	for (unsigned i = 0; i < num_blocks; i++, d += 4)
	{
		d[0] = 0;
		d[1] = 0;
		d[2] = 0;
		d[3] = 0;

		// Exhaustively test all possible block modes, randomize all other data.
		d[0] = i & 0x3ff;
		d[0] |= uint32_t(rnd()) << 11;
		d[1] = uint32_t(rnd());
		d[2] = uint32_t(rnd());
		d[3] = uint32_t(rnd());
	}

	auto readback_reference = decode_gpu(*cmd, layout, readback_format);
	auto readback_decoded = decode_compute(*cmd, layout, readback_format);
	if (!readback_decoded)
	{
		device.submit_discard(cmd);
		return false;
	}

	Fence fence;
	device.submit(cmd, &fence);
	fence->wait();

	if (readback_format == VK_FORMAT_R16G16B16A16_SFLOAT)
		return compare_rgba16f(device, *readback_reference, *readback_decoded, width, height);
	else if (readback_format == VK_FORMAT_R8G8B8A8_SRGB || readback_format == VK_FORMAT_R8G8B8A8_UNORM)
		return compare_rgba8(device, *readback_reference, *readback_decoded, width, height, 0);
	else
		return false;
}

static bool test_astc(Device &device)
{
	static const VkFormat unorm_formats[] = {
		VK_FORMAT_ASTC_4x4_UNORM_BLOCK,
		VK_FORMAT_ASTC_5x4_UNORM_BLOCK,
		VK_FORMAT_ASTC_5x5_UNORM_BLOCK,
		VK_FORMAT_ASTC_6x5_UNORM_BLOCK,
		VK_FORMAT_ASTC_6x6_UNORM_BLOCK,
		VK_FORMAT_ASTC_8x5_UNORM_BLOCK,
		VK_FORMAT_ASTC_8x6_UNORM_BLOCK,
		VK_FORMAT_ASTC_8x8_UNORM_BLOCK,
		VK_FORMAT_ASTC_10x5_UNORM_BLOCK,
		VK_FORMAT_ASTC_10x6_UNORM_BLOCK,
		VK_FORMAT_ASTC_10x8_UNORM_BLOCK,
		VK_FORMAT_ASTC_10x10_UNORM_BLOCK,
		VK_FORMAT_ASTC_12x10_UNORM_BLOCK,
		VK_FORMAT_ASTC_12x12_UNORM_BLOCK,
	};

	static const VkFormat hdr_formats[] = {
		VK_FORMAT_ASTC_4x4_SFLOAT_BLOCK,
		VK_FORMAT_ASTC_5x4_SFLOAT_BLOCK,
		VK_FORMAT_ASTC_5x5_SFLOAT_BLOCK,
		VK_FORMAT_ASTC_6x5_SFLOAT_BLOCK,
		VK_FORMAT_ASTC_6x6_SFLOAT_BLOCK,
		VK_FORMAT_ASTC_8x5_SFLOAT_BLOCK,
		VK_FORMAT_ASTC_8x6_SFLOAT_BLOCK,
		VK_FORMAT_ASTC_8x8_SFLOAT_BLOCK,
		VK_FORMAT_ASTC_10x5_SFLOAT_BLOCK,
		VK_FORMAT_ASTC_10x6_SFLOAT_BLOCK,
		VK_FORMAT_ASTC_10x8_SFLOAT_BLOCK,
		VK_FORMAT_ASTC_10x10_SFLOAT_BLOCK,
		VK_FORMAT_ASTC_12x10_SFLOAT_BLOCK,
		VK_FORMAT_ASTC_12x12_SFLOAT_BLOCK,
	};

	static const VkFormat srgb_formats[] = {
		VK_FORMAT_ASTC_4x4_SRGB_BLOCK,
		VK_FORMAT_ASTC_5x4_SRGB_BLOCK,
		VK_FORMAT_ASTC_5x5_SRGB_BLOCK,
		VK_FORMAT_ASTC_6x5_SRGB_BLOCK,
		VK_FORMAT_ASTC_6x6_SRGB_BLOCK,
		VK_FORMAT_ASTC_8x5_SRGB_BLOCK,
		VK_FORMAT_ASTC_8x6_SRGB_BLOCK,
		VK_FORMAT_ASTC_8x8_SRGB_BLOCK,
		VK_FORMAT_ASTC_10x5_SRGB_BLOCK,
		VK_FORMAT_ASTC_10x6_SRGB_BLOCK,
		VK_FORMAT_ASTC_10x8_SRGB_BLOCK,
		VK_FORMAT_ASTC_10x10_SRGB_BLOCK,
		VK_FORMAT_ASTC_12x10_SRGB_BLOCK,
		VK_FORMAT_ASTC_12x12_SRGB_BLOCK,
	};

	const auto test_formats = [&](bool (*func)(Device &, VkFormat, VkFormat)) -> bool {
		for (auto format : srgb_formats)
		{
			uint32_t w, h;
			Vulkan::TextureFormatLayout::format_block_dim(format, w, h);
			LOGI(" ... %u x %u sRGB\n", w, h);
			if (!func(device, format, VK_FORMAT_R8G8B8A8_SRGB))
			{
				LOGE("    ... FAILED!\n");
				return false;
			}
			else
				LOGI("    ... Success!\n");

			device.wait_idle();
		}

		for (auto format : unorm_formats)
		{
			uint32_t w, h;
			Vulkan::TextureFormatLayout::format_block_dim(format, w, h);
			LOGI(" ... %u x %u UNORM (LDR)\n", w, h);
			if (!func(device, format, VK_FORMAT_R8G8B8A8_UNORM))
			{
				LOGE("    ... FAILED!\n");
				return false;
			}
			else
				LOGI("    ... Success!\n");

			device.wait_idle();
		}

		for (auto format : hdr_formats)
		{
			uint32_t w, h;
			Vulkan::TextureFormatLayout::format_block_dim(format, w, h);
			LOGI(" ... %u x %u UNORM (HDR)\n", w, h);
			if (!func(device, format, VK_FORMAT_R16G16B16A16_SFLOAT))
			{
				LOGE("    ... FAILED!\n");
				return false;
			}
			else
				LOGI("    ... Success!\n");

			device.wait_idle();
		}

		return true;
	};

	const auto test = [&](bool (*func)(Device &, VkFormat, VkFormat)) -> bool {
		if (!func(device, VK_FORMAT_ASTC_4x4_UNORM_BLOCK, VK_FORMAT_R16G16B16A16_SFLOAT))
		{
			LOGE("    ... FAILED!\n");
			return false;
		}
		else
			LOGI("    ... Success!\n");

		device.wait_idle();
		return true;
	};

	LOGI("Testing ASTC weight encoding and interpolation ...\n");
	if (!test_formats(test_astc_weights<false>))
		return false;
	LOGI("Testing ASTC dual plane encoding ...\n");
	if (!test_formats(test_astc_weights<true>))
		return false;
	LOGI("Testing ASTC endpoint formats ...\n");
	if (!test(test_astc_endpoint_formats))
		return false;
	LOGI("Testing ASTC multi-partition ...\n");
	if (!test(test_astc_partitions<false>))
		return false;
	LOGI("Testing ASTC multi-partition with dual-plane ...\n");
	if (!test(test_astc_partitions<true>))
		return false;
	LOGI("Testing ASTC multi-partition complex encoding ...\n");
	if (!test(test_astc_partitions_complex<false>))
		return false;
	LOGI("Testing ASTC multi-partition with dual-plane encoding ...\n");
	if (!test(test_astc_partitions_complex<true>))
		return false;
	LOGI("Testing ASTC void extent.\n");
	if (!test(test_astc_void_extent))
		return false;
	LOGI("Testing ASTC block mode.\n");
	if (!test_formats(test_astc_block_mode))
		return false;

	return true;
}

static bool test_bc6(Device &device, VkFormat format)
{
	auto cmd = device.request_command_buffer();
	std::mt19937 rnd(1337);

	Vulkan::MemoryMappedTexture tex;
	unsigned width = 4096;
	unsigned height = 4096;
	unsigned blocks_x = (width + 3) / 4;
	unsigned blocks_y = (height + 3) / 4;
	unsigned num_words = blocks_x * blocks_y *
	                     (TextureFormatLayout::format_block_size(format, VK_IMAGE_ASPECT_COLOR_BIT) / 4);
	tex.set_2d(format, width, height);
	if (!tex.map_write_scratch())
		return false;

	auto &layout = tex.get_layout();
	auto *d = static_cast<uint32_t *>(layout.data_opaque(0, 0, 0, 0));
	for (unsigned i = 0; i < num_words; i++)
	{
		uint32_t w = rnd();
		d[i] = w;
	}

	auto readback_reference = decode_gpu(*cmd, layout, VK_FORMAT_R16G16B16A16_SFLOAT);
	auto readback_decoded = decode_compute(*cmd, layout, VK_FORMAT_R16G16B16A16_SFLOAT);
	if (!readback_decoded)
	{
		device.submit_discard(cmd);
		return false;
	}

	Fence fence;
	device.submit(cmd, &fence);
	fence->wait();

	return compare_rgba16f(device, *readback_reference, *readback_decoded, width, height);
}

static bool test_bc7(Device &device, VkFormat format, VkFormat readback_format)
{
	auto cmd = device.request_command_buffer();
	std::mt19937 rnd(1337);

	Vulkan::MemoryMappedTexture tex;
	unsigned width = 4096;
	unsigned height = 4096;
	unsigned blocks_x = (width + 3) / 4;
	unsigned blocks_y = (height + 3) / 4;
	unsigned num_words = blocks_x * blocks_y *
	                     (TextureFormatLayout::format_block_size(format, VK_IMAGE_ASPECT_COLOR_BIT) / 4);
	tex.set_2d(format, width, height);
	if (!tex.map_write_scratch())
		return false;

	auto &layout = tex.get_layout();
	auto *d = static_cast<uint32_t *>(layout.data_opaque(0, 0, 0, 0));
	for (unsigned i = 0; i < num_words; i++)
	{
		uint32_t w = rnd();
		d[i] = w;
	}

	auto readback_reference = decode_gpu(*cmd, layout, readback_format);
	auto readback_decoded = decode_compute(*cmd, layout, readback_format);
	if (!readback_decoded)
	{
		device.submit_discard(cmd);
		return false;
	}

	Fence fence;
	device.submit(cmd, &fence);
	fence->wait();

	return compare_rgba8(device, *readback_reference, *readback_decoded, width, height, 0);
}

static bool test_eac(Device &device, VkFormat format, VkFormat readback_format)
{
	auto cmd = device.request_command_buffer();
	std::mt19937 rnd(1337);

	Vulkan::MemoryMappedTexture tex;
	unsigned width = 2048;
	unsigned height = 2048;
	unsigned blocks_x = (width + 3) / 4;
	unsigned blocks_y = (height + 3) / 4;
	unsigned num_words = blocks_x * blocks_y *
	                     (TextureFormatLayout::format_block_size(format, VK_IMAGE_ASPECT_COLOR_BIT) / 4);
	tex.set_2d(format, width, height);
	if (!tex.map_write_scratch())
		return false;

	auto &layout = tex.get_layout();
	auto *d = static_cast<uint32_t *>(layout.data_opaque(0, 0, 0, 0));
	for (unsigned i = 0; i < num_words; i++)
	{
		uint32_t w = rnd();
		d[i] = w;
	}

	auto readback_reference = decode_gpu(*cmd, layout, readback_format);
	auto readback_decoded = decode_compute(*cmd, layout, readback_format);
	if (!readback_decoded)
	{
		device.submit_discard(cmd);
		return false;
	}

	Fence fence;
	device.submit(cmd, &fence);
	fence->wait();

	if (readback_format == VK_FORMAT_R16G16_SFLOAT)
		return compare_rg16f(device, *readback_reference, *readback_decoded, width, height);
	else if (readback_format == VK_FORMAT_R16_SFLOAT)
		return compare_r16f(device, *readback_reference, *readback_decoded, width, height);
	else
		return false;
}

static bool test_etc2(Device &device, VkFormat format, VkFormat readback_format)
{
	auto cmd = device.request_command_buffer();
	std::mt19937 rnd(1337);

	Vulkan::MemoryMappedTexture tex;
	unsigned width = 2048;
	unsigned height = 2048;
	unsigned blocks_x = (width + 3) / 4;
	unsigned blocks_y = (height + 3) / 4;
	unsigned num_words = blocks_x * blocks_y *
	                     (TextureFormatLayout::format_block_size(format, VK_IMAGE_ASPECT_COLOR_BIT) / 4);
	tex.set_2d(format, width, height);
	if (!tex.map_write_scratch())
		return false;

	auto &layout = tex.get_layout();
	auto *d = static_cast<uint32_t *>(layout.data_opaque(0, 0, 0, 0));
	for (unsigned i = 0; i < num_words; i++)
	{
		uint32_t w = rnd();
		d[i] = w;
	}

	auto readback_reference = decode_gpu(*cmd, layout, readback_format);
	auto readback_decoded = decode_compute(*cmd, layout, readback_format);
	if (!readback_decoded)
	{
		device.submit_discard(cmd);
		return false;
	}

	Fence fence;
	device.submit(cmd, &fence);
	fence->wait();

	return compare_rgba8(device, *readback_reference, *readback_decoded, width, height, 0);
}

static bool test_rgtc(Device &device, VkFormat format, VkFormat readback_format)
{
	auto cmd = device.request_command_buffer();
	std::mt19937 rnd(1337);

	Vulkan::MemoryMappedTexture tex;
	unsigned width = 2048;
	unsigned height = 2048;
	unsigned blocks_x = (width + 3) / 4;
	unsigned blocks_y = (height + 3) / 4;
	unsigned num_words = blocks_x * blocks_y *
	                     (TextureFormatLayout::format_block_size(format, VK_IMAGE_ASPECT_COLOR_BIT) / 4);
	tex.set_2d(format, width, height);
	if (!tex.map_write_scratch())
		return false;

	auto &layout = tex.get_layout();
	auto *d = static_cast<uint32_t *>(layout.data_opaque(0, 0, 0, 0));
	for (unsigned i = 0; i < num_words; i++)
		d[i] = uint32_t(rnd());

	auto readback_reference = decode_gpu(*cmd, layout, readback_format);
	auto readback_decoded = decode_compute(*cmd, layout, readback_format);
	if (!readback_decoded)
	{
		device.submit_discard(cmd);
		return false;
	}

	Fence fence;
	device.submit(cmd, &fence);
	fence->wait();

	if (readback_format == VK_FORMAT_R8_UNORM)
		return compare_r8(device, *readback_reference, *readback_decoded, width, height, 1);
	else if (readback_format == VK_FORMAT_R8G8_UNORM)
		return compare_rg8(device, *readback_reference, *readback_decoded, width, height, 1);
	else
		return false;
}

static bool test_s3tc(Device &device, VkFormat format, VkFormat readback_format)
{
	auto cmd = device.request_command_buffer();
	std::mt19937 rnd(1337);

	Vulkan::MemoryMappedTexture tex;
	unsigned width = 2048;
	unsigned height = 2048;
	unsigned blocks_x = (width + 3) / 4;
	unsigned blocks_y = (height + 3) / 4;
	unsigned num_words = blocks_x * blocks_y *
	                     (TextureFormatLayout::format_block_size(format, VK_IMAGE_ASPECT_COLOR_BIT) / 4);
	tex.set_2d(format, width, height);
	if (!tex.map_write_scratch())
		return false;

	auto &layout = tex.get_layout();
	auto *d = static_cast<uint32_t *>(layout.data_opaque(0, 0, 0, 0));
	for (unsigned i = 0; i < num_words; i++)
		d[i] = uint32_t(rnd());

	auto readback_reference = decode_gpu(*cmd, layout, readback_format);
	auto readback_decoded = decode_compute(*cmd, layout, readback_format);
	if (!readback_decoded)
	{
		device.submit_discard(cmd);
		return false;
	}

	Fence fence;
	device.submit(cmd, &fence);
	fence->wait();

	return compare_rgba8(device, *readback_reference, *readback_decoded, width, height, 1);
}

static bool test_s3tc(Device &device)
{
	LOGI("Testing BC1 RGBA UNORM.\n");
	if (!test_s3tc(device, VK_FORMAT_BC1_RGBA_UNORM_BLOCK, VK_FORMAT_R8G8B8A8_UNORM))
		return false;
	device.wait_idle();
	LOGI("Testing BC1 RGB UNORM.\n");
	if (!test_s3tc(device, VK_FORMAT_BC1_RGB_UNORM_BLOCK, VK_FORMAT_R8G8B8A8_UNORM))
		return false;
	device.wait_idle();
	LOGI("Testing BC1 sRGBA UNORM.\n");
	if (!test_s3tc(device, VK_FORMAT_BC1_RGBA_SRGB_BLOCK, VK_FORMAT_R8G8B8A8_SRGB))
		return false;
	device.wait_idle();
	LOGI("Testing BC1 sRGB UNORM.\n");
	if (!test_s3tc(device, VK_FORMAT_BC1_RGB_SRGB_BLOCK, VK_FORMAT_R8G8B8A8_SRGB))
		return false;
	device.wait_idle();
	LOGI("Testing BC2 UNORM.\n");
	if (!test_s3tc(device, VK_FORMAT_BC2_UNORM_BLOCK, VK_FORMAT_R8G8B8A8_UNORM))
		return false;
	device.wait_idle();
	LOGI("Testing BC2 sRGB.\n");
	if (!test_s3tc(device, VK_FORMAT_BC2_SRGB_BLOCK, VK_FORMAT_R8G8B8A8_SRGB))
		return false;
	device.wait_idle();
	LOGI("Testing BC3 UNORM.\n");
	if (!test_s3tc(device, VK_FORMAT_BC3_UNORM_BLOCK, VK_FORMAT_R8G8B8A8_UNORM))
		return false;
	device.wait_idle();
	LOGI("Testing BC3 sRGB.\n");
	if (!test_s3tc(device, VK_FORMAT_BC3_SRGB_BLOCK, VK_FORMAT_R8G8B8A8_SRGB))
		return false;
	device.wait_idle();
	return true;
}

static bool test_rgtc(Device &device)
{
	LOGI("Testing BC4 UNORM.\n");
	if (!test_rgtc(device, VK_FORMAT_BC4_UNORM_BLOCK, VK_FORMAT_R8_UNORM))
		return false;
	device.wait_idle();
	LOGI("Testing BC5 UNORM.\n");
	if (!test_rgtc(device, VK_FORMAT_BC5_UNORM_BLOCK, VK_FORMAT_R8G8_UNORM))
		return false;
	device.wait_idle();
	return true;
}

static bool test_etc2(Device &device)
{
	LOGI("Testing ETC2 RGB UNORM.\n");
	if (!test_etc2(device, VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK, VK_FORMAT_R8G8B8A8_UNORM))
		return false;
	device.wait_idle();
	LOGI("Testing ETC2 RGB sRGB.\n");
	if (!test_etc2(device, VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK, VK_FORMAT_R8G8B8A8_SRGB))
		return false;
	device.wait_idle();
	LOGI("Testing ETC2 RGB8A1 UNORM.\n");
	if (!test_etc2(device, VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK, VK_FORMAT_R8G8B8A8_UNORM))
		return false;
	device.wait_idle();
	LOGI("Testing ETC2 RGB8A1 sRGB.\n");
	if (!test_etc2(device, VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK, VK_FORMAT_R8G8B8A8_SRGB))
		return false;
	device.wait_idle();
	LOGI("Testing ETC2 RGB8A8 UNORM.\n");
	if (!test_etc2(device, VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK, VK_FORMAT_R8G8B8A8_UNORM))
		return false;
	device.wait_idle();
	LOGI("Testing ETC2 RGB8A8 sRGB.\n");
	if (!test_etc2(device, VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK, VK_FORMAT_R8G8B8A8_SRGB))
		return false;
	device.wait_idle();
	return true;
}

static bool test_eac(Device &device)
{
	LOGI("Testing EAC R11 UNORM.\n");
	if (!test_eac(device, VK_FORMAT_EAC_R11_UNORM_BLOCK, VK_FORMAT_R16_SFLOAT))
		return false;
	device.wait_idle();
	LOGI("Testing EAC R11G11 UNORM.\n");
	if (!test_eac(device, VK_FORMAT_EAC_R11G11_UNORM_BLOCK, VK_FORMAT_R16G16_SFLOAT))
		return false;
	device.wait_idle();
	return true;
}

static bool test_bc7(Device &device)
{
	LOGI("Testing BC7 sRGB.\n");
	if (!test_bc7(device, VK_FORMAT_BC7_SRGB_BLOCK, VK_FORMAT_R8G8B8A8_SRGB))
		return false;
	device.wait_idle();
	LOGI("Testing BC7 UNORM.\n");
	if (!test_bc7(device, VK_FORMAT_BC7_UNORM_BLOCK, VK_FORMAT_R8G8B8A8_UNORM))
		return false;
	device.wait_idle();
	return true;
}

static bool test_bc6(Device &device)
{
	LOGI("Testing BC6 SFLOAT.\n");
	if (!test_bc6(device, VK_FORMAT_BC6H_SFLOAT_BLOCK))
		return false;
	device.wait_idle();
	LOGI("Testing BC6 UFLOAT.\n");
	if (!test_bc6(device, VK_FORMAT_BC6H_UFLOAT_BLOCK))
		return false;
	device.wait_idle();
	return true;
}

int main()
{
	Global::init(Global::MANAGER_FEATURE_DEFAULT_BITS, 1);

	if (!Context::init_loader(nullptr))
		return EXIT_FAILURE;

	Context ctx;

	Context::SystemHandles handles;
	handles.filesystem = GRANITE_FILESYSTEM();
	handles.thread_group = GRANITE_THREAD_GROUP();
	ctx.set_system_handles(handles);

	ctx.set_num_thread_indices(2);
	if (!ctx.init_instance_and_device(nullptr, 0, nullptr, 0))
		return EXIT_FAILURE;

	Device device;
	device.set_context(ctx);

	if (!test_s3tc(device))
		return EXIT_FAILURE;
	if (!test_rgtc(device))
		return EXIT_FAILURE;
	if (!test_etc2(device))
		return EXIT_FAILURE;
	if (!test_eac(device))
		return EXIT_FAILURE;
	if (!test_bc7(device))
		return EXIT_FAILURE;
	if (!test_bc6(device))
		return EXIT_FAILURE;
	if (!test_astc(device))
		return EXIT_FAILURE;
}

redpajama_set_name: RedPajamaGithub


text:
package org.docryze.talk.talkutil.zookeeper;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

import static org.jboss.netty.handler.codec.rtsp.RtspHeaders.Values.CLIENT_PORT;

/**
 * Zookeeper工具类,用于连接服务,交互数据
 */
public class ZookeeperUtil {
    public static String QueryFromZookeeper(String path) {
        ZooKeeper zk = null;
        String data = null;
        try {
            // 创建一个与服务器的连接
            zk = new ZooKeeper("localhost:" + 2181, 3000, null);
            // 获取指定路径的数据
            if (zk.exists(path, false) == null) {
                return data;
            }
            data = new String(zk.getData(path, false, null), Charset.forName("UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接
            if (zk == null) {
                try {
                    zk.close();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return data;
        }
    }
}


text:
define([], function() {
  'use strict';
  // this is a simple sanity check to verify
  // that the test framwork is up and running
  describe('sanity check', function() {
    it('should pass', function() {

      expect(1).to.equal(1);

    });
  });
});


text:
package tjs.tuneramblr.meta.model;

/**
 * Enumeration of the types of checkins
 */
public enum CheckinType {
	USER_LIKE("user_like"), SKIP("skip"), FULLY_LISTENED("fully_listened");

	private String typeName;

	CheckinType(String typeName) {
		this.typeName = typeName;
	}

	public String toValue() {
		return this.typeName;
	}

	public static CheckinType fromValue(String s) {
		CheckinType retVal = null;
		if (s == null) {
			retVal = null;
		} else if (USER_LIKE.toString().equals(s)) {
			retVal = USER_LIKE;
		} else if (SKIP.toString().equals(s)) {
			retVal = SKIP;
		} else {
			retVal = FULLY_LISTENED;
		}

		return retVal;
	}
}


text:
package org.gaul.s3proxy;

import java.util.Collection;

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;

// CHECKSTYLE:OFF
final class DeleteMultipleObjectsRequest {
    @JacksonXmlProperty(localName = "Quiet")
    boolean quiet;

    @JacksonXmlProperty(localName = "Object")
    @JacksonXmlElementWrapper(useWrapping = false)
    Collection<S3Object> objects;

    static final class S3Object {
        @JacksonXmlProperty(localName = "Key")
        String key;
        @JacksonXmlProperty(localName = "VersionID")
        String versionId;
    }
}
// CHECKSTYLE:ON


text: export { ListItem } from './listItem';


text:
<link rel="import" href="/components/core-icon/core-icon.html">

<polymer-element name="alert-icon">
  <template>
    <style>

      .highlighted {
        box-shadow: 0px 0px 5px #ffba02;
        border: 2px solid #ffba02;
        border-radius: 14px;
      }

    </style>

    <core-icon id="icon"></core-icon>

  </template>
  <script>
    'use strict';
    Polymer('alert-icon', {

      initialize: function(alertAnnotation, alertKey) {
        var bugId = alertAnnotation['bug_id'];
        var improvement = alertAnnotation['improvement'];
        var recovered = alertAnnotation['recovered'];
        var key = alertAnnotation['key'];

        this.$.icon.icon = 'report';
        var color = 'black';
        if (!bugId && !improvement) {
          color = 'red';
        } else if (!bugId && improvement) {
          color = 'green';
          this.$.icon.icon = 'info';
        }

        this.$.icon.style.color = color;

        if (bugId && bugId < 0 || recovered) {
          // Triaged as invalid, ignored, or recovered; lower opacity.
          this.$.icon.style.opacity = 0.25;
        }

        // alertKey is an optional attribute to specify that this chart
        // is associated with an alert. If this alert is the one alert that
        // this chart is meant to draw attention to, we want to distinguish
        // this alert from any others on the chart.
        if (alertKey == key) {
           this.$.icon.classList.add('highlighted');
        }
      },

      setPosition: function(top, left) {
        this.$.icon.style.top = top + 'px';
        this.$.icon.style.left = left + 'px';
      }
    });
  </script>
</polymer-element>


text:
angular.module("umbraco")
.controller("UmbracoForms.Dashboards.ActivityController",
	function ($scope, recordResource) {

		//var filter = {};
		//recordResource.getRecords(filter).then(function(response){
		//	$scope.records = response.data;
		//});

	});


text:
package org.springframework.security.authentication;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.Authentication;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;

/**
 * @author Rob Winch
 * @since 5.0
 */
@RunWith(MockitoJUnitRunner.class)
public class ReactiveAuthenticationManagerAdapterTests {
	@Mock
	AuthenticationManager delegate;
	@Mock
	Authentication authentication;

	ReactiveAuthenticationManagerAdapter manager;

	@Before
	public void setup() {
		manager = new ReactiveAuthenticationManagerAdapter(delegate);
	}

	@Test(expected = IllegalArgumentException.class)
	public void constructorNullAuthenticationManager() {
		new ReactiveAuthenticationManagerAdapter(null);
	}

	@Test
	public void authenticateWhenSuccessThenSucces() {
		when(delegate.authenticate(any())).thenReturn(authentication);
		when(authentication.isAuthenticated()).thenReturn(true);

		Authentication result = manager.authenticate(authentication).block();

		assertThat(result).isEqualTo(authentication);
	}

	@Test
	public void authenticateWhenReturnNotAuthenticatedThenError() {
		when(delegate.authenticate(any())).thenReturn(authentication);

		Authentication result = manager.authenticate(authentication).block();

		assertThat(result).isNull();
	}

	@Test
	public void authenticateWhenBadCredentialsThenError() {
		when(delegate.authenticate(any())).thenThrow(new BadCredentialsException("Failed"));
		when(authentication.isAuthenticated()).thenReturn(true);

		Mono<Authentication> result = manager.authenticate(authentication);

		StepVerifier.create(result)
			.expectError(BadCredentialsException.class)
			.verify();
	}
}


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe DattsRight, ".write_dynamic_attribute" do
  it "should be aliased by write_datt" do
    Page.instance_method(:write_dynamic_attribute).should == Page.instance_method(:write_datt)
  end
end


text:
- tagline: Learn about how Fable works & how to use it

# Fable documentation

The following documentation pages are generated from the `docs` pages
in the Fable repository on GitHub. Is anything unclear or missing?
Help us make Fable better by contributing!

### [ Compiling to JavaScript](docs/compiling.html)

Start here! The page covers all you need to get started
with Fable. This includes the `fable` command parameters, `fableconfig.json` file,
using Fable through Polyfill, modules, debugging, testing and more.

### [ F# language and library compatibility](docs/compatibility.html)

Provides details about the compatibility. This page explains how are primitive
F# and CLR types compiled to JavaScript, which F# and CLR classes are supported
and how they are translated.

### [ Interacting with JavaScript](docs/interacting.html)

How to call JavaScript libraries? With Fable, you can use the dynamic operator
and write `jsObject?foo`, you can use the `Emit` attribute, or define a foreign
interface. There are a couple of special attributes too. Learn more here!

### [ Fable architecture](docs/plugins.html)

Is it very easy to add features to Fable using plugins. The best example is [the
plugin to transform NUnit tests into Mocha](https://github.com/fable-compiler/Fable/tree/master/src/plugins/nunit/Fable.Plugins.NUnit.fsx).
In order to understand the plugin system we'll review briefly how Fable works.


text:
int main(int argc, char *argv[]) {
	time_t current_time;
	time(&current_time);

	putenv("TZ=America/Los_Angeles");
	printf("%s", ctime(&current_time));
}


text:
<?php

namespace Mpclarkson\ResqueBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class ResqueExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
        $loader->load('services.xml');

        $container->setParameter('resque.vendor_dir', $config['vendor_dir']);
        $container->setParameter('resque.app_include', $config['app_include']);
        $container->setParameter('resque.class', $config['class']);
        $container->setParameter('resque.redis.host', $config['redis']['host']);
        $container->setParameter('resque.redis.port', $config['redis']['port']);
        $container->setParameter('resque.redis.database', $config['redis']['database']);

        if (!empty($config['prefix'])) {
            $container->setParameter('resque.prefix', $config['prefix']);
            $container->getDefinition('resque')->addMethodCall('setPrefix', [$config['prefix']]);
        }

        if (!empty($config['worker']['root_dir'])) {
            $container->setParameter('resque.worker.root_dir', $config['worker']['root_dir']);
        }

        if (!empty($config['auto_retry'])) {
            if (isset($config['auto_retry'][0])) {
                $container->getDefinition('resque')->addMethodCall('setGlobalRetryStrategy', [$config['auto_retry'][0]]);
            } else {
                if (isset($config['auto_retry']['default'])) {
                    $container->getDefinition('resque')->addMethodCall('setGlobalRetryStrategy', [$config['auto_retry']['default']]);
                    unset($config['auto_retry']['default']);
                }
                $container->getDefinition('resque')->addMethodCall('setJobRetryStrategy', [$config['auto_retry']]);
            }
        }
    }
}


text:
(function () {
	'use strict';

	var map = new L.Map('map', {
		zoomControl: false,
		center: [48, -3],
		zoom: 5
	});

	// This is a list of example API codes, to make this preview
	// functioning. Please register with the providers to use them
	// with your own app.
	var exampleAPIcodes = {
		'HERE': {
			'app_id': 'Y8m9dK2brESDPGJPdrvs',
			'app_code': 'dq2MYIvjAotR8tHvY8Q_Dg'
		}
	};

	// save the options while creating tilelayers to cleanly access them later.
	var origTileLayerInit = L.TileLayer.prototype.initialize;
	L.TileLayer.include({
		initialize: function (url, options) {
			this._options = options;
			origTileLayerInit.apply(this, arguments);

			// replace example API codes in options
			if (this._providerName) {
				var provider = this._providerName.split('.')[0];
				if (provider in exampleAPIcodes) {
					L.extend(this.options, exampleAPIcodes[provider]);
				}
			}
		}
	});

	var origProviderInit = L.TileLayer.Provider.prototype.initialize;
	L.TileLayer.Provider.include({
		initialize: function (arg) {
			this._providerName = arg;
			origProviderInit.apply(this, arguments);
		}
	});

	var isOverlay = function (providerName) {
		var overlayPatterns = [
			'^(OpenWeatherMap|OpenSeaMap)',
			'OpenMapSurfer.AdminBounds',
			'Stamen.Toner(Hybrid|Lines|Labels)',
			'Acetate.(foreground|labels|roads)',
			'Hydda.RoadsAndLabels'
		];

		return providerName.match('(' + overlayPatterns.join('|') + ')') !== null;
	};

	// Ignore some providers in the preview
	var isIgnored = function (providerName) {
		var ignorePattern = /^(MapBox|OpenSeaMap)/;

		return providerName.match(ignorePattern) !== null;
	};

	var escapeHtml = function (string) {
		return string
			.replace(/&/g, '&')
			.replace(/</g, '<')
			.replace(/>/g, '>')
			.replace(/"/g, '"')
			.replace(/'/g, ''');
	};

	// collect all layers available in the provider definition
	var baseLayers = {};
	var overlays = {};

	var addLayer = function (name) {
		if (isOverlay(name)) {
			overlays[name] = L.tileLayer.provider(name);
		} else {
			baseLayers[name] = L.tileLayer.provider(name);
		}
	};

	for (var provider in L.TileLayer.Provider.providers) {
		if (isIgnored(provider)) {
			continue;
		}
		if (L.TileLayer.Provider.providers[provider].variants) {
			for (var variant in L.TileLayer.Provider.providers[provider].variants) {
				addLayer(provider + '.' + variant);
			}
		} else {
			addLayer(provider);
		}
	}

	// add minimap control to the map
	var layersControl = L.control.layers.minimap(baseLayers, overlays, {
		collapsed: false
	}).addTo(map);

	// Pass a filter in the hash tag to show only layers containing that string
	// for example: #filter=Open
	var filterLayersControl = function () {
		var hash = window.location.hash;
		var filterIndex = hash.indexOf('filter=');
		if (filterIndex !== -1) {
			var filterString = hash.substr(filterIndex + 7).trim();
			layersControl.filter(filterString);
		}
	};
	L.DomEvent.on(window, 'hashchange', filterLayersControl);

	// Does not work if called immediately, so ugly hack to apply filter
	// at first page load
	setTimeout(filterLayersControl, 100);

	// add OpenStreetMap.Mapnik, or the first if it does not exist
	if (baseLayers['OpenStreetMap.Mapnik']) {
		baseLayers['OpenStreetMap.Mapnik'].addTo(map);
	} else {
		baseLayers[Object.keys(baseLayers)[0]].addTo(map);
	}

	// Add the TileLayer source code control to the map
	map.addControl(new (L.Control.extend({
		options: {
			position: 'topleft'
		},
		onAdd: function (map) {
			var container = L.DomUtil.get('info');
			L.DomEvent.disableClickPropagation(container);

			L.DomUtil.create('h4', null, container).innerHTML = 'Provider names for leaflet-providers.js';
			var providerNames = L.DomUtil.create('code', 'provider-names', container);

			L.DomUtil.create('h4', '', container).innerHTML = 'Plain JavaScript:';
			var pre = L.DomUtil.create('pre', null, container);
			var code = L.DomUtil.create('code', 'javascript', pre);

			var update = function (event) {
				code.innerHTML = '';

				var names = [];

				// loop over the layers in the map and add the JS
				for (var key in map._layers) {
					var layer = map._layers[key];

					names.push(layer._providerName);
					var layerName = layer._providerName.replace('.', '_');

					// do not add the layer currently being removed
					if (event && event.type === 'layerremove' && layer === event.layer) {
						continue;
					}
					var url = layer._url;
					var options = L.extend({}, layer._options);

					// replace {variant} in urls with the selected variant, since
					// keeping it in the options map doesn't make sense for one layer
					if (options.variant) {
						url = url.replace('{variant}', options.variant);
						delete options.variant;
					}
					var tileLayerCode = 'var ' + layerName + ' = L.tileLayer(\'' + url + '\', {\n';

					var first = true;
					for (var option in options) {
						if (first) {
							first = false;
						} else {
							tileLayerCode += ',\n';
						}
						tileLayerCode += '\t' + option + ': ';
						if (typeof options[option] === 'string') {
							//jshint quotmark:double
							tileLayerCode += "'" + escapeHtml(options[option]) + "'";
							//jshint quotmark:single
						} else {
							/* global JSON:true */
							tileLayerCode += JSON.stringify(options[option]);
						}
					}
					tileLayerCode += '\n});\n';
					code.innerHTML += tileLayerCode;

					providerNames.innerHTML = names.join(', ');
				}
				/* global hljs:true */
				hljs.highlightBlock(code);
			};

			map.on({
				'layeradd': update,
				'layerremove': update
			});
			update();

			return container;
		}
	}))());

})();


text:
package racoon.tuning;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import peersim.cdsim.CDSimulator;
import peersim.config.IllegalParameterException;
import peersim.config.MissingParameterException;
import peersim.core.CommonState;
import racoon.core.RacoonProcess;
import racoon.input.CEMechanisms;
import racoon.util.OutputWriter;

/**
 * Test a single configuration settings for the {@link CEMechanisms} using the
 * open-source simulation framework PeerSim (http://peersim.sourceforge.net/).
 *
 * @author Guido Lena Cota <guido.lena@unimi.it>
 */
public class SingleSimulation {

	// LOGGER
	static final Logger LOGGER = LogManager.getLogger(SingleSimulation.class.getName());

	// INITIALIZATION
	// ------------------------------------------------------------------------------------------

	/**
	 * Default constructor, invoked in {@link RacoonProcess}.
	 */
	public SingleSimulation() {}

	// METHODS
	// ------------------------------------------------------------------------------------------

	public void startAnalysis(){

		LOGGER.info("Single simulation started.");
		long simulationStartTime = System.nanoTime();

		/* RUN THE SIMULATION */
		doSimulate();

		// update statistics about simulation time
		long simDuration = (System.nanoTime() - simulationStartTime)/1000000;
		// append the simulation time in the summary report
		OutputWriter.updateReportSummary("" + simDuration);

		LOGGER.info("Simulation completed in " + (System.nanoTime() - simulationStartTime)/1000000 + " milliseconds.");
	}

	/**
	 * Run a game-based simulation using the open-source simulation framework PeerSim
	 * (http://peersim.sourceforge.net/).
	 *
	 * @return The duration in milliseconds of the simulation.
	 */
	private void doSimulate(){
		try {
			long seed = CommonState.r.nextLong();
			CommonState.initializeRandom(seed);
			CDSimulator.nextExperiment();

		} catch (MissingParameterException | IllegalParameterException e ) {
			System.err.println(e+"");
			System.exit(1);
		}
	}
}


text:
namespace Azure.ResourceManager.RecoveryServicesSiteRecovery.Models
{
    /// <summary> InMageAzureV2 Managed disk details. </summary>
    public partial class InMageAzureV2ManagedDiskDetails
    {
        /// <summary> Initializes a new instance of InMageAzureV2ManagedDiskDetails. </summary>
        internal InMageAzureV2ManagedDiskDetails()
        {
        }

        /// <summary> Initializes a new instance of InMageAzureV2ManagedDiskDetails. </summary>
        /// <param name="diskId"> The disk id. </param>
        /// <param name="seedManagedDiskId"> Seed managed disk Id. </param>
        /// <param name="replicaDiskType"> The replica disk type. </param>
        /// <param name="diskEncryptionSetId"> The DiskEncryptionSet ARM ID. </param>
        /// <param name="targetDiskName"> The target disk name. </param>
        internal InMageAzureV2ManagedDiskDetails(string diskId, string seedManagedDiskId, string replicaDiskType, string diskEncryptionSetId, string targetDiskName)
        {
            DiskId = diskId;
            SeedManagedDiskId = seedManagedDiskId;
            ReplicaDiskType = replicaDiskType;
            DiskEncryptionSetId = diskEncryptionSetId;
            TargetDiskName = targetDiskName;
        }

        /// <summary> The disk id. </summary>
        public string DiskId { get; }
        /// <summary> Seed managed disk Id. </summary>
        public string SeedManagedDiskId { get; }
        /// <summary> The replica disk type. </summary>
        public string ReplicaDiskType { get; }
        /// <summary> The DiskEncryptionSet ARM ID. </summary>
        public string DiskEncryptionSetId { get; }
        /// <summary> The target disk name. </summary>
        public string TargetDiskName { get; }
    }
}


text:
set -e
"$(dirname "$0")"/import-prep.py "$@"
scp schedule.csv import-run.sh pycon:
cat <<'EOF'

Copy complete!  Now log on to the server and run:
./import-run.sh ...

EOF


text:
import os

from .. import env
from ..config import config

env.CLOUDIFY_WORKDIR = '/tmp/.cloudify-test'
env.PROFILES_DIR = os.path.join(env.CLOUDIFY_WORKDIR, 'profiles')
env.ACTIVE_PRO_FILE = os.path.join(env.CLOUDIFY_WORKDIR, 'active.profile')
env.MULTIPLE_LOCAL_BLUEPRINTS = False

config.CLOUDIFY_CONFIG_PATH = os.path.join(env.CLOUDIFY_WORKDIR, 'config.yaml')


text:
<?php

namespace Hospitalisation\Model;

use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Where;
use Zend\Db\Sql\Predicate\NotIn;
use Facturation\View\Helper\DateHelper;

class PatientTable {
	protected $tableGateway;
	public function __construct(TableGateway $tableGateway) {
		$this->tableGateway = $tableGateway;
	}
	public function fetchAll() {
		$resultSet = $this->tableGateway->select ();
		return $resultSet;
	}
	public function getPatient($id_personne) {
		$id_personne = ( int ) $id_personne;
		$rowset = $this->tableGateway->select ( array (
				'ID_PERSONNE' => $id_personne
		) );
		$row =  $rowset->current ();
		if (! $row) {
			return null;
		}
		return $row;
	}
	public function savePatient(Patient $patient) {
		$control = new DateHelper();
		$data = array (
				'civilite' => $patient->civilite,
				'prenom' => $patient->prenom,
				'nom' => $patient->nom,
				'date_naissance' => $control->convertDateInAnglais($patient->date_naissance),
				'lieu_naissance' => $patient->lieu_naissance,
				'adresse' => $patient->adresse,
				'sexe' => $patient->sexe,
				'nationalite_actuelle' => $patient->nationalite_actuelle,
				'nationalite_origine' => $patient->nationalite_origine,
				'telephone' => $patient->telephone,
				'email' => $patient->email,
				'profession' => $patient->profession,
				'photo' => $patient->photo,
				'date_enregistrement' => $patient->date_enregistrement,

		);

		$id = ( int ) $patient->id_personne;
		if ($id == 0) {
			$this->tableGateway->insert ( $data );
		} else {
			if ($this->getPatient ( $id )) {
				$this->tableGateway->update ( $data, array (
						'ID_PERSONNE' => $id
				) );
			} else {
				throw new \Exception ( 'Patient id does not exist' );
			}
		}
	}

	public function addPatient($donnees){
		$this->tableGateway->insert ( $donnees );
	}

	public function addPatientNe($donnees){
 		return($this->tableGateway->getLastInsertValue($this->tableGateway->insert ( $donnees )));
	}

	public  function updatePatient($donnees, $id_personne){
		$this->tableGateway->update( $donnees, array('ID_PERSONNE' => $id_personne) );
	}

	public function deletePatient($id) {
		$this->tableGateway->delete ( array (
				'ID_PERSONNE' => $id
		) );
	}
	function quoteInto($text, $value, $platform, $count = null)
	{
		if ($count === null) {
			return str_replace('?', $platform->quoteValue($value), $text);
		} else {
			while ($count > 0) {
				if (strpos($text, '?') !== false) {
					$text = substr_replace($text, $platform->quoteValue($value), strpos($text, '?'), 1);
				}
				--$count;
			}
			return $text;
		}
	}
	//Réduire la chaine addresse
	function adresseText($Text){
		$chaine = $Text;
		if(strlen($Text)>36){
			$chaine = substr($Text, 0, 36);
			$nb = strrpos($chaine, ' ');
			$chaine = substr($chaine, 0, $nb);
			$chaine .=' ...';
		}
		return $chaine;
	}
	public function getListePatient(){

		$db = $this->tableGateway->getAdapter();

		$aColumns = array('Nom','Prenom','Datenaissance','Sexe', 'Adresse', 'Nationalite', 'id');

		/* Indexed column (used for fast and accurate table cardinality) */
		$sIndexColumn = "id";

		/*
		 * Paging
		*/
		$sLimit = array();
		if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
		{
			$sLimit[0] = $_GET['iDisplayLength'];
			$sLimit[1] = $_GET['iDisplayStart'];
		}

		/*
		 * Ordering
		*/
		if ( isset( $_GET['iSortCol_0'] ) )
		{
			$sOrder = array();
			$j = 0;
			for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ )
			{
				if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
				{
					$sOrder[$j++] = $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
								 	".$_GET['sSortDir_'.$i];
				}
			}
		}

		/*
		 * SQL queries
		*/
		$sql = new Sql($db);
		$sQuery = $sql->select()
		->from(array('pat' => 'patient'))->columns(array('Nom'=>'NOM','Prenom'=>'PRENOM','Datenaissance'=>'DATE_NAISSANCE','Sexe'=>'SEXE','Adresse'=>'ADRESSE','Nationalite'=>'NATIONALITE_ACTUELLE','Taille'=>'TAILLE','id'=>'ID_PERSONNE'));

		/* Data set length after filtering */
		$stat = $sql->prepareStatementForSqlObject($sQuery);
		$rResultFt = $stat->execute();
		$iFilteredTotal = count($rResultFt);

		$rResult = $rResultFt;

		$output = array(
				//"sEcho" => intval($_GET['sEcho']),
				//"iTotalRecords" => $iTotal,
				"iTotalDisplayRecords" => $iFilteredTotal,
				"aaData" => array()
		);

		/*
		 * $Control pour convertir la date en fran�ais
		 */
		$Control = new DateHelper();

		/*
		 * ADRESSE URL RELATIF
		 */
		$baseUrl = $_SERVER['REQUEST_URI'];
		$tabURI  = explode('public', $baseUrl);

		/*
		 * Pr�parer la liste
		 */
		foreach ( $rResult as $aRow )
		{
			$row = array();
			for ( $i=0 ; $i<count($aColumns) ; $i++ )
			{
				if ( $aColumns[$i] != ' ' )
				{
					/* General output */
					if ($aColumns[$i] == 'Nom'){
						$row[] = "<khass id='nomMaj'>".$aRow[ $aColumns[$i]]."</khass>";
					}

				    else if ($aColumns[$i] == 'Datenaissance') {
						$row[] = $Control->convertDate($aRow[ $aColumns[$i] ]);
					}

					else if ($aColumns[$i] == 'Adresse') {
						$row[] = $this->adresseText($aRow[ $aColumns[$i] ]);
					}

					else if ($aColumns[$i] == 'id') {
						$html ="";
						$html .="";

						$html .= "";
						$html .="";

						$html .= "";
						$html .="";

						$row[] = $html;
					}

					else {
						$row[] = $aRow[ $aColumns[$i] ];
					}

				}
			}
			$output['aaData'][] = $row;
		}
		return $output;
	}

	public function tousPatientsAdmis($service) {
		//var_dump($service);exit();
		$today = new \DateTime();
		$date = $today->format('Y-m-d');
		$adapter = $this->tableGateway->getAdapter ();
		$sql = new Sql ( $adapter );
		$select1 = $sql->select ();
		$select1->from ( array (
				'p' => 'patient'
		) );
		$select1->columns(array (
				'Nom' => 'NOM',
				'Prenom' => 'PRENOM',
				'Datenaissance' => 'DATE_NAISSANCE',
				'Sexe' => 'SEXE',
				'Adresse' => 'ADRESSE',
				'Nationalite' => 'NATIONALITE_ACTUELLE',
				'Taille' => 'TAILLE',
				'Id' => 'ID_PERSONNE'
		) );
		$select1->join(array('f' => 'facturation'), 'p.ID_PERSONNE = f.id_patient', array('Id_facturation' => 'id_facturation'));
		$select1->join(array('s' => 'service'), 'f.id_service = s.id_service', array('Nomservice' => 'NOM'));
		$select1->where(array('date_cons' => $date, 's.NOM' => $service));
		$select1->order('id_facturation ASC');
		$statement1 = $sql->prepareStatementForSqlObject ( $select1 );
		$result1 = $statement1->execute ();

		//var_dump($result1);exit();
		$select2 = $sql->select ('consultation');
		$select2->columns(array('Id' => 'PAT_ID_PERSONNE',
				'Id_cons' => 'ID_CONS',
				'Date_cons' => 'DATEONLY',));
		$select2->where(array('DATEONLY' => $date));
		$statement2 = $sql->prepareStatementForSqlObject ( $select2 );
		$result2 = $statement2->execute ();
		$tab = array($result1,$result2);
		return $tab;
	}
	public function listePatients() {
		$adapter = $this->tableGateway->getAdapter ();
		$sql1 = new Sql ( $adapter );
		$subselect = $sql1->select ();
		$subselect->from ( array (
				'd' => 'deces'
		) );
		$subselect->columns ( array (
				'id_personne'
		) );
		$sql2 = new Sql ( $adapter );
		$rowset = $sql2->select ();
		$rowset->from(array (
				'p' => 'patient'
		) );
		$rowset->columns( array (
				'Nom' => 'NOM',
				'Prenom' => 'PRENOM',
				'Datenaissance' => 'DATE_NAISSANCE',
				'Sexe' => 'SEXE',
				'Adresse' => 'ADRESSE',
				'Nationalite' => 'NATIONALITE_ACTUELLE',
				'Taille' => 'TAILLE',
				'Id' => 'ID_PERSONNE'
		) );
		$rowset->where(array (
				'ID_PERSONNE > 800',
				'SEXE =\'FEMININ\'',
				new NotIn ( 'ID_PERSONNE', $subselect )
		) );
		$rowset->order( 'ID_PERSONNE ASC' );
		$statement = $sql2->prepareStatementForSqlObject ( $rowset );
		$result = $statement->execute ();
		return $result;
	}

	// LISTE DES PATIENTS SAUF LES PATIENTS DECEDES
	public function laListePatients() {
		$date = new \DateTime ("now");
		$formatDate = $date->format ( 'Y-m-d' );
		$adapter = $this->tableGateway->getAdapter ();
		$sql1 = new Sql ($adapter );
		$subselect1 = $sql1->select ();
		$subselect1->from ( array (
				'd' => 'deces'
		) );
		$subselect1->columns (array (
				'id_personne'
		) );
		$sql2 = new Sql ($adapter);
		$subselect2 = $sql2->select ();
		$subselect2->from ('facturation');
		$subselect2->columns ( array (
				'id_patient'
		) );
		$subselect2->where ( array (
				'date_cons' => $formatDate
		) );
		$sql3 = new Sql($adapter);
		$rowset = $sql3->select ();
		$rowset->from ( array (
				'p' => 'patient'
		) );
		$rowset->columns(array (
				'Nom' => 'NOM',
				'Prenom' => 'PRENOM',
				'Datenaissance' => 'DATE_NAISSANCE',
				'Sexe' => 'SEXE',
				'Adresse' => 'ADRESSE',
				'Nationalite' => 'NATIONALITE_ACTUELLE',
				'Taille' => 'TAILLE',
				'Id' => 'ID_PERSONNE'
		) );
		$rowset->where( array (
				'ID_PERSONNE > 800',
				new NotIn ( 'ID_PERSONNE', $subselect1 ),
				new NotIn ( 'ID_PERSONNE', $subselect2 )
		) );
		$rowset->order('ID_PERSONNE ASC');
		//$req = $sql3->getSqlStringForSqlObject($rowset);
		//var_dump($req); exit();
		$statement = $sql3->prepareStatementForSqlObject($rowset);
		$result = $statement->execute();
		return $result;
	}
	//Modification des donnees du bebe
	public function updatePatientBebe($data)
	{
		$donnees = array(
				'PRENOM' => $data['prenom'],
				'NOM' => $data['nom'],
				'DATE_NAISSANCE' => $data['date_naissance'],
				'LIEU_NAISSANCE' => $data['lieu_naissance'],
				'SEXE' =>$data['sexe'],
				'CIVILITE' =>$data['civilite'],
		);
		$this->tableGateway->update($donnees, array('ID_PERSONNE'=> $data['id_bebe']));
	}

	//Tous les patients qui ont pour ID_PESONNE > 900
	public function tousPatients(){
		$adapter = $this->tableGateway->getAdapter ();
		$sql = new Sql ( $adapter );
		$select = $sql->select ();
		$select->from ( array (
				'p' => 'patient'
		) );
		$select->columns(array (
				'Nom' => 'NOM',
				'Prenom' => 'PRENOM',
				'Datenaissance' => 'DATE_NAISSANCE',
				'Sexe' => 'SEXE',
				'Adresse' => 'ADRESSE',
				'Nationalite' => 'NATIONALITE_ACTUELLE',
				'Taille' => 'TAILLE',
				'Id' => 'ID_PERSONNE'
		) );
		$select->where( array (
				'ID_PERSONNE > 900'
		) );
		$select->order('ID_PERSONNE DESC');

		$stmt = $sql->prepareStatementForSqlObject($select);
		$result = $stmt->execute();
		return $result;
	}

	//le nombre de patients qui ont pour ID_PESONNE > 900
	public function nbPatientSUP900(){
		$adapter = $this->tableGateway->getAdapter ();
		$sql = new Sql ( $adapter );
		$select = $sql->select ('patient');
		$select->columns(array ('ID_PERSONNE'));
		$select->where( array (
				'ID_PERSONNE > 900'
		) );
		$stmt = $sql->prepareStatementForSqlObject($select);
		$result = $stmt->execute();
		return $result->count();
	}
	public function listePays()
	{
		$adapter = $this->tableGateway->getAdapter ();
		$sql = new Sql ( $adapter );
		$select = $sql->select ();
		$select->from(array('nation'=>'nationalite'));
		$select->columns(array ('PAYS', 'PAYS'));
		$select->order('PAYS ASC');
		$stmt = $sql->prepareStatementForSqlObject($select);
		$result = $stmt->execute();
		foreach ($result as $data) {
			$options[$data['PAYS']] = $data['PAYS'];
		}
		return $options;
	}

	public function listeServices()
	{
		$adapter = $this->tableGateway->getAdapter ();
		$sql = new Sql ( $adapter );
		$select = $sql->select ();
		$select->from(array('serv'=>'service'));
		$select->columns(array ('ID_SERVICE', 'NOM'));
		$select->order('ID_SERVICE ASC');
		$stmt = $sql->prepareStatementForSqlObject($select);
		$result = $stmt->execute();
		foreach ($result as $data) {
			$options[$data['ID_SERVICE']] = $data['NOM'];
		}
		return $options;
	}

	public function listeHopitaux()
	{
		$adapter = $this->tableGateway->getAdapter();
		$sql = new Sql($adapter);
		$select = $sql->select('hopital');
		$select->order('ID_HOPITAL ASC');
		$stat = $sql->prepareStatementForSqlObject($select);
		$result = $stat->execute();
		foreach ($result as $data) {
			$options[$data['ID_HOPITAL']] = $data['NOM_HOPITAL'];
		}
		return $options;
	}

	//Tous les patients consultes sauf ceux du jour
	public function tousPatientsCons($service){
		$today = new \DateTime();
		$date = $today->format('Y-m-d');
		$adapter = $this->tableGateway->getAdapter ();
		$sql = new Sql ( $adapter );
		$select = $sql->select ();
		$select->from ( array (
				'p' => 'patient'
		) );
		$select->columns(array (
				'Nom' => 'NOM',
				'Prenom' => 'PRENOM',
				'Datenaissance' => 'DATE_NAISSANCE',
				'Sexe' => 'SEXE',
				'Adresse' => 'ADRESSE',
				'Nationalite' => 'NATIONALITE_ACTUELLE',
				'Taille' => 'TAILLE',
				'Id' => 'ID_PERSONNE'
		) );
		$select->join(array('c' => 'consultation'), 'p.ID_PERSONNE = c.PAT_ID_PERSONNE', array('Id_cons' => 'ID_CONS', 'Dateonly' => 'DATEONLY', 'Consprise' => 'CONSPRISE'));
		$select->join(array('s' => 'service'), 'c.ID_SERVICE = s.ID_SERVICE', array('Nomservice' => 'NOM'));
		$where = new Where();
		$where->equalTo('s.NOM', $service);
		$where->notEqualTo('DATEONLY', $date);
		$select->where($where);
		$stmt = $sql->prepareStatementForSqlObject($select);
		$result = $stmt->execute();
		return $result;

	}
	//liste des patients à consulter par le medecin dans ce service
	public function listePatientsConsParMedecin($idDuService){
		$today = new \DateTime();
		$date = $today->format('Y-m-d');
		$adapter = $this->tableGateway->getAdapter ();
		$sql = new Sql ( $adapter );
		$select = $sql->select ();
		$select->from ( array (
				'p' => 'patient'
		) );
		$select->columns(array (
				'Nom' => 'NOM',
				'Prenom' => 'PRENOM',
				'Datenaissance' => 'DATE_NAISSANCE',
				'Sexe' => 'SEXE',
				'Adresse' => 'ADRESSE',
				'Nationalite' => 'NATIONALITE_ACTUELLE',
				'Taille' => 'TAILLE',
				'Id' => 'ID_PERSONNE'
		) );
		$select->join(array('c' => 'consultation'), 'p.ID_PERSONNE = c.PAT_ID_PERSONNE', array('Id_cons' => 'ID_CONS', 'dateonly' => 'DATEONLY', 'Consprise' => 'CONSPRISE', 'date' => 'DATE'));
		$where = new Where();
		$where->equalTo('c.ID_SERVICE', $idDuService);
		$where->equalTo('DATEONLY', $date);
		$select->where($where);
		$stmt = $sql->prepareStatementForSqlObject($select);
		$result = $stmt->execute();
		return $result;
	}
	//liste des patients consultés par le medecin pour l'espace recherche
	public function listePatientsConsMedecin($service){
		$today = new \DateTime();
		$date = $today->format('Y-m-d');
		$adapter = $this->tableGateway->getAdapter ();
		$sql = new Sql ( $adapter );
		$select = $sql->select ();
		$select->from ( array (
				'p' => 'patient'
		) );
		$select->columns(array (
				'Nom' => 'NOM',
				'Prenom' => 'PRENOM',
				'Datenaissance' => 'DATE_NAISSANCE',
				'Sexe' => 'SEXE',
				'Adresse' => 'ADRESSE',
				'Nationalite' => 'NATIONALITE_ACTUELLE',
				'Taille' => 'TAILLE',
				'Id' => 'ID_PERSONNE'
		) );
		$select->join(array('c' => 'consultation'), 'p.ID_PERSONNE = c.PAT_ID_PERSONNE', array('Id_cons' => 'ID_CONS', 'Dateonly' => 'DATEONLY', 'Consprise' => 'CONSPRISE', 'date' => 'DATE'));
		$select->join(array('s' => 'service'), 'c.ID_SERVICE = s.ID_SERVICE', array('Nomservice' => 'NOM'));
		$where = new Where();
		$where->equalTo('s.NOM', $service);
		$where->notEqualTo('DATEONLY', $date);
		$select->where($where);
		$stmt = $sql->prepareStatementForSqlObject($select);
		$result = $stmt->execute();
		return $result;

	}

	public function getInfoPatient($id_personne) {
		$db = $this->tableGateway->getAdapter();
		$sql = new Sql($db);
		$sQuery = $sql->select()
		->from(array('pat' => 'patient'))
		->columns( array( '*' ))
		->join(array('pers' => 'personne'), 'pers.id_personne = pat.id_personne' , array('*'))
		->where(array('pat.ID_PERSONNE' => $id_personne));

		$stat = $sql->prepareStatementForSqlObject($sQuery);
		$resultat = $stat->execute()->current();

		return $resultat;
	}

	public function getPhoto($id) {
		$donneesPatient =  $this->getInfoPatient( $id );

		$nom = null;
		if($donneesPatient){$nom = $donneesPatient['PHOTO'];}
		if ($nom) {
			return $nom . '.jpg';
		} else {
			return 'identite.jpg';
		}
	}

	public function getInfoMedecin($id_medecin) {
		$db = $this->tableGateway->getAdapter();
		$sql = new Sql($db);
		$sQuery = $sql->select()
		->from(array('e' => 'employe'))
		->columns( array( '*' ))
		->join(array('pers' => 'personne'), 'pers.id_personne = e.id_personne' , array('*'))
		->where(array('pers.id_personne' => $id_medecin));

		$stat = $sql->prepareStatementForSqlObject($sQuery);
		$resultat = $stat->execute()->current();

		return $resultat;
	}
}


text:
<?php

/**
 * @author Luis
 *
 */
class Evento
{
    private $id="";
    public $nombre="";
    public $descripcion="";
    public $fechaInicio="";
    public $fechaFin="";
    public $aforo="";
    public $local="";
    public $direccion="";
    public $ciudad="";
    public $pais="";
    public $gps="";
    public $estadoEvento="";

    /**
     * Constructor de evento vacío.
     */
    public function __construct(){

    }

    public function getID(){
        return $this->id;
    }

    public function setID($id){
        $this->id=$id;
    }

    /**
     * Esta función guarda la información pasada como parámetros en los atributos del objeto. NO se puede modificar el atributo $id.
     * @param string $nombre
     * @param string $descripcion
     * @param string $fechaInicio Fecha y hora de inicio del evento. Formato en la base de datos-> "1900-1-31 00:00:00"
     * @param string $fechaFin Fecha y hora de fin del evento. Formato en la base de datos-> "1900-1-31 00:00:00"
     * @param integer $aforo
     * @param string $local
     * @param string $direccion
     * @param string $ciudad
     * @param string $pais
     * @param string $gps
     * @param string $estadoEvento
     */
    public function crearEvento($nombre,$descripcion,$fechaInicio,$fechaFin,$aforo,$local,$direccion,$ciudad,$pais,$gps,$estadoEvento="inactivo"){
        $this->nombre=$nombre;
        $this->descripcion=$descripcion;
        $this->fechaInicio=$fechaInicio;
        $this->aforo=$aforo;
        $this->local=$local;
        $this->direccion=$direccion;
        $this->ciudad=$ciudad;
        $this->pais=$pais;
        $this->gps=$gps;
        if($estadoEvento=="inactivo" || $estadoEvento=="activo" || $estadoEvento=="cancelado"){
            $this->estadoEvento=$estadoEvento;
        }
        else{
            $this->estadoEvento="inactivo";
        }
    }

    /**
     * Está funcion carga la información de la base de datos con id igual al parámetro de entrada en el objeto actual.
     * @param integer $id_evento
     */
    public function dbGetEvento($id_evento){
        $sql="SELECT * FROM Eventos WHERE Id=" . $id_evento;
    }

    /**
     * Esta función guarda los datos del objeto $evento en la base de datos.
     * @param Evento $evento
     */
    public function dbSetEvento($evento){
        $sql="INSERT INTO EVENTOS (nombre,descripcion,fechaInicio,fechaFin,aforo,local,direccion,ciudad,pais,gps,estadoEvento) VALUES "
            . "("
            . "'" . $evento->nombre . "',"
            . "'" . $evento->descripcion . "',"
            . "'" . $evento->fechaInicio . "',"
            . "'" . $evento->fechaFin . "',"
            . "" . $evento->aforo . ","
            . "'" . $evento->local . "',"
            . "'" . $evento->direccion . "',"
            . "'" . $evento->ciudad . "',"
            . "'" . $evento->pais . "',"
            . "'" . $evento->gps . "',"
            . "'" . $evento->estadoEvento . "'"
            . ")";
    }

    /**
     * Esta función comprueba que los atributos del objeto sean distinto de null.
     */
    private function listoParaBD(){

    }
}


text:
/* eslint-disable */
/* tslint:disable */
/*
 * ---------------------------------------------------------------
 * ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API        ##
 * ##                                                           ##
 * ## AUTHOR: acacode                                           ##
 * ## SOURCE: https://github.com/acacode/swagger-typescript-api ##
 * ---------------------------------------------------------------
 */
export var ContentType;
(function (ContentType) {
    ContentType["Json"] = "application/json";
    ContentType["FormData"] = "multipart/form-data";
    ContentType["UrlEncoded"] = "application/x-www-form-urlencoded";
})(ContentType || (ContentType = {}));
export class HttpClient {
    constructor(apiConfig = {}) {
        this.baseUrl = "";
        this.securityData = null;
        this.securityWorker = null;
        this.abortControllers = new Map();
        this.baseApiParams = {
            credentials: "same-origin",
            headers: {},
            redirect: "follow",
            referrerPolicy: "no-referrer",
        };
        this.setSecurityData = (data) => {
            this.securityData = data;
        };
        this.contentFormatters = {
            [ContentType.Json]: (input) => input !== null && (typeof input === "object" || typeof input === "string") ? JSON.stringify(input) : input,
            [ContentType.FormData]: (input) => Object.keys(input || {}).reduce((data, key) => {
                data.append(key, input[key]);
                return data;
            }, new FormData()),
            [ContentType.UrlEncoded]: (input) => this.toQueryString(input),
        };
        this.createAbortSignal = (cancelToken) => {
            if (this.abortControllers.has(cancelToken)) {
                const abortController = this.abortControllers.get(cancelToken);
                if (abortController) {
                    return abortController.signal;
                }
                return void 0;
            }
            const abortController = new AbortController();
            this.abortControllers.set(cancelToken, abortController);
            return abortController.signal;
        };
        this.abortRequest = (cancelToken) => {
            const abortController = this.abortControllers.get(cancelToken);
            if (abortController) {
                abortController.abort();
                this.abortControllers.delete(cancelToken);
            }
        };
        this.request = ({ body, secure, path, type, query, format = "json", baseUrl, cancelToken, ...params }) => {
            const secureParams = (secure && this.securityWorker && this.securityWorker(this.securityData)) || {};
            const requestParams = this.mergeRequestParams(params, secureParams);
            const queryString = query && this.toQueryString(query);
            const payloadFormatter = this.contentFormatters[type || ContentType.Json];
            return fetch(`${baseUrl || this.baseUrl || ""}${path}${queryString ? `?${queryString}` : ""}`, {
                ...requestParams,
                headers: {
                    ...(type && type !== ContentType.FormData ? { "Content-Type": type } : {}),
                    ...(requestParams.headers || {}),
                },
                signal: cancelToken ? this.createAbortSignal(cancelToken) : void 0,
                body: typeof body === "undefined" || body === null ? null : payloadFormatter(body),
            }).then(async (response) => {
                const r = response;
                r.data = null;
                r.error = null;
                const data = await response[format]()
                    .then((data) => {
                    if (r.ok) {
                        r.data = data;
                    }
                    else {
                        r.error = data;
                    }
                    return r;
                })
                    .catch((e) => {
                    r.error = e;
                    return r;
                });
                if (cancelToken) {
                    this.abortControllers.delete(cancelToken);
                }
                if (!response.ok)
                    throw data;
                return data;
            });
        };
        Object.assign(this, apiConfig);
    }
    addQueryParam(query, key) {
        const value = query[key];
        return (encodeURIComponent(key) +
            "=" +
            encodeURIComponent(Array.isArray(value) ? value.join(",") : typeof value === "number" ? value : `${value}`));
    }
    toQueryString(rawQuery) {
        const query = rawQuery || {};
        const keys = Object.keys(query).filter((key) => "undefined" !== typeof query[key]);
        return keys
            .map((key) => typeof query[key] === "object" && !Array.isArray(query[key])
            ? this.toQueryString(query[key])
            : this.addQueryParam(query, key))
            .join("&");
    }
    addQueryParams(rawQuery) {
        const queryString = this.toQueryString(rawQuery);
        return queryString ? `?${queryString}` : "";
    }
    mergeRequestParams(params1, params2) {
        return {
            ...this.baseApiParams,
            ...params1,
            ...(params2 || {}),
            headers: {
                ...(this.baseApiParams.headers || {}),
                ...(params1.headers || {}),
                ...((params2 && params2.headers) || {}),
            },
        };
    }
}
/**
 * @title cosmos/authz/v1beta1/authz.proto
 * @version version not set
 */
export class Api extends HttpClient {
    constructor() {
        super(...arguments);
        /**
         * No description
         *
         * @tags Query
         * @name QueryGrants
         * @summary Returns list of `Authorization`, granted to the grantee by the granter.
         * @request GET:/cosmos/authz/v1beta1/grants
         */
        this.queryGrants = (query, params = {}) => this.request({
            path: `/cosmos/authz/v1beta1/grants`,
            method: "GET",
            query: query,
            format: "json",
            ...params,
        });
    }
}


text:
![bives logo](https://sems.uni-rostock.de/wp-content/uploads/2012/12/logo-icon-16.png) BiVeS is a library based on the XyDiff algorithm. It is able to detect differences between two versions of a computational model and to communicate these changes.

The Algorithm implemented in BiVeS was published as
> Martin Scharm, Olaf Wolkenhauer, Dagmar Waltemath:
> [An algorithm to detect and communicate the differences in computational models describing biological systems.](https://doi.org/10.1093/bioinformatics/btv484)
> *Bioinformatics* 32 (4): 563-570;

**More documentation on the BiVeS framework** can be found and the [GitHub pages of the SEMS project](https://semsproject.github.io/BiVeS/).

## BiVeS consists of several modules

![bives modules](art/dependency-graph.png)

BiVeS itself consists of a number of modules:

* [xmlutils](https://github.com/binfalse/xmlutils) is a library for advanced XML handling
* [jCOMODI](https://github.com/binfalse/jCOMODI/) provides programmatic access to the [COMODI ontology](http://purl.uni-rostock.de/comodi/)
* [BiVeS-Core](https://github.com/binfalse/BiVeS-Core) is the core library for comparison of computational models
* [BiVeS-SBML](https://github.com/binfalse/BiVeS-SBML/) is a module providing special strategies for models encoded in SBML
* [BiVeS-CellML](https://github.com/binfalse/BiVeS-CellML) is a module providing special strategies for models encoded in CellML
* [BiVeS](https://github.com/binfalse/BiVeS) ties all modules together and provides command line access
* [BiVeS-WebApp](https://github.com/binfalse/BiVeS-WebApp) is a web interface to access BiVeS through the network
* [BiVeS-WebApp-Client](https://github.com/binfalse/BiVeS-WebApp-Client) provides a Java library for comparing models using the BiVeS-WebApp

## Usage of BiVeS

BiVeS currently supports different flavours of XML documents.
It supports special comparison strategies for computational models encoded in SBML (though [BiVeS-SBML](https://github.com/binfalse/BiVeS-SBML)) or CellML (through [BiVeS-CellML](https://github.com/binfalse/BiVeS-CellML)).

To just compare two documents `A.xml` and `B.xml` just call it as:

    java -jar BiVeS.jar A.xml B.xml

The output will be an XML patch listing all operations necessary to convert `A.xml` into `B.xml`.
An XSD schema for the XML can be found in [res/bives-diff-schema.xsd](res/bives-diff-schema.xsd).

BiVeS supports other output formats and flags to activate special merge strategies, just call it with `--help` to get a full list of available options.

There is also a Web Application that happily accepts thrown models and returns comparison results.
Just have a look at [BiVeS-WebApp](https://github.com/binfalse/BiVeS-WebApp) and its demo instance at [bives.bio.informatik.uni-rostock.de](https://bives.bio.informatik.uni-rostock.de/).

## LICENSE

Artwork and text etc is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/) ![Creative Commons License](https://i.creativecommons.org/l/by-sa/4.0/80x15.png)

The code is licensed under an [Apache 2.0 license](LICENSE):

    Copyright martin scharm <https://binfalse.de/contact/>

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.


text:
/**
 * This file is used to build ngHandsontable from `src/*`
 *
 * Installation:
 * 1. Install Grunt CLI (`npm install -g grunt-cli`)
 * 1. Install Grunt 0.4.0 and other dependencies (`npm install`)
 *
 * Build:
 * Execute `grunt` from root directory of this directory (where Gruntfile.js is)
 * To execute automatically after each change, execute `grunt --force default watch`
 *
 * Result:
 * building ngHandsontable will create files:
 *  - dist/ngHandsontable.js
 *  - dist/ngHandsontable.min.js
 *
 * See http://gruntjs.com/getting-started for more information about Grunt
 */
module.exports = function (grunt) {
  var myBanner = '/**\n' +
    ' * <%= pkg.name %> <%= pkg.version %>\n' +
    ' * \n' +
    ' * Copyright 2012-2015 Marcin Warpechowski\n' +
    ' * Copyright 2015 Handsoncode sp. z o.o. <hello@handsontable.com>\n' +
    ' * Licensed under the MIT license.\n' +
    ' * https://github.com/handsontable/ngHandsontable\n' +
    ' * Date: <%= (new Date()).toString() %>\n' +
    '*/\n\n';

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    concat: {
      options: {
        banner: myBanner
      },
      new: {
        src: [
          'src/ie-shim.js',
          'src/ngHandsontable.js',
          'src/services/*.js',
          'src/directives/*.js'
        ],
        dest: 'dist/ngHandsontable.js'
      }
    },

    uglify: {
      options: {
        banner: myBanner
      },
      "dist/ngHandsontable.min.js": ["dist/ngHandsontable.js"]
    },

    jshint: {
      options: {
        jshintrc:true
      },
      files:['src/**/*.js', 'src/*.js']
    },

    watch: {
      files: ['src/**/*', 'bower_components/**/*'],
      tasks: ['concat', 'uglify']
    },

    browserify: {
      demoApp: {
        src: [
          './demo/js/**/*.js'
        ],
        dest: './demo/build/app.js',
        options: {
          alias: [
            './demo/js/demos.js:demos',
            './demo/js/modules.js:modules',
            './demo/js/routing.js:routing'
          ],
          transform: [
            ['browserify-replace', {
              replace: [
                { from: /@@version/, to: '<%= pkg.version %>' }
              ]
            }
            ]
          ]
        }
      },
      demoAppWatch: {
        src: [
          './demo/js/**/*.js'
        ],
        dest: './demo/build/app.js',
        options: {
          alias: [
            './demo/js/demos.js:demos',
            './demo/js/modules.js:modules',
            './demo/js/routing.js:routing'
          ],
          watch: true,
          keepAlive: true
        }
      }
    }
  });

  grunt.registerTask('default', ['jshint', 'concat', 'uglify']);
  grunt.registerTask('watch-demo-app', ['browserify:demoAppWatch']);
  grunt.registerTask('build-demo-app', ['browserify:demoApp']);

  grunt.loadNpmTasks('grunt-browserify');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-watch');
};