text:
package org.hawkular.agent.monitor.scheduler.polling.dmr;

import org.hawkular.agent.monitor.scheduler.polling.Task;
import org.hawkular.agent.monitor.scheduler.polling.TaskGroup;
import org.hawkular.dmrclient.JBossASClient;
import org.jboss.dmr.ModelNode;

/**
 * Given a task group of DMR tasks, creates a batch operation to read the attributes.
 */
public class ReadAttributeOperationBuilder {
    // Returns a batch operation that obtains all the data in one request.
    public ModelNode createBatchOperation(final TaskGroup group) {
        return JBossASClient.createBatchRequest(createOperations(group));
    }

    // Returns one request operation per group item
    public ModelNode[] createOperations(final TaskGroup group) {
        if (group.isEmpty()) {
            throw new IllegalArgumentException("Empty groups are not allowed");
        }

        ModelNode[] readOps = new ModelNode[group.size()];
        int i = 0;
        for (Task task : group) {
            DMRTask dmrTask = (DMRTask) task;
            readOps[i++] = JBossASClient.createReadAttributeRequest(dmrTask.getAttribute(), dmrTask.getAddress());
        }

        return readOps;
    }
}


text:
package org.openwms.tms;

import org.ameba.annotation.Measured;
import org.ameba.mapping.BeanMapper;
import org.openwms.tms.api.TransportOrderApi;
import org.openwms.tms.api.TransportOrderVO;
import org.openwms.tms.api.UpdateTransportOrderVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * A TransportationFacade is a transactional Spring managed bean that is independent from the used API exporter pattern.
 *
 * @author Heiko Scherrer
 */
@Transactional
@Component
public class TransportationFacade implements TransportOrderApi {

    private static final Logger LOGGER = LoggerFactory.getLogger(TransportationFacade.class);
    private final BeanMapper mapper;
    private final TransportationService<TransportOrder> service;

    TransportationFacade(BeanMapper mapper, TransportationService<TransportOrder> service) {
        this.mapper = mapper;
        this.service = service;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @Measured
    public void createTO(String barcode, String target) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Create TransportOrder with Barcode [{}] and Target [{}]", barcode, target);
        }
        service.create(barcode, target, null);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @Measured
    public void createTO(String barcode, String target, String priority) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Create TransportOrder with Barcode [{}] and Target [{}] and Priority [{}]", barcode, target, priority);
        }
        service.create(barcode, target, priority);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @Measured
    public void changeState(String pKey, String state) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Change the state of the TransportOrder with persistent key [{}] to [{}]", pKey, state);
        }
        var order = service.findByPKey(pKey);
        var failures = service.change(
                order.getTransportUnitBK(),
                order.getState(),
                TransportOrderState.valueOf(state),
                null
        );
        if (!failures.isEmpty()) {
            LOGGER.error("Failed to changed TransportOrders [{}]", failures.toArray());
            var message = failures.iterator().next();
            throw new StateChangeException(message.getMessageText(), message.getMessageNo(), message.getpKey());
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @Measured
    public void updateTO(String pKey, UpdateTransportOrderVO vo) {
        if (vo.getPriority() != null && !vo.getPriority().isEmpty()) {
            PriorityLevel.of(vo.getPriority());
        }
        if (vo.getpKey() == null || !pKey.equals(vo.getpKey())) {
            vo.setpKey(pKey);
        }
        service.update(mapper.map(vo, TransportOrder.class));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @Measured
    public List<TransportOrderVO> findBy(String barcode, String state) {
        var orders = mapper.map(service.findBy(barcode, state), TransportOrderVO.class);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Found [{}] TransportOrders with barcode [{}] in state [{}]", orders.size(), barcode, state);
        }
        return orders;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @Measured
    public TransportOrderVO findByPKey(String pKey) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Find TransportOrder with persistent key [{}]", pKey);
        }
        return mapper.map(service.findByPKey(pKey), TransportOrderVO.class);
    }
}

redpajama_set_name: RedPajamaGithub


text:
QuadKey
=======

Quad key object used for Geospatial segmentation. Based off the idea of a quadtree and used as the Bing Maps tile system.

Given a (lat, lon) and level produce a quadkey to be used in Bing Maps.
Can also supply methods to generate a Google Maps TileXYZ

Built off of the TileSystem static class outlined here: http://msdn.microsoft.com/en-us/library/bb259689.aspx

Converts a lat,lon to pixel space to tile space to a quadkey

    import quadkey

    qk = quadkey.from_geo((-105, 40), 17)
    print qk.key # => 02310101232121212
    assert qk.level is 17
    tile = qk.to_tile() # => [(x, y), z]

Not a lot of documentation here, but the implementation has quite a bit, so look at the QuadKey definitions for better documention

Install
-------

The package on pypi is quadtweet, so the recommended installation is with pip

     pip install quadkey

Methods
-------

There are many straightforward methods, so I'll only go into detail of the unique ones

* children()
* parent()
* is_ancestor()
* is_descendent()
* area()
* to_geo()
* to_tile()

####difference(to)

Gets the quadkeys between self and to forming a rectangle, inclusive.

    qk.difference(to) -> [qk,,,,,to]

####unwind()

Gets a list of all ancestors in descending order by level, inclusive.

    QuadKey('0123').unwind() -> ['0123','012','01','0']


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta http-equiv="Content-Style-Type" content="text/css" />
  <link rel="stylesheet" href="css/setting.css" type="text/css" />

  <title>設定ウィンドウ</title>

  <form name="settingForm">
    URL1

    <input type="text" name="baseUrl1" class="textBox" />

    URL2

    <input type="text" name="baseUrl2" class="textBox" />

    URL3

    <input type="text" name="baseUrl3" class="textBox" />

    URL4

    <input type="text" name="baseUrl4" class="textBox" />

    URL5

    <input type="text" name="baseUrl5" class="textBox" />

    (使わないURL欄は空白にしてください)

    更新間隔(秒)

    <input type="text" name="intervalBox" class="textBox" />

    <input type="checkbox" name="isFade" />フェードイン

  </form>


text:
if (!String.prototype.hasOwnProperty("repeat")){
  String.prototype.repeat = function(num){
    return new Array( num + 1 ).join( this );
  };
}

if (!String.prototype.hasOwnProperty("endsWith")){
  String.prototype.endsWith = function(str){
    var myRegExp = new RegExp(str + "$");
    return myRegExp.test(this);
  };
}


text:
namespace gl
{
	bool IsUnsizedInternalFormat(GLint internalformat)
	{
		switch(internalformat)
		{
		case GL_ALPHA:
		case GL_LUMINANCE:
		case GL_LUMINANCE_ALPHA:
		case GL_RED:
		case GL_RG:
		case GL_RGB:
		case GL_RGBA:
		case GL_RED_INTEGER:
		case GL_RG_INTEGER:
		case GL_RGB_INTEGER:
		case GL_RGBA_INTEGER:
		case GL_BGRA_EXT:
		case GL_DEPTH_COMPONENT:
		case GL_DEPTH_STENCIL:
		// GL_EXT_sRGB
	//	case GL_SRGB_EXT:
	//	case GL_SRGB_ALPHA_EXT:
			return true;
		default:
			return false;
		}
	}

	GLenum GetBaseInternalFormat(GLint internalformat)
	{
		switch(internalformat)
		{
		// [OpenGL ES 3.0 Table 3.13]
		case GL_R8:       return GL_RED;
		case GL_R8_SNORM: return GL_RED;
		case GL_RG8:       return GL_RG;
		case GL_RG8_SNORM: return GL_RG;
		case GL_RGB8:       return GL_RGB;
		case GL_RGB8_SNORM: return GL_RGB;
		case GL_RGB565:     return GL_RGB;
		case GL_RGBA4:        return GL_RGBA;
		case GL_RGB5_A1:      return GL_RGBA;
		case GL_RGBA8:        return GL_RGBA;
		case GL_RGBA8_SNORM:  return GL_RGBA;
		case GL_RGB10_A2:     return GL_RGBA;
		case GL_RGB10_A2UI:   return GL_RGBA;
		case GL_SRGB8:        return GL_RGB;
		case GL_SRGB8_ALPHA8: return GL_RGBA;
		case GL_R16F:    return GL_RED;
		case GL_RG16F:   return GL_RG;
		case GL_RGB16F:  return GL_RGB;
		case GL_RGBA16F: return GL_RGBA;
		case GL_R32F:    return GL_RED;
		case GL_RG32F:   return GL_RG;
		case GL_RGB32F:  return GL_RGB;
		case GL_RGBA32F: return GL_RGBA;
		case GL_R11F_G11F_B10F: return GL_RGB;
		case GL_RGB9_E5:        return GL_RGB;
		case GL_R8I:      return GL_RED;
		case GL_R8UI:     return GL_RED;
		case GL_R16I:     return GL_RED;
		case GL_R16UI:    return GL_RED;
		case GL_R32I:     return GL_RED;
		case GL_R32UI:    return GL_RED;
		case GL_RG8I:     return GL_RG;
		case GL_RG8UI:    return GL_RG;
		case GL_RG16I:    return GL_RG;
		case GL_RG16UI:   return GL_RG;
		case GL_RG32I:    return GL_RG;
		case GL_RG32UI:   return GL_RG;
		case GL_RGB8I:    return GL_RGB;
		case GL_RGB8UI:   return GL_RGB;
		case GL_RGB16I:   return GL_RGB;
		case GL_RGB16UI:  return GL_RGB;
		case GL_RGB32I:   return GL_RGB;
		case GL_RGB32UI:  return GL_RGB;
		case GL_RGBA8I:   return GL_RGBA;
		case GL_RGBA8UI:  return GL_RGBA;
		case GL_RGBA16I:  return GL_RGBA;
		case GL_RGBA16UI: return GL_RGBA;
		case GL_RGBA32I:  return GL_RGBA;
		case GL_RGBA32UI: return GL_RGBA;

		// GL_EXT_texture_storage
		case GL_ALPHA8_EXT:             return GL_ALPHA;
		case GL_LUMINANCE8_EXT:         return GL_LUMINANCE;
		case GL_LUMINANCE8_ALPHA8_EXT:  return GL_LUMINANCE_ALPHA;
		case GL_ALPHA32F_EXT:           return GL_ALPHA;
		case GL_LUMINANCE32F_EXT:       return GL_LUMINANCE;
		case GL_LUMINANCE_ALPHA32F_EXT: return GL_LUMINANCE_ALPHA;
		case GL_ALPHA16F_EXT:           return GL_ALPHA;
		case GL_LUMINANCE16F_EXT:       return GL_LUMINANCE;
		case GL_LUMINANCE_ALPHA16F_EXT: return GL_LUMINANCE_ALPHA;

		case GL_BGRA8_EXT: return GL_BGRA_EXT;   // GL_APPLE_texture_format_BGRA8888

		case GL_DEPTH_COMPONENT24:     return GL_DEPTH_COMPONENT;
		case GL_DEPTH_COMPONENT32_OES: return GL_DEPTH_COMPONENT;
		case GL_DEPTH_COMPONENT32F:    return GL_DEPTH_COMPONENT;
		case GL_DEPTH_COMPONENT16:     return GL_DEPTH_COMPONENT;
		case GL_DEPTH32F_STENCIL8:     return GL_DEPTH_STENCIL;
		case GL_DEPTH24_STENCIL8:      return GL_DEPTH_STENCIL;
		case GL_STENCIL_INDEX8:        return GL_STENCIL_INDEX_OES;
		default:
			UNREACHABLE(internalformat);
			break;
		}

		return GL_NONE;
	}

	GLint GetSizedInternalFormat(GLint internalformat, GLenum type)
	{
		if(!IsUnsizedInternalFormat(internalformat))
		{
			return internalformat;
		}

		switch(internalformat)
		{
		case GL_RGBA:
			switch(type)
			{
			case GL_UNSIGNED_BYTE: return GL_RGBA8;
			case GL_BYTE:          return GL_RGBA8_SNORM;
			case GL_UNSIGNED_SHORT_4_4_4_4:      return GL_RGBA4;
			case GL_UNSIGNED_SHORT_5_5_5_1:      return GL_RGB5_A1;
			case GL_UNSIGNED_INT_2_10_10_10_REV: return GL_RGB10_A2;
			case GL_FLOAT:          return GL_RGBA32F;
			case GL_HALF_FLOAT:     return GL_RGBA16F;
			case GL_HALF_FLOAT_OES: return GL_RGBA16F;
			default: UNREACHABLE(type); return GL_NONE;
			}
		case GL_RGBA_INTEGER:
			switch(type)
			{
			case GL_UNSIGNED_BYTE:  return GL_RGBA8UI;
			case GL_BYTE:           return GL_RGBA8I;
			case GL_UNSIGNED_SHORT: return GL_RGBA16UI;
			case GL_SHORT:          return GL_RGBA16I;
			case GL_UNSIGNED_INT:   return GL_RGBA32UI;
			case GL_INT:            return GL_RGBA32I;
			case GL_UNSIGNED_INT_2_10_10_10_REV: return GL_RGB10_A2UI;
			default: UNREACHABLE(type); return GL_NONE;
			}
		case GL_RGB:
			switch(type)
			{
			case GL_UNSIGNED_BYTE:  return GL_RGB8;
			case GL_BYTE:           return GL_RGB8_SNORM;
			case GL_UNSIGNED_SHORT_5_6_5:         return GL_RGB565;
			case GL_UNSIGNED_INT_10F_11F_11F_REV: return GL_R11F_G11F_B10F;
			case GL_UNSIGNED_INT_5_9_9_9_REV:     return GL_RGB9_E5;
			case GL_FLOAT:          return GL_RGB32F;
			case GL_HALF_FLOAT:     return GL_RGB16F;
			case GL_HALF_FLOAT_OES: return GL_RGB16F;
			default: UNREACHABLE(type); return GL_NONE;
			}
		case GL_RGB_INTEGER:
			switch(type)
			{
			case GL_UNSIGNED_BYTE:  return GL_RGB8UI;
			case GL_BYTE:           return GL_RGB8I;
			case GL_UNSIGNED_SHORT: return GL_RGB16UI;
			case GL_SHORT:          return GL_RGB16I;
			case GL_UNSIGNED_INT:   return GL_RGB32UI;
			case GL_INT:            return GL_RGB32I;
			default: UNREACHABLE(type); return GL_NONE;
			}
		case GL_RG:
			switch(type)
			{
			case GL_UNSIGNED_BYTE:  return GL_RG8;
			case GL_BYTE:           return GL_RG8_SNORM;
			case GL_FLOAT:          return GL_RG32F;
			case GL_HALF_FLOAT:     return GL_RG16F;
			case GL_HALF_FLOAT_OES: return GL_RG16F;
			default: UNREACHABLE(type); return GL_NONE;
			}
		case GL_RG_INTEGER:
			switch(type)
			{
			case GL_UNSIGNED_BYTE:  return GL_RG8UI;
			case GL_BYTE:           return GL_RG8I;
			case GL_UNSIGNED_SHORT: return GL_RG16UI;
			case GL_SHORT:          return GL_RG16I;
			case GL_UNSIGNED_INT:   return GL_RG32UI;
			case GL_INT:            return GL_RG32I;
			default: UNREACHABLE(type); return GL_NONE;
			}
		case GL_RED:
			switch(type)
			{
			case GL_UNSIGNED_BYTE:  return GL_R8;
			case GL_BYTE:           return GL_R8_SNORM;
			case GL_FLOAT:          return GL_R32F;
			case GL_HALF_FLOAT:     return GL_R16F;
			case GL_HALF_FLOAT_OES: return GL_R16F;
			default: UNREACHABLE(type); return GL_NONE;
			}
		case GL_RED_INTEGER:
			switch(type)
			{
			case GL_UNSIGNED_BYTE:  return GL_R8UI;
			case GL_BYTE:           return GL_R8I;
			case GL_UNSIGNED_SHORT: return GL_R16UI;
			case GL_SHORT:          return GL_R16I;
			case GL_UNSIGNED_INT:   return GL_R32UI;
			case GL_INT:            return GL_R32I;
			default: UNREACHABLE(type); return GL_NONE;
			}
		case GL_LUMINANCE_ALPHA:
			switch(type)
			{
			case GL_UNSIGNED_BYTE:  return GL_LUMINANCE8_ALPHA8_EXT;
			case GL_FLOAT:          return GL_LUMINANCE_ALPHA32F_EXT;
			case GL_HALF_FLOAT:     return GL_LUMINANCE_ALPHA16F_EXT;
			case GL_HALF_FLOAT_OES: return GL_LUMINANCE_ALPHA16F_EXT;
			default: UNREACHABLE(type); return GL_NONE;
			}
		case GL_LUMINANCE:
			switch(type)
			{
			case GL_UNSIGNED_BYTE:  return GL_LUMINANCE8_EXT;
			case GL_FLOAT:          return GL_LUMINANCE32F_EXT;
			case GL_HALF_FLOAT:     return GL_LUMINANCE16F_EXT;
			case GL_HALF_FLOAT_OES: return GL_LUMINANCE16F_EXT;
			default: UNREACHABLE(type); return GL_NONE;
			}
		case GL_ALPHA:
			switch(type)
			{
			case GL_UNSIGNED_BYTE:  return GL_ALPHA8_EXT;
			case GL_FLOAT:          return GL_ALPHA32F_EXT;
			case GL_HALF_FLOAT:     return GL_ALPHA16F_EXT;
			case GL_HALF_FLOAT_OES: return GL_ALPHA16F_EXT;
			default: UNREACHABLE(type); return GL_NONE;
			}
		case GL_BGRA_EXT:
			switch(type)
			{
			case GL_UNSIGNED_BYTE:                  return GL_BGRA8_EXT;
			case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT: // Only valid for glReadPixels calls.
			case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT: // Only valid for glReadPixels calls.
			default: UNREACHABLE(type); return GL_NONE;
			}
		case GL_DEPTH_COMPONENT:
			switch(type)
			{
			case GL_UNSIGNED_SHORT: return GL_DEPTH_COMPONENT16;
			case GL_UNSIGNED_INT:   return GL_DEPTH_COMPONENT32_OES;
			case GL_FLOAT:          return GL_DEPTH_COMPONENT32F;
			default: UNREACHABLE(type); return GL_NONE;
			}
		case GL_DEPTH_STENCIL:
			switch(type)
			{
			case GL_UNSIGNED_INT_24_8:              return GL_DEPTH24_STENCIL8;
			case GL_FLOAT_32_UNSIGNED_INT_24_8_REV: return GL_DEPTH32F_STENCIL8;
			default: UNREACHABLE(type); return GL_NONE;
			}

		// GL_OES_texture_stencil8
	//	case GL_STENCIL_INDEX_OES / GL_UNSIGNED_BYTE: return GL_STENCIL_INDEX8;

		// GL_EXT_sRGB
	//	case GL_SRGB_EXT / GL_UNSIGNED_BYTE: return GL_SRGB8;
	//	case GL_SRGB_ALPHA_EXT / GL_UNSIGNED_BYTE: return GL_SRGB8_ALPHA8;

		default:
			UNREACHABLE(internalformat);
		}

		return GL_NONE;
	}

	sw::Format SelectInternalFormat(GLint format)
	{
		switch(format)
		{
		case GL_RGBA4:   return sw::FORMAT_A8B8G8R8;
		case GL_RGB5_A1: return sw::FORMAT_A8B8G8R8;
		case GL_RGBA8:   return sw::FORMAT_A8B8G8R8;
		case GL_RGB565:  return sw::FORMAT_R5G6B5;
		case GL_RGB8:    return sw::FORMAT_X8B8G8R8;

		case GL_DEPTH_COMPONENT32F:    return sw::FORMAT_D32F_LOCKABLE;
		case GL_DEPTH_COMPONENT16:     return sw::FORMAT_D32F_LOCKABLE;
		case GL_DEPTH_COMPONENT24:     return sw::FORMAT_D32F_LOCKABLE;
		case GL_DEPTH_COMPONENT32_OES: return sw::FORMAT_D32F_LOCKABLE;
		case GL_DEPTH24_STENCIL8:      return sw::FORMAT_D32FS8_TEXTURE;
		case GL_DEPTH32F_STENCIL8:     return sw::FORMAT_D32FS8_TEXTURE;
		case GL_STENCIL_INDEX8:        return sw::FORMAT_S8;

		case GL_R8:             return sw::FORMAT_R8;
		case GL_RG8:            return sw::FORMAT_G8R8;
		case GL_R8I:            return sw::FORMAT_R8I;
		case GL_RG8I:           return sw::FORMAT_G8R8I;
		case GL_RGB8I:          return sw::FORMAT_X8B8G8R8I;
		case GL_RGBA8I:         return sw::FORMAT_A8B8G8R8I;
		case GL_R8UI:           return sw::FORMAT_R8UI;
		case GL_RG8UI:          return sw::FORMAT_G8R8UI;
		case GL_RGB8UI:         return sw::FORMAT_X8B8G8R8UI;
		case GL_RGBA8UI:        return sw::FORMAT_A8B8G8R8UI;
		case GL_R16I:           return sw::FORMAT_R16I;
		case GL_RG16I:          return sw::FORMAT_G16R16I;
		case GL_RGB16I:         return sw::FORMAT_X16B16G16R16I;
		case GL_RGBA16I:        return sw::FORMAT_A16B16G16R16I;
		case GL_R16UI:          return sw::FORMAT_R16UI;
		case GL_RG16UI:         return sw::FORMAT_G16R16UI;
		case GL_RGB16UI:        return sw::FORMAT_X16B16G16R16UI;
		case GL_RGBA16UI:       return sw::FORMAT_A16B16G16R16UI;
		case GL_R32I:           return sw::FORMAT_R32I;
		case GL_RG32I:          return sw::FORMAT_G32R32I;
		case GL_RGB32I:         return sw::FORMAT_X32B32G32R32I;
		case GL_RGBA32I:        return sw::FORMAT_A32B32G32R32I;
		case GL_R32UI:          return sw::FORMAT_R32UI;
		case GL_RG32UI:         return sw::FORMAT_G32R32UI;
		case GL_RGB32UI:        return sw::FORMAT_X32B32G32R32UI;
		case GL_RGBA32UI:       return sw::FORMAT_A32B32G32R32UI;
		case GL_R16F:           return sw::FORMAT_R16F;
		case GL_RG16F:          return sw::FORMAT_G16R16F;
		case GL_R11F_G11F_B10F: return sw::FORMAT_X16B16G16R16F_UNSIGNED;
		case GL_RGB16F:         return sw::FORMAT_X16B16G16R16F;
		case GL_RGBA16F:        return sw::FORMAT_A16B16G16R16F;
		case GL_R32F:           return sw::FORMAT_R32F;
		case GL_RG32F:          return sw::FORMAT_G32R32F;
		case GL_RGB32F:         return sw::FORMAT_X32B32G32R32F;
		case GL_RGBA32F:        return sw::FORMAT_A32B32G32R32F;
		case GL_RGB10_A2:       return sw::FORMAT_A2B10G10R10;
		case GL_RGB10_A2UI:     return sw::FORMAT_A2B10G10R10UI;
		case GL_SRGB8:          return sw::FORMAT_SRGB8_X8;
		case GL_SRGB8_ALPHA8:   return sw::FORMAT_SRGB8_A8;

		case GL_ETC1_RGB8_OES:              return sw::FORMAT_ETC1;
		case GL_COMPRESSED_R11_EAC:         return sw::FORMAT_R11_EAC;
		case GL_COMPRESSED_SIGNED_R11_EAC:  return sw::FORMAT_SIGNED_R11_EAC;
		case GL_COMPRESSED_RG11_EAC:        return sw::FORMAT_RG11_EAC;
		case GL_COMPRESSED_SIGNED_RG11_EAC: return sw::FORMAT_SIGNED_RG11_EAC;
		case GL_COMPRESSED_RGB8_ETC2:       return sw::FORMAT_RGB8_ETC2;
		case GL_COMPRESSED_SRGB8_ETC2:      return sw::FORMAT_SRGB8_ETC2;
		case GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:  return sw::FORMAT_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;
		case GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2: return sw::FORMAT_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2;
		case GL_COMPRESSED_RGBA8_ETC2_EAC:        return sw::FORMAT_RGBA8_ETC2_EAC;
		case GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC: return sw::FORMAT_SRGB8_ALPHA8_ETC2_EAC;
		case GL_COMPRESSED_RGBA_ASTC_4x4_KHR:   return sw::FORMAT_RGBA_ASTC_4x4_KHR;
		case GL_COMPRESSED_RGBA_ASTC_5x4_KHR:   return sw::FORMAT_RGBA_ASTC_5x4_KHR;
		case GL_COMPRESSED_RGBA_ASTC_5x5_KHR:   return sw::FORMAT_RGBA_ASTC_5x5_KHR;
		case GL_COMPRESSED_RGBA_ASTC_6x5_KHR:   return sw::FORMAT_RGBA_ASTC_6x5_KHR;
		case GL_COMPRESSED_RGBA_ASTC_6x6_KHR:   return sw::FORMAT_RGBA_ASTC_6x6_KHR;
		case GL_COMPRESSED_RGBA_ASTC_8x5_KHR:   return sw::FORMAT_RGBA_ASTC_8x5_KHR;
		case GL_COMPRESSED_RGBA_ASTC_8x6_KHR:   return sw::FORMAT_RGBA_ASTC_8x6_KHR;
		case GL_COMPRESSED_RGBA_ASTC_8x8_KHR:   return sw::FORMAT_RGBA_ASTC_8x8_KHR;
		case GL_COMPRESSED_RGBA_ASTC_10x5_KHR:  return sw::FORMAT_RGBA_ASTC_10x5_KHR;
		case GL_COMPRESSED_RGBA_ASTC_10x6_KHR:  return sw::FORMAT_RGBA_ASTC_10x6_KHR;
		case GL_COMPRESSED_RGBA_ASTC_10x8_KHR:  return sw::FORMAT_RGBA_ASTC_10x8_KHR;
		case GL_COMPRESSED_RGBA_ASTC_10x10_KHR: return sw::FORMAT_RGBA_ASTC_10x10_KHR;
		case GL_COMPRESSED_RGBA_ASTC_12x10_KHR: return sw::FORMAT_RGBA_ASTC_12x10_KHR;
		case GL_COMPRESSED_RGBA_ASTC_12x12_KHR: return sw::FORMAT_RGBA_ASTC_12x12_KHR;
		case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:   return sw::FORMAT_SRGB8_ALPHA8_ASTC_4x4_KHR;
		case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:   return sw::FORMAT_SRGB8_ALPHA8_ASTC_5x4_KHR;
		case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:   return sw::FORMAT_SRGB8_ALPHA8_ASTC_5x5_KHR;
		case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:   return sw::FORMAT_SRGB8_ALPHA8_ASTC_6x5_KHR;
		case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:   return sw::FORMAT_SRGB8_ALPHA8_ASTC_6x6_KHR;
		case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:   return sw::FORMAT_SRGB8_ALPHA8_ASTC_8x5_KHR;
		case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:   return sw::FORMAT_SRGB8_ALPHA8_ASTC_8x6_KHR;
		case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:   return sw::FORMAT_SRGB8_ALPHA8_ASTC_8x8_KHR;
		case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:  return sw::FORMAT_SRGB8_ALPHA8_ASTC_10x5_KHR;
		case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:  return sw::FORMAT_SRGB8_ALPHA8_ASTC_10x6_KHR;
		case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:  return sw::FORMAT_SRGB8_ALPHA8_ASTC_10x8_KHR;
		case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR: return sw::FORMAT_SRGB8_ALPHA8_ASTC_10x10_KHR;
		case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR: return sw::FORMAT_SRGB8_ALPHA8_ASTC_12x10_KHR;
		case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR: return sw::FORMAT_SRGB8_ALPHA8_ASTC_12x12_KHR;
		case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:    return sw::FORMAT_DXT1;
		case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:   return sw::FORMAT_DXT1;
		case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE: return sw::FORMAT_DXT3;
		case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE: return sw::FORMAT_DXT5;

		case GL_ALPHA32F_EXT:           return sw::FORMAT_A32F;
		case GL_LUMINANCE32F_EXT:       return sw::FORMAT_L32F;
		case GL_LUMINANCE_ALPHA32F_EXT: return sw::FORMAT_A32L32F;
		case GL_RGB9_E5:                return sw::FORMAT_X16B16G16R16F_UNSIGNED;
		case GL_ALPHA16F_EXT:           return sw::FORMAT_A16F;
		case GL_LUMINANCE16F_EXT:       return sw::FORMAT_L16F;
		case GL_LUMINANCE_ALPHA16F_EXT: return sw::FORMAT_A16L16F;
		case GL_R8_SNORM:    return sw::FORMAT_R8_SNORM;
		case GL_RG8_SNORM:   return sw::FORMAT_G8R8_SNORM;
		case GL_RGB8_SNORM:  return sw::FORMAT_X8B8G8R8_SNORM;
		case GL_RGBA8_SNORM: return sw::FORMAT_A8B8G8R8_SNORM;
		case GL_LUMINANCE8_EXT:        return sw::FORMAT_L8;
		case GL_LUMINANCE8_ALPHA8_EXT: return sw::FORMAT_A8L8;
		case GL_BGRA8_EXT:  return sw::FORMAT_A8R8G8B8;
		case GL_ALPHA8_EXT: return sw::FORMAT_A8;

		case SW_YV12_BT601: return sw::FORMAT_YV12_BT601;
		case SW_YV12_BT709: return sw::FORMAT_YV12_BT709;
		case SW_YV12_JFIF:  return sw::FORMAT_YV12_JFIF;

		default:
			UNREACHABLE(format);   // Not a sized internal format.
			return sw::FORMAT_NULL;
		}
	}

	// Returns the size, in bytes, of a single client-side pixel.
    // OpenGL ES 3.0.5 table 3.2.
	GLsizei ComputePixelSize(GLenum format, GLenum type)
	{
		switch(format)
		{
		case GL_RED:
		case GL_RED_INTEGER:
		case GL_ALPHA:
		case GL_LUMINANCE:
			switch(type)
			{
			case GL_BYTE:           return 1;
			case GL_UNSIGNED_BYTE:  return 1;
			case GL_FLOAT:          return 4;
			case GL_HALF_FLOAT:     return 2;
			case GL_HALF_FLOAT_OES: return 2;
			case GL_SHORT:          return 2;
			case GL_UNSIGNED_SHORT: return 2;
			case GL_INT:            return 4;
			case GL_UNSIGNED_INT:   return 4;
			default: UNREACHABLE(type);
			}
			break;
		case GL_RG:
		case GL_RG_INTEGER:
		case GL_LUMINANCE_ALPHA:
			switch(type)
			{
			case GL_BYTE:           return 2;
			case GL_UNSIGNED_BYTE:  return 2;
			case GL_FLOAT:          return 8;
			case GL_HALF_FLOAT:     return 4;
			case GL_HALF_FLOAT_OES: return 4;
			case GL_SHORT:          return 4;
			case GL_UNSIGNED_SHORT: return 4;
			case GL_INT:            return 8;
			case GL_UNSIGNED_INT:   return 8;
			default: UNREACHABLE(type);
			}
			break;
		case GL_RGB:
		case GL_RGB_INTEGER:
			switch(type)
			{
			case GL_BYTE:                         return 3;
			case GL_UNSIGNED_BYTE:                return 3;
			case GL_UNSIGNED_SHORT_5_6_5:         return 2;
			case GL_UNSIGNED_INT_10F_11F_11F_REV: return 4;
			case GL_UNSIGNED_INT_5_9_9_9_REV:     return 4;
			case GL_FLOAT:                        return 12;
			case GL_HALF_FLOAT:                   return 6;
			case GL_HALF_FLOAT_OES:               return 6;
			case GL_SHORT:                        return 6;
			case GL_UNSIGNED_SHORT:               return 6;
			case GL_INT:                          return 12;
			case GL_UNSIGNED_INT:                 return 12;
			default: UNREACHABLE(type);
			}
			break;
		case GL_RGBA:
		case GL_RGBA_INTEGER:
		case GL_BGRA_EXT:
			switch(type)
			{
			case GL_BYTE:                           return 4;
			case GL_UNSIGNED_BYTE:                  return 4;
			case GL_UNSIGNED_SHORT_4_4_4_4:         return 2;
			case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT: return 2;
			case GL_UNSIGNED_SHORT_5_5_5_1:         return 2;
			case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT: return 2;
			case GL_UNSIGNED_INT_2_10_10_10_REV:    return 4;
			case GL_FLOAT:                          return 16;
			case GL_HALF_FLOAT:                     return 8;
			case GL_HALF_FLOAT_OES:                 return 8;
			case GL_SHORT:                          return 8;
			case GL_UNSIGNED_SHORT:                 return 8;
			case GL_INT:                            return 16;
			case GL_UNSIGNED_INT:                   return 16;
			default: UNREACHABLE(type);
			}
			break;
		case GL_DEPTH_COMPONENT:
			switch(type)
			{
			case GL_FLOAT:          return 4;
			case GL_UNSIGNED_SHORT: return 2;
			case GL_UNSIGNED_INT:   return 4;
			default: UNREACHABLE(type);
			}
			break;
		case GL_DEPTH_STENCIL:
			switch(type)
			{
			case GL_UNSIGNED_INT_24_8:              return 4;
			case GL_FLOAT_32_UNSIGNED_INT_24_8_REV: return 8;
			default: UNREACHABLE(type);
			}
			break;
		default:
			UNREACHABLE(format);
		}

		return 0;
	}

	GLsizei ComputePitch(GLsizei width, GLenum format, GLenum type, GLint alignment)
	{
		ASSERT(alignment > 0 && sw::isPow2(alignment));

		GLsizei rawPitch = ComputePixelSize(format, type) * width;
		return (rawPitch + alignment - 1) & ~(alignment - 1);
	}

	size_t ComputePackingOffset(GLenum format, GLenum type, GLsizei width, GLsizei height, const gl::PixelStorageModes &storageModes)
	{
		GLsizei pitchB = ComputePitch(width, format, type, storageModes.alignment);
		return (storageModes.skipImages * height + storageModes.skipRows) * pitchB + storageModes.skipPixels * ComputePixelSize(format, type);
	}

	inline GLsizei ComputeCompressedPitch(GLsizei width, GLenum format)
	{
		return ComputeCompressedSize(width, 1, format);
	}

	inline int GetNumCompressedBlocks(int w, int h, int blockSizeX, int blockSizeY)
	{
		return ((w + blockSizeX - 1) / blockSizeX) * ((h + blockSizeY - 1) / blockSizeY);
	}

	GLsizei ComputeCompressedSize(GLsizei width, GLsizei height, GLenum format)
	{
		switch(format)
		{
		case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
		case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
		case GL_ETC1_RGB8_OES:
		case GL_COMPRESSED_R11_EAC:
		case GL_COMPRESSED_SIGNED_R11_EAC:
		case GL_COMPRESSED_RGB8_ETC2:
		case GL_COMPRESSED_SRGB8_ETC2:
		case GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:
		case GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2:
			return 8 * GetNumCompressedBlocks(width, height, 4, 4);
		case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
		case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
		case GL_COMPRESSED_RG11_EAC:
		case GL_COMPRESSED_SIGNED_RG11_EAC:
		case GL_COMPRESSED_RGBA8_ETC2_EAC:
		case GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:
		case GL_COMPRESSED_RGBA_ASTC_4x4_KHR:
		case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:
			return 16 * GetNumCompressedBlocks(width, height, 4, 4);
		case GL_COMPRESSED_RGBA_ASTC_5x4_KHR:
		case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:
			return 16 * GetNumCompressedBlocks(width, height, 5, 4);
		case GL_COMPRESSED_RGBA_ASTC_5x5_KHR:
		case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:
			return 16 * GetNumCompressedBlocks(width, height, 5, 5);
		case GL_COMPRESSED_RGBA_ASTC_6x5_KHR:
		case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:
			return 16 * GetNumCompressedBlocks(width, height, 6, 5);
		case GL_COMPRESSED_RGBA_ASTC_6x6_KHR:
		case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:
			return 16 * GetNumCompressedBlocks(width, height, 6, 6);
		case GL_COMPRESSED_RGBA_ASTC_8x5_KHR:
		case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:
			return 16 * GetNumCompressedBlocks(width, height, 8, 5);
		case GL_COMPRESSED_RGBA_ASTC_8x6_KHR:
		case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:
			return 16 * GetNumCompressedBlocks(width, height, 8, 6);
		case GL_COMPRESSED_RGBA_ASTC_8x8_KHR:
		case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:
			return 16 * GetNumCompressedBlocks(width, height, 8, 8);
		case GL_COMPRESSED_RGBA_ASTC_10x5_KHR:
		case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:
			return 16 * GetNumCompressedBlocks(width, height, 10, 5);
		case GL_COMPRESSED_RGBA_ASTC_10x6_KHR:
		case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:
			return 16 * GetNumCompressedBlocks(width, height, 10, 6);
		case GL_COMPRESSED_RGBA_ASTC_10x8_KHR:
		case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:
			return 16 * GetNumCompressedBlocks(width, height, 10, 8);
		case GL_COMPRESSED_RGBA_ASTC_10x10_KHR:
		case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:
			return 16 * GetNumCompressedBlocks(width, height, 10, 10);
		case GL_COMPRESSED_RGBA_ASTC_12x10_KHR:
		case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:
			return 16 * GetNumCompressedBlocks(width, height, 12, 10);
		case GL_COMPRESSED_RGBA_ASTC_12x12_KHR:
		case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:
			return 16 * GetNumCompressedBlocks(width, height, 12, 12);
		default:
			UNREACHABLE(format);
			return 0;
		}
	}
}

namespace egl
{
	// We assume the image data can be indexed with a signed 32-bit offset,
	// so we must keep the size reasonable. 1 GiB ought to be enough for anybody.
	// 4 extra bytes account for the padding added in Surface::size().
	// They are not addressed separately, so can't cause overflow.
	// TODO(b/145229887): Eliminate or don't hard-code the padding bytes.
	enum : uint64_t { IMPLEMENTATION_MAX_IMAGE_SIZE_BYTES = 0x40000000u + 4 };

	enum TransferType
	{
		Bytes,
		RGB8toRGBX8,
		RGB16toRGBX16,
		RGB32toRGBX32,
		RGB32FtoRGBX32F,
		RGB16FtoRGBX16F,
		RGBA4toRGBA8,
		RGBA5_A1toRGBA8,
		R11G11B10FtoRGBX16F,
		RGB9_E5FtoRGBX16F,
		D16toD32F,
		D24X8toD32F,
		D32toD32F,
		D32FtoD32F_CLAMPED,
		D32FX32toD32F,
		X24S8toS8,
		X56S8toS8,
		RGBA1010102toRGBA8,
		RGB8toRGB565,
		R32FtoR16F,
		RG32FtoRG16F,
		RGB32FtoRGB16F,
		RGB32FtoRGB16F_UNSIGNED,
		RGBA32FtoRGBA16F
	};

	template<TransferType transferType>
	void TransferRow(unsigned char *dest, const unsigned char *source, GLsizei width, GLsizei bytes);

	template<>
	void TransferRow<Bytes>(unsigned char *dest, const unsigned char *source, GLsizei width, GLsizei bytes)
	{
		memcpy(dest, source, width * bytes);
	}

	template<>
	void TransferRow<RGB8toRGBX8>(unsigned char *dest, const unsigned char *source, GLsizei width, GLsizei bytes)
	{
		unsigned char *destB = dest;

		for(int x = 0; x < width; x++)
		{
			destB[4 * x + 0] = source[x * 3 + 0];
			destB[4 * x + 1] = source[x * 3 + 1];
			destB[4 * x + 2] = source[x * 3 + 2];
			destB[4 * x + 3] = 0xFF;
		}
	}

	template<>
	void TransferRow<RGB16toRGBX16>(unsigned char *dest, const unsigned char *source, GLsizei width, GLsizei bytes)
	{
		const unsigned short *sourceS = reinterpret_cast<const unsigned short*>(source);
		unsigned short *destS = reinterpret_cast<unsigned short*>(dest);

		for(int x = 0; x < width; x++)
		{
			destS[4 * x + 0] = sourceS[x * 3 + 0];
			destS[4 * x + 1] = sourceS[x * 3 + 1];
			destS[4 * x + 2] = sourceS[x * 3 + 2];
			destS[4 * x + 3] = 0xFFFF;
		}
	}

	template<>
	void TransferRow<RGB32toRGBX32>(unsigned char *dest, const unsigned char *source, GLsizei width, GLsizei bytes)
	{
		const unsigned int *sourceI = reinterpret_cast<const unsigned int*>(source);
		unsigned int *destI = reinterpret_cast<unsigned int*>(dest);

		for(int x = 0; x < width; x++)
		{
			destI[4 * x + 0] = sourceI[x * 3 + 0];
			destI[4 * x + 1] = sourceI[x * 3 + 1];
			destI[4 * x + 2] = sourceI[x * 3 + 2];
			destI[4 * x + 3] = 0xFFFFFFFF;
		}
	}

	template<>
	void TransferRow<RGB32FtoRGBX32F>(unsigned char *dest, const unsigned char *source, GLsizei width, GLsizei bytes)
	{
		const float *sourceF = reinterpret_cast<const float*>(source);
		float *destF = reinterpret_cast<float*>(dest);

		for(int x = 0; x < width; x++)
		{
			destF[4 * x + 0] = sourceF[x * 3 + 0];
			destF[4 * x + 1] = sourceF[x * 3 + 1];
			destF[4 * x + 2] = sourceF[x * 3 + 2];
			destF[4 * x + 3] = 1.0f;
		}
	}

	template<>
	void TransferRow<RGB16FtoRGBX16F>(unsigned char *dest, const unsigned char *source, GLsizei width, GLsizei bytes)
	{
		const unsigned short *sourceH = reinterpret_cast<const unsigned short*>(source);
		unsigned short *destH = reinterpret_cast<unsigned short*>(dest);

		for(int x = 0; x < width; x++)
		{
			destH[4 * x + 0] = sourceH[x * 3 + 0];
			destH[4 * x + 1] = sourceH[x * 3 + 1];
			destH[4 * x + 2] = sourceH[x * 3 + 2];
			destH[4 * x + 3] = 0x3C00;   // SEEEEEMMMMMMMMMM, S = 0, E = 15, M = 0: 16-bit floating-point representation of 1.0
		}
	}

	template<>
	void TransferRow<RGBA4toRGBA8>(unsigned char *dest, const unsigned char *source, GLsizei width, GLsizei bytes)
	{
		const unsigned short *source4444 = reinterpret_cast<const unsigned short*>(source);
		unsigned char *dest4444 = dest;

		for(int x = 0; x < width; x++)
		{
			unsigned short rgba = source4444[x];
			dest4444[4 * x + 0] = ((rgba & 0xF000) >> 8) | ((rgba & 0xF000) >> 12);
			dest4444[4 * x + 1] = ((rgba & 0x0F00) >> 4) | ((rgba & 0x0F00) >> 8);
			dest4444[4 * x + 2] = ((rgba & 0x00F0) << 0) | ((rgba & 0x00F0) >> 4);
			dest4444[4 * x + 3] = ((rgba & 0x000F) << 4) | ((rgba & 0x000F) >> 0);
		}
	}

	template<>
	void TransferRow<RGBA5_A1toRGBA8>(unsigned char *dest, const unsigned char *source, GLsizei width, GLsizei bytes)
	{
		const unsigned short *source5551 = reinterpret_cast<const unsigned short*>(source);
		unsigned char *dest8888 = dest;

		for(int x = 0; x < width; x++)
		{
			unsigned short rgba = source5551[x];
			dest8888[4 * x + 0] = ((rgba & 0xF800) >> 8) | ((rgba & 0xF800) >> 13);
			dest8888[4 * x + 1] = ((rgba & 0x07C0) >> 3) | ((rgba & 0x07C0) >> 8);
			dest8888[4 * x + 2] = ((rgba & 0x003E) << 2) | ((rgba & 0x003E) >> 3);
			dest8888[4 * x + 3] = (rgba & 0x0001) ? 0xFF : 0;
		}
	}

	template<>
	void TransferRow<RGBA1010102toRGBA8>(unsigned char *dest, const unsigned char *source, GLsizei width, GLsizei bytes)
	{
		const unsigned int *source1010102 = reinterpret_cast<const unsigned int*>(source);
		unsigned char *dest8888 = dest;

		for(int x = 0; x < width; x++)
		{
			unsigned int rgba = source1010102[x];
			dest8888[4 * x + 0] = sw::unorm<8>((rgba & 0x000003FF) * (1.0f / 0x000003FF));
			dest8888[4 * x + 1] = sw::unorm<8>((rgba & 0x000FFC00) * (1.0f / 0x000FFC00));
			dest8888[4 * x + 2] = sw::unorm<8>((rgba & 0x3FF00000) * (1.0f / 0x3FF00000));
			dest8888[4 * x + 3] = sw::unorm<8>((rgba & 0xC0000000) * (1.0f / 0xC0000000));
		}
	}

	template<>
	void TransferRow<RGB8toRGB565>(unsigned char *dest, const unsigned char *source, GLsizei width, GLsizei bytes)
	{
		unsigned short *dest565 = reinterpret_cast<unsigned short*>(dest);

		for(int x = 0; x < width; x++)
		{
			float r = source[3 * x + 0] * (1.0f / 0xFF);
			float g = source[3 * x + 1] * (1.0f / 0xFF);
			float b = source[3 * x + 2] * (1.0f / 0xFF);
			dest565[x] = (sw::unorm<5>(r) << 11) | (sw::unorm<6>(g) << 5) | (sw::unorm<5>(b) << 0);
		}
	}

	template<>
	void TransferRow<R11G11B10FtoRGBX16F>(unsigned char *dest, const unsigned char *source, GLsizei width, GLsizei bytes)
	{
		const sw::R11G11B10F *sourceRGB = reinterpret_cast<const sw::R11G11B10F*>(source);
		sw::half *destF = reinterpret_cast<sw::half*>(dest);

		for(int x = 0; x < width; x++, sourceRGB++, destF += 4)
		{
			sourceRGB->toRGB16F(destF);
			destF[3] = 1.0f;
		}
	}

	template<>
	void TransferRow<RGB9_E5FtoRGBX16F>(unsigned char *dest, const unsigned char *source, GLsizei width, GLsizei bytes)
	{
		const sw::RGB9E5 *sourceRGB = reinterpret_cast<const sw::RGB9E5*>(source);
		sw::half *destF = reinterpret_cast<sw::half*>(dest);

		for(int x = 0; x < width; x++, sourceRGB++, destF += 4)
		{
			sourceRGB->toRGB16F(destF);
			destF[3] = 1.0f;
		}
	}

	template<>
	void TransferRow<R32FtoR16F>(unsigned char *dest, const unsigned char *source, GLsizei width, GLsizei bytes)
	{
		const float *source32F = reinterpret_cast<const float*>(source);
		sw::half *dest16F = reinterpret_cast<sw::half*>(dest);

		for(int x = 0; x < width; x++)
		{
			dest16F[x] = source32F[x];
		}
	}

	template<>
	void TransferRow<RG32FtoRG16F>(unsigned char *dest, const unsigned char *source, GLsizei width, GLsizei bytes)
	{
		const float *source32F = reinterpret_cast<const float*>(source);
		sw::half *dest16F = reinterpret_cast<sw::half*>(dest);

		for(int x = 0; x < width; x++)
		{
			dest16F[2 * x + 0] = source32F[2 * x + 0];
			dest16F[2 * x + 1] = source32F[2 * x + 1];
		}
	}

	template<>
	void TransferRow<RGB32FtoRGB16F>(unsigned char *dest, const unsigned char *source, GLsizei width, GLsizei bytes)
	{
		const float *source32F = reinterpret_cast<const float*>(source);
		sw::half *dest16F = reinterpret_cast<sw::half*>(dest);

		for(int x = 0; x < width; x++)
		{
			dest16F[4 * x + 0] = source32F[3 * x + 0];
			dest16F[4 * x + 1] = source32F[3 * x + 1];
			dest16F[4 * x + 2] = source32F[3 * x + 2];
			dest16F[4 * x + 3] = 1.0f;
		}
	}

	template<>
	void TransferRow<RGB32FtoRGB16F_UNSIGNED>(unsigned char *dest, const unsigned char *source, GLsizei width, GLsizei bytes)
	{
		const float *source32F = reinterpret_cast<const float*>(source);
		sw::half *dest16F = reinterpret_cast<sw::half*>(dest);

		for(int x = 0; x < width; x++)
		{
			dest16F[4 * x + 0] = std::max(source32F[3 * x + 0], 0.0f);
			dest16F[4 * x + 1] = std::max(source32F[3 * x + 1], 0.0f);
			dest16F[4 * x + 2] = std::max(source32F[3 * x + 2], 0.0f);
			dest16F[4 * x + 3] = 1.0f;
		}
	}

	template<>
	void TransferRow<RGBA32FtoRGBA16F>(unsigned char *dest, const unsigned char *source, GLsizei width, GLsizei bytes)
	{
		const float *source32F = reinterpret_cast<const float*>(source);
		sw::half *dest16F = reinterpret_cast<sw::half*>(dest);

		for(int x = 0; x < width; x++)
		{
			dest16F[4 * x + 0] = source32F[4 * x + 0];
			dest16F[4 * x + 1] = source32F[4 * x + 1];
			dest16F[4 * x + 2] = source32F[4 * x + 2];
			dest16F[4 * x + 3] = source32F[4 * x + 3];
		}
	}

	template<>
	void TransferRow<D16toD32F>(unsigned char *dest, const unsigned char *source, GLsizei width, GLsizei bytes)
	{
		const unsigned short *sourceD16 = reinterpret_cast<const unsigned short*>(source);
		float *destF = reinterpret_cast<float*>(dest);

		for(int x = 0; x < width; x++)
		{
			destF[x] = (float)sourceD16[x] / 0xFFFF;
		}
	}

	template<>
	void TransferRow<D24X8toD32F>(unsigned char *dest, const unsigned char *source, GLsizei width, GLsizei bytes)
	{
		const unsigned int *sourceD24 = reinterpret_cast<const unsigned int*>(source);
		float *destF = reinterpret_cast<float*>(dest);

		for(int x = 0; x < width; x++)
		{
			destF[x] = (float)(sourceD24[x] & 0xFFFFFF00) / 0xFFFFFF00;
		}
	}

	template<>
	void TransferRow<D32toD32F>(unsigned char *dest, const unsigned char *source, GLsizei width, GLsizei bytes)
	{
		const unsigned int *sourceD32 = reinterpret_cast<const unsigned int*>(source);
		float *destF = reinterpret_cast<float*>(dest);

		for(int x = 0; x < width; x++)
		{
			// NOTE: Second (float) cast is required to avoid compiler warning:
			// error: implicit conversion from 'unsigned int' to 'float' changes value from
			// 4294967295 to 4294967296 [-Werror,-Wimplicit-int-float-conversion]
			destF[x] = (float)sourceD32[x] / (float)0xFFFFFFFF;
		}
	}

	template<>
	void TransferRow<D32FtoD32F_CLAMPED>(unsigned char *dest, const unsigned char *source, GLsizei width, GLsizei bytes)
	{
		const float *sourceF = reinterpret_cast<const float*>(source);
		float *destF = reinterpret_cast<float*>(dest);

		for(int x = 0; x < width; x++)
		{
			destF[x] = sw::clamp(sourceF[x], 0.0f, 1.0f);
		}
	}

	template<>
	void TransferRow<D32FX32toD32F>(unsigned char *dest, const unsigned char *source, GLsizei width, GLsizei bytes)
	{
		struct D32FS8 { float depth32f; unsigned int stencil24_8; };
		const D32FS8 *sourceD32FS8 = reinterpret_cast<const D32FS8*>(source);
		float *destF = reinterpret_cast<float*>(dest);

		for(int x = 0; x < width; x++)
		{
			destF[x] = sw::clamp(sourceD32FS8[x].depth32f, 0.0f, 1.0f);
		}
	}

	template<>
	void TransferRow<X24S8toS8>(unsigned char *dest, const unsigned char *source, GLsizei width, GLsizei bytes)
	{
		const unsigned int *sourceI = reinterpret_cast<const unsigned int*>(source);
		unsigned char *destI = dest;

		for(int x = 0; x < width; x++)
		{
			destI[x] = static_cast<unsigned char>(sourceI[x] & 0x000000FF);   // FIXME: Quad layout
		}
	}

	template<>
	void TransferRow<X56S8toS8>(unsigned char *dest, const unsigned char *source, GLsizei width, GLsizei bytes)
	{
		struct D32FS8 { float depth32f; unsigned int stencil24_8; };
		const D32FS8 *sourceD32FS8 = reinterpret_cast<const D32FS8*>(source);
		unsigned char *destI = dest;

		for(int x = 0; x < width; x++)
		{
			destI[x] = static_cast<unsigned char>(sourceD32FS8[x].stencil24_8 & 0x000000FF);   // FIXME: Quad layout
		}
	}

	struct Rectangle
	{
		GLsizei bytes;
		GLsizei width;
		GLsizei height;
		GLsizei depth;
		int inputPitch;
		int inputHeight;
		int destPitch;
		GLsizei destSlice;
	};

	template<TransferType transferType>
	void Transfer(void *buffer, const void *input, const Rectangle &rect)
	{
		for(int z = 0; z < rect.depth; z++)
		{
			const unsigned char *inputStart = static_cast<const unsigned char*>(input) + (z * rect.inputPitch * rect.inputHeight);
			unsigned char *destStart = static_cast<unsigned char*>(buffer) + (z * rect.destSlice);
			for(int y = 0; y < rect.height; y++)
			{
				const unsigned char *source = inputStart + y * rect.inputPitch;
				unsigned char *dest = destStart + y * rect.destPitch;

				TransferRow<transferType>(dest, source, rect.width, rect.bytes);
			}
		}
	}

	class ImageImplementation : public Image
	{
	public:
		ImageImplementation(Texture *parentTexture, GLsizei width, GLsizei height, GLint internalformat)
			: Image(parentTexture, width, height, internalformat) {}
		ImageImplementation(Texture *parentTexture, GLsizei width, GLsizei height, GLsizei depth, int border, GLint internalformat)
			: Image(parentTexture, width, height, depth, border, internalformat) {}
		ImageImplementation(GLsizei width, GLsizei height, GLint internalformat, int pitchP)
			: Image(width, height, internalformat, pitchP) {}
		ImageImplementation(GLsizei width, GLsizei height, GLint internalformat, int multiSampleDepth, bool lockable)
			: Image(width, height, internalformat, multiSampleDepth, lockable) {}

		~ImageImplementation() override
		{
			sync();   // Wait for any threads that use this image to finish.
		}

		void *lockInternal(int x, int y, int z, sw::Lock lock, sw::Accessor client) override
		{
			return Image::lockInternal(x, y, z, lock, client);
		}

		void unlockInternal() override
		{
			return Image::unlockInternal();
		}

		void release() override
		{
			return Image::release();
		}
	};

	Image *Image::create(Texture *parentTexture, GLsizei width, GLsizei height, GLint internalformat)
	{
		if(size(width, height, 1, 0, 1, internalformat) > IMPLEMENTATION_MAX_IMAGE_SIZE_BYTES)
		{
			return nullptr;
		}

		return new ImageImplementation(parentTexture, width, height, internalformat);
	}

	Image *Image::create(Texture *parentTexture, GLsizei width, GLsizei height, GLsizei depth, int border, GLint internalformat)
	{
		if(size(width, height, depth, border, 1, internalformat) > IMPLEMENTATION_MAX_IMAGE_SIZE_BYTES)
		{
			return nullptr;
		}

		return new ImageImplementation(parentTexture, width, height, depth, border, internalformat);
	}

	Image *Image::create(GLsizei width, GLsizei height, GLint internalformat, int pitchP)
	{
		if(size(pitchP, height, 1, 0, 1, internalformat) > IMPLEMENTATION_MAX_IMAGE_SIZE_BYTES)
		{
			return nullptr;
		}

		return new ImageImplementation(width, height, internalformat, pitchP);
	}

	Image *Image::create(GLsizei width, GLsizei height, GLint internalformat, int multiSampleDepth, bool lockable)
	{
		if(size(width, height, 1, 0, multiSampleDepth, internalformat) > IMPLEMENTATION_MAX_IMAGE_SIZE_BYTES)
		{
			return nullptr;
		}

		return new ImageImplementation(width, height, internalformat, multiSampleDepth, lockable);
	}

	size_t Image::size(int width, int height, int depth, int border, int samples, GLint internalformat)
	{
		return sw::Surface::size(width, height, depth, border, samples, gl::SelectInternalFormat(internalformat));
	}

	int ClientBuffer::getWidth() const
	{
		return width;
	}

	int ClientBuffer::getHeight() const
	{
		return height;
	}

	sw::Format ClientBuffer::getFormat() const
	{
		return format;
	}

	size_t ClientBuffer::getPlane() const
	{
		return plane;
	}

	int ClientBuffer::pitchP() const
	{
#if defined(__APPLE__)
		if(buffer)
		{
			IOSurfaceRef ioSurface = reinterpret_cast<IOSurfaceRef>(buffer);
			int pitchB = static_cast<int>(IOSurfaceGetBytesPerRowOfPlane(ioSurface, plane));
			int bytesPerPixel = sw::Surface::bytes(format);
			ASSERT((pitchB % bytesPerPixel) == 0);
			return pitchB / bytesPerPixel;
		}

		return 0;
#else
		return sw::Surface::pitchP(width, 0, format, false);
#endif
	}

	void ClientBuffer::retain()
	{
#if defined(__APPLE__)
		if(buffer)
		{
			CFRetain(reinterpret_cast<IOSurfaceRef>(buffer));
		}
#endif
	}

	void ClientBuffer::release()
	{
#if defined(__APPLE__)
		if(buffer)
		{
			CFRelease(reinterpret_cast<IOSurfaceRef>(buffer));
			buffer = nullptr;
		}
#endif
	}

	void* ClientBuffer::lock(int x, int y, int z)
	{
#if defined(__APPLE__)
		if(buffer)
		{
			IOSurfaceRef ioSurface = reinterpret_cast<IOSurfaceRef>(buffer);
			IOSurfaceLock(ioSurface, 0, nullptr);
			void* pixels = IOSurfaceGetBaseAddressOfPlane(ioSurface, plane);
			int bytes = sw::Surface::bytes(format);
			int pitchB = static_cast<int>(IOSurfaceGetBytesPerRowOfPlane(ioSurface, plane));
			int sliceB = static_cast<int>(IOSurfaceGetHeightOfPlane(ioSurface, plane)) * pitchB;
			return (unsigned char*)pixels + x * bytes + y * pitchB + z * sliceB;
		}

		return nullptr;
#else
		int bytes = sw::Surface::bytes(format);
		int pitchB = sw::Surface::pitchB(width, 0, format, false);
		int sliceB = height * pitchB;
		return (unsigned char*)buffer + x * bytes + y * pitchB + z * sliceB;
#endif
	}

	void ClientBuffer::unlock()
	{
#if defined(__APPLE__)
		if(buffer)
		{
			IOSurfaceRef ioSurface = reinterpret_cast<IOSurfaceRef>(buffer);
			IOSurfaceUnlock(ioSurface, 0, nullptr);
		}
#endif
	}

	bool ClientBuffer::requiresSync() const
	{
#if defined(__APPLE__)
		return true;
#else
		return false;
#endif
	}

	class ClientBufferImage : public egl::Image
	{
	public:
		explicit ClientBufferImage(const ClientBuffer& clientBuffer) :
			egl::Image(clientBuffer.getWidth(),
				clientBuffer.getHeight(),
				getClientBufferInternalFormat(clientBuffer.getFormat()),
				clientBuffer.pitchP()),
			clientBuffer(clientBuffer)
		{
			shared = false;
			this->clientBuffer.retain();
		}

	private:
		ClientBuffer clientBuffer;

		~ClientBufferImage() override
		{
			sync();   // Wait for any threads that use this image to finish.

			clientBuffer.release();
		}

		static GLint getClientBufferInternalFormat(sw::Format format)
		{
			switch(format)
			{
			case sw::FORMAT_R8:            return GL_R8;
			case sw::FORMAT_G8R8:          return GL_RG8;
			case sw::FORMAT_X8R8G8B8:      return GL_RGB8;
			case sw::FORMAT_A8R8G8B8:      return GL_BGRA8_EXT;
			case sw::FORMAT_R16UI:         return GL_R16UI;
			case sw::FORMAT_A16B16G16R16F: return GL_RGBA16F;
			default:                       return GL_NONE;
			}
		}

		void *lockInternal(int x, int y, int z, sw::Lock lock, sw::Accessor client) override
		{
			LOGLOCK("image=%p op=%s.swsurface lock=%d", this, __FUNCTION__, lock);

			// Always do this for reference counting.
			void *data = sw::Surface::lockInternal(x, y, z, lock, client);

			if(x != 0 || y != 0 || z != 0)
			{
				LOGLOCK("badness: %s called with unsupported parms: image=%p x=%d y=%d z=%d", __FUNCTION__, this, x, y, z);
			}

			LOGLOCK("image=%p op=%s.ani lock=%d", this, __FUNCTION__, lock);

			// Lock the ClientBuffer and use its address.
			data = clientBuffer.lock(x, y, z);

			if(lock == sw::LOCK_UNLOCKED)
			{
				// We're never going to get a corresponding unlock, so unlock
				// immediately. This keeps the reference counts sane.
				clientBuffer.unlock();
			}

			return data;
		}

		void unlockInternal() override
		{
			LOGLOCK("image=%p op=%s.ani", this, __FUNCTION__);
			clientBuffer.unlock();

			LOGLOCK("image=%p op=%s.swsurface", this, __FUNCTION__);
			sw::Surface::unlockInternal();
		}

		void *lock(int x, int y, int z, sw::Lock lock) override
		{
			LOGLOCK("image=%p op=%s lock=%d", this, __FUNCTION__, lock);
			(void)sw::Surface::lockExternal(x, y, z, lock, sw::PUBLIC);

			return clientBuffer.lock(x, y, z);
		}

		void unlock() override
		{
			LOGLOCK("image=%p op=%s.ani", this, __FUNCTION__);
			clientBuffer.unlock();

			LOGLOCK("image=%p op=%s.swsurface", this, __FUNCTION__);
			sw::Surface::unlockExternal();
		}

		bool requiresSync() const override
		{
			return clientBuffer.requiresSync();
		}

		void release() override
		{
			Image::release();
		}
	};

	Image *Image::create(const egl::ClientBuffer& clientBuffer)
	{
		return new ClientBufferImage(clientBuffer);
	}

	Image::~Image()
	{
		// sync() must be called in the destructor of the most derived class to ensure their vtable isn't destroyed
		// before all threads are done using this image. Image itself is abstract so it can't be the most derived.
		ASSERT(isUnlocked());

		if(parentTexture)
		{
			parentTexture->release();
		}

		ASSERT(!shared);
	}

	void *Image::lockInternal(int x, int y, int z, sw::Lock lock, sw::Accessor client)
	{
		return Surface::lockInternal(x, y, z, lock, client);
	}

	void Image::unlockInternal()
	{
		Surface::unlockInternal();
	}

	void Image::release()
	{
		int refs = dereference();

		if(refs > 0)
		{
			if(parentTexture)
			{
				parentTexture->sweep();
			}
		}
		else
		{
			delete this;
		}
	}

	void Image::unbind(const egl::Texture *parent)
	{
		if(parentTexture == parent)
		{
			parentTexture = nullptr;
		}

		release();
	}

	bool Image::isChildOf(const egl::Texture *parent) const
	{
		return parentTexture == parent;
	}

	void Image::loadImageData(GLsizei width, GLsizei height, GLsizei depth, int inputPitch, int inputHeight, GLenum format, GLenum type, const void *input, void *buffer)
	{
		Rectangle rect;
		rect.bytes = gl::ComputePixelSize(format, type);
		rect.width = width;
		rect.height = height;
		rect.depth = depth;
		rect.inputPitch = inputPitch;
		rect.inputHeight = inputHeight;
		rect.destPitch = getPitch();
		rect.destSlice = getSlice();

		// [OpenGL ES 3.0.5] table 3.2 and 3.3.
		switch(format)
		{
		case GL_RGBA:
			switch(type)
			{
			case GL_UNSIGNED_BYTE:
				switch(internalformat)
				{
				case GL_RGBA8:
				case GL_SRGB8_ALPHA8:
					return Transfer<Bytes>(buffer, input, rect);
				case GL_RGB5_A1:
				case GL_RGBA4:
					ASSERT_OR_RETURN(getExternalFormat() == sw::FORMAT_A8B8G8R8);
					return Transfer<Bytes>(buffer, input, rect);
				default:
					UNREACHABLE(internalformat);
				}
			case GL_BYTE:
				ASSERT_OR_RETURN(internalformat == GL_RGBA8_SNORM && getExternalFormat() == sw::FORMAT_A8B8G8R8_SNORM);
				return Transfer<Bytes>(buffer, input, rect);
			case GL_UNSIGNED_SHORT_4_4_4_4:
				ASSERT_OR_RETURN(internalformat == GL_RGBA4 && getExternalFormat() == sw::FORMAT_A8B8G8R8);
				return Transfer<RGBA4toRGBA8>(buffer, input, rect);
			case GL_UNSIGNED_SHORT_5_5_5_1:
				ASSERT_OR_RETURN(internalformat == GL_RGB5_A1 && getExternalFormat() == sw::FORMAT_A8B8G8R8);
				return Transfer<RGBA5_A1toRGBA8>(buffer, input, rect);
			case GL_UNSIGNED_INT_2_10_10_10_REV:
				switch(internalformat)
				{
				case GL_RGB10_A2:
					ASSERT_OR_RETURN(getExternalFormat() == sw::FORMAT_A2B10G10R10);
					return Transfer<Bytes>(buffer, input, rect);
				case GL_RGB5_A1:
					ASSERT_OR_RETURN(getExternalFormat() == sw::FORMAT_A8B8G8R8);
					return Transfer<RGBA1010102toRGBA8>(buffer, input, rect);
				default:
					UNREACHABLE(internalformat);
				}
			case GL_HALF_FLOAT:
			case GL_HALF_FLOAT_OES:
				ASSERT_OR_RETURN(internalformat == GL_RGBA16F && getExternalFormat() == sw::FORMAT_A16B16G16R16F);
				return Transfer<Bytes>(buffer, input, rect);
			case GL_FLOAT:
				switch(internalformat)
				{
				case GL_RGBA32F: return Transfer<Bytes>(buffer, input, rect);
				case GL_RGBA16F: return Transfer<RGBA32FtoRGBA16F>(buffer, input, rect);
				default: UNREACHABLE(internalformat);
				}
			default:
				UNREACHABLE(type);
			}
		case GL_RGBA_INTEGER:
			switch(type)
			{
			case GL_UNSIGNED_BYTE:
				ASSERT_OR_RETURN(internalformat == GL_RGBA8UI && getExternalFormat() == sw::FORMAT_A8B8G8R8UI);
				return Transfer<Bytes>(buffer, input, rect);
			case GL_BYTE:
				ASSERT_OR_RETURN(internalformat == GL_RGBA8I && getExternalFormat() == sw::FORMAT_A8B8G8R8I);
				return Transfer<Bytes>(buffer, input, rect);
			case GL_UNSIGNED_SHORT:
				ASSERT_OR_RETURN(internalformat == GL_RGBA16UI && getExternalFormat() == sw::FORMAT_A16B16G16R16UI);
				return Transfer<Bytes>(buffer, input, rect);
			case GL_SHORT:
				ASSERT_OR_RETURN(internalformat == GL_RGBA16I && getExternalFormat() == sw::FORMAT_A16B16G16R16I);
				return Transfer<Bytes>(buffer, input, rect);
			case GL_UNSIGNED_INT:
				ASSERT_OR_RETURN(internalformat == GL_RGBA32UI && getExternalFormat() == sw::FORMAT_A32B32G32R32UI);
				return Transfer<Bytes>(buffer, input, rect);
			case GL_INT:
				ASSERT_OR_RETURN(internalformat == GL_RGBA32I && getExternalFormat() == sw::FORMAT_A32B32G32R32I);
				return Transfer<Bytes>(buffer, input, rect);
			case GL_UNSIGNED_INT_2_10_10_10_REV:
				ASSERT_OR_RETURN(internalformat == GL_RGB10_A2UI && getExternalFormat() == sw::FORMAT_A2B10G10R10UI);
				return Transfer<Bytes>(buffer, input, rect);
			default:
				UNREACHABLE(type);
			}
		case GL_BGRA_EXT:
			switch(type)
			{
			case GL_UNSIGNED_BYTE:
				ASSERT_OR_RETURN(internalformat == GL_BGRA8_EXT && getExternalFormat() == sw::FORMAT_A8R8G8B8);
				return Transfer<Bytes>(buffer, input, rect);
			case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:   // Only valid for glReadPixels calls.
			case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:   // Only valid for glReadPixels calls.
			default:
				UNREACHABLE(type);
			}
		case GL_RGB:
			switch(type)
			{
			case GL_UNSIGNED_BYTE:
				switch(internalformat)
				{
				case GL_RGB8:   return Transfer<RGB8toRGBX8>(buffer, input, rect);
				case GL_SRGB8:  return Transfer<RGB8toRGBX8>(buffer, input, rect);
				case GL_RGB565: return Transfer<RGB8toRGB565>(buffer, input, rect);
				default: UNREACHABLE(internalformat);
				}
			case GL_BYTE:
				ASSERT_OR_RETURN(internalformat == GL_RGB8_SNORM && getExternalFormat() == sw::FORMAT_X8B8G8R8_SNORM);
				return Transfer<RGB8toRGBX8>(buffer, input, rect);
			case GL_UNSIGNED_SHORT_5_6_5:
				ASSERT_OR_RETURN(internalformat == GL_RGB565 && getExternalFormat() == sw::FORMAT_R5G6B5);
				return Transfer<Bytes>(buffer, input, rect);
			case GL_UNSIGNED_INT_10F_11F_11F_REV:
				ASSERT_OR_RETURN(internalformat == GL_R11F_G11F_B10F && getExternalFormat() == sw::FORMAT_X16B16G16R16F_UNSIGNED);
				return Transfer<R11G11B10FtoRGBX16F>(buffer, input, rect);
			case GL_UNSIGNED_INT_5_9_9_9_REV:
				ASSERT_OR_RETURN(internalformat == GL_RGB9_E5 && getExternalFormat() == sw::FORMAT_X16B16G16R16F_UNSIGNED);
				return Transfer<RGB9_E5FtoRGBX16F>(buffer, input, rect);
			case GL_HALF_FLOAT:
			case GL_HALF_FLOAT_OES:
				switch(internalformat)
				{
				case GL_RGB16F:
					ASSERT_OR_RETURN(getExternalFormat() == sw::FORMAT_X16B16G16R16F);
					return Transfer<RGB16FtoRGBX16F>(buffer, input, rect);
				case GL_R11F_G11F_B10F:
				case GL_RGB9_E5:
					ASSERT_OR_RETURN(getExternalFormat() == sw::FORMAT_X16B16G16R16F_UNSIGNED);
					return Transfer<RGB16FtoRGBX16F>(buffer, input, rect);
				default:
					UNREACHABLE(internalformat);
				}
			case GL_FLOAT:
				switch(internalformat)
				{
				case GL_RGB32F:
					ASSERT_OR_RETURN(getExternalFormat() == sw::FORMAT_X32B32G32R32F);
					return Transfer<RGB32FtoRGBX32F>(buffer, input, rect);
				case GL_RGB16F:
					ASSERT_OR_RETURN(getExternalFormat() == sw::FORMAT_X16B16G16R16F);
					return Transfer<RGB32FtoRGB16F>(buffer, input, rect);
				case GL_R11F_G11F_B10F:
				case GL_RGB9_E5:
					ASSERT_OR_RETURN(getExternalFormat() == sw::FORMAT_X16B16G16R16F_UNSIGNED);
					return Transfer<RGB32FtoRGB16F_UNSIGNED>(buffer, input, rect);
				default:
					UNREACHABLE(internalformat);
				}
			default:
				UNREACHABLE(type);
			}
		case GL_RGB_INTEGER:
			switch(type)
			{
			case GL_UNSIGNED_BYTE:
				ASSERT_OR_RETURN(internalformat == GL_RGB8UI && getExternalFormat() == sw::FORMAT_X8B8G8R8UI);
				return Transfer<RGB8toRGBX8>(buffer, input, rect);
			case GL_BYTE:
				ASSERT_OR_RETURN(internalformat == GL_RGB8I && getExternalFormat() == sw::FORMAT_X8B8G8R8I);
				return Transfer<RGB8toRGBX8>(buffer, input, rect);
			case GL_UNSIGNED_SHORT:
				ASSERT_OR_RETURN(internalformat == GL_RGB16UI && getExternalFormat() == sw::FORMAT_X16B16G16R16UI);
				return Transfer<RGB16toRGBX16>(buffer, input, rect);
			case GL_SHORT:
				ASSERT_OR_RETURN(internalformat == GL_RGB16I && getExternalFormat() == sw::FORMAT_X16B16G16R16I);
				return Transfer<RGB16toRGBX16>(buffer, input, rect);
			case GL_UNSIGNED_INT:
				ASSERT_OR_RETURN(internalformat == GL_RGB32UI && getExternalFormat() == sw::FORMAT_X32B32G32R32UI);
				return Transfer<RGB32toRGBX32>(buffer, input, rect);
			case GL_INT:
				ASSERT_OR_RETURN(internalformat == GL_RGB32I && getExternalFormat() == sw::FORMAT_X32B32G32R32I);
				return Transfer<RGB32toRGBX32>(buffer, input, rect);
			default:
				UNREACHABLE(type);
			}
		case GL_RG:
			switch(type)
			{
			case GL_UNSIGNED_BYTE:
			case GL_BYTE:
			case GL_HALF_FLOAT:
			case GL_HALF_FLOAT_OES:
				return Transfer<Bytes>(buffer, input, rect);
			case GL_FLOAT:
				switch(internalformat)
				{
				case GL_RG32F: return Transfer<Bytes>(buffer, input, rect);
				case GL_RG16F: return Transfer<RG32FtoRG16F>(buffer, input, rect);
				default: UNREACHABLE(internalformat);
				}
			default:
				UNREACHABLE(type);
			}
		case GL_RG_INTEGER:
			switch(type)
			{
			case GL_UNSIGNED_BYTE:
				ASSERT_OR_RETURN(internalformat == GL_RG8UI && getExternalFormat() == sw::FORMAT_G8R8UI);
				return Transfer<Bytes>(buffer, input, rect);
			case GL_BYTE:
				ASSERT_OR_RETURN(internalformat == GL_RG8I && getExternalFormat() == sw::FORMAT_G8R8I);
				return Transfer<Bytes>(buffer, input, rect);
			case GL_UNSIGNED_SHORT:
				ASSERT_OR_RETURN(internalformat == GL_RG16UI && getExternalFormat() == sw::FORMAT_G16R16UI);
				return Transfer<Bytes>(buffer, input, rect);
			case GL_SHORT:
				ASSERT_OR_RETURN(internalformat == GL_RG16I && getExternalFormat() == sw::FORMAT_G16R16I);
				return Transfer<Bytes>(buffer, input, rect);
			case GL_UNSIGNED_INT:
				ASSERT_OR_RETURN(internalformat == GL_RG32UI && getExternalFormat() == sw::FORMAT_G32R32UI);
				return Transfer<Bytes>(buffer, input, rect);
			case GL_INT:
				ASSERT_OR_RETURN(internalformat == GL_RG32I && getExternalFormat() == sw::FORMAT_G32R32I);
				return Transfer<Bytes>(buffer, input, rect);
			default:
				UNREACHABLE(type);
			}
		case GL_RED:
			switch(type)
			{
			case GL_UNSIGNED_BYTE:
			case GL_BYTE:
			case GL_HALF_FLOAT:
			case GL_HALF_FLOAT_OES:
				return Transfer<Bytes>(buffer, input, rect);
			case GL_FLOAT:
				switch(internalformat)
				{
				case GL_R32F: return Transfer<Bytes>(buffer, input, rect);
				case GL_R16F: return Transfer<R32FtoR16F>(buffer, input, rect);
				default: UNREACHABLE(internalformat);
				}
			default:
				UNREACHABLE(type);
			}
		case GL_RED_INTEGER:
			switch(type)
			{
			case GL_UNSIGNED_BYTE:
				ASSERT_OR_RETURN(internalformat == GL_R8UI && getExternalFormat() == sw::FORMAT_R8UI);
				return Transfer<Bytes>(buffer, input, rect);
			case GL_BYTE:
				ASSERT_OR_RETURN(internalformat == GL_R8I && getExternalFormat() == sw::FORMAT_R8I);
				return Transfer<Bytes>(buffer, input, rect);
			case GL_UNSIGNED_SHORT:
				ASSERT_OR_RETURN(internalformat == GL_R16UI && getExternalFormat() == sw::FORMAT_R16UI);
				return Transfer<Bytes>(buffer, input, rect);
			case GL_SHORT:
				ASSERT_OR_RETURN(internalformat == GL_R16I && getExternalFormat() == sw::FORMAT_R16I);
				return Transfer<Bytes>(buffer, input, rect);
			case GL_UNSIGNED_INT:
				ASSERT_OR_RETURN(internalformat == GL_R32UI && getExternalFormat() == sw::FORMAT_R32UI);
				return Transfer<Bytes>(buffer, input, rect);
			case GL_INT:
				ASSERT_OR_RETURN(internalformat == GL_R32I && getExternalFormat() == sw::FORMAT_R32I);
				return Transfer<Bytes>(buffer, input, rect);
			default:
				UNREACHABLE(type);
			}
		case GL_DEPTH_COMPONENT:
			switch(type)
			{
			case GL_UNSIGNED_SHORT: return Transfer<D16toD32F>(buffer, input, rect);
			case GL_UNSIGNED_INT:   return Transfer<D32toD32F>(buffer, input, rect);
			case GL_FLOAT:          return Transfer<D32FtoD32F_CLAMPED>(buffer, input, rect);
			case GL_DEPTH_COMPONENT24:       // Only valid for glRenderbufferStorage calls.
			case GL_DEPTH_COMPONENT32_OES:   // Only valid for glRenderbufferStorage calls.
			default: UNREACHABLE(type);
			}
		case GL_DEPTH_STENCIL:
			switch(type)
			{
			case GL_UNSIGNED_INT_24_8:              return Transfer<D24X8toD32F>(buffer, input, rect);
			case GL_FLOAT_32_UNSIGNED_INT_24_8_REV: return Transfer<D32FX32toD32F>(buffer, input, rect);
			default: UNREACHABLE(type);
			}
		case GL_LUMINANCE_ALPHA:
			switch(type)
			{
			case GL_UNSIGNED_BYTE:
				return Transfer<Bytes>(buffer, input, rect);
			case GL_FLOAT:
				switch(internalformat)
				{
				case GL_LUMINANCE_ALPHA32F_EXT: return Transfer<Bytes>(buffer, input, rect);
				case GL_LUMINANCE_ALPHA16F_EXT: return Transfer<RG32FtoRG16F>(buffer, input, rect);
				default: UNREACHABLE(internalformat);
				}
			case GL_HALF_FLOAT:
			case GL_HALF_FLOAT_OES:
				ASSERT_OR_RETURN(internalformat == GL_LUMINANCE_ALPHA16F_EXT);
				return Transfer<Bytes>(buffer, input, rect);
			default:
				UNREACHABLE(type);
			}
		case GL_LUMINANCE:
		case GL_ALPHA:
			switch(type)
			{
			case GL_UNSIGNED_BYTE:
				return Transfer<Bytes>(buffer, input, rect);
			case GL_FLOAT:
				switch(internalformat)
				{
				case GL_LUMINANCE32F_EXT: return Transfer<Bytes>(buffer, input, rect);
				case GL_LUMINANCE16F_EXT: return Transfer<R32FtoR16F>(buffer, input, rect);
				case GL_ALPHA32F_EXT:     return Transfer<Bytes>(buffer, input, rect);
				case GL_ALPHA16F_EXT:     return Transfer<R32FtoR16F>(buffer, input, rect);
				default: UNREACHABLE(internalformat);
				}
			case GL_HALF_FLOAT:
			case GL_HALF_FLOAT_OES:
				ASSERT_OR_RETURN(internalformat == GL_LUMINANCE16F_EXT || internalformat == GL_ALPHA16F_EXT);
				return Transfer<Bytes>(buffer, input, rect);
			default:
				UNREACHABLE(type);
			}
		default:
			UNREACHABLE(format);
		}
	}

	void Image::loadStencilData(GLsizei width, GLsizei height, GLsizei depth, int inputPitch, int inputHeight, GLenum format, GLenum type, const void *input, void *buffer)
	{
		Rectangle rect;
		rect.bytes = gl::ComputePixelSize(format, type);
		rect.width = width;
		rect.height = height;
		rect.depth = depth;
		rect.inputPitch = inputPitch;
		rect.inputHeight = inputHeight;
		rect.destPitch = getStencilPitchB();
		rect.destSlice = getStencilSliceB();

		switch(type)
		{
		case GL_UNSIGNED_INT_24_8:              return Transfer<X24S8toS8>(buffer, input, rect);
		case GL_FLOAT_32_UNSIGNED_INT_24_8_REV: return Transfer<X56S8toS8>(buffer, input, rect);
		default: UNREACHABLE(format);
		}
	}

	void Image::loadImageData(GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const gl::PixelStorageModes &unpackParameters, const void *pixels)
	{
		GLsizei inputWidth = (unpackParameters.rowLength == 0) ? width : unpackParameters.rowLength;
		GLsizei inputPitch = gl::ComputePitch(inputWidth, format, type, unpackParameters.alignment);
		GLsizei inputHeight = (unpackParameters.imageHeight == 0) ? height : unpackParameters.imageHeight;
		char *input = ((char*)pixels) + gl::ComputePackingOffset(format, type, inputWidth, inputHeight, unpackParameters);

		void *buffer = lock(xoffset, yoffset, zoffset, sw::LOCK_WRITEONLY);

		if(buffer)
		{
			loadImageData(width, height, depth, inputPitch, inputHeight, format, type, input, buffer);
		}

		unlock();

		if(hasStencil())
		{
			unsigned char *stencil = reinterpret_cast<unsigned char*>(lockStencil(xoffset, yoffset, zoffset, sw::PUBLIC));

			if(stencil)
			{
				loadStencilData(width, height, depth, inputPitch, inputHeight, format, type, input, stencil);
			}

			unlockStencil();
		}
	}

	void Image::loadCompressedData(GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei imageSize, const void *pixels)
	{
		int inputPitch = gl::ComputeCompressedPitch(width, internalformat);
		int inputSlice = imageSize / depth;
		int rows = inputSlice / inputPitch;

		void *buffer = lock(xoffset, yoffset, zoffset, sw::LOCK_WRITEONLY);

		if(buffer)
		{
			for(int z = 0; z < depth; z++)
			{
				for(int y = 0; y < rows; y++)
				{
					GLbyte *dest = (GLbyte*)buffer + y * getPitch() + z * getSlice();
					GLbyte *source = (GLbyte*)pixels + y * inputPitch + z * inputSlice;
					memcpy(dest, source, inputPitch);
				}
			}
		}

		unlock();
	}
}


text:
layout: splash
permalink: /about/
title: "About"
header:
  image: /assets/images/Thames-thin.jpg
---

### Who Am I?

I am an Information Security professional with an MSc in Computer Security,
and two undergraduate degrees. One degree focusing on System Administration &
Networking, the other a three year BSc focusing on Software Development.

I have professional experience in Systems & Network Security, IAM, Web
Development, and System Administration (Linux & Windows). I am a confident
programmer and have  experience coding for and both Linux & Windows environments
across multiple technologies.

I love discovering and learning about how systems and infrastructures are
designed and truly function.

My current interests include Systems and Network Security, Application Security,
Reverse Engineering, Vulnerability Research and Obfuscation / Anti-Debug
techniques.

This blog grants me a place to post and explain topics, concepts, systems and
tools I find interesting. It also serves as a location I use for personal
resources and to discuss tools I develop.

### Contact me

[kevin.almansa@gmail.com](mailto:kevin.almansa@gmail.com)


text:
import logging
import optparse
import os
import sys
from StringIO import StringIO
import re
import unittest

# Run build_server so that files needed by tests are copied to the local
# third_party directory.
import build_server
build_server.main()

BASE_PATH = None
EXPLICIT_TEST_FILES = None

from fake_fetchers import ConfigureFakeFetchers
ConfigureFakeFetchers(os.path.join(sys.path[0], os.pardir))

# Import Handler later because it immediately makes a request to github. We need
# the fake urlfetch to be in place first.
from handler import Handler

class _MockResponse(object):
  def __init__(self):
    self.status = 200
    self.out = StringIO()
    self.headers = {}

  def set_status(self, status):
    self.status = status

class _MockRequest(object):
  def __init__(self, path):
    self.headers = {}
    self.path = path
    self.url = 'http://localhost' + path

class IntegrationTest(unittest.TestCase):
  def _TestSamplesLocales(self, sample_path, failures):
    # Use US English, Spanish, and Arabic.
    for lang in ['en-US', 'es', 'ar']:
      request = _MockRequest(sample_path)
      request.headers['Accept-Language'] = lang + ';q=0.8'
      response = _MockResponse()
      try:
        Handler(request, response, local_path=BASE_PATH).get()
        if 200 != response.status:
          failures.append(
              'Samples page with language %s does not have 200 status.'
              ' Status was %d.' %  (lang, response.status))
        if not response.out.getvalue():
          failures.append(
              'Rendering samples page with language %s produced no output.' %
                  lang)
      except Exception as e:
        failures.append('Error rendering samples page with language %s: %s' %
            (lang, e))

  def _RunPublicTemplatesTest(self):
    base_path = os.path.join(BASE_PATH, 'docs', 'templates', 'public')
    if EXPLICIT_TEST_FILES is None:
      test_files = []
      for path, dirs, files in os.walk(base_path):
        for dir_ in dirs:
          if dir_.startswith('.'):
            dirs.remove(dir_)
        for name in files:
          if name.startswith('.') or name == '404.html':
            continue
          test_files.append(os.path.join(path, name)[len(base_path + os.sep):])
    else:
      test_files = EXPLICIT_TEST_FILES
    test_files = [f.replace(os.sep, '/') for f in test_files]
    failures = []
    for filename in test_files:
      request = _MockRequest(filename)
      response = _MockResponse()
      try:
        Handler(request, response, local_path=BASE_PATH).get()
        if 200 != response.status:
          failures.append('%s does not have 200 status. Status was %d.' %
              (filename, response.status))
        if not response.out.getvalue():
          failures.append('Rendering %s produced no output.' % filename)
        if filename.endswith('samples.html'):
          self._TestSamplesLocales(filename, failures)
      except Exception as e:
        failures.append('Error rendering %s: %s' % (filename, e))
    if failures:
      self.fail('\n'.join(failures))

  def testAllPublicTemplates(self):
    logging.getLogger().setLevel(logging.ERROR)
    logging_error = logging.error
    try:
      logging.error = self.fail
      self._RunPublicTemplatesTest()
    finally:
      logging.error = logging_error

  def testNonexistentFile(self):
    logging.getLogger().setLevel(logging.CRITICAL)
    request = _MockRequest('extensions/junk.html')
    bad_response = _MockResponse()
    Handler(request, bad_response, local_path=BASE_PATH).get()
    self.assertEqual(404, bad_response.status)
    request_404 = _MockRequest('404.html')
    response_404 = _MockResponse()
    Handler(request_404, response_404, local_path=BASE_PATH).get()
    self.assertEqual(200, response_404.status)
    self.assertEqual(response_404.out.getvalue(), bad_response.out.getvalue())

  def testCron(self):
    if EXPLICIT_TEST_FILES is not None:
      return
    logging_error = logging.error
    try:
      logging.error = self.fail
      request = _MockRequest('/cron/trunk')
      response = _MockResponse()
      Handler(request, response, local_path=BASE_PATH).get()
      self.assertEqual(200, response.status)
      self.assertEqual('Success', response.out.getvalue())
    finally:
      logging.error = logging_error

if __name__ == '__main__':
  parser = optparse.OptionParser()
  parser.add_option('-p',
                    '--path',
                    default=os.path.join(
                        os.path.abspath(os.path.dirname(__file__)),
                        os.pardir,
                        os.pardir))
  parser.add_option('-a',
                    '--all',
                    action='store_true',
                    default=False)
  (opts, args) = parser.parse_args()

  if not opts.all:
    EXPLICIT_TEST_FILES = args
  BASE_PATH = opts.path
  suite = unittest.TestSuite(tests=[
    IntegrationTest('testNonexistentFile'),
    IntegrationTest('testCron'),
    IntegrationTest('testAllPublicTemplates')
  ])
  result = unittest.TestResult()
  suite.run(result)
  if result.failures:
    print('*----------------------------------*')
    print('| integration_test.py has failures |')
    print('*----------------------------------*')
    for test, failure in result.failures:
      print(test)
      print(failure)
    exit(1)
  exit(0)


text:
Interpolation and Template Expressions

Interpolation

Current customer: {{ currentCustomer }}

{{title}}

Evaluating template expressions

Simple evaluation (to a string):

The sum of 1 + 1 is {{1 + 1}}.

Evaluates using a method (also evaluates to a string):

The sum of 1 + 1 is not {{1 + 1 + getVal()}}.

Expression Context

Component context, properties of app.component.ts:

{{recommended}}

Template context, template input variables (let customer):

{{customer.name}}

Template context: template reference variables (#customerInput):

  Type something:
    <input #customerInput>{{customerInput.value}}


text:
package org.laladev.moneyjinn.server.controller.mapper;

import java.sql.Timestamp;
import java.time.LocalDateTime;

import org.laladev.moneyjinn.core.mapper.IMapper;
import org.laladev.moneyjinn.core.rest.model.etf.transport.EtfFlowTransport;
import org.laladev.moneyjinn.model.etf.EtfFlow;
import org.laladev.moneyjinn.model.etf.EtfFlowID;
import org.laladev.moneyjinn.model.etf.EtfIsin;

public class EtfFlowTransportMapper implements IMapper<EtfFlow, EtfFlowTransport> {

	@Override
	public EtfFlow mapBToA(final EtfFlowTransport etfFlowTransport) {
		final EtfFlow etfFlow = new EtfFlow();
		if (etfFlowTransport.getEtfflowid() != null) {
			etfFlow.setId(new EtfFlowID(etfFlowTransport.getEtfflowid()));
		}
		etfFlow.setAmount(etfFlowTransport.getAmount());
		etfFlow.setIsin(new EtfIsin(etfFlowTransport.getIsin()));
		etfFlow.setPrice(etfFlowTransport.getPrice());
		if (etfFlowTransport.getTimestamp() != null) {
			final LocalDateTime time = etfFlowTransport.getTimestamp().toLocalDateTime();
			final int nanos = etfFlowTransport.getNanoseconds() != null ? etfFlowTransport.getNanoseconds() : 0;
			etfFlow.setTime(time.withNano(nanos));
		}

		return etfFlow;
	}

	@Override
	public EtfFlowTransport mapAToB(final EtfFlow etfFlow) {
		final EtfFlowTransport transport = new EtfFlowTransport();

		transport.setEtfflowid(etfFlow.getId().getId());
		transport.setIsin(etfFlow.getIsin().getId());
		if (etfFlow.getTime() != null) {
			final Timestamp time = Timestamp.valueOf(etfFlow.getTime());
			transport.setTimestamp(time);
			transport.setNanoseconds(etfFlow.getTime().getNano());
		}

		transport.setAmount(etfFlow.getAmount());
		transport.setPrice(etfFlow.getPrice());

		return transport;
	}
}


text:
<?xml version="1.0"?>
<package>
  <name>rslidar_driver</name>
  <version>1.0.0</version>
  <description>segmentation</description>

  <maintainer email="tony.zhang@robosense.cn">Tony</maintainer>
  <author>Tony Zhang</author>
  <license>BSD</license>

  <buildtool_depend>catkin</buildtool_depend>

  <build_depend>angles</build_depend>
  <build_depend>nodelet</build_depend>
  <build_depend>pcl_conversions</build_depend>

  <build_depend>pluginlib</build_depend>
  <build_depend>roscpp</build_depend>
  <build_depend>roslib</build_depend>
  <build_depend>sensor_msgs</build_depend>
  <build_depend>tf</build_depend>
  <build_depend>dynamic_reconfigure</build_depend>
  <build_depend>roslaunch</build_depend>
  <build_depend>rostest</build_depend>
  <build_depend>tf2_ros</build_depend>
  <build_depend>message_generation</build_depend>
  <build_depend>rospy</build_depend>
  <build_depend>std_msgs</build_depend>
  <build_depend>rslidar_input</build_depend>
  <build_depend>pcl_conversions</build_depend>

  <build_depend>libpcl-all-dev</build_depend>
  <build_depend>rslidar_msgs</build_depend>
  <build_depend>diagnostic_updater</build_depend>

  <run_depend>angles</run_depend>

  <run_depend>pluginlib</run_depend>
  <run_depend>python-yaml</run_depend>
  <run_depend>roscpp</run_depend>
  <run_depend>roslib</run_depend>
  <run_depend>rospy</run_depend>
  <run_depend>sensor_msgs</run_depend>
  <run_depend>tf</run_depend>
  <run_depend>yaml-cpp</run_depend>
  <run_depend>dynamic_reconfigure</run_depend>
  <run_depend>message_runtime</run_depend>
  <run_depend>pcl_conversions</run_depend>

  <run_depend>libpcl-all</run_depend>
  <run_depend>std_msgs</run_depend>
  <run_depend>rslidar_msgs</run_depend>
  <run_depend>diagnostic_updater</run_depend>

</package>


text:
:mod:`~pwnypack.flow` -- Communication
======================================

.. automodule:: pwnypack.flow
    :members:
    :undoc-members:
    :show-inheritance:


text:
#include "dns.h"

#if defined NN_HAVE_GETADDRINFO_A
#include "dns_getaddrinfo_a.inc"
#else
#include "dns_getaddrinfo.inc"
#endif


text:
#import "CCTransition.h"

/** CCTransitionPageTurn transition.
 * A transition which peels back the bottom right hand corner of a scene
 * to transition to the scene beneath it simulating a page turn
 *
 * This uses a 3DAction so it's strongly recommended that depth buffering
 * is turned on in CCDirector using:
 *
 * 	[[CCDirector sharedDirector] setDepthBufferFormat:kCCDepthBuffer16];
 *
 * @since v0.8.2
 */
@interface CCTransitionPageTurn : CCTransitionScene
{
	BOOL	back_;
}
/**
 * creates a base transition with duration and incoming scene
 * if back is TRUE then the effect is reversed to appear as if the incoming
 * scene is being turned from left over the outgoing scene
 */
+(id) transitionWithDuration:(ccTime) t scene:(CCScene*)s backwards:(BOOL) back;

/**
 * creates a base transition with duration and incoming scene
 * if back is TRUE then the effect is reversed to appear as if the incoming
 * scene is being turned from left over the outgoing scene
 */
-(id) initWithDuration:(ccTime) t scene:(CCScene*)s backwards:(BOOL) back;

-(CCActionInterval*) actionWithSize:(ccGridSize) vector;

@end


text:
{% load i18n %}
{% load rssplug %}
{{ item.description|safe|truncatewords_html:10 }}

{% blocktrans with item.date_parsed|todatetime|timesince as when %}{{ when }} ago{% endblocktrans %}


text:
namespace commerce::metrics {

class ScheduledMetricsManagerTest : public testing::Test {
 public:
  ScheduledMetricsManagerTest()
      : bookmark_model_(bookmarks::TestBookmarkClient::CreateModel()),
        pref_service_(std::make_unique<TestingPrefServiceSimple>()) {}
  ScheduledMetricsManagerTest(const ScheduledMetricsManagerTest&) = delete;
  ScheduledMetricsManagerTest operator=(const ScheduledMetricsManagerTest&) =
      delete;
  ~ScheduledMetricsManagerTest() override = default;

  void TestBody() override {}

  void SetUp() override { RegisterPrefs(pref_service_->registry()); }

  void CreateUpdateManagerAndWait() {
    auto metrics_manager = std::make_unique<ScheduledMetricsManager>(
        pref_service_.get(), bookmark_model_.get());
    base::RunLoop().RunUntilIdle();
  }

 protected:
  base::test::TaskEnvironment task_environment_;
  std::unique_ptr<bookmarks::BookmarkModel> bookmark_model_;
  std::unique_ptr<TestingPrefServiceSimple> pref_service_;
};

TEST_F(ScheduledMetricsManagerTest, TrackedProductCountRecorded) {
  // Set the last updated time to "never" so the scheduled task runs
  // immediately.
  pref_service_->SetTime(kCommerceDailyMetricsLastUpdateTime, base::Time());
  base::HistogramTester histogram_tester;

  // Add two tracked products and one untracked product.
  AddProductBookmark(bookmark_model_.get(), u"product 1",
                     GURL("http://example.com"), 123L, true);
  AddProductBookmark(bookmark_model_.get(), u"product 2",
                     GURL("http://example.com"), 456L, false);
  AddProductBookmark(bookmark_model_.get(), u"product 3",
                     GURL("http://example.com"), 789L, true);

  CreateUpdateManagerAndWait();

  histogram_tester.ExpectTotalCount(kTrackedProductCountHistogramName, 1);
}

TEST_F(ScheduledMetricsManagerTest, TrackedProductCountNotRecordedEarly) {
  // Set the last updated time to now so the task doesn't immediately run.
  pref_service_->SetTime(kCommerceDailyMetricsLastUpdateTime,
                         base::Time::Now());
  base::HistogramTester histogram_tester;

  AddProductBookmark(bookmark_model_.get(), u"product 1",
                     GURL("http://example.com"), 123L, true);

  CreateUpdateManagerAndWait();

  histogram_tester.ExpectTotalCount(kTrackedProductCountHistogramName, 0);
}

TEST_F(ScheduledMetricsManagerTest, EmailNotification_NoTrackedProducts) {
  // Set the last updated time to "never" so the scheduled task runs
  // immediately.
  pref_service_->SetTime(kCommerceDailyMetricsLastUpdateTime, base::Time());
  base::HistogramTester histogram_tester;

  // Assume the user has enabled notifications but has no tracked products.
  pref_service_->SetBoolean(kPriceEmailNotificationsEnabled, true);

  CreateUpdateManagerAndWait();

  histogram_tester.ExpectUniqueSample(
      kPriceNotificationEmailHistogramName,
      PriceNotificationEmailState::kNotResponded, 1);
  histogram_tester.ExpectTotalCount(kPriceNotificationEmailHistogramName, 1);
}

TEST_F(ScheduledMetricsManagerTest, EmailNotification_TrackedProducts) {
  // Set the last updated time to "never" so the scheduled task runs
  // immediately.
  pref_service_->SetTime(kCommerceDailyMetricsLastUpdateTime, base::Time());
  base::HistogramTester histogram_tester;

  // Assume the user has enabled notifications.
  pref_service_->SetBoolean(kPriceEmailNotificationsEnabled, true);

  // Have at least one tracked product.
  AddProductBookmark(bookmark_model_.get(), u"product 1",
                     GURL("http://example.com"), 123L, true);

  CreateUpdateManagerAndWait();

  histogram_tester.ExpectUniqueSample(kPriceNotificationEmailHistogramName,
                                      PriceNotificationEmailState::kEnabled, 1);
  histogram_tester.ExpectTotalCount(kPriceNotificationEmailHistogramName, 1);
}

TEST_F(ScheduledMetricsManagerTest,
       EmailNotification_TrackedProducts_Disabled) {
  // Set the last updated time to "never" so the scheduled task runs
  // immediately.
  pref_service_->SetTime(kCommerceDailyMetricsLastUpdateTime, base::Time());
  base::HistogramTester histogram_tester;

  // Assume the user has disabled notifications.
  pref_service_->SetBoolean(kPriceEmailNotificationsEnabled, false);

  // Have at least one tracked product.
  AddProductBookmark(bookmark_model_.get(), u"product 1",
                     GURL("http://example.com"), 123L, true);

  CreateUpdateManagerAndWait();

  histogram_tester.ExpectUniqueSample(kPriceNotificationEmailHistogramName,
                                      PriceNotificationEmailState::kDisabled,
                                      1);
  histogram_tester.ExpectTotalCount(kPriceNotificationEmailHistogramName, 1);
}

}  // namespace commerce::metrics


text:
"""This module exports the linter classes and the highlight, linter, persist and util submodules."""

from . import (
    highlight,
    linter,
    persist,
    util,
)

from .linter import Linter
from .python_linter import PythonLinter
from .ruby_linter import RubyLinter
from .node_linter import NodeLinter


text:
import Ember from 'ember';
import route from 'ember-redux/route';

var model = () => {
  return [];
};

var SuperRoute = Ember.Route.extend({
  invoked: null,
  init: function() {
    this.set('invoked', true);
  }
});

export default route({model})(SuperRoute);


text:
package com.fkeglevich.rawdumper.raw.reprocessing;

import com.fkeglevich.rawdumper.camera.async.CameraSelector;
import com.fkeglevich.rawdumper.raw.info.DeviceInfo;

/**
 * TODO: add header comment
 * Created by Flávio Keglevich on 27/05/18.
 */
class DummyCameraSelector extends CameraSelector
{
    private final int numCameras;

    DummyCameraSelector(DeviceInfo deviceInfo, int cameraId)
    {
        super(cameraId);
        numCameras = deviceInfo.getCameras().length;
    }

    @Override
    protected int getNumOfCameras()
    {
        return numCameras;
    }
}


text:
package com.google.zxing.oned;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.ResultPoint;
import com.google.zxing.common.BitArray;

import java.util.Arrays;
import java.util.Map;

/**
 *
Decodes Code 93 barcodes.

 *
 * @author Sean Owen
 * @see com.google.zxing.oned.Code39Reader
 */
public final class Code93Reader extends OneDReader {

  // Note that 'abcd' are dummy characters in place of control characters.
  private static final String ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%abcd*";
  private static final char[] ALPHABET = ALPHABET_STRING.toCharArray();

  /**
   * These represent the encodings of characters, as patterns of wide and narrow bars.
   * The 9 least-significant bits of each int correspond to the pattern of wide and narrow.
   */
  private static final int[] CHARACTER_ENCODINGS = {
      0x114, 0x148, 0x144, 0x142, 0x128, 0x124, 0x122, 0x150, 0x112, 0x10A, // 0-9
      0x1A8, 0x1A4, 0x1A2, 0x194, 0x192, 0x18A, 0x168, 0x164, 0x162, 0x134, // A-J
      0x11A, 0x158, 0x14C, 0x146, 0x12C, 0x116, 0x1B4, 0x1B2, 0x1AC, 0x1A6, // K-T
      0x196, 0x19A, 0x16C, 0x166, 0x136, 0x13A, // U-Z
      0x12E, 0x1D4, 0x1D2, 0x1CA, 0x16E, 0x176, 0x1AE, // - - %
      0x126, 0x1DA, 0x1D6, 0x132, 0x15E, // Control chars? $-*
  };
  private static final int ASTERISK_ENCODING = CHARACTER_ENCODINGS[47];

  private final StringBuilder decodeRowResult;
  private final int[] counters;

  public Code93Reader() {
    decodeRowResult = new StringBuilder(20);
    counters = new int[6];
  }

  @Override
  public Result decodeRow(int rowNumber, BitArray row, Map<DecodeHintType,?> hints)
      throws NotFoundException, ChecksumException, FormatException {

    int[] start = findAsteriskPattern(row);
    // Read off white space
    int nextStart = row.getNextSet(start[1]);
    int end = row.getSize();

    int[] theCounters = counters;
    Arrays.fill(theCounters, 0);
    StringBuilder result = decodeRowResult;
    result.setLength(0);

    char decodedChar;
    int lastStart;
    do {
      recordPattern(row, nextStart, theCounters);
      int pattern = toPattern(theCounters);
      if (pattern < 0) {
        throw NotFoundException.getNotFoundInstance();
      }
      decodedChar = patternToChar(pattern);
      result.append(decodedChar);
      lastStart = nextStart;
      for (int counter : theCounters) {
        nextStart += counter;
      }
      // Read off white space
      nextStart = row.getNextSet(nextStart);
    } while (decodedChar != '*');
    result.deleteCharAt(result.length() - 1); // remove asterisk

    int lastPatternSize = 0;
    for (int counter : theCounters) {
      lastPatternSize += counter;
    }

    // Should be at least one more black module
    if (nextStart == end || !row.get(nextStart)) {
      throw NotFoundException.getNotFoundInstance();
    }

    if (result.length() < 2) {
      // false positive -- need at least 2 checksum digits
      throw NotFoundException.getNotFoundInstance();
    }

    checkChecksums(result);
    // Remove checksum digits
    result.setLength(result.length() - 2);

    String resultString = decodeExtended(result);

    float left = (float) (start[1] + start[0]) / 2.0f;
    float right = lastStart + lastPatternSize / 2.0f;
    return new Result(
        resultString,
        null,
        new ResultPoint[]{
            new ResultPoint(left, (float) rowNumber),
            new ResultPoint(right, (float) rowNumber)},
        BarcodeFormat.CODE_93);

  }

  private int[] findAsteriskPattern(BitArray row) throws NotFoundException {
    int width = row.getSize();
    int rowOffset = row.getNextSet(0);

    Arrays.fill(counters, 0);
    int[] theCounters = counters;
    int patternStart = rowOffset;
    boolean isWhite = false;
    int patternLength = theCounters.length;

    int counterPosition = 0;
    for (int i = rowOffset; i < width; i++) {
      if (row.get(i) ^ isWhite) {
        theCounters[counterPosition]++;
      } else {
        if (counterPosition == patternLength - 1) {
          if (toPattern(theCounters) == ASTERISK_ENCODING) {
            return new int[]{patternStart, i};
          }
          patternStart += theCounters[0] + theCounters[1];
          System.arraycopy(theCounters, 2, theCounters, 0, patternLength - 2);
          theCounters[patternLength - 2] = 0;
          theCounters[patternLength - 1] = 0;
          counterPosition--;
        } else {
          counterPosition++;
        }
        theCounters[counterPosition] = 1;
        isWhite = !isWhite;
      }
    }
    throw NotFoundException.getNotFoundInstance();
  }

  private static int toPattern(int[] counters) {
    int max = counters.length;
    int sum = 0;
    for (int counter : counters) {
      sum += counter;
    }
    int pattern = 0;
    for (int i = 0; i < max; i++) {
      int scaled = Math.round(counters[i] * 9.0f / sum);
      if (scaled < 1 || scaled > 4) {
        return -1;
      }
      if ((i & 0x01) == 0) {
        for (int j = 0; j < scaled; j++) {
          pattern = (pattern << 1) | 0x01;
        }
      } else {
        pattern <<= scaled;
      }
    }
    return pattern;
  }

  private static char patternToChar(int pattern) throws NotFoundException {
    for (int i = 0; i < CHARACTER_ENCODINGS.length; i++) {
      if (CHARACTER_ENCODINGS[i] == pattern) {
        return ALPHABET[i];
      }
    }
    throw NotFoundException.getNotFoundInstance();
  }

  private static String decodeExtended(CharSequence encoded) throws FormatException {
    int length = encoded.length();
    StringBuilder decoded = new StringBuilder(length);
    for (int i = 0; i < length; i++) {
      char c = encoded.charAt(i);
      if (c >= 'a' && c <= 'd') {
        if (i >= length - 1) {
          throw FormatException.getFormatInstance();
        }
        char next = encoded.charAt(i + 1);
        char decodedChar = '\0';
        switch (c) {
          case 'd':
            // +A to +Z map to a to z
            if (next >= 'A' && next <= 'Z') {
              decodedChar = (char) (next + 32);
            } else {
              throw FormatException.getFormatInstance();
            }
            break;
          case 'a':
            // $A to $Z map to control codes SH to SB
            if (next >= 'A' && next <= 'Z') {
              decodedChar = (char) (next - 64);
            } else {
              throw FormatException.getFormatInstance();
            }
            break;
          case 'b':
            // %A to %E map to control codes ESC to US
            if (next >= 'A' && next <= 'E') {
              decodedChar = (char) (next - 38);
            } else if (next >= 'F' && next <= 'W') {
              decodedChar = (char) (next - 11);
            } else {
              throw FormatException.getFormatInstance();
            }
            break;
          case 'c':
            // /A to /O map to ! to , and /Z maps to :
            if (next >= 'A' && next <= 'O') {
              decodedChar = (char) (next - 32);
            } else if (next == 'Z') {
              decodedChar = ':';
            } else {
              throw FormatException.getFormatInstance();
            }
            break;
        }
        decoded.append(decodedChar);
        // bump up i again since we read two characters
        i++;
      } else {
        decoded.append(c);
      }
    }
    return decoded.toString();
  }

  private static void checkChecksums(CharSequence result) throws ChecksumException {
    int length = result.length();
    checkOneChecksum(result, length - 2, 20);
    checkOneChecksum(result, length - 1, 15);
  }

  private static void checkOneChecksum(CharSequence result, int checkPosition, int weightMax)
      throws ChecksumException {
    int weight = 1;
    int total = 0;
    for (int i = checkPosition - 1; i >= 0; i--) {
      total += weight * ALPHABET_STRING.indexOf(result.charAt(i));
      if (++weight > weightMax) {
        weight = 1;
      }
    }
    if (result.charAt(checkPosition) != ALPHABET[total % 47]) {
      throw ChecksumException.getChecksumInstance();
    }
  }

}


text:
namespace chromecast {
namespace bluetooth {

class GattClientManagerImpl;
class RemoteDescriptor;
class RemoteDescriptorImpl;
class RemoteDeviceImpl;

// A proxy for a remote characteristic on a RemoteDevice. Unless otherwise
// specified, all callbacks are run on the caller's thread.
class RemoteCharacteristicImpl : public RemoteCharacteristic {
 public:
  RemoteCharacteristicImpl(const RemoteCharacteristicImpl&) = delete;
  RemoteCharacteristicImpl& operator=(const RemoteCharacteristicImpl&) = delete;

  // RemoteCharacteristic impl:
  std::vector<scoped_refptr<RemoteDescriptor>> GetDescriptors() override;
  scoped_refptr<RemoteDescriptor> GetDescriptorByUuid(
      const bluetooth_v2_shlib::Uuid& uuid) override;
  void SetRegisterNotification(bool enable, StatusCallback cb) override;
  void SetNotification(bool enable, StatusCallback cb) override;
  void SetRegisterNotificationOrIndication(bool enable,
                                           StatusCallback cb) override;
  void ReadAuth(bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req,
                ReadCallback callback) override;
  void Read(ReadCallback callback) override;
  void WriteAuth(bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req,
                 bluetooth_v2_shlib::Gatt::WriteType write_type,
                 const std::vector<uint8_t>& value,
                 StatusCallback callback) override;
  void Write(const std::vector<uint8_t>& value,
             StatusCallback callback) override;
  bool NotificationEnabled() override;
  const bluetooth_v2_shlib::Uuid& uuid() const override;
  HandleId handle() const override;
  bluetooth_v2_shlib::Gatt::Permissions permissions() const override;
  bluetooth_v2_shlib::Gatt::Properties properties() const override;

  const bluetooth_v2_shlib::Gatt::Characteristic& characteristic() const;

  // Mark the object as out of scope.
  void Invalidate();

 private:
  friend class GattClientManagerImpl;
  friend class RemoteDeviceImpl;
  friend class RemoteServiceImpl;

  RemoteCharacteristicImpl(
      RemoteDeviceImpl* device,
      base::WeakPtr<GattClientManagerImpl> gatt_client_manager,
      const bluetooth_v2_shlib::Gatt::Characteristic* characteristic,
      scoped_refptr<base::SingleThreadTaskRunner> io_task_runner);
  ~RemoteCharacteristicImpl() override;

  std::map<bluetooth_v2_shlib::Uuid, scoped_refptr<RemoteDescriptorImpl>>
  CreateDescriptorMap();

  // If |indication| is true, register or deregister indication.
  // If |indication| is false, register or deregister notification.
  void SetRegisterNotificationOrIndicationInternal(bool indication,
                                                   bool enable,
                                                   StatusCallback cb);

  // Weak reference to avoid refcount loop.
  RemoteDeviceImpl* const device_;
  base::WeakPtr<GattClientManagerImpl> gatt_client_manager_;
  const bluetooth_v2_shlib::Gatt::Characteristic* const characteristic_;

  // All bluetooth_v2_shlib calls are run on this task_runner. All members must
  // be accessed on this task_runner.
  const scoped_refptr<base::SingleThreadTaskRunner> io_task_runner_;

  // Work around http://crbug/831878. This allows notifications on
  // characteristics which do not have a CCCD.
  const std::unique_ptr<bluetooth_v2_shlib::Gatt::Descriptor> fake_cccd_;

  const std::map<bluetooth_v2_shlib::Uuid, scoped_refptr<RemoteDescriptorImpl>>
      uuid_to_descriptor_;

  std::atomic<bool> notification_enabled_{false};
};

}  // namespace bluetooth
}  // namespace chromecast

#endif  // CHROMECAST_DEVICE_BLUETOOTH_LE_REMOTE_CHARACTERISTIC_IMPL_H_


text:
var Chess = (function(Chess) {
    'use strict';

    Chess.Piece = Chess.Piece || {};
    Chess.Piece.Type = Chess.Piece.Type || {};

    Chess.Piece.Type.Queen = (function() {

        function Queen(color, displacementsNumber) {
            this.__super__.constructor.call(this, color, displacementsNumber);
        }

        Queen.prototype.getName = function() {
            return 'Q';
        };

        Queen.prototype.getDisplacementsSuite = function() {
            return [
                new Chess.Movement.Displacement(0, 1, true),
                new Chess.Movement.Displacement(1, 1, true),
                new Chess.Movement.Displacement(1, 0, true),
                new Chess.Movement.Displacement(1, -1, true),
                new Chess.Movement.Displacement(0, -1, true),
                new Chess.Movement.Displacement(-1, -1, true),
                new Chess.Movement.Displacement(-1, 0, true),
                new Chess.Movement.Displacement(-1, 1, true)
            ];
        };

        return Queen;

    })();

    return Chess;

})(Chess || {});


text:
cd docs
rm -rf _book
gitbook build
cd _book
git init
git add -A
git commit -m 'update book'
git push -f git@github.com:Toilal/vue-webpack-template.git master:gh-pages