text:
#include "fm10k_tlv.h"

/**
 *  fm10k_tlv_msg_init - Initialize message block for TLV data storage
 *  @msg: Pointer to message block
 *  @msg_id: Message ID indicating message type
 *
 *  This function return success if provided with a valid message pointer
 **/
s32 fm10k_tlv_msg_init(u32 *msg, u16 msg_id)
{
	/* verify pointer is not NULL */
	if (!msg)
		return FM10K_ERR_PARAM;

	*msg = (FM10K_TLV_FLAGS_MSG << FM10K_TLV_FLAGS_SHIFT) | msg_id;

	return 0;
}

/**
 *  fm10k_tlv_attr_put_null_string - Place null terminated string on message
 *  @msg: Pointer to message block
 *  @attr_id: Attribute ID
 *  @string: Pointer to string to be stored in attribute
 *
 *  This function will reorder a string to be CPU endian and store it in
 *  the attribute buffer.  It will return success if provided with a valid
 *  pointers.
 **/
s32 fm10k_tlv_attr_put_null_string(u32 *msg, u16 attr_id,
				   const unsigned char *string)
{
	u32 attr_data = 0, len = 0;
	u32 *attr;

	/* verify pointers are not NULL */
	if (!string || !msg)
		return FM10K_ERR_PARAM;

	attr = &msg[FM10K_TLV_DWORD_LEN(*msg)];

	/* copy string into local variable and then write to msg */
	do {
		/* write data to message */
		if (len && !(len % 4)) {
			attr[len / 4] = attr_data;
			attr_data = 0;
		}

		/* record character to offset location */
		attr_data |= (u32)(*string) << (8 * (len % 4));
		len++;

		/* test for NULL and then increment */
	} while (*(string++));

	/* write last piece of data to message */
	attr[(len + 3) / 4] = attr_data;

	/* record attribute header, update message length */
	len <<= FM10K_TLV_LEN_SHIFT;
	attr[0] = len | attr_id;

	/* add header length to length */
	len += FM10K_TLV_HDR_LEN << FM10K_TLV_LEN_SHIFT;
	*msg += FM10K_TLV_LEN_ALIGN(len);

	return 0;
}

/**
 *  fm10k_tlv_attr_get_null_string - Get null terminated string from attribute
 *  @attr: Pointer to attribute
 *  @string: Pointer to location of destination string
 *
 *  This function pulls the string back out of the attribute and will place
 *  it in the array pointed by by string.  It will return success if provided
 *  with a valid pointers.
 **/
s32 fm10k_tlv_attr_get_null_string(u32 *attr, unsigned char *string)
{
	u32 len;

	/* verify pointers are not NULL */
	if (!string || !attr)
		return FM10K_ERR_PARAM;

	len = *attr >> FM10K_TLV_LEN_SHIFT;
	attr++;

	while (len--)
		string[len] = (u8)(attr[len / 4] >> (8 * (len % 4)));

	return 0;
}

/**
 *  fm10k_tlv_attr_put_mac_vlan - Store MAC/VLAN attribute in message
 *  @msg: Pointer to message block
 *  @attr_id: Attribute ID
 *  @mac_addr: MAC address to be stored
 *
 *  This function will reorder a MAC address to be CPU endian and store it
 *  in the attribute buffer.  It will return success if provided with a
 *  valid pointers.
 **/
s32 fm10k_tlv_attr_put_mac_vlan(u32 *msg, u16 attr_id,
				const u8 *mac_addr, u16 vlan)
{
	u32 len = ETH_ALEN << FM10K_TLV_LEN_SHIFT;
	u32 *attr;

	/* verify pointers are not NULL */
	if (!msg || !mac_addr)
		return FM10K_ERR_PARAM;

	attr = &msg[FM10K_TLV_DWORD_LEN(*msg)];

	/* record attribute header, update message length */
	attr[0] = len | attr_id;

	/* copy value into local variable and then write to msg */
	attr[1] = le32_to_cpu(*(const __le32 *)&mac_addr[0]);
	attr[2] = le16_to_cpu(*(const __le16 *)&mac_addr[4]);
	attr[2] |= (u32)vlan << 16;

	/* add header length to length */
	len += FM10K_TLV_HDR_LEN << FM10K_TLV_LEN_SHIFT;
	*msg += FM10K_TLV_LEN_ALIGN(len);

	return 0;
}

/**
 *  fm10k_tlv_attr_get_mac_vlan - Get MAC/VLAN stored in attribute
 *  @attr: Pointer to attribute
 *  @attr_id: Attribute ID
 *  @mac_addr: location of buffer to store MAC address
 *
 *  This function pulls the MAC address back out of the attribute and will
 *  place it in the array pointed by by mac_addr.  It will return success
 *  if provided with a valid pointers.
 **/
s32 fm10k_tlv_attr_get_mac_vlan(u32 *attr, u8 *mac_addr, u16 *vlan)
{
	/* verify pointers are not NULL */
	if (!mac_addr || !attr)
		return FM10K_ERR_PARAM;

	*(__le32 *)&mac_addr[0] = cpu_to_le32(attr[1]);
	*(__le16 *)&mac_addr[4] = cpu_to_le16((u16)(attr[2]));
	*vlan = (u16)(attr[2] >> 16);

	return 0;
}

/**
 *  fm10k_tlv_attr_put_bool - Add header indicating value "true"
 *  @msg: Pointer to message block
 *  @attr_id: Attribute ID
 *
 *  This function will simply add an attribute header, the fact
 *  that the header is here means the attribute value is true, else
 *  it is false.  The function will return success if provided with a
 *  valid pointers.
 **/
s32 fm10k_tlv_attr_put_bool(u32 *msg, u16 attr_id)
{
	/* verify pointers are not NULL */
	if (!msg)
		return FM10K_ERR_PARAM;

	/* record attribute header */
	msg[FM10K_TLV_DWORD_LEN(*msg)] = attr_id;

	/* add header length to length */
	*msg += FM10K_TLV_HDR_LEN << FM10K_TLV_LEN_SHIFT;

	return 0;
}

/**
 *  fm10k_tlv_attr_put_value - Store integer value attribute in message
 *  @msg: Pointer to message block
 *  @attr_id: Attribute ID
 *  @value: Value to be written
 *  @len: Size of value
 *
 *  This function will place an integer value of up to 8 bytes in size
 *  in a message attribute.  The function will return success provided
 *  that msg is a valid pointer, and len is 1, 2, 4, or 8.
 **/
s32 fm10k_tlv_attr_put_value(u32 *msg, u16 attr_id, s64 value, u32 len)
{
	u32 *attr;

	/* verify non-null msg and len is 1, 2, 4, or 8 */
	if (!msg || !len || len > 8 || (len & (len - 1)))
		return FM10K_ERR_PARAM;

	attr = &msg[FM10K_TLV_DWORD_LEN(*msg)];

	if (len < 4) {
		attr[1] = (u32)value & ((0x1ul << (8 * len)) - 1);
	} else {
		attr[1] = (u32)value;
		if (len > 4)
			attr[2] = (u32)(value >> 32);
	}

	/* record attribute header, update message length */
	len <<= FM10K_TLV_LEN_SHIFT;
	attr[0] = len | attr_id;

	/* add header length to length */
	len += FM10K_TLV_HDR_LEN << FM10K_TLV_LEN_SHIFT;
	*msg += FM10K_TLV_LEN_ALIGN(len);

	return 0;
}

/**
 *  fm10k_tlv_attr_get_value - Get integer value stored in attribute
 *  @attr: Pointer to attribute
 *  @value: Pointer to destination buffer
 *  @len: Size of value
 *
 *  This function will place an integer value of up to 8 bytes in size
 *  in the offset pointed to by value.  The function will return success
 *  provided that pointers are valid and the len value matches the
 *  attribute length.
 **/
s32 fm10k_tlv_attr_get_value(u32 *attr, void *value, u32 len)
{
	/* verify pointers are not NULL */
	if (!attr || !value)
		return FM10K_ERR_PARAM;

	if ((*attr >> FM10K_TLV_LEN_SHIFT) != len)
		return FM10K_ERR_PARAM;

	if (len == 8)
		*(u64 *)value = ((u64)attr[2] << 32) | attr[1];
	else if (len == 4)
		*(u32 *)value = attr[1];
	else if (len == 2)
		*(u16 *)value = (u16)attr[1];
	else
		*(u8 *)value = (u8)attr[1];

	return 0;
}

/**
 *  fm10k_tlv_attr_put_le_struct - Store little endian structure in message
 *  @msg: Pointer to message block
 *  @attr_id: Attribute ID
 *  @le_struct: Pointer to structure to be written
 *  @len: Size of le_struct
 *
 *  This function will place a little endian structure value in a message
 *  attribute.  The function will return success provided that all pointers
 *  are valid and length is a non-zero multiple of 4.
 **/
s32 fm10k_tlv_attr_put_le_struct(u32 *msg, u16 attr_id,
				 const void *le_struct, u32 len)
{
	const __le32 *le32_ptr = (const __le32 *)le_struct;
	u32 *attr;
	u32 i;

	/* verify non-null msg and len is in 32 bit words */
	if (!msg || !len || (len % 4))
		return FM10K_ERR_PARAM;

	attr = &msg[FM10K_TLV_DWORD_LEN(*msg)];

	/* copy le32 structure into host byte order at 32b boundaries */
	for (i = 0; i < (len / 4); i++)
		attr[i + 1] = le32_to_cpu(le32_ptr[i]);

	/* record attribute header, update message length */
	len <<= FM10K_TLV_LEN_SHIFT;
	attr[0] = len | attr_id;

	/* add header length to length */
	len += FM10K_TLV_HDR_LEN << FM10K_TLV_LEN_SHIFT;
	*msg += FM10K_TLV_LEN_ALIGN(len);

	return 0;
}

/**
 *  fm10k_tlv_attr_get_le_struct - Get little endian struct form attribute
 *  @attr: Pointer to attribute
 *  @le_struct: Pointer to structure to be written
 *  @len: Size of structure
 *
 *  This function will place a little endian structure in the buffer
 *  pointed to by le_struct.  The function will return success
 *  provided that pointers are valid and the len value matches the
 *  attribute length.
 **/
s32 fm10k_tlv_attr_get_le_struct(u32 *attr, void *le_struct, u32 len)
{
	__le32 *le32_ptr = (__le32 *)le_struct;
	u32 i;

	/* verify pointers are not NULL */
	if (!le_struct || !attr)
		return FM10K_ERR_PARAM;

	if ((*attr >> FM10K_TLV_LEN_SHIFT) != len)
		return FM10K_ERR_PARAM;

	attr++;

	for (i = 0; len; i++, len -= 4)
		le32_ptr[i] = cpu_to_le32(attr[i]);

	return 0;
}

/**
 *  fm10k_tlv_attr_nest_start - Start a set of nested attributes
 *  @msg: Pointer to message block
 *  @attr_id: Attribute ID
 *
 *  This function will mark off a new nested region for encapsulating
 *  a given set of attributes.  The idea is if you wish to place a secondary
 *  structure within the message this mechanism allows for that.  The
 *  function will return NULL on failure, and a pointer to the start
 *  of the nested attributes on success.
 **/
u32 *fm10k_tlv_attr_nest_start(u32 *msg, u16 attr_id)
{
	u32 *attr;

	/* verify pointer is not NULL */
	if (!msg)
		return NULL;

	attr = &msg[FM10K_TLV_DWORD_LEN(*msg)];

	attr[0] = attr_id;

	/* return pointer to nest header */
	return attr;
}

/**
 *  fm10k_tlv_attr_nest_start - Start a set of nested attributes
 *  @msg: Pointer to message block
 *
 *  This function closes off an existing set of nested attributes.  The
 *  message pointer should be pointing to the parent of the nest.  So in
 *  the case of a nest within the nest this would be the outer nest pointer.
 *  This function will return success provided all pointers are valid.
 **/
s32 fm10k_tlv_attr_nest_stop(u32 *msg)
{
	u32 *attr;
	u32 len;

	/* verify pointer is not NULL */
	if (!msg)
		return FM10K_ERR_PARAM;

	/* locate the nested header and retrieve its length */
	attr = &msg[FM10K_TLV_DWORD_LEN(*msg)];
	len = (attr[0] >> FM10K_TLV_LEN_SHIFT) << FM10K_TLV_LEN_SHIFT;

	/* only include nest if data was added to it */
	if (len) {
		len += FM10K_TLV_HDR_LEN << FM10K_TLV_LEN_SHIFT;
		*msg += len;
	}

	return 0;
}

/**
 *  fm10k_tlv_attr_validate - Validate attribute metadata
 *  @attr: Pointer to attribute
 *  @tlv_attr: Type and length info for attribute
 *
 *  This function does some basic validation of the input TLV.  It
 *  verifies the length, and in the case of null terminated strings
 *  it verifies that the last byte is null.  The function will
 *  return FM10K_ERR_PARAM if any attribute is malformed, otherwise
 *  it returns 0.
 **/
static s32 fm10k_tlv_attr_validate(u32 *attr,
				   const struct fm10k_tlv_attr *tlv_attr)
{
	u32 attr_id = *attr & FM10K_TLV_ID_MASK;
	u16 len = *attr >> FM10K_TLV_LEN_SHIFT;

	/* verify this is an attribute and not a message */
	if (*attr & (FM10K_TLV_FLAGS_MSG << FM10K_TLV_FLAGS_SHIFT))
		return FM10K_ERR_PARAM;

	/* search through the list of attributes to find a matching ID */
	while (tlv_attr->id < attr_id)
		tlv_attr++;

	/* if didn't find a match then we should exit */
	if (tlv_attr->id != attr_id)
		return FM10K_NOT_IMPLEMENTED;

	/* move to start of attribute data */
	attr++;

	switch (tlv_attr->type) {
	case FM10K_TLV_NULL_STRING:
		if (!len ||
		    (attr[(len - 1) / 4] & (0xFF << (8 * ((len - 1) % 4)))))
			return FM10K_ERR_PARAM;
		if (len > tlv_attr->len)
			return FM10K_ERR_PARAM;
		break;
	case FM10K_TLV_MAC_ADDR:
		if (len != ETH_ALEN)
			return FM10K_ERR_PARAM;
		break;
	case FM10K_TLV_BOOL:
		if (len)
			return FM10K_ERR_PARAM;
		break;
	case FM10K_TLV_UNSIGNED:
	case FM10K_TLV_SIGNED:
		if (len != tlv_attr->len)
			return FM10K_ERR_PARAM;
		break;
	case FM10K_TLV_LE_STRUCT:
		/* struct must be 4 byte aligned */
		if ((len % 4) || len != tlv_attr->len)
			return FM10K_ERR_PARAM;
		break;
	case FM10K_TLV_NESTED:
		/* nested attributes must be 4 byte aligned */
		if (len % 4)
			return FM10K_ERR_PARAM;
		break;
	default:
		/* attribute id is mapped to bad value */
		return FM10K_ERR_PARAM;
	}

	return 0;
}

/**
 *  fm10k_tlv_attr_parse - Parses stream of attribute data
 *  @attr: Pointer to attribute list
 *  @results: Pointer array to store pointers to attributes
 *  @tlv_attr: Type and length info for attributes
 *
 *  This function validates a stream of attributes and parses them
 *  up into an array of pointers stored in results.  The function will
 *  return FM10K_ERR_PARAM on any input or message error,
 *  FM10K_NOT_IMPLEMENTED for any attribute that is outside of the array
 *  and 0 on success.
 **/
s32 fm10k_tlv_attr_parse(u32 *attr, u32 **results,
			 const struct fm10k_tlv_attr *tlv_attr)
{
	u32 i, attr_id, offset = 0;
	s32 err = 0;
	u16 len;

	/* verify pointers are not NULL */
	if (!attr || !results)
		return FM10K_ERR_PARAM;

	/* initialize results to NULL */
	for (i = 0; i < FM10K_TLV_RESULTS_MAX; i++)
		results[i] = NULL;

	/* pull length from the message header */
	len = *attr >> FM10K_TLV_LEN_SHIFT;

	/* no attributes to parse if there is no length */
	if (!len)
		return 0;

	/* no attributes to parse, just raw data, message becomes attribute */
	if (!tlv_attr) {
		results[0] = attr;
		return 0;
	}

	/* move to start of attribute data */
	attr++;

	/* run through list parsing all attributes */
	while (offset < len) {
		attr_id = *attr & FM10K_TLV_ID_MASK;

		if (attr_id < FM10K_TLV_RESULTS_MAX)
			err = fm10k_tlv_attr_validate(attr, tlv_attr);
		else
			err = FM10K_NOT_IMPLEMENTED;

		if (err < 0)
			return err;
		if (!err)
			results[attr_id] = attr;

		/* update offset */
		offset += FM10K_TLV_DWORD_LEN(*attr) * 4;

		/* move to next attribute */
		attr = &attr[FM10K_TLV_DWORD_LEN(*attr)];
	}

	/* we should find ourselves at the end of the list */
	if (offset != len)
		return FM10K_ERR_PARAM;

	return 0;
}

/**
 *  fm10k_tlv_msg_parse - Parses message header and calls function handler
 *  @hw: Pointer to hardware structure
 *  @msg: Pointer to message
 *  @mbx: Pointer to mailbox information structure
 *  @func: Function array containing list of message handling functions
 *
 *  This function should be the first function called upon receiving a
 *  message.  The handler will identify the message type and call the correct
 *  handler for the given message.  It will return the value from the function
 *  call on a recognized message type, otherwise it will return
 *  FM10K_NOT_IMPLEMENTED on an unrecognized type.
 **/
s32 fm10k_tlv_msg_parse(struct fm10k_hw *hw, u32 *msg,
			struct fm10k_mbx_info *mbx,
			const struct fm10k_msg_data *data)
{
	u32 *results[FM10K_TLV_RESULTS_MAX];
	u32 msg_id;
	s32 err;

	/* verify pointer is not NULL */
	if (!msg || !data)
		return FM10K_ERR_PARAM;

	/* verify this is a message and not an attribute */
	if (!(*msg & (FM10K_TLV_FLAGS_MSG << FM10K_TLV_FLAGS_SHIFT)))
		return FM10K_ERR_PARAM;

	/* grab message ID */
	msg_id = *msg & FM10K_TLV_ID_MASK;

	while (data->id < msg_id)
		data++;

	/* if we didn't find it then pass it up as an error */
	if (data->id != msg_id) {
		while (data->id != FM10K_TLV_ERROR)
			data++;
	}

	/* parse the attributes into the results list */
	err = fm10k_tlv_attr_parse(msg, results, data->attr);
	if (err < 0)
		return err;

	return data->func(hw, results, mbx);
}

/**
 *  fm10k_tlv_msg_error - Default handler for unrecognized TLV message IDs
 *  @hw: Pointer to hardware structure
 *  @results: Pointer array to message, results[0] is pointer to message
 *  @mbx: Unused mailbox pointer
 *
 *  This function is a default handler for unrecognized messages.  At a
 *  a minimum it just indicates that the message requested was
 *  unimplemented.
 **/
s32 fm10k_tlv_msg_error(struct fm10k_hw *hw, u32 **results,
			struct fm10k_mbx_info *mbx)
{
	return FM10K_NOT_IMPLEMENTED;
}

static const unsigned char test_str[] =	"fm10k";
static const unsigned char test_mac[ETH_ALEN] = { 0x12, 0x34, 0x56,
						  0x78, 0x9a, 0xbc };
static const u16 test_vlan = 0x0FED;
static const u64 test_u64 = 0xfedcba9876543210ull;
static const u32 test_u32 = 0x87654321;
static const u16 test_u16 = 0x8765;
static const u8  test_u8  = 0x87;
static const s64 test_s64 = -0x123456789abcdef0ll;
static const s32 test_s32 = -0x1235678;
static const s16 test_s16 = -0x1234;
static const s8  test_s8  = -0x12;
static const __le32 test_le[2] = { cpu_to_le32(0x12345678),
				   cpu_to_le32(0x9abcdef0)};

/* The message below is meant to be used as a test message to demonstrate
 * how to use the TLV interface and to test the types.  Normally this code
 * be compiled out by stripping the code wrapped in FM10K_TLV_TEST_MSG
 */
const struct fm10k_tlv_attr fm10k_tlv_msg_test_attr[] = {
	FM10K_TLV_ATTR_NULL_STRING(FM10K_TEST_MSG_STRING, 80),
	FM10K_TLV_ATTR_MAC_ADDR(FM10K_TEST_MSG_MAC_ADDR),
	FM10K_TLV_ATTR_U8(FM10K_TEST_MSG_U8),
	FM10K_TLV_ATTR_U16(FM10K_TEST_MSG_U16),
	FM10K_TLV_ATTR_U32(FM10K_TEST_MSG_U32),
	FM10K_TLV_ATTR_U64(FM10K_TEST_MSG_U64),
	FM10K_TLV_ATTR_S8(FM10K_TEST_MSG_S8),
	FM10K_TLV_ATTR_S16(FM10K_TEST_MSG_S16),
	FM10K_TLV_ATTR_S32(FM10K_TEST_MSG_S32),
	FM10K_TLV_ATTR_S64(FM10K_TEST_MSG_S64),
	FM10K_TLV_ATTR_LE_STRUCT(FM10K_TEST_MSG_LE_STRUCT, 8),
	FM10K_TLV_ATTR_NESTED(FM10K_TEST_MSG_NESTED),
	FM10K_TLV_ATTR_S32(FM10K_TEST_MSG_RESULT),
	FM10K_TLV_ATTR_LAST
};

/**
 *  fm10k_tlv_msg_test_generate_data - Stuff message with data
 *  @msg: Pointer to message
 *  @attr_flags: List of flags indicating what attributes to add
 *
 *  This function is meant to load a message buffer with attribute data
 **/
static void fm10k_tlv_msg_test_generate_data(u32 *msg, u32 attr_flags)
{
	if (attr_flags & (1 << FM10K_TEST_MSG_STRING))
		fm10k_tlv_attr_put_null_string(msg, FM10K_TEST_MSG_STRING,
					       test_str);
	if (attr_flags & (1 << FM10K_TEST_MSG_MAC_ADDR))
		fm10k_tlv_attr_put_mac_vlan(msg, FM10K_TEST_MSG_MAC_ADDR,
					    test_mac, test_vlan);
	if (attr_flags & (1 << FM10K_TEST_MSG_U8))
		fm10k_tlv_attr_put_u8(msg, FM10K_TEST_MSG_U8,  test_u8);
	if (attr_flags & (1 << FM10K_TEST_MSG_U16))
		fm10k_tlv_attr_put_u16(msg, FM10K_TEST_MSG_U16, test_u16);
	if (attr_flags & (1 << FM10K_TEST_MSG_U32))
		fm10k_tlv_attr_put_u32(msg, FM10K_TEST_MSG_U32, test_u32);
	if (attr_flags & (1 << FM10K_TEST_MSG_U64))
		fm10k_tlv_attr_put_u64(msg, FM10K_TEST_MSG_U64, test_u64);
	if (attr_flags & (1 << FM10K_TEST_MSG_S8))
		fm10k_tlv_attr_put_s8(msg, FM10K_TEST_MSG_S8,  test_s8);
	if (attr_flags & (1 << FM10K_TEST_MSG_S16))
		fm10k_tlv_attr_put_s16(msg, FM10K_TEST_MSG_S16, test_s16);
	if (attr_flags & (1 << FM10K_TEST_MSG_S32))
		fm10k_tlv_attr_put_s32(msg, FM10K_TEST_MSG_S32, test_s32);
	if (attr_flags & (1 << FM10K_TEST_MSG_S64))
		fm10k_tlv_attr_put_s64(msg, FM10K_TEST_MSG_S64, test_s64);
	if (attr_flags & (1 << FM10K_TEST_MSG_LE_STRUCT))
		fm10k_tlv_attr_put_le_struct(msg, FM10K_TEST_MSG_LE_STRUCT,
					     test_le, 8);
}

/**
 *  fm10k_tlv_msg_test_create - Create a test message testing all attributes
 *  @msg: Pointer to message
 *  @attr_flags: List of flags indicating what attributes to add
 *
 *  This function is meant to load a message buffer with all attribute types
 *  including a nested attribute.
 **/
void fm10k_tlv_msg_test_create(u32 *msg, u32 attr_flags)
{
	u32 *nest = NULL;

	fm10k_tlv_msg_init(msg, FM10K_TLV_MSG_ID_TEST);

	fm10k_tlv_msg_test_generate_data(msg, attr_flags);

	/* check for nested attributes */
	attr_flags >>= FM10K_TEST_MSG_NESTED;

	if (attr_flags) {
		nest = fm10k_tlv_attr_nest_start(msg, FM10K_TEST_MSG_NESTED);

		fm10k_tlv_msg_test_generate_data(nest, attr_flags);

		fm10k_tlv_attr_nest_stop(msg);
	}
}

/**
 *  fm10k_tlv_msg_test - Validate all results on test message receive
 *  @hw: Pointer to hardware structure
 *  @results: Pointer array to attributes in the message
 *  @mbx: Pointer to mailbox information structure
 *
 *  This function does a check to verify all attributes match what the test
 *  message placed in the message buffer.  It is the default handler
 *  for TLV test messages.
 **/
s32 fm10k_tlv_msg_test(struct fm10k_hw *hw, u32 **results,
		       struct fm10k_mbx_info *mbx)
{
	u32 *nest_results[FM10K_TLV_RESULTS_MAX];
	unsigned char result_str[80];
	unsigned char result_mac[ETH_ALEN];
	s32 err = 0;
	__le32 result_le[2];
	u16 result_vlan;
	u64 result_u64;
	u32 result_u32;
	u16 result_u16;
	u8  result_u8;
	s64 result_s64;
	s32 result_s32;
	s16 result_s16;
	s8  result_s8;
	u32 reply[3];

	/* retrieve results of a previous test */
	if (!!results[FM10K_TEST_MSG_RESULT])
		return fm10k_tlv_attr_get_s32(results[FM10K_TEST_MSG_RESULT],
					      &mbx->test_result);

parse_nested:
	if (!!results[FM10K_TEST_MSG_STRING]) {
		err = fm10k_tlv_attr_get_null_string(
					results[FM10K_TEST_MSG_STRING],
					result_str);
		if (!err && memcmp(test_str, result_str, sizeof(test_str)))
			err = FM10K_ERR_INVALID_VALUE;
		if (err)
			goto report_result;
	}
	if (!!results[FM10K_TEST_MSG_MAC_ADDR]) {
		err = fm10k_tlv_attr_get_mac_vlan(
					results[FM10K_TEST_MSG_MAC_ADDR],
					result_mac, &result_vlan);
		if (!err && memcmp(test_mac, result_mac, ETH_ALEN))
			err = FM10K_ERR_INVALID_VALUE;
		if (!err && test_vlan != result_vlan)
			err = FM10K_ERR_INVALID_VALUE;
		if (err)
			goto report_result;
	}
	if (!!results[FM10K_TEST_MSG_U8]) {
		err = fm10k_tlv_attr_get_u8(results[FM10K_TEST_MSG_U8],
					    &result_u8);
		if (!err && test_u8 != result_u8)
			err = FM10K_ERR_INVALID_VALUE;
		if (err)
			goto report_result;
	}
	if (!!results[FM10K_TEST_MSG_U16]) {
		err = fm10k_tlv_attr_get_u16(results[FM10K_TEST_MSG_U16],
					     &result_u16);
		if (!err && test_u16 != result_u16)
			err = FM10K_ERR_INVALID_VALUE;
		if (err)
			goto report_result;
	}
	if (!!results[FM10K_TEST_MSG_U32]) {
		err = fm10k_tlv_attr_get_u32(results[FM10K_TEST_MSG_U32],
					     &result_u32);
		if (!err && test_u32 != result_u32)
			err = FM10K_ERR_INVALID_VALUE;
		if (err)
			goto report_result;
	}
	if (!!results[FM10K_TEST_MSG_U64]) {
		err = fm10k_tlv_attr_get_u64(results[FM10K_TEST_MSG_U64],
					     &result_u64);
		if (!err && test_u64 != result_u64)
			err = FM10K_ERR_INVALID_VALUE;
		if (err)
			goto report_result;
	}
	if (!!results[FM10K_TEST_MSG_S8]) {
		err = fm10k_tlv_attr_get_s8(results[FM10K_TEST_MSG_S8],
					    &result_s8);
		if (!err && test_s8 != result_s8)
			err = FM10K_ERR_INVALID_VALUE;
		if (err)
			goto report_result;
	}
	if (!!results[FM10K_TEST_MSG_S16]) {
		err = fm10k_tlv_attr_get_s16(results[FM10K_TEST_MSG_S16],
					     &result_s16);
		if (!err && test_s16 != result_s16)
			err = FM10K_ERR_INVALID_VALUE;
		if (err)
			goto report_result;
	}
	if (!!results[FM10K_TEST_MSG_S32]) {
		err = fm10k_tlv_attr_get_s32(results[FM10K_TEST_MSG_S32],
					     &result_s32);
		if (!err && test_s32 != result_s32)
			err = FM10K_ERR_INVALID_VALUE;
		if (err)
			goto report_result;
	}
	if (!!results[FM10K_TEST_MSG_S64]) {
		err = fm10k_tlv_attr_get_s64(results[FM10K_TEST_MSG_S64],
					     &result_s64);
		if (!err && test_s64 != result_s64)
			err = FM10K_ERR_INVALID_VALUE;
		if (err)
			goto report_result;
	}
	if (!!results[FM10K_TEST_MSG_LE_STRUCT]) {
		err = fm10k_tlv_attr_get_le_struct(
					results[FM10K_TEST_MSG_LE_STRUCT],
					result_le,
					sizeof(result_le));
		if (!err && memcmp(test_le, result_le, sizeof(test_le)))
			err = FM10K_ERR_INVALID_VALUE;
		if (err)
			goto report_result;
	}

	if (!!results[FM10K_TEST_MSG_NESTED]) {
		/* clear any pointers */
		memset(nest_results, 0, sizeof(nest_results));

		/* parse the nested attributes into the nest results list */
		err = fm10k_tlv_attr_parse(results[FM10K_TEST_MSG_NESTED],
					   nest_results,
					   fm10k_tlv_msg_test_attr);
		if (err)
			goto report_result;

		/* loop back through to the start */
		results = nest_results;
		goto parse_nested;
	}

report_result:
	/* generate reply with test result */
	fm10k_tlv_msg_init(reply, FM10K_TLV_MSG_ID_TEST);
	fm10k_tlv_attr_put_s32(reply, FM10K_TEST_MSG_RESULT, err);

	/* load onto outgoing mailbox */
	return mbx->ops.enqueue_tx(hw, mbx, reply);
}


text:
using System;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Analytics.Synapse.Artifacts.Models;
using Azure.Core;
using Azure.Core.Pipeline;

namespace Azure.Analytics.Synapse.Artifacts
{
    internal partial class TriggerRunRestClient
    {
        private string endpoint;
        private string apiVersion;
        private ClientDiagnostics _clientDiagnostics;
        private HttpPipeline _pipeline;

        /// <summary> Initializes a new instance of TriggerRunRestClient. </summary>
        /// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param>
        /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
        /// <param name="endpoint"> The workspace development endpoint, for example https://myworkspace.dev.azuresynapse.net. </param>
        /// <param name="apiVersion"> Api Version. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="endpoint"/> or <paramref name="apiVersion"/> is null. </exception>
        public TriggerRunRestClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string endpoint, string apiVersion = "2019-06-01-preview")
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException(nameof(endpoint));
            }
            if (apiVersion == null)
            {
                throw new ArgumentNullException(nameof(apiVersion));
            }

            this.endpoint = endpoint;
            this.apiVersion = apiVersion;
            _clientDiagnostics = clientDiagnostics;
            _pipeline = pipeline;
        }

        internal HttpMessage CreateRerunTriggerInstanceRequest(string triggerName, string runId)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Post;
            var uri = new RawRequestUriBuilder();
            uri.AppendRaw(endpoint, false);
            uri.AppendPath("/triggers/", false);
            uri.AppendPath(triggerName, true);
            uri.AppendPath("/triggerRuns/", false);
            uri.AppendPath(runId, true);
            uri.AppendPath("/rerun", false);
            uri.AppendQuery("api-version", apiVersion, true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            return message;
        }

        /// <summary> Rerun single trigger instance by runId. </summary>
        /// <param name="triggerName"> The trigger name. </param>
        /// <param name="runId"> The pipeline run identifier. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="triggerName"/> or <paramref name="runId"/> is null. </exception>
        public async Task<Response> RerunTriggerInstanceAsync(string triggerName, string runId, CancellationToken cancellationToken = default)
        {
            if (triggerName == null)
            {
                throw new ArgumentNullException(nameof(triggerName));
            }
            if (runId == null)
            {
                throw new ArgumentNullException(nameof(runId));
            }

            using var message = CreateRerunTriggerInstanceRequest(triggerName, runId);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                    return message.Response;
                default:
                    throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
            }
        }

        /// <summary> Rerun single trigger instance by runId. </summary>
        /// <param name="triggerName"> The trigger name. </param>
        /// <param name="runId"> The pipeline run identifier. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="triggerName"/> or <paramref name="runId"/> is null. </exception>
        public Response RerunTriggerInstance(string triggerName, string runId, CancellationToken cancellationToken = default)
        {
            if (triggerName == null)
            {
                throw new ArgumentNullException(nameof(triggerName));
            }
            if (runId == null)
            {
                throw new ArgumentNullException(nameof(runId));
            }

            using var message = CreateRerunTriggerInstanceRequest(triggerName, runId);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                    return message.Response;
                default:
                    throw _clientDiagnostics.CreateRequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateCancelTriggerInstanceRequest(string triggerName, string runId)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Post;
            var uri = new RawRequestUriBuilder();
            uri.AppendRaw(endpoint, false);
            uri.AppendPath("/triggers/", false);
            uri.AppendPath(triggerName, true);
            uri.AppendPath("/triggerRuns/", false);
            uri.AppendPath(runId, true);
            uri.AppendPath("/cancel", false);
            uri.AppendQuery("api-version", apiVersion, true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            return message;
        }

        /// <summary> Cancel single trigger instance by runId. </summary>
        /// <param name="triggerName"> The trigger name. </param>
        /// <param name="runId"> The pipeline run identifier. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="triggerName"/> or <paramref name="runId"/> is null. </exception>
        public async Task<Response> CancelTriggerInstanceAsync(string triggerName, string runId, CancellationToken cancellationToken = default)
        {
            if (triggerName == null)
            {
                throw new ArgumentNullException(nameof(triggerName));
            }
            if (runId == null)
            {
                throw new ArgumentNullException(nameof(runId));
            }

            using var message = CreateCancelTriggerInstanceRequest(triggerName, runId);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                    return message.Response;
                default:
                    throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
            }
        }

        /// <summary> Cancel single trigger instance by runId. </summary>
        /// <param name="triggerName"> The trigger name. </param>
        /// <param name="runId"> The pipeline run identifier. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="triggerName"/> or <paramref name="runId"/> is null. </exception>
        public Response CancelTriggerInstance(string triggerName, string runId, CancellationToken cancellationToken = default)
        {
            if (triggerName == null)
            {
                throw new ArgumentNullException(nameof(triggerName));
            }
            if (runId == null)
            {
                throw new ArgumentNullException(nameof(runId));
            }

            using var message = CreateCancelTriggerInstanceRequest(triggerName, runId);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                    return message.Response;
                default:
                    throw _clientDiagnostics.CreateRequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateQueryTriggerRunsByWorkspaceRequest(RunFilterParameters filterParameters)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Post;
            var uri = new RawRequestUriBuilder();
            uri.AppendRaw(endpoint, false);
            uri.AppendPath("/queryTriggerRuns", false);
            uri.AppendQuery("api-version", apiVersion, true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            request.Headers.Add("Content-Type", "application/json");
            var content = new Utf8JsonRequestContent();
            content.JsonWriter.WriteObjectValue(filterParameters);
            request.Content = content;
            return message;
        }

        /// <summary> Query trigger runs. </summary>
        /// <param name="filterParameters"> Parameters to filter the pipeline run. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="filterParameters"/> is null. </exception>
        public async Task<Response<TriggerRunsQueryResponse>> QueryTriggerRunsByWorkspaceAsync(RunFilterParameters filterParameters, CancellationToken cancellationToken = default)
        {
            if (filterParameters == null)
            {
                throw new ArgumentNullException(nameof(filterParameters));
            }

            using var message = CreateQueryTriggerRunsByWorkspaceRequest(filterParameters);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        TriggerRunsQueryResponse value = default;
                        using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
                        value = TriggerRunsQueryResponse.DeserializeTriggerRunsQueryResponse(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
            }
        }

        /// <summary> Query trigger runs. </summary>
        /// <param name="filterParameters"> Parameters to filter the pipeline run. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="filterParameters"/> is null. </exception>
        public Response<TriggerRunsQueryResponse> QueryTriggerRunsByWorkspace(RunFilterParameters filterParameters, CancellationToken cancellationToken = default)
        {
            if (filterParameters == null)
            {
                throw new ArgumentNullException(nameof(filterParameters));
            }

            using var message = CreateQueryTriggerRunsByWorkspaceRequest(filterParameters);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        TriggerRunsQueryResponse value = default;
                        using var document = JsonDocument.Parse(message.Response.ContentStream);
                        value = TriggerRunsQueryResponse.DeserializeTriggerRunsQueryResponse(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw _clientDiagnostics.CreateRequestFailedException(message.Response);
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
cask 'catlight' do
  version '2.29.0'
  sha256 '65dfb967d3d76c92975d90967deedb4405fdce7f131ec289154d4fcf293ff94e'

  # de2nac35bcll0.cloudfront.net was verified as official when first introduced to the cask
  url "https://de2nac35bcll0.cloudfront.net/dl/mac/beta/CatLightSetup-#{version}.zip"
  appcast 'https://catlight.io/downloads'
  name 'catlight'
  homepage 'https://catlight.io/'

  depends_on macos: '>= :sierra'

  app 'Catlight.app'
end


text:
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/Assembly/Writer.h"
#include "llvm/CodeGen/ScheduleDAG.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/GraphWriter.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/StringExtras.h"
#include <fstream>
using namespace llvm;

namespace llvm {
  template<>
  struct DOTGraphTraits<ScheduleDAG*> : public DefaultDOTGraphTraits {

  DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}

    static std::string getGraphName(const ScheduleDAG *G) {
      return G->MF.getFunction()->getName();
    }

    static bool renderGraphFromBottomUp() {
      return true;
    }

    static bool hasNodeAddressLabel(const SUnit *Node,
                                    const ScheduleDAG *Graph) {
      return true;
    }

    /// If you want to override the dot attributes printed for a particular
    /// edge, override this method.
    static std::string getEdgeAttributes(const SUnit *Node,
                                         SUnitIterator EI,
                                         const ScheduleDAG *Graph) {
      if (EI.isArtificialDep())
        return "color=cyan,style=dashed";
      if (EI.isCtrlDep())
        return "color=blue,style=dashed";
      return "";
    }

    std::string getNodeLabel(const SUnit *Node, const ScheduleDAG *Graph);
    static std::string getNodeAttributes(const SUnit *N,
                                         const ScheduleDAG *Graph) {
      return "shape=Mrecord";
    }

    static void addCustomGraphFeatures(ScheduleDAG *G,
                                       GraphWriter<ScheduleDAG*> &GW) {
      return G->addCustomGraphFeatures(GW);
    }
  };
}

std::string DOTGraphTraits<ScheduleDAG*>::getNodeLabel(const SUnit *SU,
                                                       const ScheduleDAG *G) {
  return G->getGraphNodeLabel(SU);
}

/// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
/// rendered using 'dot'.
///
void ScheduleDAG::viewGraph(const Twine &Name, const Twine &Title) {
  // This code is only for debugging!
#ifndef NDEBUG
  ViewGraph(this, Name, false, Title);
#else
  errs() << "ScheduleDAG::viewGraph is only available in debug builds on "
         << "systems with Graphviz or gv!\n";
#endif  // NDEBUG
}

/// Out-of-line implementation with no arguments is handy for gdb.
void ScheduleDAG::viewGraph() {
  viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
}


text:
create or replace function perl_elog(text) returns void language plperl as $$

  my $msg = shift;
  elog(NOTICE,$msg);

$$;

select perl_elog('explicit elog');

create or replace function perl_warn(text) returns void language plperl as $$

  my $msg = shift;
  warn($msg);

$$;

select perl_warn('implicit elog via warn');

-- test strict mode on/off

SET plperl.use_strict = true;

create or replace function uses_global() returns text language plperl as $$

  $global = 1;
  $other_global = 2;
  return 'uses_global worked';

$$;

select uses_global();

SET plperl.use_strict = false;

create or replace function uses_global() returns text language plperl as $$

  $global = 1;
  $other_global=2;
  return 'uses_global worked';

$$;

select uses_global();


text:
<!DOCTYPE html>
<meta charset=utf-8>
<title>invalid src: port-single-letter</title>
<embed src="http://f:b/c">


text:
class Sprite {
	constructor(tag, img, clipX, clipY, size){
		this.tag = tag
		this.img = img
		this.clipX = clipX
		this.clipY = clipY
		this.size = size
	}
}


text:
package org.apache.ignite.internal.processors.cache;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.cache.CacheKeyConfiguration;
import org.apache.ignite.cache.QueryEntity;
import org.apache.ignite.cache.QueryIndex;
import org.apache.ignite.cache.affinity.Affinity;
import org.apache.ignite.cache.affinity.AffinityKeyMapped;
import org.apache.ignite.cache.query.QueryCursor;
import org.apache.ignite.cache.query.SqlFieldsQuery;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;

import static org.apache.ignite.cache.CacheAtomicWriteOrderMode.PRIMARY;
import static org.apache.ignite.cache.CacheAtomicityMode.ATOMIC;
import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC;

/**
 *
 */
public class IgniteCacheDistributedJoinCollocatedAndNotTest extends GridCommonAbstractTest {
    /** */
    private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true);

    /** */
    private static final String PERSON_CACHE = "person";

    /** */
    private static final String ORG_CACHE = "org";

    /** */
    private static final String ACCOUNT_CACHE = "acc";

    /** */
    private boolean client;

    /** {@inheritDoc} */
    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
        IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);

        CacheKeyConfiguration keyCfg = new CacheKeyConfiguration(PersonKey.class.getName(), "affKey");

        cfg.setCacheKeyConfiguration(keyCfg);

        TcpDiscoverySpi spi = ((TcpDiscoverySpi)cfg.getDiscoverySpi());

        spi.setIpFinder(IP_FINDER);

        List<CacheConfiguration> ccfgs = new ArrayList<>();

        {
            CacheConfiguration ccfg = configuration(PERSON_CACHE);

            QueryEntity entity = new QueryEntity();
            entity.setKeyType(PersonKey.class.getName());
            entity.setValueType(Person.class.getName());
            entity.addQueryField("id", Integer.class.getName(), null);
            entity.addQueryField("affKey", Integer.class.getName(), null);
            entity.addQueryField("name", String.class.getName(), null);

            ccfg.setQueryEntities(F.asList(entity));

            ccfgs.add(ccfg);
        }

        {
            CacheConfiguration ccfg = configuration(ORG_CACHE);

            QueryEntity entity = new QueryEntity();
            entity.setKeyType(Integer.class.getName());
            entity.setValueType(Organization.class.getName());
            entity.addQueryField("name", String.class.getName(), null);
            entity.setIndexes(F.asList(new QueryIndex("name")));

            ccfg.setQueryEntities(F.asList(entity));

            ccfgs.add(ccfg);
        }

        {
            CacheConfiguration ccfg = configuration(ACCOUNT_CACHE);

            QueryEntity entity = new QueryEntity();
            entity.setKeyType(Integer.class.getName());
            entity.setValueType(Account.class.getName());
            entity.addQueryField("personId", Integer.class.getName(), null);
            entity.addQueryField("name", String.class.getName(), null);
            entity.setIndexes(F.asList(new QueryIndex("personId"), new QueryIndex("name")));

            ccfg.setQueryEntities(F.asList(entity));

            ccfgs.add(ccfg);
        }

        cfg.setCacheConfiguration(ccfgs.toArray(new CacheConfiguration[ccfgs.size()]));

        cfg.setClientMode(client);

        return cfg;
    }

    /** {@inheritDoc} */
    @Override protected void beforeTestsStarted() throws Exception {
        super.beforeTestsStarted();

        startGridsMultiThreaded(2);

        client = true;

        startGrid(2);
    }

    /** {@inheritDoc} */
    @Override protected void afterTestsStopped() throws Exception {
        stopAllGrids();

        super.afterTestsStopped();
    }

    /**
     * @param name Cache name.
     * @return Cache configuration.
     */
    private CacheConfiguration configuration(String name) {
        CacheConfiguration ccfg = new CacheConfiguration();

        ccfg.setName(name);
        ccfg.setWriteSynchronizationMode(FULL_SYNC);
        ccfg.setAtomicWriteOrderMode(PRIMARY);
        ccfg.setAtomicityMode(ATOMIC);
        ccfg.setBackups(1);

        return ccfg;
    }

    /**
     * @throws Exception If failed.
     */
    public void testJoin() throws Exception {
        Ignite client = grid(2);

        IgniteCache<Object, Object> personCache = client.cache(PERSON_CACHE);
        IgniteCache<Object, Object> orgCache = client.cache(ORG_CACHE);
        IgniteCache<Object, Object> accCache = client.cache(ACCOUNT_CACHE);

        Affinity<Object> aff = client.affinity(PERSON_CACHE);

        AtomicInteger orgKey = new AtomicInteger();
        AtomicInteger accKey = new AtomicInteger();

        ClusterNode node0 = ignite(0).cluster().localNode();
        ClusterNode node1 = ignite(1).cluster().localNode();

        /**
         * One organization, one person, two accounts.
         */

        int orgId1 = keyForNode(aff, orgKey, node0);

        orgCache.put(orgId1, new Organization("obj-" + orgId1));

        personCache.put(new PersonKey(1, orgId1), new Person(1, "o1-p1"));
        personCache.put(new PersonKey(2, orgId1), new Person(2, "o1-p2"));

        accCache.put(keyForNode(aff, accKey, node0), new Account(1, "a0"));
        accCache.put(keyForNode(aff, accKey, node1), new Account(1, "a1"));

        // Join on affinity keys equals condition should not be distributed.
        String qry = "select o.name, p._key, p.name " +
            "from \"org\".Organization o, \"person\".Person p " +
            "where p.affKey = o._key";

        assertFalse(plan(qry, orgCache, false).contains("batched"));

        checkQuery(qry, orgCache, false, 2);

        checkQuery("select o.name, p._key, p.name, a.name " +
            "from \"org\".Organization o, \"person\".Person p, \"acc\".Account a " +
            "where p.affKey = o._key and p.id = a.personId", orgCache, true, 2);
    }

    /**
     * @param sql SQL.
     * @param cache Cache.
     * @param enforceJoinOrder Enforce join order flag.
     * @return Query plan.
     */
    private String plan(String sql,
        IgniteCache<?, ?> cache,
        boolean enforceJoinOrder) {
        return (String)cache.query(new SqlFieldsQuery("explain " + sql)
            .setDistributedJoins(true)
            .setEnforceJoinOrder(enforceJoinOrder))
            .getAll().get(0).get(0);
    }

    /**
     * @param sql SQL.
     * @param cache Cache.
     * @param enforceJoinOrder Enforce join order flag.
     * @param expSize Expected results size.
     */
    private void checkQuery(String sql,
        IgniteCache<Object, Object> cache,
        boolean enforceJoinOrder,
        int expSize) {
        String plan = (String)cache.query(new SqlFieldsQuery("explain " + sql)
            .setDistributedJoins(true)
            .setEnforceJoinOrder(enforceJoinOrder))
            .getAll().get(0).get(0);

        log.info("Plan: " + plan);

        SqlFieldsQuery qry = new SqlFieldsQuery(sql);

        qry.setDistributedJoins(true);
        qry.setEnforceJoinOrder(enforceJoinOrder);

        QueryCursor<List<?>> cur = cache.query(qry);

        List<List<?>> res = cur.getAll();

        if (expSize != res.size())
            log.info("Results: " + res);

        assertEquals(expSize, res.size());
    }
    /**
     *
     */
    public static class PersonKey {
        /** */
        private int id;

        /** */
        @AffinityKeyMapped
        private int affKey;

        /**
         * @param id Key.
         * @param affKey Affinity key.
         */
        public PersonKey(int id, int affKey) {
            this.id = id;
            this.affKey = affKey;
        }

        /** {@inheritDoc} */
        @Override public boolean equals(Object o) {
            if (this == o)
                return true;

            if (o == null || getClass() != o.getClass())
                return false;

            PersonKey other = (PersonKey)o;

            return id == other.id;
        }

        /** {@inheritDoc} */
        @Override public int hashCode() {
            return id;
        }
    }

    /**
     *
     */
    private static class Account implements Serializable {
        /** */
        int personId;

        /** */
        String name;

        /**
         * @param personId Person ID.
         * @param name Name.
         */
        public Account(int personId, String name) {
            this.personId = personId;
            this.name = name;
        }

        /** {@inheritDoc} */
        @Override public String toString() {
            return S.toString(Account.class, this);
        }
    }

    /**
     *
     */
    private static class Person implements Serializable {
        /** */
        int id;

        /** */
        String name;

        /**
         * @param id Person ID.
         * @param name Name.
         */
        public Person(int id, String name) {
            this.id = id;
            this.name = name;
        }

        /** {@inheritDoc} */
        @Override public String toString() {
            return S.toString(Person.class, this);
        }
    }

    /**
     *
     */
    private static class Organization implements Serializable {
        /** */
        String name;

        /**
         * @param name Name.
         */
        public Organization(String name) {
            this.name = name;
        }

        /** {@inheritDoc} */
        @Override public String toString() {
            return S.toString(Organization.class, this);
        }
    }
}


text:
class CurrencyMExcngRate < ActiveRecord::Base
end


text:
#contenedor
{
	width: 95%;
	margin: 0 auto;
	border:1px solid red;
	height: 1024px;
	background: #034160;
	/* IE10 Consumer Preview */
	background-image: -ms-radial-gradient(center top, circle closest-corner, #61BAFF 0%, #034160 100%);

	/* Mozilla Firefox */
	background-image: -moz-radial-gradient(center top, circle closest-corner, #61BAFF 0%, #034160 100%);

	/* Opera */
	background-image: -o-radial-gradient(center top, circle closest-corner, #61BAFF 0%, #034160 100%);

	/* Webkit (Safari/Chrome 10) */
	background-image: -webkit-gradient(radial, center top, 0, center top, 487, color-stop(0, #61BAFF), color-stop(1, #034160));

	/* Webkit (Chrome 11+) */
	background-image: -webkit-radial-gradient(center top, circle closest-corner, #61BAFF 0%, #034160 100%);

	/*W3C Markup, IE10 Release Preview */
	background-image: radial-gradient(circle closest-corner at center top, #61BAFF 0%, #034160 100%);

}


text:
package org.esupportail.publisher.security;

/**
 * Test class for the SecurityUtils utility class.
 *
 * @see SecurityUtils
 */
public class SecurityUtilsTest {

	/*
	 * @Test public void testGetCurrentLogin() { SecurityContext securityContext
	 * = SecurityContextHolder .createEmptyContext(); securityContext
	 * .setAuthentication(new UsernamePasswordAuthenticationToken( "admin",
	 * "admin")); SecurityContextHolder.setContext(securityContext); String
	 * login = SecurityUtils.getCurrentLogin();
	 * assertThat(login).isEqualTo("admin"); }
	 *
	 * @Test public void testIsAuthenticated() { SecurityContext securityContext
	 * = SecurityContextHolder .createEmptyContext(); securityContext
	 * .setAuthentication(new UsernamePasswordAuthenticationToken( "admin",
	 * "admin")); SecurityContextHolder.setContext(securityContext); boolean
	 * isAuthenticated = SecurityUtils.isAuthenticated();
	 * assertThat(isAuthenticated).isTrue(); }
	 *
	 * @Test public void testAnonymousIsNotAuthenticated() { SecurityContext
	 * securityContext = SecurityContextHolder .createEmptyContext();
	 * Collection<GrantedAuthority> authorities = new ArrayList<>();
	 * authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS));
	 * securityContext .setAuthentication(new
	 * UsernamePasswordAuthenticationToken( "anonymous", "anonymous",
	 * authorities)); SecurityContextHolder.setContext(securityContext); boolean
	 * isAuthenticated = SecurityUtils.isAuthenticated();
	 * assertThat(isAuthenticated).isFalse(); }
	 */
}


text:
package com.google.gerrit.server.edit;

import com.google.gerrit.extensions.common.CommitInfo;
import com.google.gerrit.extensions.common.EditInfo;
import com.google.gerrit.extensions.common.FetchInfo;
import com.google.gerrit.extensions.config.DownloadCommand;
import com.google.gerrit.extensions.config.DownloadScheme;
import com.google.gerrit.extensions.registration.DynamicMap;
import com.google.gerrit.extensions.registration.Extension;
import com.google.gerrit.server.CommonConverters;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.change.DownloadCommandsJson;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import org.eclipse.jgit.revwalk.RevCommit;

@Singleton
public class ChangeEditJson {
  private final DynamicMap<DownloadCommand> downloadCommands;
  private final DynamicMap<DownloadScheme> downloadSchemes;
  private final Provider<CurrentUser> userProvider;

  @Inject
  ChangeEditJson(
      DynamicMap<DownloadCommand> downloadCommand,
      DynamicMap<DownloadScheme> downloadSchemes,
      Provider<CurrentUser> userProvider) {
    this.downloadCommands = downloadCommand;
    this.downloadSchemes = downloadSchemes;
    this.userProvider = userProvider;
  }

  public EditInfo toEditInfo(ChangeEdit edit, boolean downloadCommands) {
    EditInfo out = new EditInfo();
    out.commit = fillCommit(edit.getEditCommit());
    out.baseRevision = edit.getBasePatchSet().commitId().name();
    out.basePatchSetNumber = edit.getBasePatchSet().number();
    out.ref = edit.getRefName();
    if (downloadCommands) {
      out.fetch = fillFetchMap(edit);
    }
    return out;
  }

  private static CommitInfo fillCommit(RevCommit editCommit) {
    CommitInfo commit = new CommitInfo();
    commit.commit = editCommit.toObjectId().getName();
    commit.author = CommonConverters.toGitPerson(editCommit.getAuthorIdent());
    commit.committer = CommonConverters.toGitPerson(editCommit.getCommitterIdent());
    commit.subject = editCommit.getShortMessage();
    commit.message = editCommit.getFullMessage();

    commit.parents = new ArrayList<>(editCommit.getParentCount());
    for (RevCommit p : editCommit.getParents()) {
      CommitInfo i = new CommitInfo();
      i.commit = p.name();
      commit.parents.add(i);
    }

    return commit;
  }

  private Map<String, FetchInfo> fillFetchMap(ChangeEdit edit) {
    Map<String, FetchInfo> r = new LinkedHashMap<>();
    for (Extension<DownloadScheme> e : downloadSchemes) {
      String schemeName = e.getExportName();
      DownloadScheme scheme = e.getProvider().get();
      if (!scheme.isEnabled()
          || (scheme.isAuthRequired() && !userProvider.get().isIdentifiedUser())) {
        continue;
      }

      // No fluff, just stuff
      if (!scheme.isAuthSupported()) {
        continue;
      }

      String projectName = edit.getChange().getProject().get();
      String refName = edit.getRefName();
      FetchInfo fetchInfo = new FetchInfo(scheme.getUrl(projectName), refName);
      r.put(schemeName, fetchInfo);

      DownloadCommandsJson.populateFetchMap(
          scheme, downloadCommands, projectName, refName, fetchInfo);
    }

    return r;
  }
}


text:
## angular-subscribe [![travisci](https://travis-ci.org/kasperlewau/angular-subscribe.svg?branch=master)](https://travis-ci.org/kasperlewau/angular-subscribe)
> Adds a `$subscribe` method to the `$scope` prototype. $on listeners with automagic de-registration.

### installation
```js
  /** with bower **/
  bower install angular-subscribe --save
  <script src="path/to/angular-subscribe/dist/angular-subscribe.js"></script>

  /** with jspm **/
  jspm install angular-subscribe --save
  import 'angular-subscribe';
```
### usage
```js
  angular.module('your_module_name', [ 'angular-subscribe' ]);
```
```js
  $scope.$subscribe('event', callbackFn);
  /** becomes **/
  var unsub = $rootScope.$on('event', callbackFn);
  $scope.$on('$destroy', unsub);
```

### testing
`npm install; npm test`

### License
MIT © [Kasper Lewau](github.com/kasperlewau)


text:
//// [parserGenericConstraint6.ts]
class C<T extends List<List<T> >> {
}

//// [parserGenericConstraint6.js]
var C = /** @class */ (function () {
    function C() {
    }
    return C;
}());


text:
enclosed-exceptions
===================

The purpose of this module is to allow you to capture all exceptions originating from within the enclosed computation,
while still reacting to asynchronous exceptions aimed at the calling thread.

This way, you can be sure that the function that calls, for example,  ```catchAny```,
will still respond to ```ThreadKilled``` or ```Timeout``` events raised by another thread
(with ``throwTo``), while capturing all exceptions, synchronous or asynchronous,
resulting from the execution of the enclosed computation.

One particular use case is to allow the safe execution of code from various
libraries (which you do not control), capturing any faults that might occur,
while remaining responsive to higher level events and control actions.

This library was originally developed by [Michael Snoyman](http://www.snoyman.com/) for the
[ClassyPrelude](http://hackage.haskell.org/package/classy-prelude) library,
and was latter spun-off into a separate independent package.

For a more detailed explanation of the motivation behind this functions, see:

[Catching all exceptions](https://www.fpcomplete.com/user/snoyberg/general-haskell/exceptions/catching-all-exceptions)

and

[the discussion in haskell-cafe](https://groups.google.com/forum/#!topic/haskell-cafe/e9H2I-3uVJE)


text:
using UnityEngine;
using System.Collections;
using AsyncRPGSharedLib.Environment;

public class WidgetEventDispatcher
{
    private enum eMouseButton
    {
        left= 0,
        right= 1,
        middle= 2
    }

    private WidgetGroup m_rootWidgetGroup;
    private Point2d m_mousePosition;
    private bool m_mouseIsDragging;
    private bool m_mouseWasDown;
    private IWidget m_mouseDownIWidget;
    private IWidget m_mouseOverIWidget;

    public WidgetEventDispatcher()
    {
        m_mousePosition = new Point2d();
        m_rootWidgetGroup = null;
        m_mouseOverIWidget = null;
        m_mouseDownIWidget = null;
        m_mouseIsDragging = false;
        m_mouseWasDown = false;
    }

    public IWidget MouseOverWidget
    {
        get { return m_mouseOverIWidget; }
    }

    public bool LogEnabled
    {
        get
        {
            return Debug.isDebugBuild ? DebugRegistry.TestToggle("ui.event.log") : false;
        }
    }

    public void Start(WidgetGroup widgetGroup)
    {
        Point2d newMousePosition = GetMousePosition();

        m_rootWidgetGroup = widgetGroup;

        m_mousePosition.Set(newMousePosition.x, newMousePosition.y);
        m_mouseOverIWidget = m_rootWidgetGroup.FindChildIWidgetContainingPoint(m_mousePosition);
        m_mouseIsDragging = false;
        m_mouseWasDown = Input.GetMouseButton((int)eMouseButton.left);

        if (Debug.isDebugBuild)
        {
            DebugRegistry.SetToggle("ui.event.log", false);
        }
    }

    public void Update()
    {
        Point2d mousePosition = GetMousePosition();
        float mouseScrollAmount= Input.GetAxis("Mouse ScrollWheel");
        bool mouseIsDown = Input.GetMouseButton((int)eMouseButton.left);

        if (mousePosition.x != m_mousePosition.x || mousePosition.y != m_mousePosition.y)
        {
            OnMouseMove(mousePosition.x, mousePosition.y);
        }

        if (mouseScrollAmount != 0.0f)
        {
            OnMouseWheel(mouseScrollAmount);
        }

        if (!m_mouseWasDown && mouseIsDown)
        {
            OnMouseDown();
        }
        else if (m_mouseWasDown && !mouseIsDown)
        {
            OnMouseUp();
        }

        m_mouseWasDown = mouseIsDown;
    }

    public void OnDestroy()
    {
        m_mouseOverIWidget = null;
    }

	// Unity Mouse Event Handlers
	private void OnMouseUp()
	{
		m_mouseIsDragging = false;

		if (m_mouseOverIWidget != null)
        {
            {
                WidgetEvent.MouseUpEventParameters eventParameters =
                    new WidgetEvent.MouseUpEventParameters
                    {
                        worldX = m_mousePosition.x,
                        worldY = m_mousePosition.y,
                        localX = m_mousePosition.x - m_mouseOverIWidget.WorldX,
                        localY = m_mousePosition.y - m_mouseOverIWidget.WorldY
                    };

                if (LogEnabled)
                {
                    Debug.Log("[MouseUp] on Widget " + m_mouseOverIWidget.GetType().Name);
                }

                // Notify the widget that the mouse was released
                (m_mouseOverIWidget as IWidgetEventListener).OnWidgetEvent(
                    new WidgetEvent(WidgetEvent.eEventType.mouseUp, m_mouseOverIWidget, eventParameters));
            }

            // Notify the widget if we clicked on it
            if (m_mouseOverIWidget == m_mouseDownIWidget)
            {
                WidgetEvent.MouseClickEventParameters eventParameters =
                    new WidgetEvent.MouseClickEventParameters
                    {
                        worldX = m_mousePosition.x,
                        worldY = m_mousePosition.y,
                        localX = m_mousePosition.x - m_mouseOverIWidget.WorldX,
                        localY = m_mousePosition.y - m_mouseOverIWidget.WorldY
                    };

                if (LogEnabled)
                {
                    Debug.Log("[MouseClick] on Widget " + m_mouseOverIWidget.GetType().Name);
                }

                (m_mouseOverIWidget as IWidgetEventListener).OnWidgetEvent(
                    new WidgetEvent(WidgetEvent.eEventType.mouseClick, m_mouseOverIWidget, eventParameters));
            }
        }

		m_mouseDownIWidget = null;
	}

	private void OnMouseDown()
	{
		m_mouseIsDragging = true;

		// Notify the widget of a drag event
		if (m_mouseOverIWidget != null)
		{
			WidgetEvent.MouseDownEventParameters eventParameters =
                new WidgetEvent.MouseDownEventParameters {
				    worldX= m_mousePosition.x,
                    worldY= m_mousePosition.y,
				    localX= m_mousePosition.x - m_mouseOverIWidget.WorldX,
                    localY= m_mousePosition.y - m_mouseOverIWidget.WorldY };

            if (LogEnabled)
            {
                Debug.Log("[MouseDown] on Widget " + m_mouseOverIWidget.GetType().Name);
            }

			(m_mouseOverIWidget as IWidgetEventListener).OnWidgetEvent(
				new WidgetEvent(WidgetEvent.eEventType.mouseDown, m_mouseOverIWidget, eventParameters));

			m_mouseDownIWidget = m_mouseOverIWidget;
		}
	}

	private void OnMouseMove(float newMouseX, float newMouseY)
	{
		float mouseDeltaX = newMouseX - m_mousePosition.x;
		float mouseDeltaY = newMouseY - m_mousePosition.y;

        //Debug.Log("Mouse: " + newMouseX.ToString() + ", " + newMouseY.ToString());

		m_mousePosition.Set(newMouseX, newMouseY);

		// Notify the widget of a drag event
		if (m_mouseOverIWidget != null)
		{
			if (m_mouseIsDragging)
			{
                if (LogEnabled)
                {
                    Debug.Log("[MouseDrag] on Widget " + m_mouseOverIWidget.GetType().Name);
                }

				(m_mouseOverIWidget as IWidgetEventListener).OnWidgetEvent(
					new WidgetEvent(
                        WidgetEvent.eEventType.mouseDrag,
                        m_mouseOverIWidget,
                        new WidgetEvent.MouseDragEventParameters { deltaX= mouseDeltaX, deltaY= mouseDeltaY } ));
			}
			else
			{
                if (LogEnabled)
                {
                    Debug.Log("[MouseMove] on Widget " + m_mouseOverIWidget.GetType().Name);
                }

                (m_mouseOverIWidget as IWidgetEventListener).OnWidgetEvent(
					new WidgetEvent(
                        WidgetEvent.eEventType.mouseMove,
                        m_mouseOverIWidget,
                        new WidgetEvent.MouseMoveEventParameters { deltaX= mouseDeltaX, deltaY= mouseDeltaY } ));
			}
		}

        {
            IWidget newMouseOverWidget = m_rootWidgetGroup.FindChildIWidgetContainingPoint(m_mousePosition);

		    // See if we have moved over a new widget
		    if (newMouseOverWidget != m_mouseOverIWidget)
		    {
			    // Notify the old widget the cursor left
			    if (m_mouseOverIWidget != null)
			    {
                    if (LogEnabled)
                    {
                        Debug.Log("[MouseOut] on Widget " + m_mouseOverIWidget.GetType().Name);
                    }

				    (m_mouseOverIWidget as IWidgetEventListener).OnWidgetEvent(
					    new WidgetEvent(
                            WidgetEvent.eEventType.mouseOut,
                            m_mouseOverIWidget,
							null));
			    }

			    // Notify the new mouse over widget we entered
			    if (newMouseOverWidget != null)
			    {
                    if (LogEnabled)
                    {
                        Debug.Log("[MouseOver] on Widget " + newMouseOverWidget.GetType().Name);
                    }

				    (newMouseOverWidget as IWidgetEventListener).OnWidgetEvent(
					    new WidgetEvent(
                            WidgetEvent.eEventType.mouseOver,
                            newMouseOverWidget,
							null));
			    }

			    // Remember the new mouse over widget
			    m_mouseOverIWidget = newMouseOverWidget;
		    }
        }
	}

	private void OnMouseWheel(float scrollDelta)
	{
		if (m_mouseOverIWidget != null)
		{
            if (LogEnabled)
            {
                Debug.Log("[MouseWheel] on Widget " + m_mouseOverIWidget.GetType().Name);
            }

			(m_mouseOverIWidget as IWidgetEventListener).OnWidgetEvent(
				new WidgetEvent(
                    WidgetEvent.eEventType.mouseWheel,
                    m_mouseOverIWidget,
                    new WidgetEvent.MousWheelEventParameters {delta= scrollDelta} ));
		}
	}

    public static Point2d GetMousePosition()
    {
        Vector3 unityMousePosition = Input.mousePosition;
        Point2d gameMousePosition = new Point2d(unityMousePosition.x, Screen.height - unityMousePosition.y);

        return gameMousePosition;
    }
}


text:
package fake

import (
	v1alpha1 "github.com/google/kf/v2/pkg/client/kf/clientset/versioned/typed/kf/v1alpha1"
	rest "k8s.io/client-go/rest"
	testing "k8s.io/client-go/testing"
)

type FakeKfV1alpha1 struct {
	*testing.Fake
}

func (c *FakeKfV1alpha1) Apps(namespace string) v1alpha1.AppInterface {
	return &FakeApps{c, namespace}
}

func (c *FakeKfV1alpha1) Builds(namespace string) v1alpha1.BuildInterface {
	return &FakeBuilds{c, namespace}
}

func (c *FakeKfV1alpha1) ClusterServiceBrokers() v1alpha1.ClusterServiceBrokerInterface {
	return &FakeClusterServiceBrokers{c}
}

func (c *FakeKfV1alpha1) Routes(namespace string) v1alpha1.RouteInterface {
	return &FakeRoutes{c, namespace}
}

func (c *FakeKfV1alpha1) Scales(namespace string) v1alpha1.ScaleInterface {
	return &FakeScales{c, namespace}
}

func (c *FakeKfV1alpha1) ServiceBrokers(namespace string) v1alpha1.ServiceBrokerInterface {
	return &FakeServiceBrokers{c, namespace}
}

func (c *FakeKfV1alpha1) ServiceInstances(namespace string) v1alpha1.ServiceInstanceInterface {
	return &FakeServiceInstances{c, namespace}
}

func (c *FakeKfV1alpha1) ServiceInstanceBindings(namespace string) v1alpha1.ServiceInstanceBindingInterface {
	return &FakeServiceInstanceBindings{c, namespace}
}

func (c *FakeKfV1alpha1) SourcePackages(namespace string) v1alpha1.SourcePackageInterface {
	return &FakeSourcePackages{c, namespace}
}

func (c *FakeKfV1alpha1) Spaces() v1alpha1.SpaceInterface {
	return &FakeSpaces{c}
}

func (c *FakeKfV1alpha1) Tasks(namespace string) v1alpha1.TaskInterface {
	return &FakeTasks{c, namespace}
}

func (c *FakeKfV1alpha1) TaskSchedules(namespace string) v1alpha1.TaskScheduleInterface {
	return &FakeTaskSchedules{c, namespace}
}

// RESTClient returns a RESTClient that is used to communicate
// with API server by this client implementation.
func (c *FakeKfV1alpha1) RESTClient() rest.Interface {
	var ret *rest.RESTClient
	return ret
}


text:
require 'mida/vocabulary'

module Mida
  module SchemaOrg

    autoload :Thing, 'mida/vocabularies/schemaorg/thing'
    autoload :Place, 'mida/vocabularies/schemaorg/place'
    autoload :Organization, 'mida/vocabularies/schemaorg/organization'
    autoload :LocalBusiness, 'mida/vocabularies/schemaorg/localbusiness'

    # An auto parts store.
    class AutoPartsStore < Mida::Vocabulary
      itemtype %r{http://schema.org/AutoPartsStore}i
      include_vocabulary Mida::SchemaOrg::Thing
      include_vocabulary Mida::SchemaOrg::Place
      include_vocabulary Mida::SchemaOrg::Organization
      include_vocabulary Mida::SchemaOrg::LocalBusiness
    end

  end
end


text:
#ifndef configment_config_h_20130321
#define configment_config_h_20130321

#include <iostream>
#include <configment/configment.h>
#include <configment/debug.h>
#include <configment/section.h>
#include <configment/validation_error.h>

namespace configment
{

class Config : public Section
{
    str_type				_filename;
  public:
    static const str_type CLASS_NAME;
    Config(const str_type & filename) : Section(), _filename()
    {
        this->set_file(filename);
        this->load_file(filename);
    }
    Config() : Section(), _filename() { }
    Config(const Section & s) : Section(s), _filename() { }

    virtual ~Config() { }

    /*virtual*/ Object clone() const { return Object::from_pointer(new Config(*this)); }

    /*virtual*/ std::string class_name() const { return this->CLASS_NAME; }

    /*virtual*/ operator bool() const { return ! this->empty(); }

    virtual void set_file(const str_type & filename)
    {
        this->_filename = filename;
    }

    /*virtual*/ void dump_file(const DumpOptions & dump_options=DEFAULT_DUMP_OPTIONS) const;
    /*virtual*/ void dump_file(const str_type & filename,
                               const DumpOptions & dump_options=DEFAULT_DUMP_OPTIONS) const
    {
        return this->Section::dump_file(filename, dump_options);
    }
    /*virtual*/ void dump_file(const char * filename,
                               const DumpOptions & dump_options=DEFAULT_DUMP_OPTIONS) const
    {
        return this->Section::dump_file(filename, dump_options);
    }

    Config & operator =(const Object & o);
    Config & operator =(const Section & o) { return this->operator =(Config(o)); }
    Config & operator =(const Config & o)
    {
        this->Section::operator =(o);
        this->_filename = o._filename;
        return *this;
    }

};

} //namespace configment

#endif // #define configment_config_h_20130321


text:
#include "org_mitk_gui_qt_xnatinterface_Activator.h"

#include <QtPlugin>

#include "QmitkXnatEditor.h"
#include "QmitkXnatTreeBrowserView.h"
#include "QmitkXnatConnectionPreferencePage.h"

#include <usGetModuleContext.h>
#include <usModuleInitialization.h>

US_INITIALIZE_MODULE

namespace mitk {

ctkPluginContext* org_mitk_gui_qt_xnatinterface_Activator::m_Context = 0;
us::ModuleContext* org_mitk_gui_qt_xnatinterface_Activator::m_ModuleContext = 0;

QmitkXnatSessionManager* org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()
{
  static QmitkXnatSessionManager manager;
  return &manager;
}

ctkPluginContext* org_mitk_gui_qt_xnatinterface_Activator::GetContext()
{
  return m_Context;
}

us::ModuleContext* org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()
{
  return m_ModuleContext;
}

void org_mitk_gui_qt_xnatinterface_Activator::start(ctkPluginContext* context)
{
  this->m_Context = context;
  this->m_ModuleContext = us::GetModuleContext();

  BERRY_REGISTER_EXTENSION_CLASS(QmitkXnatEditor, context)
  BERRY_REGISTER_EXTENSION_CLASS(QmitkXnatTreeBrowserView, context)
  BERRY_REGISTER_EXTENSION_CLASS(QmitkXnatConnectionPreferencePage, context)
}

void org_mitk_gui_qt_xnatinterface_Activator::stop(ctkPluginContext* context)
{
  Q_UNUSED(context)
  Q_UNUSED(us::GetModuleContext())
  this->m_Context = 0;
  this->m_ModuleContext = 0;
}

}

#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
  Q_EXPORT_PLUGIN2(org_mitk_gui_qt_xnatinterface, mitk::org_mitk_gui_qt_xnatinterface_Activator)
#endif


text:
public class EmptySequence<E> implements SequenceBase<E> {
    private static final EmptySequence _empty = new EmptySequence();
    public static <T> EmptySequence<T> empty() { return _empty; }
    private EmptySequence() {}

    @Override
    public SequenceBase seq(E elem) {
        return new Sequence(elem, this);
    }

    @Override
    public E head() throws EmptySequenceException {
        throw new EmptySequenceException();
    }

    @Override
    public SequenceBase tail() throws EmptySequenceException {
        throw new EmptySequenceException();
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project-private xmlns="http://www.netbeans.org/ns/project-private/1">
    <editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/2" lastBookmarkId="0"/>
    <open-files xmlns="http://www.netbeans.org/ns/projectui-open-files/2">
        <group>
            <file>file:/opt/lampp/htdocs/lwl/TempNotifier/src/network/NotifierHTTP.java</file>
            <file>file:/opt/lampp/htdocs/lwl/TempNotifier/src/App.java</file>
            <file>file:/opt/lampp/htdocs/lwl/TempNotifier/src/utils/RXCommunication.java</file>
            <file>file:/opt/lampp/htdocs/lwl/TempNotifier/src/utils/Encrypter.java</file>
            <file>file:/opt/lampp/htdocs/lwl/TempNotifier/src/utils/FileManager.java</file>
            <file>file:/opt/lampp/htdocs/lwl/TempNotifier/src/configuration/Configurator.java</file>
            <file>file:/opt/lampp/htdocs/lwl/TempNotifier/src/utils/Interpreter.java</file>
        </group>
    </open-files>
</project-private>


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Trans. Mycol. Soc. Japan 28(4): 424 (1988)

#### Original name
Corollospora fusca Nakagiri & Tokura, 1988

### Remarks
null


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

<title>Overview</title>
<meta name="date" content="2018-10-24">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Packages

Package
Description

com.fitpay.android.a2averification

com.fitpay.android.api

com.fitpay.android.api.callbacks

com.fitpay.android.api.enums

com.fitpay.android.api.models

com.fitpay.android.api.models.apdu

com.fitpay.android.api.models.card

com.fitpay.android.api.models.collection

com.fitpay.android.api.models.device

com.fitpay.android.api.models.issuer

com.fitpay.android.api.models.security

com.fitpay.android.api.models.sync

com.fitpay.android.api.models.user

com.fitpay.android.api.services

com.fitpay.android.api.sse

com.fitpay.android.cardscanner

com.fitpay.android.configs

com.fitpay.android.paymentdevice

com.fitpay.android.paymentdevice.callbacks

com.fitpay.android.paymentdevice.constants

com.fitpay.android.paymentdevice.enums

com.fitpay.android.paymentdevice.events

com.fitpay.android.paymentdevice.impl

com.fitpay.android.paymentdevice.impl.ble

com.fitpay.android.paymentdevice.impl.ble.activities

com.fitpay.android.paymentdevice.impl.ble.message

com.fitpay.android.paymentdevice.impl.mock

com.fitpay.android.paymentdevice.interfaces

com.fitpay.android.paymentdevice.models

com.fitpay.android.paymentdevice.utils

com.fitpay.android.paymentdevice.utils.sync

com.fitpay.android.rtm.callbacks

com.fitpay.android.rtm.enums

com.fitpay.android.rtm.models

com.fitpay.android.utils

com.fitpay.android.webview

com.fitpay.android.webview.callbacks

com.fitpay.android.webview.enums

com.fitpay.android.webview.events

com.fitpay.android.webview.impl

com.fitpay.android.webview.impl.parser

com.fitpay.android.webview.impl.webclients

com.fitpay.android.webview.models

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
namespace spvtools {
namespace reduce {

using opt::IRContext;

std::vector<std::unique_ptr<ReductionOpportunity>>
OperandToUndefReductionOpportunityFinder::GetAvailableOpportunities(
    IRContext* context) const {
  std::vector<std::unique_ptr<ReductionOpportunity>> result;

  for (auto& function : *context->module()) {
    for (auto& block : function) {
      for (auto& inst : block) {
        // Skip instructions that result in a pointer type.
        auto type_id = inst.type_id();
        if (type_id) {
          auto type_id_def = context->get_def_use_mgr()->GetDef(type_id);
          if (type_id_def->opcode() == SpvOpTypePointer) {
            continue;
          }
        }

        // We iterate through the operands using an explicit index (rather
        // than using a lambda) so that we use said index in the construction
        // of a ChangeOperandToUndefReductionOpportunity
        for (uint32_t index = 0; index < inst.NumOperands(); index++) {
          const auto& operand = inst.GetOperand(index);

          if (spvIsInIdType(operand.type)) {
            const auto operand_id = operand.words[0];
            auto operand_id_def =
                context->get_def_use_mgr()->GetDef(operand_id);

            // Skip constant and undef operands.
            // We always want the reducer to make the module "smaller", which
            // ensures termination.
            // Therefore, we assume: id > undef id > constant id.
            if (spvOpcodeIsConstantOrUndef(operand_id_def->opcode())) {
              continue;
            }

            // Don't replace function operands with undef.
            if (operand_id_def->opcode() == SpvOpFunction) {
              continue;
            }

            // Only consider operands that have a type.
            auto operand_type_id = operand_id_def->type_id();
            if (operand_type_id) {
              auto operand_type_id_def =
                  context->get_def_use_mgr()->GetDef(operand_type_id);

              // Skip pointer operands.
              if (operand_type_id_def->opcode() == SpvOpTypePointer) {
                continue;
              }

              result.push_back(
                  MakeUnique<ChangeOperandToUndefReductionOpportunity>(
                      context, &inst, index));
            }
          }
        }
      }
    }
  }
  return result;
}

std::string OperandToUndefReductionOpportunityFinder::GetName() const {
  return "OperandToUndefReductionOpportunityFinder";
}

}  // namespace reduce
}  // namespace spvtools


text:
<?php app("events")->fire("admin.dashboard.pre"); ?>

    <?php

    //  Get Registered Dashboard Widgets
    $widgets = app("events")->fire("admin.dashboard.widgets");

    //  Loop Each Widgets
    foreach($widgets as $widget) {

        //  Check for Full Inner Width Request
        $full_inner_width = (isset($widget["full_inner_width"]) && (bool)$widget["full_inner_width"] == true ? true : false);

        //  Get Widget State
        $widget_state = (isset($widget["widget_state"]) ? 'panel-' . $widget["widget_state"] : '');

        //  Col Class
        $column_class = (isset($widget["columns"]) && $widget["columns"] < 4 ? 'col-md-' . ($widget["columns"] * 4) : 'col-md-4');
    ?>
    <div class="<?php echo $column_class; ?> dashboard-widget-holder">
        <div class="panel panel-default <?php echo $widget_state; ?> dashboard-widget-item" id="<?php $widget["id"]; ?>">

                <?php echo $widget["title"]; ?>
                <?php if(isset($widget["actions"]) && sizeof($widget["actions"]) > 0) { ?>

                    <?php foreach($widget["actions"] as $action) { ?>
                    <a href="<?php echo (isset($action["link"]) ? $action["link"] : 'javascript:void(0);'); ?>" title="<?php echo @$action["title"]; ?>" id="<?php echo @$action["id"]; ?>" class="widget-action-item <?php echo @$action["class"]; ?>"><i class="glyphicon <?php echo $action["icon"]; ?>">
                    <?php } ?>

                <?php } ?>

            <div class="panel-body <?php echo ($full_inner_width ? 'no-padding' : ''); ?>"><?php echo call_user_func_array($widget["callback"], array()); ?>

            <?php if(isset($widget["footer"])) { ?>

<?php echo $widget["footer"]; ?>

            <?php } ?>

    <?php
    }
    ?>

<?php app("events")->fire("admin.dashboard.post"); ?>


text:
class ArticlesController < ApplicationController

  def index
    @articles = Article.all
  end

  def show
    @article = Article.find(params[:id])
  end

  def new
  end

  def edit
  end

  def create
    @article = Article.new(article_params)

    @article.save
    redirect_to @article
  end

  def update
  end

  private
    def article_params
      params.require(:article).permit(:title, :text)
    end

end


text:
package org.jsimpledb.util;

import com.google.common.base.Converter;

import java.util.AbstractMap;
import java.util.Map;

/**
 * Converted {@link Map.Entry}.
 *
 * @param <K> key type of this entry
 * @param <V> value type of this entry
 * @param <WK> key type of wrapped entry
 * @param <WV> value type of wrapped entry
 */
@SuppressWarnings("serial")
class ConvertedMapEntry<K, V, WK, WV> extends AbstractMap.SimpleEntry<K, V> {

    private final Converter<K, WK> keyConverter;
    private final Converter<V, WV> valueConverter;
    private final Map.Entry<WK, WV> wentry;

    ConvertedMapEntry(Converter<K, WK> keyConverter, Converter<V, WV> valueConverter, Map.Entry<WK, WV> wentry) {
        super(wentry.getKey() != null ? keyConverter.reverse().convert(wentry.getKey()) : null,
          wentry.getValue() != null ? valueConverter.reverse().convert(wentry.getValue()) : null);
        this.keyConverter = keyConverter;
        this.valueConverter = valueConverter;
        this.wentry = wentry;
    }

    public Converter<K, WK> getKeyConverter() {
        return this.keyConverter;
    }

    public Converter<V, WV> getValueConverter() {
        return this.valueConverter;
    }

    @Override
    public K getKey() {
        final WK key = this.wentry.getKey();
        return key != null ? this.keyConverter.reverse().convert(key) : null;
    }

    @Override
    public V getValue() {
        final WV value = this.wentry.getValue();
        return value != null ? this.valueConverter.reverse().convert(value) : null;
    }

    @Override
    public V setValue(V value) {
        final WV prev = this.wentry.setValue(value != null ? this.valueConverter.convert(value) : null);
        return prev != null ? this.valueConverter.reverse().convert(prev) : null;
    }
}


text:
export type Point = $ReadOnly<{x: number, y: number}>;
export type Size = $ReadOnly<{width: number, height: number}>;
export type IntrinsicSize = {
  ...Size,

  // If content is this height or less, hide the scrollbar entirely,
  // so that it doesn't take up vertical space unnecessarily (e.g. for a single row of content).
  hideScrollBarIfLessThanHeight?: number,

  // The initial height should be the height of the content, or this, whichever is less.
  maxInitialHeight?: number,
};
export type Rect = $ReadOnly<{origin: Point, size: Size}>;

/**
 * Alternative representation of `Rect`.
 * A tuple of (`top`, `right`, `bottom`, `left`) coordinates.
 */
type Box = [number, number, number, number];

export const zeroPoint: Point = Object.freeze({x: 0, y: 0});
export const zeroSize: Size = Object.freeze({width: 0, height: 0});
export const zeroRect: Rect = Object.freeze({
  origin: zeroPoint,
  size: zeroSize,
});

export function pointEqualToPoint(point1: Point, point2: Point): boolean {
  return point1.x === point2.x && point1.y === point2.y;
}

export function sizeEqualToSize(size1: Size, size2: Size): boolean {
  return size1.width === size2.width && size1.height === size2.height;
}

export function rectEqualToRect(rect1: Rect, rect2: Rect): boolean {
  return (
    pointEqualToPoint(rect1.origin, rect2.origin) &&
    sizeEqualToSize(rect1.size, rect2.size)
  );
}

export function sizeIsValid({width, height}: Size): boolean {
  return width >= 0 && height >= 0;
}

export function sizeIsEmpty({width, height}: Size): boolean {
  return width <= 0 || height <= 0;
}

function rectToBox(rect: Rect): Box {
  const top = rect.origin.y;
  const right = rect.origin.x + rect.size.width;
  const bottom = rect.origin.y + rect.size.height;
  const left = rect.origin.x;
  return [top, right, bottom, left];
}

function boxToRect(box: Box): Rect {
  const [top, right, bottom, left] = box;
  return {
    origin: {
      x: left,
      y: top,
    },
    size: {
      width: right - left,
      height: bottom - top,
    },
  };
}

export function rectIntersectsRect(rect1: Rect, rect2: Rect): boolean {
  if (
    rect1.size.width === 0 ||
    rect1.size.height === 0 ||
    rect2.size.width === 0 ||
    rect2.size.height === 0
  ) {
    return false;
  }

  const [top1, right1, bottom1, left1] = rectToBox(rect1);
  const [top2, right2, bottom2, left2] = rectToBox(rect2);
  return !(
    right1 < left2 ||
    right2 < left1 ||
    bottom1 < top2 ||
    bottom2 < top1
  );
}

/**
 * Returns the intersection of the 2 rectangles.
 *
 * Prerequisite: `rect1` must intersect with `rect2`.
 */
export function intersectionOfRects(rect1: Rect, rect2: Rect): Rect {
  const [top1, right1, bottom1, left1] = rectToBox(rect1);
  const [top2, right2, bottom2, left2] = rectToBox(rect2);
  return boxToRect([
    Math.max(top1, top2),
    Math.min(right1, right2),
    Math.min(bottom1, bottom2),
    Math.max(left1, left2),
  ]);
}

export function rectContainsPoint({x, y}: Point, rect: Rect): boolean {
  const [top, right, bottom, left] = rectToBox(rect);
  return left <= x && x <= right && top <= y && y <= bottom;
}

/**
 * Returns the smallest rectangle that contains all provided rects.
 *
 * @returns Union of `rects`. If `rects` is empty, returns `zeroRect`.
 */
export function unionOfRects(...rects: Rect[]): Rect {
  if (rects.length === 0) {
    return zeroRect;
  }

  const [firstRect, ...remainingRects] = rects;
  const boxUnion = remainingRects
    .map(rectToBox)
    .reduce((intermediateUnion, nextBox): Box => {
      const [unionTop, unionRight, unionBottom, unionLeft] = intermediateUnion;
      const [nextTop, nextRight, nextBottom, nextLeft] = nextBox;
      return [
        Math.min(unionTop, nextTop),
        Math.max(unionRight, nextRight),
        Math.max(unionBottom, nextBottom),
        Math.min(unionLeft, nextLeft),
      ];
    }, rectToBox(firstRect));
  return boxToRect(boxUnion);
}


text:
{{
###
# response._varscontains the dictionary returned by thecontroller action
###
try:
   from gluon.serializers import xml
   response.write(xml(response._vars),escape=False)
   response.headers['Content-Type']='text/xml'
except:
   raise HTTP(405, T('This information cannot be represented in XML.'))
}}


text:
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="custom.css">

            <button class="btn-info">7</button>
            <button class="btn-info">8</button>
            <button class="btn-info">9</button>
            <button class="btn-info">+</button>

            <button class="btn-info">4</button>
            <button class="btn-info">5</button>
            <button class="btn-info">6</button>
            <button class="btn-info">-</button>

            <button class="btn-info">1</button>
            <button class="btn-info">2</button>
            <button class="btn-info">3</button>
            <button class="btn-info">*</button>

            <button class="btn-info">0</button>
            <button class="btn-info">=</button>
            <button class="btn-info">/</button>
            <button class="btn-info">c</button>


text:
package com.nec.harvest.model;

import javax.persistence.AssociationOverride;
import javax.persistence.AssociationOverrides;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.JoinColumn;
import javax.persistence.Table;
import javax.persistence.Transient;

import com.nec.harvest.constant.TblConstants;
import com.nec.harvest.model.identifier.SectorVendorIdentifier;

/**
 * 部門別仕入先マスタAT105
 *
 * @author Ngoc Son Dang
 * @version Departmental.java
 * @since 2014/05/21
 *
 */
@javax.persistence.Entity
@Table(name = TblConstants.TBL_SECTORVENDOR)
public class SectorVendor extends BaseEntity {

	private static final long serialVersionUID = 8711502558858690916L;

	private SectorVendorIdentifier pk;

	/**
	 * 最大表示枠数
	 */
	private Integer maxWaku;

	/**
	 * 新規フラグ
	 * 0:新規ではない 1:新規
	 */
	private String newFlg;

	public SectorVendor() {
		super();
	}

	@EmbeddedId
    @AssociationOverrides({
        @AssociationOverride(name = "pk.organization", joinColumns = @JoinColumn(name = "StrCode")),
        @AssociationOverride(name = "pk.vendor", joinColumns = @JoinColumn(name = "SrsCode")),
        @AssociationOverride(name = "pk.category", joinColumns = @JoinColumn(name = "CtgCode"))
    })
	public SectorVendorIdentifier getPk() {
		return pk;
	}

	public void setPk(SectorVendorIdentifier pk) {
		this.pk = pk;
	}

	@Transient
	public Organization getOrganization() {
		return getPk().getOrganization();
	}

	@Transient
	public Vendor getVendor() {
		return getPk().getVendor();
	}

	@Transient
	public PurchaseCategory getCategory() {
	    return getPk().getCategory();
	}

	@Column(name = "MaxWaku", length = 4)
	public Integer getMaxWaku() {
        return maxWaku;
    }

    public void setMaxWaku(Integer maxWaku) {
        this.maxWaku = maxWaku;
    }

    /**
	 * 0:新規ではない 1:新規
	 *
	 * @return
	 */
	@Column(name = "NewFlg", length = 1)
	public String getNewFlg() {
		return newFlg;
	}

	public void setNewFlg(String newFlg) {
		this.newFlg = value(newFlg);
	}

}


text:
// Copyright (c), Firelight Technologies Pty, Ltd. 2012-2020.

#include "FMODEventControlSectionTemplate.h"
#include "FMODAmbientSound.h"
#include "FMODAudioComponent.h"
#include "Evaluation/MovieSceneEvaluation.h"
#include "IMovieScenePlayer.h"

struct FPlayingToken : IMovieScenePreAnimatedToken
{
    FPlayingToken(UObject &InObject)
    {
        bPlaying = false;

        if (UFMODAudioComponent *AudioComponent = Cast<UFMODAudioComponent>(&InObject))
        {
            if (IsValid(AudioComponent))
            {
                bPlaying = AudioComponent->IsPlaying();
            }
        }
    }

    virtual void RestoreState(UObject &Object, IMovieScenePlayer &Player) override
    {
        UFMODAudioComponent *AudioComponent = CastChecked<UFMODAudioComponent>(&Object);

        if (AudioComponent)
        {
            if (bPlaying)
            {
                AudioComponent->Play();
            }
            else
            {
                AudioComponent->Stop();
            }
        }
    }

private:
    bool bPlaying;
};

struct FPlayingTokenProducer : IMovieScenePreAnimatedTokenProducer
{
    static FMovieSceneAnimTypeID GetAnimTypeID() { return TMovieSceneAnimTypeID<FPlayingTokenProducer>(); }

private:
    virtual IMovieScenePreAnimatedTokenPtr CacheExistingState(UObject &Object) const override { return FPlayingToken(Object); }
};

struct FFMODEventKeyState : IPersistentEvaluationData
{
    FKeyHandle LastKeyHandle;
    FKeyHandle InvalidKeyHandle;
};

struct FFMODEventControlExecutionToken : IMovieSceneExecutionToken
{
    FFMODEventControlExecutionToken(EFMODEventControlKey InEventControlKey, FFrameTime InKeyTime)
        : EventControlKey(InEventControlKey)
        , KeyTime(InKeyTime)
    {
    }

    /** Execute this token, operating on all objects referenced by 'Operand' */
    virtual void Execute(const FMovieSceneContext &Context, const FMovieSceneEvaluationOperand &Operand, FPersistentEvaluationData &PersistentData,
        IMovieScenePlayer &Player)
    {
        for (TWeakObjectPtr<> &WeakObject : Player.FindBoundObjects(Operand))
        {
            UFMODAudioComponent *AudioComponent = Cast<UFMODAudioComponent>(WeakObject.Get());

            if (!AudioComponent)
            {
                AFMODAmbientSound *AmbientSound = Cast<AFMODAmbientSound>(WeakObject.Get());
                AudioComponent = AmbientSound ? AmbientSound->AudioComponent : nullptr;
            }

            if (IsValid(AudioComponent))
            {
                Player.SavePreAnimatedState(*AudioComponent, FPlayingTokenProducer::GetAnimTypeID(), FPlayingTokenProducer());

                if (EventControlKey == EFMODEventControlKey::Play)
                {
                    if (AudioComponent->IsPlaying())
                    {
                        AudioComponent->Stop();
                    }

                    EFMODSystemContext::Type SystemContext =
                        (GWorld && GWorld->WorldType == EWorldType::Editor) ? EFMODSystemContext::Editor : EFMODSystemContext::Runtime;
                    AudioComponent->PlayInternal(SystemContext);
                }
                else if (EventControlKey == EFMODEventControlKey::Stop)
                {
                    AudioComponent->Stop();
                }
            }
        }
    }

    EFMODEventControlKey EventControlKey;
    FFrameTime KeyTime;
};

FFMODEventControlSectionTemplate::FFMODEventControlSectionTemplate(const UFMODEventControlSection &Section)
    : ControlKeys(Section.ControlKeys)
{
}

void FFMODEventControlSectionTemplate::Evaluate(const FMovieSceneEvaluationOperand &Operand, const FMovieSceneContext &Context,
    const FPersistentEvaluationData &PersistentData, FMovieSceneExecutionTokens &ExecutionTokens) const
{
    const bool bPlaying = Context.IsSilent() == false && Context.GetDirection() == EPlayDirection::Forwards &&
                          Context.GetRange().Size<FFrameTime>() >= FFrameTime(0) && Context.GetStatus() == EMovieScenePlayerStatus::Playing;

    if (!bPlaying)
    {
        ExecutionTokens.Add(FFMODEventControlExecutionToken(EFMODEventControlKey::Stop, FFrameTime(0)));
    }
    else
    {
        TRange<FFrameNumber> PlaybackRange = Context.GetFrameNumberRange();
        TMovieSceneChannelData<const uint8> ChannelData = ControlKeys.GetData();

        // Find the index of the key handle that exists before this time
        TArrayView<const FFrameNumber> Times = ChannelData.GetTimes();
        TArrayView<const uint8> Values = ChannelData.GetValues();

        const int32 LastKeyIndex = Algo::UpperBound(Times, PlaybackRange.GetUpperBoundValue()) - 1;
        if (LastKeyIndex >= 0 && PlaybackRange.Contains(Times[LastKeyIndex]))
        {
            FFMODEventControlExecutionToken NewToken((EFMODEventControlKey)Values[LastKeyIndex], Times[LastKeyIndex]);
            ExecutionTokens.Add(MoveTemp(NewToken));
        }
    }
}