// Based on Eclipse Paho.
/*******************************************************************************
 * Copyright (c) 2014 IBM Corp.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and Eclipse Distribution License v1.0 which accompany this distribution.
 *
 * The Eclipse Public License is available at
 *    http://www.eclipse.org/legal/epl-v10.html
 * and the Eclipse Distribution License is available at
 *   http://www.eclipse.org/org/documents/edl-v10.php.
 *
 * Contributors:
 *    Ian Craggs - initial API and implementation and/or initial documentation
 *    Sergio R. Caprile - non-blocking packet read functions for stream transport
 *******************************************************************************/

/**
 * @file aws_iot_mqtt_client_common_internal.c
 * @brief MQTT client internal API definitions
 */

#ifdef __cplusplus
extern "C" {
#endif

#include <aws_iot_mqtt_client.h>
#include "aws_iot_mqtt_client_common_internal.h"

/* Max length of packet header */
#define MAX_NO_OF_REMAINING_LENGTH_BYTES 4

/**
 * Encodes the message length according to the MQTT algorithm
 * @param buf the buffer into which the encoded data is written
 * @param length the length to be encoded
 * @return the number of bytes written to buffer
 */
size_t aws_iot_mqtt_internal_write_len_to_buffer(unsigned char *buf, uint32_t length) {
	size_t outLen = 0;
	unsigned char encodedByte;

	FUNC_ENTRY;
	do {
		encodedByte = (unsigned char) (length % 128);
		length /= 128;
		/* if there are more digits to encode, set the top bit of this digit */
		if(length > 0) {
			encodedByte |= 0x80;
		}
		buf[outLen++] = encodedByte;
	} while(length > 0);

	FUNC_EXIT_RC(outLen);
}

/**
 * Decodes the message length according to the MQTT algorithm
 * @param the buffer containing the message
 * @param value the decoded length returned
 * @return the number of bytes read from the socket
 */
IoT_Error_t aws_iot_mqtt_internal_decode_remaining_length_from_buffer(unsigned char *buf, uint32_t *decodedLen,
																	  uint32_t *readBytesLen) {
	unsigned char encodedByte;
	uint32_t multiplier, len;
	FUNC_ENTRY;

	multiplier = 1;
	len = 0;
	*decodedLen = 0;

	do {
		if(++len > MAX_NO_OF_REMAINING_LENGTH_BYTES) {
			/* bad data */
			FUNC_EXIT_RC(MQTT_DECODE_REMAINING_LENGTH_ERROR);
		}
		encodedByte = *buf;
		buf++;
		*decodedLen += (encodedByte & 127) * multiplier;
		multiplier *= 128;
	} while((encodedByte & 128) != 0);

	*readBytesLen = len;

	FUNC_EXIT_RC(SUCCESS);
}

uint32_t aws_iot_mqtt_internal_get_final_packet_length_from_remaining_length(uint32_t rem_len) {
	rem_len += 1; /* header byte */
	/* now remaining_length field (MQTT 3.1.1 - 2.2.3)*/
	if(rem_len < 128) {
		rem_len += 1;
	} else if(rem_len < 16384) {
		rem_len += 2;
	} else if(rem_len < 2097152) {
		rem_len += 3;
	} else {
		rem_len += 4;
	}
	return rem_len;
}

/**
 * Calculates uint16 packet id from two bytes read from the input buffer
 * Checks Endianness at runtime
 *
 * @param pptr pointer to the input buffer - incremented by the number of bytes used & returned
 * @return the value calculated
 */
uint16_t aws_iot_mqtt_internal_read_uint16_t(unsigned char **pptr) {
	unsigned char *ptr = *pptr;
	uint16_t len = 0;
	uint8_t firstByte = (uint8_t) (*ptr);
	uint8_t secondByte = (uint8_t) (*(ptr + 1));
	len = (uint16_t) (secondByte + (256 * firstByte));

	*pptr += 2;
	return len;
}

/**
 * Writes an integer as 2 bytes to an output buffer.
 * @param pptr pointer to the output buffer - incremented by the number of bytes used & returned
 * @param anInt the integer to write
 */
void aws_iot_mqtt_internal_write_uint_16(unsigned char **pptr, uint16_t anInt) {
	**pptr = (unsigned char) (anInt / 256);
	(*pptr)++;
	**pptr = (unsigned char) (anInt % 256);
	(*pptr)++;
}

/**
 * Reads one character from the input buffer.
 * @param pptr pointer to the input buffer - incremented by the number of bytes used & returned
 * @return the character read
 */
unsigned char aws_iot_mqtt_internal_read_char(unsigned char **pptr) {
	unsigned char c = **pptr;
	(*pptr)++;
	return c;
}

/**
 * Writes one character to an output buffer.
 * @param pptr pointer to the output buffer - incremented by the number of bytes used & returned
 * @param c the character to write
 */
void aws_iot_mqtt_internal_write_char(unsigned char **pptr, unsigned char c) {
	**pptr = c;
	(*pptr)++;
}

void aws_iot_mqtt_internal_write_utf8_string(unsigned char **pptr, const char *string, uint16_t stringLen) {
	/* Nothing that calls this function will have a stringLen with a size larger than 2 bytes (MQTT 3.1.1 - 1.5.3) */
	aws_iot_mqtt_internal_write_uint_16(pptr, stringLen);
	if(stringLen > 0) {
		memcpy(*pptr, string, stringLen);
		*pptr += stringLen;
	}
}

/**
 * Initialize the MQTTHeader structure. Used to ensure that Header bits are
 * always initialized using the proper mappings. No Endianness issues here since
 * the individual fields are all less than a byte. Also generates no warnings since
 * all fields are initialized using hex constants
 */
IoT_Error_t aws_iot_mqtt_internal_init_header(MQTTHeader *pHeader, MessageTypes message_type,
											  QoS qos, uint8_t dup, uint8_t retained) {
	FUNC_ENTRY;

	if(NULL == pHeader) {
		FUNC_EXIT_RC(NULL_VALUE_ERROR);
	}

	/* Set all bits to zero */
	pHeader->byte = 0;
	uint8_t type = 0;
	switch(message_type) {
		case UNKNOWN:
			/* Should never happen */
			return FAILURE;
		case CONNECT:
			type = 0x01;
			break;
		case CONNACK:
			type = 0x02;
			break;
		case PUBLISH:
			type = 0x03;
			break;
		case PUBACK:
			type = 0x04;
			break;
		case PUBREC:
			type = 0x05;
			break;
		case PUBREL:
			type = 0x06;
			break;
		case PUBCOMP:
			type = 0x07;
			break;
		case SUBSCRIBE:
			type = 0x08;
			break;
		case SUBACK:
			type = 0x09;
			break;
		case UNSUBSCRIBE:
			type = 0x0A;
			break;
		case UNSUBACK:
			type = 0x0B;
			break;
		case PINGREQ:
			type = 0x0C;
			break;
		case PINGRESP:
			type = 0x0D;
			break;
		case DISCONNECT:
			type = 0x0E;
			break;
		default:
			/* Should never happen */
		FUNC_EXIT_RC(FAILURE);
	}

	pHeader->byte = type << 4;
	pHeader->byte |= dup << 3;

	switch(qos) {
		case QOS0:
			break;
		case QOS1:
			pHeader->byte |= 1 << 1;
			break;
		default:
			/* Using QOS0 as default */
			break;
	}

	pHeader->byte |= (1 == retained) ? 0x01 : 0x00;

	FUNC_EXIT_RC(SUCCESS);
}

IoT_Error_t aws_iot_mqtt_internal_send_packet(AWS_IoT_Client *pClient, size_t length, Timer *pTimer) {

	size_t sentLen, sent;
	IoT_Error_t rc;

	FUNC_ENTRY;

	if(NULL == pClient || NULL == pTimer) {
		FUNC_EXIT_RC(NULL_VALUE_ERROR);
	}

	if(length >= pClient->clientData.writeBufSize) {
		FUNC_EXIT_RC(MQTT_TX_BUFFER_TOO_SHORT_ERROR);
	}

#ifdef _ENABLE_THREAD_SUPPORT_
	rc = aws_iot_mqtt_client_lock_mutex(pClient, &(pClient->clientData.tls_write_mutex));
	if(SUCCESS != rc) {
		FUNC_EXIT_RC(rc);
	}
#endif

	sentLen = 0;
	sent = 0;

	while(sent < length && !has_timer_expired(pTimer)) {
		rc = pClient->networkStack.write(&(pClient->networkStack),
						 &pClient->clientData.writeBuf[sent],
						 (length - sent),
						 pTimer,
						 &sentLen);
		if(SUCCESS != rc) {
			/* there was an error writing the data */
			break;
		}
		sent += sentLen;
	}

#ifdef _ENABLE_THREAD_SUPPORT_
	rc = aws_iot_mqtt_client_unlock_mutex(pClient, &(pClient->clientData.tls_write_mutex));
	if(SUCCESS != rc) {
		FUNC_EXIT_RC(rc);
	}
#endif

	if(sent == length) {
		/* record the fact that we have successfully sent the packet */
		//countdown_sec(&c->pingTimer, c->clientData.keepAliveInterval);
		FUNC_EXIT_RC(SUCCESS);
	}

	FUNC_EXIT_RC(rc);
}

static IoT_Error_t _aws_iot_mqtt_internal_readWrapper( AWS_IoT_Client *pClient, size_t offset, size_t size, Timer *pTimer, size_t * read_len ) {
    IoT_Error_t rc;
    int byteToRead;
    size_t byteRead = 0;

    byteToRead = ( offset + size ) - pClient->clientData.readBufIndex;

    if ( byteToRead > 0 )
    {
        rc = pClient->networkStack.read( &( pClient->networkStack ),
            pClient->clientData.readBuf + pClient->clientData.readBufIndex,
            (size_t)byteToRead,
            pTimer,
            &byteRead );
        pClient->clientData.readBufIndex += byteRead;

        /* refresh byte to read */
        byteToRead = ( offset + size ) - ((int)pClient->clientData.readBufIndex);
        *read_len = size - (size_t)byteToRead;
    }
    else
    {
        *read_len = size;
        rc = SUCCESS;
    }

    return rc;
}
static IoT_Error_t _aws_iot_mqtt_internal_decode_packet_remaining_len(AWS_IoT_Client *pClient, size_t * offset,
																	  size_t *rem_len, Timer *pTimer) {
	size_t multiplier, len;
	IoT_Error_t rc;
    size_t read_len;

	FUNC_ENTRY;

	multiplier = 1;
	len = 0;
	*rem_len = 0;

	do {
		if(++len > MAX_NO_OF_REMAINING_LENGTH_BYTES) {
			/* bad data */
			FUNC_EXIT_RC(MQTT_DECODE_REMAINING_LENGTH_ERROR);
		}
        rc = _aws_iot_mqtt_internal_readWrapper( pClient, len, 1, pTimer, &read_len );

		if(SUCCESS != rc) {
			FUNC_EXIT_RC(rc);
		}

		*rem_len += (( pClient->clientData.readBuf[len] & 127) * multiplier);
		multiplier *= 128;
	} while(( pClient->clientData.readBuf[len] & 128) != 0);
    *offset = len + 1;
	FUNC_EXIT_RC(rc);
}

static IoT_Error_t _aws_iot_mqtt_internal_read_packet(AWS_IoT_Client *pClient, Timer *pTimer, uint8_t *pPacketType) {
	size_t rem_len, total_bytes_read, bytes_to_be_read, read_len;
	IoT_Error_t rc;
    size_t offset = 0;
	MQTTHeader header = {0};
	Timer packetTimer;
	init_timer(&packetTimer);
	countdown_ms(&packetTimer, pClient->clientData.packetTimeoutMs);

	rem_len = 0;
	total_bytes_read = 0;
	bytes_to_be_read = 0;
	read_len = 0;

    rc = _aws_iot_mqtt_internal_readWrapper( pClient, offset, 1, pTimer, &read_len );
	/* 1. read the header byte.  This has the packet type in it */
	if(NETWORK_SSL_NOTHING_TO_READ == rc) {
		return MQTT_NOTHING_TO_READ;
	} else if(SUCCESS != rc) {
		return rc;
	}

	/* 2. read the remaining length.  This is variable in itself */
	rc = _aws_iot_mqtt_internal_decode_packet_remaining_len(pClient, &offset, &rem_len, pTimer);
	if(SUCCESS != rc) {
		return rc;
	}

	/* if the buffer is too short then the message will be dropped silently */
	if((rem_len + offset) >= pClient->clientData.readBufSize) {
		bytes_to_be_read = pClient->clientData.readBufSize;
		do {
			rc = pClient->networkStack.read(&(pClient->networkStack), pClient->clientData.readBuf, bytes_to_be_read,
											pTimer, &read_len);
			if(SUCCESS == rc) {
				total_bytes_read += read_len;
				if((rem_len - total_bytes_read) >= pClient->clientData.readBufSize) {
					bytes_to_be_read = pClient->clientData.readBufSize;
				} else {
					bytes_to_be_read = rem_len - total_bytes_read;
				}
			}
		} while(total_bytes_read < rem_len && SUCCESS == rc);

        /* Check buffer was correctly emptied, otherwise, return error message. */
        if ( total_bytes_read == rem_len )
        {
            aws_iot_mqtt_internal_flushBuffers( pClient );
            return MQTT_RX_BUFFER_TOO_SHORT_ERROR;
        }
        else
        {
            return rc;
        }
	}

	/* 3. read the rest of the buffer using a callback to supply the rest of the data */
	if(rem_len > 0) {
        rc = _aws_iot_mqtt_internal_readWrapper( pClient, offset, rem_len, pTimer, &read_len );
		if(SUCCESS != rc || read_len != rem_len) {
			return FAILURE;
		}
	}

    /* Pack has been received, we can flush the buffers for next call. */
    aws_iot_mqtt_internal_flushBuffers( pClient );
	header.byte = pClient->clientData.readBuf[0];
	*pPacketType = MQTT_HEADER_FIELD_TYPE(header.byte);

	FUNC_EXIT_RC(rc);
}

// assume topic filter and name is in correct format
// # can only be at end
// + and # can only be next to separator
static bool _aws_iot_mqtt_internal_is_topic_matched(char *pTopicFilter, char *pTopicName, uint16_t topicNameLen) {

	char *curf, *curn, *curn_end;

	if(NULL == pTopicFilter || NULL == pTopicName) {
		return false;
	}

	curf = pTopicFilter;
	curn = pTopicName;
	curn_end = curn + topicNameLen;

	while(*curf && (curn < curn_end)) {
		if(*curn == '/' && *curf != '/') {
			break;
		}
		if(*curf != '+' && *curf != '#' && *curf != *curn) {
			break;
		}
		if(*curf == '+') {
			/* skip until we meet the next separator, or end of string */
			char *nextpos = curn + 1;
			while(nextpos < curn_end && *nextpos != '/')
				nextpos = ++curn + 1;
		} else if(*curf == '#') {
			/* skip until end of string */
			curn = curn_end - 1;
		}

		curf++;
		curn++;
	};

	return (curn == curn_end) && (*curf == '\0');
}

static IoT_Error_t _aws_iot_mqtt_internal_deliver_message(AWS_IoT_Client *pClient, char *pTopicName,
														  uint16_t topicNameLen,
														  IoT_Publish_Message_Params *pMessageParams) {
	uint32_t itr;
	IoT_Error_t rc;
	ClientState clientState;

	FUNC_ENTRY;

	if(NULL == pTopicName) {
		FUNC_EXIT_RC(NULL_VALUE_ERROR);
	}

	/* This function can be called from all MQTT APIs
	 * But while callback return is in progress, Yield should not be called.
	 * The state for CB_RETURN accomplishes that, as yield cannot be called while in that state */
	clientState = aws_iot_mqtt_get_client_state(pClient);
	aws_iot_mqtt_set_client_state(pClient, clientState, CLIENT_STATE_CONNECTED_WAIT_FOR_CB_RETURN);

	/* Find the right message handler - indexed by topic */
	for(itr = 0; itr < AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS; ++itr) {
		if(NULL != pClient->clientData.messageHandlers[itr].topicName) {
			if(((topicNameLen == pClient->clientData.messageHandlers[itr].topicNameLen)
				&&
				(strncmp(pTopicName, (char *) pClient->clientData.messageHandlers[itr].topicName, topicNameLen) == 0))
			   || _aws_iot_mqtt_internal_is_topic_matched((char *) pClient->clientData.messageHandlers[itr].topicName,
														  pTopicName, topicNameLen)) {
				if(NULL != pClient->clientData.messageHandlers[itr].pApplicationHandler) {
					pClient->clientData.messageHandlers[itr].pApplicationHandler(pClient, pTopicName, topicNameLen,
																				 pMessageParams,
																				 pClient->clientData.messageHandlers[itr].pApplicationHandlerData);
				}
			}
		}
	}
	rc = aws_iot_mqtt_set_client_state(pClient, CLIENT_STATE_CONNECTED_WAIT_FOR_CB_RETURN, clientState);

	FUNC_EXIT_RC(rc);
}

static IoT_Error_t _aws_iot_mqtt_internal_handle_publish(AWS_IoT_Client *pClient, Timer *pTimer) {
	char *topicName;
	uint16_t topicNameLen;
	uint32_t len;
	IoT_Error_t rc;
	IoT_Publish_Message_Params msg;

	FUNC_ENTRY;

	topicName = NULL;
	topicNameLen = 0;
	len = 0;

	rc = aws_iot_mqtt_internal_deserialize_publish(&msg.isDup, &msg.qos, &msg.isRetained,
												   &msg.id, &topicName, &topicNameLen,
												   (unsigned char **) &msg.payload, &msg.payloadLen,
												   pClient->clientData.readBuf,
												   pClient->clientData.readBufSize);

	if(SUCCESS != rc) {
		FUNC_EXIT_RC(rc);
	}

	rc = _aws_iot_mqtt_internal_deliver_message(pClient, topicName, topicNameLen, &msg);
	if(SUCCESS != rc) {
		FUNC_EXIT_RC(rc);
	}

	if(QOS0 == msg.qos) {
		/* No further processing required for QoS0 */
		FUNC_EXIT_RC(SUCCESS);
	}

	/* Message assumed to be QoS1 since we do not support QoS2 at this time */
	rc = aws_iot_mqtt_internal_serialize_ack(pClient->clientData.writeBuf, pClient->clientData.writeBufSize,
											 PUBACK, 0, msg.id, &len);

	if(SUCCESS != rc) {
		FUNC_EXIT_RC(rc);
	}

	rc = aws_iot_mqtt_internal_send_packet(pClient, len, pTimer);
	if(SUCCESS != rc) {
		FUNC_EXIT_RC(rc);
	}

	FUNC_EXIT_RC(SUCCESS);
}

IoT_Error_t aws_iot_mqtt_internal_cycle_read(AWS_IoT_Client *pClient, Timer *pTimer, uint8_t *pPacketType) {
	IoT_Error_t rc;

#ifdef _ENABLE_THREAD_SUPPORT_
	IoT_Error_t threadRc;
#endif

	if(NULL == pClient || NULL == pTimer) {
		return NULL_VALUE_ERROR;
	}

#ifdef _ENABLE_THREAD_SUPPORT_
	threadRc = aws_iot_mqtt_client_lock_mutex(pClient, &(pClient->clientData.tls_read_mutex));
	if(SUCCESS != threadRc) {
		FUNC_EXIT_RC(threadRc);
	}
#endif

	/* read the socket, see what work is due */
	rc = _aws_iot_mqtt_internal_read_packet(pClient, pTimer, pPacketType);

#ifdef _ENABLE_THREAD_SUPPORT_
	threadRc = aws_iot_mqtt_client_unlock_mutex(pClient, &(pClient->clientData.tls_read_mutex));
	if(SUCCESS != threadRc && (MQTT_NOTHING_TO_READ == rc || SUCCESS == rc)) {
		return threadRc;
	}
#endif

	if(MQTT_NOTHING_TO_READ == rc) {
		/* Nothing to read, not a cycle failure */
		return SUCCESS;
	} else if(SUCCESS != rc) {
		return rc;
	}

	switch(*pPacketType) {
		case CONNACK:
		case PUBACK:
		case SUBACK:
		case UNSUBACK:
			/* SDK is blocking, these responses will be forwarded to calling function to process */
			break;
		case PUBLISH: {
			rc = _aws_iot_mqtt_internal_handle_publish(pClient, pTimer);
			break;
		}
		case PUBREC:
		case PUBCOMP:
			/* QoS2 not supported at this time */
			break;
		case PINGRESP: {
			pClient->clientStatus.isPingOutstanding = 0;
			countdown_sec(&pClient->pingTimer, pClient->clientData.keepAliveInterval);
			break;
		}
		default: {
			/* Either unknown packet type or Failure occurred
             * Should not happen */
			rc = MQTT_RX_MESSAGE_PACKET_TYPE_INVALID_ERROR;
			break;
		}
	}

	return rc;
}

IoT_Error_t aws_iot_mqtt_internal_flushBuffers( AWS_IoT_Client *pClient ) {
    pClient->clientData.readBufIndex = 0;
    return SUCCESS;
}

/* only used in single-threaded mode where one command at a time is in process */
IoT_Error_t aws_iot_mqtt_internal_wait_for_read(AWS_IoT_Client *pClient, uint8_t packetType, Timer *pTimer) {
	IoT_Error_t rc;
	uint8_t read_packet_type;

	FUNC_ENTRY;
	if(NULL == pClient || NULL == pTimer) {
		FUNC_EXIT_RC(NULL_VALUE_ERROR);
	}

	read_packet_type = 0;
	do {
		if(has_timer_expired(pTimer)) {
			/* we timed out */
			rc = MQTT_REQUEST_TIMEOUT_ERROR;
			break;
		}
		rc = aws_iot_mqtt_internal_cycle_read(pClient, pTimer, &read_packet_type);
	} while(((SUCCESS == rc) || (MQTT_NOTHING_TO_READ == rc)) && (read_packet_type != packetType));

	/* If rc is SUCCESS, we have received the expected
	 * MQTT packet. Otherwise rc tells the error. */
	FUNC_EXIT_RC(rc);
}

/**
  * Serializes a 0-length packet into the supplied buffer, ready for writing to a socket
  * @param buf the buffer into which the packet will be serialized
  * @param buflen the length in bytes of the supplied buffer, to avoid overruns
  * @param packettype the message type
  * @param serialized length
  * @return IoT_Error_t indicating function execution status
  */
IoT_Error_t aws_iot_mqtt_internal_serialize_zero(unsigned char *pTxBuf, size_t txBufLen, MessageTypes packetType,
												 size_t *pSerializedLength) {
	unsigned char *ptr;
	IoT_Error_t rc;
	MQTTHeader header = {0};

	FUNC_ENTRY;
	if(NULL == pTxBuf || NULL == pSerializedLength) {
		FUNC_EXIT_RC(NULL_VALUE_ERROR);
	}

	/* Buffer should have at least 2 bytes for the header */
	if(4 > txBufLen) {
		FUNC_EXIT_RC(MQTT_TX_BUFFER_TOO_SHORT_ERROR);
	}

	ptr = pTxBuf;

	rc = aws_iot_mqtt_internal_init_header(&header, packetType, QOS0, 0, 0);
	if(SUCCESS != rc) {
		FUNC_EXIT_RC(rc);
	}

	/* write header */
	aws_iot_mqtt_internal_write_char(&ptr, header.byte);

	/* write remaining length */
	ptr += aws_iot_mqtt_internal_write_len_to_buffer(ptr, 0);
	*pSerializedLength = (uint32_t) (ptr - pTxBuf);

	FUNC_EXIT_RC(SUCCESS);
}

#ifdef __cplusplus
}
#endif


<?php

require __DIR__ . '/../src/ControlClient.php';
require __DIR__ . '/../src/TorCurlWrapper.php';

// list of country codes to use
$countries = array('US', 'FR', 'RU', 'GB', 'CA');

// get new control client for connecting to Tor's control port
$tc = new Dapphp\TorUtils\ControlClient();

$tc->connect(); // connect
$tc->authenticate('password'); // authenticate

foreach($countries as $country) {
    $country = '{' . $country . '}'; // e.g. {US}

    $tc->setConf(array('ExitNodes' => $country)); // set config to use exit node from country

    // get new curl wrapped through Tor SOCKS5 proxy
    $curl = new Dapphp\TorUtils\TorCurlWrapper();
    $curl->setopt(CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:41.0) Gecko/20100101 Firefox 41.0');

    // make request - should go through exit node from specified country
    if ($curl->httpGet('http://whatismycountry.com')) {
        echo $curl->getResponseBody();
    }
}


using namespace fs;

TEST_SUITE(recursive_directory_iterator_depth_tests)

TEST_CASE(test_depth)
{
    const path testDir = StaticEnv::Dir;
    const path DirDepth1 = StaticEnv::Dir2;
    const path DirDepth2 = StaticEnv::Dir3;
    const recursive_directory_iterator endIt{};

    std::error_code ec;
    recursive_directory_iterator it(testDir, ec);
    TEST_REQUIRE(!ec);
    TEST_CHECK(it.depth() == 0);

    bool seen_d1, seen_d2;
    seen_d1 = seen_d2 = false;

    while (it != endIt) {
        const path entry = *it;
        const path parent = entry.parent_path();
        if (parent == testDir) {
            TEST_CHECK(it.depth() == 0);
        } else if (parent == DirDepth1) {
            TEST_CHECK(it.depth() == 1);
            seen_d1 = true;
        } else if (parent == DirDepth2) {
            TEST_CHECK(it.depth() == 2);
            seen_d2 = true;
        } else {
            TEST_CHECK(!"Unexpected depth while iterating over static env");
        }
        ++it;
    }
    TEST_REQUIRE(seen_d1 && seen_d2);
    TEST_CHECK(it == endIt);
}

TEST_SUITE_END()


describe ManageIQ::Providers::AnsibleRoleWorkflow do
  let(:job)          { described_class.create_job(*options).tap { |job| job.state = state } }
  let(:role_options) { {:role_name => 'role_name', :roles_path => 'path/role', :role_skip_facts => true } }
  let(:options)      { [{"ENV" => "VAR"}, {"arg1" => "val1"}, role_options, {:verbosity => 4}] }
  let(:state)        { "waiting_to_start" }

  context ".create_job" do
    it "leaves job waiting to start" do
      expect(job.state).to eq("waiting_to_start")
    end
  end

  context ".signal" do
    %w[start pre_execute execute poll_runner post_execute finish abort_job cancel error].each do |signal|
      shared_examples_for "allows #{signal} signal" do
        it signal.to_s do
          expect(job).to receive(signal.to_sym)
          job.signal(signal.to_sym)
        end
      end
    end

    %w[start pre_execute execute poll_runner post_execute].each do |signal|
      shared_examples_for "doesn't allow #{signal} signal" do
        it signal.to_s do
          expect { job.signal(signal.to_sym) }.to raise_error(RuntimeError, /#{signal} is not permitted at state #{job.state}/)
        end
      end
    end

    context "waiting_to_start" do
      let(:state) { "waiting_to_start" }

      it_behaves_like "allows start signal"
      it_behaves_like "allows finish signal"
      it_behaves_like "allows abort_job signal"
      it_behaves_like "allows cancel signal"
      it_behaves_like "allows error signal"

      it_behaves_like "doesn't allow execute signal"
      it_behaves_like "doesn't allow poll_runner signal"
      it_behaves_like "doesn't allow post_execute signal"
    end

    context "per_role" do
      let(:state) { "pre_execute" }

      it_behaves_like "allows execute signal"
      it_behaves_like "allows finish signal"
      it_behaves_like "allows abort_job signal"
      it_behaves_like "allows cancel signal"
      it_behaves_like "allows error signal"

      it_behaves_like "doesn't allow start signal"
      it_behaves_like "doesn't allow poll_runner signal"
      it_behaves_like "doesn't allow post_execute signal"
    end

    context "running" do
      let(:state) { "running" }

      it_behaves_like "allows poll_runner signal"
      it_behaves_like "allows finish signal"
      it_behaves_like "allows abort_job signal"
      it_behaves_like "allows cancel signal"
      it_behaves_like "allows error signal"

      it_behaves_like "doesn't allow start signal"
      it_behaves_like "doesn't allow pre_execute signal"
    end

    context "post_execute" do
      let(:state) { "post_execute" }

      it_behaves_like "allows finish signal"
      it_behaves_like "allows abort_job signal"
      it_behaves_like "allows cancel signal"
      it_behaves_like "allows error signal"

      it_behaves_like "doesn't allow start signal"
      it_behaves_like "doesn't allow pre_execute signal"
      it_behaves_like "doesn't allow execute signal"
      it_behaves_like "doesn't allow poll_runner signal"
      it_behaves_like "doesn't allow post_execute signal"
    end
  end

  context ".execute" do
    let(:state) { "pre_execute" }
    let(:response_async) { Ansible::Runner::ResponseAsync.new(:base_dir => "/path/to/results") }

    it "ansible-runner succeeds" do
      response_async = Ansible::Runner::ResponseAsync.new(:base_dir => "/path/to/results")
      runner_options = [
        {"ENV" => "VAR"},
        {"arg1" => "val1"},
        "role_name",
        {
          :roles_path      => "path/role",
          :role_skip_facts => true
        }
      ]

      expect(Ansible::Runner).to receive(:run_role_async).with(*runner_options).and_return(response_async)
      expect(job).to receive(:queue_signal).with(:poll_runner)

      job.signal(:execute)

      expect(job.context[:ansible_runner_response]).to eq(response_async.dump)
    end

    it "ansible-runner fails" do
      expect(Ansible::Runner).to receive(:run_role_async).and_return(nil)
      expect(job).to receive(:queue_signal).with(:abort, "Failed to run ansible role", "error")

      job.signal(:execute)
    end
  end

  context "#current_job_timeout" do
    it "sets the job current timeout" do
      expect(job.current_job_timeout).to eq(1.hour)
    end
  end

  context ".poll_runner" do
    let(:state)          { "running" }
    let(:response_async) { Ansible::Runner::ResponseAsync.new(:base_dir => "/path/to/results") }

    before do
      allow(Ansible::Runner::ResponseAsync).to receive(:new).and_return(response_async)

      job.context[:ansible_runner_response] = response_async.dump
      job.started_on = Time.now.utc
      job.save!
    end

    it "ansible-runner completed" do
      expect(response_async).to receive(:running?).and_return(false)

      response = Ansible::Runner::Response.new(response_async.dump.merge(:return_code => 0))
      expect(response_async).to receive(:response).and_return(response)
      expect(job).to receive(:queue_signal).with(:post_execute)

      job.signal(:poll_runner)
    end

    it "ansible-runner still running" do
      now = Time.now.utc
      allow(Time).to receive(:now).and_return(now)
      expect(response_async).to receive(:running?).and_return(true)
      expect(job).to receive(:queue_signal).with(:poll_runner, :deliver_on => now + 1.second)

      job.signal(:poll_runner)
    end

    it "fails if the role has been running too long" do
      time = job.started_on + job.options[:timeout] + 5.minutes

      Timecop.travel(time) do
        expect(response_async).to receive(:running?).and_return(true)
        expect(response_async).to receive(:stop)
        expect(job).to receive(:queue_signal).with(:abort, "ansible role has been running longer than timeout", "error")

        job.signal(:poll_runner)
      end
    end

    context ".deliver_on" do
      let(:options) { [{"ENV" => "VAR"}, {"arg1" => "val1"}, {:roles_path => "/path/to/role"}, :poll_interval => 5.minutes] }

      it "uses the option to queue poll_runner" do
        now = Time.now.utc
        allow(Time).to receive(:now).and_return(now)
        expect(response_async).to receive(:running?).and_return(true)
        expect(job).to receive(:queue_signal).with(:poll_runner, :deliver_on => now + 5.minutes)

        job.signal(:poll_runner)
      end
    end
  end
end


package com.google.javascript.jscomp;

import static com.google.javascript.jscomp.AstFactory.type;
import static com.google.javascript.jscomp.Es6ToEs3Util.cannotConvertYet;

import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
import com.google.javascript.jscomp.parsing.parser.FeatureSet;
import com.google.javascript.jscomp.parsing.parser.FeatureSet.Feature;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;

/** Transpiles away `new.target`. */
final class RewriteNewDotTarget implements CompilerPass {
  private static final FeatureSet TRANSPILED_FEATURES =
      FeatureSet.BARE_MINIMUM.with(Feature.NEW_TARGET);

  private final AbstractCompiler compiler;
  private final AstFactory astFactory;

  RewriteNewDotTarget(AbstractCompiler compiler) {
    this.compiler = compiler;
    this.astFactory = compiler.createAstFactory();
  }

  private class RewriteNewDotTargetCallback extends AbstractPostOrderCallback {
    @Override
    public void visit(NodeTraversal t, Node n, Node parent) {
      if (n.getToken() == Token.NEW_TARGET) {
        final Node enclosingNonArrowFunction = NodeUtil.getEnclosingNonArrowFunction(n);
        if (enclosingNonArrowFunction != null
            && NodeUtil.isEs6Constructor(enclosingNonArrowFunction)) {
          // Within an ES6 class constructor that we're about to transpile.
          // `new.target` -> `this.constructor`
          Node enclosingClass = enclosingNonArrowFunction.getParent().getGrandparent();
          n.replaceWith(
              astFactory
                  .createGetProp(
                      astFactory.createThisForEs6Class(enclosingClass), "constructor", type(n))
                  .srcrefTree(n));
          t.reportCodeChange();
        } else {
          // Getting new.target correct in functions other than transpiled ES6 class constructors
          // requires determining whether the function was called with `new` or not, which is more
          // hassle than its worth. There's no good reason to use `new.target` in such places
          // anyway.
          cannotConvertYet(compiler, n, "new.target");
        }
      }
    }
  }

  @Override
  public void process(Node externs, Node root) {
    TranspilationPasses.processTranspile(
        compiler, root, TRANSPILED_FEATURES, new RewriteNewDotTargetCallback());
    TranspilationPasses.maybeMarkFeaturesAsTranspiledAway(compiler, TRANSPILED_FEATURES);
  }
}


# generated vars
$packageName = 'keepass.portable'
$url = 'https://sourceforge.net/projects/keepass/files/KeePass%202.x/2.38/KeePass-2.38.zip'
$checksum = 'DB71CBA72C321ECAEDA7EEC6F4E71E215864D4113AB9E29DC97AD4D56C80A7A9'

# static vars
$checksumType = 'sha256'
$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"

# $Env:ChocolateyInstall\helpers\functions
Install-ChocolateyZipPackage -PackageName "$packageName" `
                             -Url "$url" `
                             -UnzipLocation "$toolsDir" `
                             -Checksum "$checksum" `
                             -ChecksumType "$checksumType"

# create empty sidecar so shimgen creates shim for GUI rather than console
$installFile = Join-Path -Path $toolsDir `
                         -ChildPath "KeePass.exe.gui"
Set-Content -Path $installFile `
            -Value $null


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 1.0 Transitional//EN">

        <META http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="stylesheet" href="../includes/main.css" type="text/css">
        <link rel="shortcut icon" href="../favicon.ico" type="image/x-icon">
        <title>Apache CloudStack | The Power Behind Your Cloud</title>

						Apache CloudStack 4.15.0.0 Root Admin API Reference

createCondition

Creates a condition

Request parameters

                                            Parameter Name	Description	Required

                                            counterid	ID of the Counter.	true

                                            relationaloperator	Relational Operator to be used with threshold.	true

                                            threshold	Threshold value.	true

                                            account	the account of the condition. Must be used with the domainId parameter.	false

                                            domainid	the domain ID of the account.	false

Response Tags

                                            Response Name	Description

                                            id	the id of the Condition

                                            account	the owner of the Condition.

                                            counter	Details of the Counter.

                                            domain	the domain name of the owner.

                                            domainid	the domain id of the Condition owner

                                            project	the project name of the Condition

                                            projectid	the project id of the Condition.

                                            relationaloperator	Relational Operator to be used with threshold.

                                            threshold	Threshold Value for the counter.

                                            zoneid	zone id of counter

                            Copyright © 2015 The Apache Software Foundation, Licensed under the
                   Apache License, Version 2.0.

                                            Apache, CloudStack, Apache CloudStack, the Apache CloudStack logo, the CloudMonkey logo  and the Apache feather logo are trademarks of The Apache Software Foundation.


{% extends "xblog/blog_base.html" %}
{% block maincontent %}
<form action="" method="post">{% csrf_token %}
        <button type="submit">Save</button>
</form>

{% endblock %}


package com.ezweather.app.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ezweather.app.R;
import com.ezweather.app.model.City;
import com.ezweather.app.model.County;
import com.ezweather.app.db.EzWeatherDB;
import com.ezweather.app.model.Province;
import com.ezweather.app.util.HttpCallbackListener;
import com.ezweather.app.util.HttpUtil;
import com.ezweather.app.util.Utility;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Oniros on 2016/4/8.
 */
public class ChooseAreaActivity extends Activity {

    public static final int LEVEL_PROVINCE = 0;
    public static final int LEVEL_CITY = 1;
    public static final int LEVEL_COUNTY = 2;

    private ProgressDialog progressDialog;
    private TextView titleText;
    private ListView listView;
    private ArrayAdapter<String> adapter;
    private EzWeatherDB ezWeatherDB;
    private List<String> dataList = new ArrayList<String>();
    /**
     * 省列表
     */
    private List<Province> provinceList;
    /**
     * 市列表
     */
    private List<City> cityList;
    /**
     * 县列表
     */
    private List<County> countyList;
    /**
     * 选中的省份
     */
    private Province selectedProvince;
    /**
     * 选中的城市
     */
    private City selectedCity;
    /**
     * 当前选中的级别
     */
    private int currentLevel;
    /**
     * 是否从WeatherActivity中跳转过来。
     */
    private boolean isFromWeatherActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isFromWeatherActivity = getIntent().getBooleanExtra("from_weather_activity", false);
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        if (prefs.getBoolean("city_selected", false) && !isFromWeatherActivity) {
            Intent intent = new Intent(this, WeatherActivity.class);
            startActivity(intent);
            finish();
            return;
        }
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.choose_area);
        listView = (ListView) findViewById(R.id.list_view);
        titleText = (TextView) findViewById(R.id.title_text);
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataList);
        listView.setAdapter(adapter);
        ezWeatherDB = EzWeatherDB.getInstance(this);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int index,
                                    long arg3) {
                if (currentLevel == LEVEL_PROVINCE) {
                    selectedProvince = provinceList.get(index);
                    queryCities();
                } else if (currentLevel == LEVEL_CITY) {
                    selectedCity = cityList.get(index);
                    queryCounties();
                } else if (currentLevel == LEVEL_COUNTY) {
                    String countyCode = countyList.get(index).getCountyCode();
                    Intent intent = new Intent(ChooseAreaActivity.this, WeatherActivity.class);
                    intent.putExtra("county_code", countyCode);
                    startActivity(intent);
                    finish();
                }
            }
        });
        queryProvinces();  // 加载省级数据
    }

    /**
     * 查询全国所有的省，优先从数据库查询，如果没有查询到再去服务器上查询。
     */
    private void queryProvinces() {
        provinceList =ezWeatherDB .loadProvince();
        if (provinceList.size() > 0) {
            dataList.clear();
            for (Province province : provinceList) {
                dataList.add(province.getProvinceName());
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            titleText.setText("中国");
            currentLevel = LEVEL_PROVINCE;
        } else {
            queryFromServer(null, "province");
        }
    }

    /**
     * 查询选中省内所有的市，优先从数据库查询，如果没有查询到再去服务器上查询。
     */
    private void queryCities() {
        cityList = ezWeatherDB.loadCities(selectedProvince.getId());
        if (cityList.size() > 0) {
            dataList.clear();
            for (City city : cityList) {
                dataList.add(city.getCityName());
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            titleText.setText(selectedProvince.getProvinceName());
            currentLevel = LEVEL_CITY;
        } else {
            queryFromServer(selectedProvince.getProvinceCode(), "city");
        }
    }

    /**
     * 查询选中市内所有的县，优先从数据库查询，如果没有查询到再去服务器上查询。
     */
    private void queryCounties() {
        countyList = ezWeatherDB.loadCounties(selectedCity.getId());
        if (countyList.size() > 0) {
            dataList.clear();
            for (County county : countyList) {
                dataList.add(county.getCountyName());
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            titleText.setText(selectedCity.getCityName());
            currentLevel = LEVEL_COUNTY;
        } else {
            queryFromServer(selectedCity.getCityCode(), "county");
        }
    }

    /**
     * 根据传入的代号和类型从服务器上查询省市县数据。
     */
    private void queryFromServer(final String code, final String type) {
        String address;
        if (!TextUtils.isEmpty(code)) {
            address = "http://www.weather.com.cn/data/list3/city" + code + ".xml";
        } else {
            address = "http://www.weather.com.cn/data/list3/city.xml";
        }
        showProgressDialog();
        HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                boolean result = false;
                if ("province".equals(type)) {
                    result = Utility.handleProvinceResponse(ezWeatherDB,
                            response);
                } else if ("city".equals(type)) {
                    result = Utility.handleCitiesResponse(ezWeatherDB,
                            response, selectedProvince.getId());
                } else if ("county".equals(type)) {
                    result = Utility.handleCountiesResponse(ezWeatherDB,
                            response, selectedCity.getId());
                }
                if (result) {
                    // 通过runOnUiThread()方法回到主线程处理逻辑
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            closeProgressDialog();
                            if ("province".equals(type)) {
                                queryProvinces();
                            } else if ("city".equals(type)) {
                                queryCities();
                            } else if ("county".equals(type)) {
                                queryCounties();
                            }
                        }
                    });
                }
            }

            @Override
            public void onError(Exception e) {
                // 通过runOnUiThread()方法回到主线程处理逻辑
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        closeProgressDialog();
                        Toast.makeText(ChooseAreaActivity.this,
                                "加载失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    /**
     * 显示进度对话框
     */
    private void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage("正在加载...");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }

    /**
     * 关闭进度对话框
     */
    private void closeProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    /**
     * 捕获Back按键，根据当前的级别来判断，此时应该返回市列表、省列表、还是直接退出。
     */
    @Override
    public void onBackPressed() {
        if (currentLevel == LEVEL_COUNTY) {
            queryCities();
        } else if (currentLevel == LEVEL_CITY) {
            queryProvinces();
        } else {
            if (isFromWeatherActivity) {
//                Intent intent = new Intent(this, WeatherActivity.class);
//                startActivity(intent);
            }
            finish();
        }
    }

}


namespace crashpad {

class ProcessReaderWin;

namespace internal {

class ExceptionSnapshotWin final : public ExceptionSnapshot {
 public:
  ExceptionSnapshotWin();
  ~ExceptionSnapshotWin() override;

  //! \brief Initializes the object.
  //!
  //! \param[in] process_reader A ProcessReader for the process that sustained
  //!     the exception.
  //! \param[in] thread_id The thread ID in which the exception occurred.
  //! \param[in] exception_pointers_address The address of an
  //!     `EXCEPTION_POINTERS` record in the target process, passed through from
  //!     the exception handler.
  //!
  //! \return `true` if the snapshot could be created, `false` otherwise with
  //!     an appropriate message logged.
  bool Initialize(ProcessReaderWin* process_reader,
                  DWORD thread_id,
                  WinVMAddress exception_pointers);

  // ExceptionSnapshot:

  const CPUContext* Context() const override;
  uint64_t ThreadID() const override;
  uint32_t Exception() const override;
  uint32_t ExceptionInfo() const override;
  uint64_t ExceptionAddress() const override;
  const std::vector<uint64_t>& Codes() const override;

 private:
#if defined(ARCH_CPU_X86_FAMILY)
  union {
    CPUContextX86 x86;
    CPUContextX86_64 x86_64;
  } context_union_;
#endif
  CPUContext context_;
  std::vector<uint64_t> codes_;
  uint64_t thread_id_;
  uint64_t exception_address_;
  uint32_t exception_flags_;
  DWORD exception_code_;
  InitializationStateDcheck initialized_;

  DISALLOW_COPY_AND_ASSIGN(ExceptionSnapshotWin);
};

}  // namespace internal
}  // namespace crashpad

#endif  // CRASHPAD_SNAPSHOT_WIN_EXCEPTION_SNAPSHOT_WIN_H_


/*
 * timeval.h    1.0 01/12/19
 *
 * Defines gettimeofday, timeval, etc. for Win32
 *
 * By Wu Yongwei
 *
 */

#ifndef _TIMEVAL_H
#define _TIMEVAL_H

#ifdef _WIN32

/* Modified to compile as ANSI C without include of windows.h
   If this gives problems with future Windows/MSC versions, then
   uncomment the USE_WINDOWS_H definition to switch back. */
/* #define USE_WINDOWS_H */
#ifdef USE_WINDOWS_H
    #define WIN32_LEAN_AND_MEAN
    #include <windows.h>
#else
#ifndef _INC_WINDOWS
    #define VOID void
    #define WINAPI __stdcall
    #define OUT
    #define WINBASEAPI

    typedef long LONG;
    typedef unsigned long DWORD;
    typedef __int64 LONGLONG;

    typedef struct _FILETIME {
        DWORD dwLowDateTime;
        DWORD dwHighDateTime;
    } FILETIME, *LPFILETIME;

    typedef union _LARGE_INTEGER {
        /* Removed unnamed struct,
           it is not ANSI C compatible*/
        /* struct {
            DWORD LowPart;
            LONG HighPart;
        }; */
        struct {
            DWORD LowPart;
            LONG HighPart;
        } u;
        LONGLONG QuadPart;
    } LARGE_INTEGER;

    WINBASEAPI VOID WINAPI
    GetSystemTimeAsFileTime(OUT LPFILETIME lpSystemTimeAsFileTime);
#endif /* _INC_WINDOWS */
#endif /* USE_WINDOWS_H */

#include <time.h>

#ifndef __GNUC__
#define EPOCHFILETIME (116444736000000000i64)
#else
#define EPOCHFILETIME (116444736000000000LL)
#endif

struct timeval {
    long tv_sec;        /* seconds */
    long tv_usec;  /* microseconds */
};

struct timezone {
    int tz_minuteswest; /* minutes W of Greenwich */
    int tz_dsttime;     /* type of dst correction */
};

__inline int gettimeofday(struct timeval *tv, struct timezone *tz)
{
    FILETIME        ft;
    LARGE_INTEGER   li;
    __int64         t;
    static int      tzflag;

    if (tv)
    {
        GetSystemTimeAsFileTime(&ft);

        /* The following two lines have been modified to use the named
           union member. Unnamed members are not ANSI C compatible. */
        li.u.LowPart  = ft.dwLowDateTime;
        li.u.HighPart = ft.dwHighDateTime;
        t  = li.QuadPart;       /* In 100-nanosecond intervals */
        t -= EPOCHFILETIME;     /* Offset to the Epoch time */
        t /= 10;                /* In microseconds */
        tv->tv_sec  = (long)(t / 1000000);
        tv->tv_usec = (long)(t % 1000000);
    }

    if (tz)
    {
        if (!tzflag)
        {
            _tzset();
            tzflag++;
        }
        tz->tz_minuteswest = _timezone / 60;
        tz->tz_dsttime = _daylight;
    }

    return 0;
}

#else  /* _WIN32 */

#include <sys/time.h>

#endif /* _WIN32 */

#endif /* _TIMEVAL_H */


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/poi_description_container"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical"
  android:visibility="visible"
  tools:visibility="visible">

  <TextView
    android:id="@+id/poi_description"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginEnd="@dimen/margin_base"
    android:layout_marginLeft="@dimen/margin_base"
    android:layout_marginRight="@dimen/margin_base"
    android:layout_marginStart="@dimen/margin_base"
    android:layout_marginTop="@dimen/margin_base"
    android:maxLength="2000"
    android:textAppearance="?android:attr/textAppearance"/>

  <TextView
    android:id="@+id/more_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="start|bottom"
    android:layout_marginEnd="@dimen/margin_base"
    android:layout_marginLeft="@dimen/margin_base"
    android:layout_marginRight="@dimen/margin_base"
    android:layout_marginStart="@dimen/margin_base"
    android:textAppearance="?android:attr/textAppearance"
    android:gravity="start|top"
    android:textColor="?attr/colorAccent"
    android:text="@string/category_desc_more"
    android:background="@android:color/transparent"/>
  <include
    layout="@layout/divider_horizontal"/>
</LinearLayout>


#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <arpa/inet.h>

#include <pcap.h>
#include <ccn/ccn.h>
#include <ccn/ccnd.h>

#define LLC_LENGTH 4
#define IP_OFFSET LLC_LENGTH
#define IP_ADDR_LENGTH 4
#define IP_HDR_LENGTH 20
#define IP_LENGTH_OFFSET IP_OFFSET + 2
#define IP_CHKSUM_OFFSET IP_OFFSET + 10
#define IP_SRC_ADDR_OFFSET IP_CHKSUM_OFFSET + 2
#define IP_DEST_ADDR_OFFSET IP_CHKSUM_OFFSET + IP_ADDR_LENGTH

#define UDP_OFFSET IP_OFFSET + IP_HDR_LENGTH
#define UDP_HDR_LENGTH 8
#define UDP_LENGTH_OFFSET UDP_OFFSET + 4
#define UDP_CHKSUM_OFFSET UDP_OFFSET + 6
#define DATA_OFFSET UDP_OFFSET + UDP_HDR_LENGTH
#define MAX_PACKET 65536
#define DEFAULT_SRC_PORT 55555
#define DEFAULT_DEST_PORT CCN_DEFAULT_UNICAST_PORT_NUMBER

static void
usage(const char *progname)
{
    fprintf(stderr,
            "%s <infile> [<infile> ...]\n"
            "   Reads ccnb blocks from one or more files, and writes them in pcap format\n"
            "   to stdout.\n"
            "   ccnb blocks can be generated by any of the other utility programs.\n",
            progname);
    exit(1);
}

static int
dump_udp_packet(pcap_dumper_t *dump_file,
                unsigned char *ip_src_addr, /*  ipv4, localhost if NULL */
                unsigned char *ip_dest_addr, /* localhost if NULL */
                unsigned short udp_src_port, /* 55555 if 0 */
                unsigned short udp_dest_port,
                const unsigned char *data, size_t data_len,  /* data; could be whole ccnb, could
                                                           just be contents */
                struct timeval *ts) { /* timing info */

    unsigned char pktbuf[MAX_PACKET];
    uint32_t llc_val = PF_INET; // in host byte order

    uint16_t nsrc_port = htons((0 == udp_src_port) ? DEFAULT_SRC_PORT : udp_src_port);
    uint16_t ndest_port = htons((0 == udp_dest_port) ? DEFAULT_DEST_PORT : udp_dest_port);
    uint16_t nudp_len = htons(data_len + UDP_HDR_LENGTH);
    uint16_t nip_len = htons(data_len + UDP_HDR_LENGTH + IP_HDR_LENGTH);

    size_t frame_len = data_len + UDP_HDR_LENGTH + IP_HDR_LENGTH + LLC_LENGTH;
    struct pcap_pkthdr pcap_header;

    const unsigned char ipHdr[] = {
        // IP header, localhost to localhost
        0x45, // IPv4, 20 byte header
        0x00, // diff serv field
        0x00, 0x00, // length -- UDP length + 20
        0x1a, 0x62, // identification
        0x00, // flags
        0x00, // fragment offset
        0x40, // TTL (64)
        0x11, // proto (UDP=11)
        0x00, 0x00, // ip checksum (calculate, or leave 0 for validation disabled)
        0x7f, 0x00, 0x00, 0x01, // source, localhost if not overwritten
        0x7f, 0x00, 0x00, 0x01 // dest, localhost if not overwritten
    };

    unsigned char udpHdr[UDP_HDR_LENGTH];
    memset(udpHdr, 0, UDP_HDR_LENGTH);

    memcpy(&pktbuf[0], (unsigned char *)&llc_val, LLC_LENGTH);
    memcpy(&pktbuf[IP_OFFSET], ipHdr, IP_HDR_LENGTH);
    memcpy(&pktbuf[IP_LENGTH_OFFSET], &nip_len, 2);
    if (NULL != ip_src_addr) {
        memcpy(&pktbuf[IP_SRC_ADDR_OFFSET], ip_src_addr, IP_ADDR_LENGTH);
    }
    if (NULL != ip_dest_addr) {
        memcpy(&pktbuf[IP_DEST_ADDR_OFFSET], ip_dest_addr, IP_ADDR_LENGTH);
    }

    memcpy(&pktbuf[UDP_OFFSET], &nsrc_port, sizeof(unsigned short));
    memcpy(&pktbuf[UDP_OFFSET + sizeof(unsigned short)], &ndest_port, sizeof(unsigned short));
    memcpy(&pktbuf[UDP_LENGTH_OFFSET], &nudp_len, sizeof(unsigned short));

    memcpy(&pktbuf[DATA_OFFSET], data, data_len);

    pcap_header.len = pcap_header.caplen = frame_len;
    if (NULL != ts) {
        pcap_header.ts.tv_sec = ts->tv_sec;
        pcap_header.ts.tv_usec = ts->tv_usec;
    }

    pcap_dump((unsigned char *)dump_file, &pcap_header, &pktbuf[0]);

    if (0 != pcap_dump_flush(dump_file)) {
        fprintf(stderr, "Error flushing pcap dump...\n");
        return -1;
    }
    return 0;
}

static int
process_test(pcap_dumper_t *pcap_out, int content_only,
             unsigned char *ip_src_addr, /*  ipv4, localhost if NULL */
             unsigned char *ip_dest_addr, /* localhost if NULL */
             unsigned short udp_src_port, /* 55555 if 0 */
             unsigned short udp_dest_port,
             unsigned char *data, size_t n)
{
    struct ccn_skeleton_decoder skel_decoder = {0};
    struct ccn_skeleton_decoder *d = &skel_decoder;
    struct ccn_parsed_ContentObject content;
    struct ccn_indexbuf *comps = ccn_indexbuf_create();
    const unsigned char * content_value;
    size_t content_length;
    int res = 0;
    size_t s;

retry:
    s = ccn_skeleton_decode(d, data, n);
    if (d->state < 0) {
        res = 1;
        fprintf(stderr, "error state %d after %d of %d chars\n",
                (int)d->state, (int)s, (int)n);
    } else if (s == 0) {
        fprintf(stderr, "nothing to do\n");
    } else {
        if (s < n) {
            if (!content_only) {
                if (dump_udp_packet(pcap_out, ip_src_addr, ip_dest_addr,
                                    udp_src_port, udp_dest_port, data, s, NULL) != 0) {
                    res = 2;
                }
            } else {
                if (ccn_parse_ContentObject(data, s, &content, comps) != 0) {
                    fprintf(stderr, "unable to parse content object\n");
                    res = 1;
                } else if (ccn_content_get_value(data, s, &content, &content_value, &content_length) != 0) {
                    fprintf(stderr, "unable to retrieve content value\n");
                    res = 1;
                } else if (dump_udp_packet(pcap_out, ip_src_addr, ip_dest_addr,
                                           udp_src_port, udp_dest_port,
                                           content_value, content_length, NULL) != 0) {
                    res = 2;
                }
            }
            /* fprintf(stderr, "resuming at index %d\n", (int)d->index); */
            data += s;
            n -= s;
            if (res != 0) {
                fprintf(stderr, "Error dumping content.\n");
                return res;
            }
            goto retry;
        }
        fprintf(stderr, "\n");
    }
    if (!CCN_FINAL_DSTATE(d->state)) {
        res = 1;
        fprintf(stderr, "incomplete state %d after %d of %d chars\n",
                (int)d->state, (int)s, (int)n);
    } else {
        if (!content_only) {
            if (dump_udp_packet(pcap_out, ip_src_addr, ip_dest_addr,
                                udp_src_port, udp_dest_port, data, s, NULL) != 0) {
                res = 2;
            }
        } else {
            if (ccn_parse_ContentObject(data, s, &content, comps) != 0) {
                fprintf(stderr, "unable to parse content object\n");
                res = 1;
            } else if (ccn_content_get_value(data, s, &content, &content_value, &content_length) != 0) {
                fprintf(stderr, "unable to retrieve content value\n");
                res = 1;
            } else if (dump_udp_packet(pcap_out, ip_src_addr, ip_dest_addr,
                                       udp_src_port, udp_dest_port, content_value, content_length, NULL) != 0) {
                res = 2;
            }
        }

        res = 1;
    }
    return(res);
}

static int
process_fd(pcap_dumper_t *pcap_out, int fd, int content_only,
           unsigned char *ip_src_addr, /*  ipv4, localhost if NULL */
           unsigned char *ip_dest_addr, /* localhost if NULL */
           unsigned short udp_src_port, /* 55555 if 0 */
           unsigned short udp_dest_port
    )
{
    unsigned char *buf;
    ssize_t len;
    struct stat s;
    int res = 0;

    res = fstat(fd, &s);
    len = s.st_size;
    buf = (unsigned char *)mmap((void *)NULL, len, PROT_READ, MAP_PRIVATE, fd, 0);
    if (buf == (void *)-1) return (1);
    fprintf(stderr, " <!-- input is %6lu bytes -->\n", (unsigned long)len);
    res |= process_test(pcap_out, content_only,
                        ip_src_addr, ip_dest_addr, udp_src_port, udp_dest_port,
                        buf, len);
    munmap((void *)buf, len);
    return(res);
}

int
main(int argc, char **argv)
{
    pcap_t *pcap = NULL;
    pcap_dumper_t *pcap_out = NULL;
    int fd;
    int i;
    int res = 0;

    if (argc < 2) {
        usage(argv[0]);
    }

    pcap = pcap_open_dead(DLT_NULL, MAX_PACKET);
    if (NULL == pcap) {
        fprintf(stderr, "Cannot open pcap descriptor!\n");
        exit(-1);
    }

    pcap_out = pcap_dump_open(pcap, "-");
    if (NULL == pcap_out) {
        fprintf(stderr, "Cannot open output stdout!\n");
        usage(argv[0]);
    }

    for (i = 1; argv[i] != 0; i++) {
        fprintf(stderr, "<!-- Processing %s -->\n", argv[i]);

        fd = open(argv[i], O_RDONLY);
        if (-1 == fd) {
            perror(argv[i]);
            return(1);
        }

        /* DKS -- eventually take IP addresses and ports from command line,
           as well as whether to dump only the ccn content. */
        res |= process_fd(pcap_out, fd, 0, NULL, NULL, 0, 0);
    }

    pcap_dump_close(pcap_out);
    pcap_close(pcap);
    return res;
}


<?php

namespace Google\Service\CloudSearch;

class PrivateMessageInfo extends \Google\Collection
{
  protected $collection_key = 'gsuiteIntegrationMetadata';
  protected $annotationsType = Annotation::class;
  protected $annotationsDataType = 'array';
  protected $attachmentsType = Attachment::class;
  protected $attachmentsDataType = 'array';
  protected $contextualAddOnMarkupType = GoogleChatV1ContextualAddOnMarkup::class;
  protected $contextualAddOnMarkupDataType = 'array';
  protected $gsuiteIntegrationMetadataType = GsuiteIntegrationMetadata::class;
  protected $gsuiteIntegrationMetadataDataType = 'array';
  /**
   * @var string
   */
  public $text;
  protected $userIdType = UserId::class;
  protected $userIdDataType = '';

  /**
   * @param Annotation[]
   */
  public function setAnnotations($annotations)
  {
    $this->annotations = $annotations;
  }
  /**
   * @return Annotation[]
   */
  public function getAnnotations()
  {
    return $this->annotations;
  }
  /**
   * @param Attachment[]
   */
  public function setAttachments($attachments)
  {
    $this->attachments = $attachments;
  }
  /**
   * @return Attachment[]
   */
  public function getAttachments()
  {
    return $this->attachments;
  }
  /**
   * @param GoogleChatV1ContextualAddOnMarkup[]
   */
  public function setContextualAddOnMarkup($contextualAddOnMarkup)
  {
    $this->contextualAddOnMarkup = $contextualAddOnMarkup;
  }
  /**
   * @return GoogleChatV1ContextualAddOnMarkup[]
   */
  public function getContextualAddOnMarkup()
  {
    return $this->contextualAddOnMarkup;
  }
  /**
   * @param GsuiteIntegrationMetadata[]
   */
  public function setGsuiteIntegrationMetadata($gsuiteIntegrationMetadata)
  {
    $this->gsuiteIntegrationMetadata = $gsuiteIntegrationMetadata;
  }
  /**
   * @return GsuiteIntegrationMetadata[]
   */
  public function getGsuiteIntegrationMetadata()
  {
    return $this->gsuiteIntegrationMetadata;
  }
  /**
   * @param string
   */
  public function setText($text)
  {
    $this->text = $text;
  }
  /**
   * @return string
   */
  public function getText()
  {
    return $this->text;
  }
  /**
   * @param UserId
   */
  public function setUserId(UserId $userId)
  {
    $this->userId = $userId;
  }
  /**
   * @return UserId
   */
  public function getUserId()
  {
    return $this->userId;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(PrivateMessageInfo::class, 'Google_Service_CloudSearch_PrivateMessageInfo');


package java.lang.constant;

import java.lang.invoke.CallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Stream;

import static java.lang.constant.ConstantDescs.CD_String;
import static java.lang.constant.ConstantUtils.EMPTY_CONSTANTDESC;
import static java.lang.constant.ConstantUtils.validateMemberName;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.joining;

/**
 * A nominal descriptor for an
 * {@code invokedynamic} call site.
 *
 *
Concrete subtypes of {@linkplain DynamicCallSiteDesc} should be immutable
 * and their behavior should not rely on object identity.
 *
 * @since 12
 */
public class DynamicCallSiteDesc {

    private final DirectMethodHandleDesc bootstrapMethod;
    private final ConstantDesc[] bootstrapArgs;
    private final String invocationName;
    private final MethodTypeDesc invocationType;

    /**
     * Creates a nominal descriptor for an {@code invokedynamic} call site.
     *
     * @param bootstrapMethod a {@link DirectMethodHandleDesc} describing the
     *                        bootstrap method for the {@code invokedynamic}
     * @param invocationName The unqualified name that would appear in the {@code NameAndType}
     *                       operand of the {@code invokedynamic}
     * @param invocationType a {@link MethodTypeDesc} describing the invocation
     *                       type that would appear in the {@code NameAndType}
     *                       operand of the {@code invokedynamic}
     * @param bootstrapArgs {@link ConstantDesc}s describing the static arguments
     *                      to the bootstrap, that would appear in the
     *                      {@code BootstrapMethods} attribute
     * @throws NullPointerException if any parameter or its contents are {@code null}
     * @throws IllegalArgumentException if the invocation name has the incorrect
     * format
     * @jvms 4.2.2 Unqualified Names
     */
    private DynamicCallSiteDesc(DirectMethodHandleDesc bootstrapMethod,
                                String invocationName,
                                MethodTypeDesc invocationType,
                                ConstantDesc[] bootstrapArgs) {
        this.invocationName = validateMemberName(requireNonNull(invocationName), true);
        this.invocationType = requireNonNull(invocationType);
        this.bootstrapMethod = requireNonNull(bootstrapMethod);
        this.bootstrapArgs = requireNonNull(bootstrapArgs.clone());
        for (int i = 0; i < this.bootstrapArgs.length; i++) {
            requireNonNull(this.bootstrapArgs[i]);
        }
        if (invocationName.length() == 0)
            throw new IllegalArgumentException("Illegal invocation name: " + invocationName);
    }

    /**
     * Creates a nominal descriptor for an {@code invokedynamic} call site.
     *
     * @param bootstrapMethod a {@link DirectMethodHandleDesc} describing the
     *                        bootstrap method for the {@code invokedynamic}
     * @param invocationName The unqualified name that would appear in the {@code NameAndType}
     *                       operand of the {@code invokedynamic}
     * @param invocationType a {@link MethodTypeDesc} describing the invocation
     *                       type that would appear in the {@code NameAndType}
     *                       operand of the {@code invokedynamic}
     * @param bootstrapArgs {@link ConstantDesc}s describing the static arguments
     *                      to the bootstrap, that would appear in the
     *                      {@code BootstrapMethods} attribute
     * @return the nominal descriptor
     * @throws NullPointerException if any parameter or its contents are {@code null}
     * @throws IllegalArgumentException if the invocation name has the incorrect
     * format
     * @jvms 4.2.2 Unqualified Names
     */
    public static DynamicCallSiteDesc of(DirectMethodHandleDesc bootstrapMethod,
                                         String invocationName,
                                         MethodTypeDesc invocationType,
                                         ConstantDesc... bootstrapArgs) {
        return new DynamicCallSiteDesc(bootstrapMethod, invocationName, invocationType, bootstrapArgs);
    }

    /**
     * Creates a nominal descriptor for an {@code invokedynamic} call site whose
     * bootstrap method has no static arguments.
     *
     * @param bootstrapMethod The bootstrap method for the {@code invokedynamic}
     * @param invocationName The invocationName that would appear in the
     * {@code NameAndType} operand of the {@code invokedynamic}
     * @param invocationType The invocation invocationType that would appear
     * in the {@code NameAndType} operand of the {@code invokedynamic}
     * @return the nominal descriptor
     * @throws NullPointerException if any parameter is null
     * @throws IllegalArgumentException if the invocation name has the incorrect
     * format
     */
    public static DynamicCallSiteDesc of(DirectMethodHandleDesc bootstrapMethod,
                                         String invocationName,
                                         MethodTypeDesc invocationType) {
        return new DynamicCallSiteDesc(bootstrapMethod, invocationName, invocationType, EMPTY_CONSTANTDESC);
    }

    /**
     * Creates a nominal descriptor for an {@code invokedynamic} call site whose
     * bootstrap method has no static arguments and for which the name parameter
     * is {@link ConstantDescs#DEFAULT_NAME}.
     *
     * @param bootstrapMethod a {@link DirectMethodHandleDesc} describing the
     *                        bootstrap method for the {@code invokedynamic}
     * @param invocationType a {@link MethodTypeDesc} describing the invocation
     *                       type that would appear in the {@code NameAndType}
     *                       operand of the {@code invokedynamic}
     * @return the nominal descriptor
     * @throws NullPointerException if any parameter is null
     */
    public static DynamicCallSiteDesc of(DirectMethodHandleDesc bootstrapMethod,
                                         MethodTypeDesc invocationType) {
        return of(bootstrapMethod, ConstantDescs.DEFAULT_NAME, invocationType);
    }

    /**
     * Returns a nominal descriptor for an {@code invokedynamic} call site whose
     * bootstrap method, name, and invocation type are the same as this one, but
     * with the specified bootstrap arguments.
     *
     * @param bootstrapArgs {@link ConstantDesc}s describing the static arguments
     *                      to the bootstrap, that would appear in the
     *                      {@code BootstrapMethods} attribute
     * @return the nominal descriptor
     * @throws NullPointerException if the argument or its contents are {@code null}
     */
    public DynamicCallSiteDesc withArgs(ConstantDesc... bootstrapArgs) {
        return new DynamicCallSiteDesc(bootstrapMethod, invocationName, invocationType, bootstrapArgs);
    }

    /**
     * Returns a nominal descriptor for an {@code invokedynamic} call site whose
     * bootstrap and bootstrap arguments are the same as this one, but with the
     * specified invocationName and invocation invocationType
     *
     * @param invocationName The unqualified name that would appear in the {@code NameAndType}
     *                       operand of the {@code invokedynamic}
     * @param invocationType a {@link MethodTypeDesc} describing the invocation
     *                       type that would appear in the {@code NameAndType}
     *                       operand of the {@code invokedynamic}
     * @return the nominal descriptor
     * @throws NullPointerException if any parameter is null
     * @throws IllegalArgumentException if the invocation name has the incorrect
     * format
     * @jvms 4.2.2 Unqualified Names
     */
    public DynamicCallSiteDesc withNameAndType(String invocationName,
                                               MethodTypeDesc invocationType) {
        return new DynamicCallSiteDesc(bootstrapMethod, invocationName, invocationType, bootstrapArgs);
    }

    /**
     * Returns the invocation name that would appear in the {@code NameAndType}
     * operand of the {@code invokedynamic}.
     *
     * @return the invocation name
     */
    public String invocationName() {
        return invocationName;
    }

    /**
     * Returns a {@link MethodTypeDesc} describing the invocation type that
     * would appear in the {@code NameAndType} operand of the {@code invokedynamic}.
     *
     * @return the invocation type
     */
    public MethodTypeDesc invocationType() {
        return invocationType;
    }

    /**
     * Returns a {@link MethodHandleDesc} describing the bootstrap method for
     * the {@code invokedynamic}.
     *
     * @return the bootstrap method for the {@code invokedynamic}
     */
    public MethodHandleDesc bootstrapMethod() { return bootstrapMethod; }

    /**
     * Returns {@link ConstantDesc}s describing the bootstrap arguments for the
     * {@code invokedynamic}. The returned array is always non-null. A zero
     * length array is returned if this {@linkplain DynamicCallSiteDesc} has no
     * bootstrap arguments.
     *
     * @return the bootstrap arguments for the {@code invokedynamic}
     */
    public ConstantDesc[] bootstrapArgs() { return bootstrapArgs.clone(); }

    /**
     * Reflectively invokes the bootstrap method with the specified arguments,
     * and return the resulting {@link CallSite}
     *
     * @param lookup The {@link MethodHandles.Lookup} used to resolve class names
     * @return the {@link CallSite}
     * @throws Throwable if any exception is thrown by the bootstrap method
     */
    public CallSite resolveCallSiteDesc(MethodHandles.Lookup lookup) throws Throwable {
        assert bootstrapMethod.invocationType().parameterType(1).equals(CD_String);
        MethodHandle bsm = (MethodHandle) bootstrapMethod.resolveConstantDesc(lookup);
        Object[] args = new Object[bootstrapArgs.length + 3];
        args[0] = lookup;
        args[1] = invocationName;
        args[2] = invocationType.resolveConstantDesc(lookup);
        System.arraycopy(bootstrapArgs, 0, args, 3, bootstrapArgs.length);
        return (CallSite) bsm.invokeWithArguments(args);
    }

    /**
     * Compares the specified object with this descriptor for equality.  Returns
     * {@code true} if and only if the specified object is also a
     * {@linkplain DynamicCallSiteDesc}, and both descriptors have equal
     * bootstrap methods, bootstrap argument lists, invocation name, and
     * invocation type.
     *
     * @param o the {@code DynamicCallSiteDesc} to compare to this
     *       {@code DynamicCallSiteDesc}
     * @return {@code true} if the specified {@code DynamicCallSiteDesc}
     *      is equal to this {@code DynamicCallSiteDesc}.
     */
    @Override
    public final boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        DynamicCallSiteDesc specifier = (DynamicCallSiteDesc) o;
        return Objects.equals(bootstrapMethod, specifier.bootstrapMethod) &&
               Arrays.equals(bootstrapArgs, specifier.bootstrapArgs) &&
               Objects.equals(invocationName, specifier.invocationName) &&
               Objects.equals(invocationType, specifier.invocationType);
    }

    @Override
    public final int hashCode() {
        int result = Objects.hash(bootstrapMethod, invocationName, invocationType);
        result = 31 * result + Arrays.hashCode(bootstrapArgs);
        return result;
    }

    /**
     * Returns a compact textual description of this call site description,
     * including the bootstrap method, the invocation name and type, and
     * the static bootstrap arguments.
     *
     * @return A compact textual description of this call site descriptor
     */
    @Override
    public String toString() {
        return String.format("DynamicCallSiteDesc[%s::%s(%s%s):%s]",
                             bootstrapMethod.owner().displayName(),
                             bootstrapMethod.methodName(),
                             invocationName.equals(ConstantDescs.DEFAULT_NAME) ? "" : invocationName + "/",
                             Stream.of(bootstrapArgs).map(Object::toString).collect(joining(",")),
                             invocationType.displayDescriptor());
    }
}


module("wrapper", package.seeall)
local json = require("cjson.safe")

-- by default, only call json lib for encoding and decoding

function encode(object)
	return json.encode(object)
end

function decode(object)
	return json.decode(object)
end


package pl.darknessNight.AutoUpdateLauncher;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPReply;

import java.io.IOException;
import java.io.OutputStream;

class LoginException extends RuntimeException{}

public class FTPClient {
    org.apache.commons.net.ftp.FTPClient ftpLowLevelClient = null;
    FTPClient(){
        ftpLowLevelClient =new org.apache.commons.net.ftp.FTPClient();
    }
    FTPClient(org.apache.commons.net.ftp.FTPClient client) {
        ftpLowLevelClient =client;
    }

    public void RetrieveDataToStreamFromUrl(String url, OutputStream stream) throws IOException{
        ConnectToServerFromUrl(url);
        String filename=getFilenameFromUrl(url);
        RetrieveFile(filename,stream);
        Disconnect();
    }

    private static String getFilenameFromUrl(String url){
        return new String();
    }

    public void ConnectToServerFromUrl(String url) throws IOException {
        String host=getHostFromUrl(url);
        String user=getUserFromUrl(url);
        String pass=getPassFromUrl(url);
        if(user.isEmpty())
            ConnectToServerAnonymousAndPrepareConnection(host);
        else
            ConnectToServerAndPrepareConnection(host,user,pass);
    }

    private static String getHostFromUrl(String url){
        return new String();
    }

    private static String getUserFromUrl(String url){
        return new String();
    }

    private static String getPassFromUrl(String url){
        return new String();
    }

    public void ConnectToServerAndPrepareConnection(String host, String user, String pwd) throws IOException {
        ConnectToServer(host);
        LoginToServer(user, pwd);
        PrepareConnection();
    }

    private void LoginToServer(String user, String pwd) throws IOException {
        if(!ftpLowLevelClient.login(user, pwd))
            throw new LoginException();
    }

    public void ConnectToServer(String host) throws IOException {
        int reply;
        ftpLowLevelClient.connect(host);
        reply = ftpLowLevelClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpLowLevelClient.disconnect();
            throw new IOException("Exception in connecting to FTP Server");
        }
    }

    public void ConnectToServerAnonymousAndPrepareConnection(String host) throws IOException {
        ConnectToServer(host);
        PrepareConnection();
    }

    private void PrepareConnection() throws IOException {
        ftpLowLevelClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpLowLevelClient.enterLocalPassiveMode();
    }

    public void RetrieveFile(String remoteFilePath, OutputStream stream) throws IOException {
        this.ftpLowLevelClient.retrieveFile(remoteFilePath, stream);
    }

    public void Disconnect() {
        if (ftpLowLevelClient.isConnected()) {
            try {
                ftpLowLevelClient.logout();
            } catch (IOException f) {
                //pass
            }
            try {
                ftpLowLevelClient.disconnect();
            } catch (IOException f) {
                //pass
            }
        }
    }
}


using System;
using System.Linq;
using System.Threading.Tasks;
using ECommon.Components;
using ECommon.Dapper;
using ECommon.IO;
using ECommon.Logging;
using ECommon.Utilities;
using ENode.Eventing;
using ENode.Infrastructure;
using MySql.Data.MySqlClient;

namespace ENode.MySQL
{
    public class MySqlPublishedVersionStore : IPublishedVersionStore
    {
        private const string EventSingleTableNameFormat = "`{0}`";
        private const string EventTableNameFormat = "`{0}_{1}`";

        #region Private Variables

        private string _connectionString;
        private string _tableName;
        private int _tableCount;
        private string _uniqueIndexName;
        private ILogger _logger;
        private ITimeProvider _timeProvider;
        private IOHelper _ioHelper;

        #endregion

        public MySqlPublishedVersionStore Initialize(string connectionString, string tableName = "PublishedVersion", int tableCount = 1, string uniqueIndexName = "IX_PublishedVersion_AggId_Version")
        {
            _connectionString = connectionString;
            _tableName = tableName;
            _tableCount = tableCount;
            _uniqueIndexName = uniqueIndexName;

            Ensure.NotNull(_connectionString, "_connectionString");
            Ensure.NotNull(_tableName, "_tableName");
            Ensure.Positive(_tableCount, "_tableCount");
            Ensure.NotNull(_uniqueIndexName, "_uniqueIndexName");

            _logger = ObjectContainer.Resolve<ILoggerFactory>().Create(GetType().FullName);
            _timeProvider = ObjectContainer.Resolve<ITimeProvider>();
            _ioHelper = ObjectContainer.Resolve<IOHelper>();

            return this;
        }
        public async Task UpdatePublishedVersionAsync(string processorName, string aggregateRootTypeName, string aggregateRootId, int publishedVersion)
        {
            await _ioHelper.TryIOActionAsync(async () =>
            {
                if (publishedVersion == 1)
                {
                    try
                    {
                        using (var connection = GetConnection())
                        {
                            var currentTime = _timeProvider.GetCurrentTime();
                            await connection.OpenAsync().ConfigureAwait(false);
                            await connection.InsertAsync(new
                            {
                                ProcessorName = processorName,
                                AggregateRootTypeName = aggregateRootTypeName,
                                AggregateRootId = aggregateRootId,
                                Version = 1,
                                CreatedOn = currentTime,
                                UpdatedOn = currentTime
                            }, GetTableName(aggregateRootId)).ConfigureAwait(false);
                        }
                    }
                    catch (MySqlException ex)
                    {
                        if (ex.Number == 1062 && ex.Message.Contains(_uniqueIndexName))
                        {
                            return;
                        }
                        var errorMessage = string.Format("Insert aggregate published version has sql exception, aggregateRootType: {0}, aggregateRootId: {1}", aggregateRootTypeName, aggregateRootId);
                        _logger.Error(errorMessage, ex);
                        throw;
                    }
                    catch (Exception ex)
                    {
                        var errorMessage = string.Format("Insert aggregate published version has unknown exception, aggregateRootType: {0}, aggregateRootId: {1}", aggregateRootTypeName, aggregateRootId);
                        _logger.Error(errorMessage, ex);
                        throw;
                    }
                }
                else
                {
                    try
                    {
                        using (var connection = GetConnection())
                        {
                            await connection.OpenAsync().ConfigureAwait(false);
                            await connection.UpdateAsync(
                            new
                            {
                                Version = publishedVersion,
                                UpdatedOn = _timeProvider.GetCurrentTime()
                            },
                            new
                            {
                                ProcessorName = processorName,
                                AggregateRootId = aggregateRootId,
                                Version = publishedVersion - 1
                            }, GetTableName(aggregateRootId)).ConfigureAwait(false);
                        }
                    }
                    catch (MySqlException ex)
                    {
                        var errorMessage = string.Format("Update aggregate published version has sql exception, aggregateRootType: {0}, aggregateRootId: {1}", aggregateRootTypeName, aggregateRootId);
                        _logger.Error(errorMessage, ex);
                        throw;
                    }
                    catch (Exception ex)
                    {
                        var errorMessage = string.Format("Update aggregate published version has unknown exception, aggregateRootType: {0}, aggregateRootId: {1}", aggregateRootTypeName, aggregateRootId);
                        _logger.Error(errorMessage, ex);
                        throw;
                    }
                }
            }, "UpdatePublishedVersionAsync");
        }
        public async Task<int> GetPublishedVersionAsync(string processorName, string aggregateRootTypeName, string aggregateRootId)
        {
            return await _ioHelper.TryIOFuncAsync(async () =>
            {
                try
                {
                    using (var connection = GetConnection())
                    {
                        await connection.OpenAsync().ConfigureAwait(false);
                        var result = await connection.QueryListAsync<int>(new
                        {
                            ProcessorName = processorName,
                            AggregateRootId = aggregateRootId
                        }, GetTableName(aggregateRootId), "Version").ConfigureAwait(false);
                        return result.SingleOrDefault();
                    }
                }
                catch (MySqlException ex)
                {
                    var errorMessage = string.Format("Get aggregate published version has sql exception, aggregateRootType: {0}, aggregateRootId: {1}", aggregateRootTypeName, aggregateRootId);
                    _logger.Error(errorMessage, ex);
                    throw;
                }
                catch (Exception ex)
                {
                    var errorMessage = string.Format("Get aggregate published version has unknown exception, aggregateRootType: {0}, aggregateRootId: {1}", aggregateRootTypeName, aggregateRootId);
                    _logger.Error(errorMessage, ex);
                    throw;
                }
            }, "GetPublishedVersionAsync");
        }

        private int GetTableIndex(string aggregateRootId)
        {
            int hash = 23;
            foreach (char c in aggregateRootId)
            {
                hash = (hash << 5) - hash + c;
            }
            if (hash < 0)
            {
                hash = Math.Abs(hash);
            }
            return hash % _tableCount;
        }
        private string GetTableName(string aggregateRootId)
        {
            if (_tableCount <= 1)
            {
                return string.Format(EventSingleTableNameFormat, _tableName);
            }

            var tableIndex = GetTableIndex(aggregateRootId);

            return string.Format(EventTableNameFormat, _tableName, tableIndex);
        }
        private MySqlConnection GetConnection()
        {
            return new MySqlConnection(_connectionString);
        }
    }
}


package com.wuyin.supermarket.httpresult;

import com.wuyin.supermarket.httpresult.base.BaseHttpRequest;
import com.wuyin.supermarket.model.AppInfo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yinlong on 2016/5/11.
 */
public class DetailHttpRequest extends BaseHttpRequest<AppInfo> {

    String packageName;

    public DetailHttpRequest(String packageName) {
        this.packageName = packageName;
    }

    @Override
    public AppInfo parseJson(String results) {

        try {
            JSONObject result = new JSONObject(results);
            String id = result.getString("id");
            String name = result.getString("name");
            String packageName = result.getString("packageName");
            String iconUrl = result.getString("iconUrl");
            float stars = result.getLong("stars");
            long size = result.getLong("size");
            String downLoadUrl = result.getString("downloadUrl");
            String des = result.getString("des");

            String downloadNum = result.getString("downloadNum");
            String version = result.getString("version");
            String date = result.getString("date");
            String author = result.getString("author");

            List<String> screen = new ArrayList<>();
            JSONArray screenArray = result.getJSONArray("screen");
            for (int i = 0; i < screenArray.length(); i++) {
                screen.add(screenArray.getString(i));
            }

            List<String> safeUrl = new ArrayList<>();
            List<String> safeDesUrl = new ArrayList<>();
            List<String> safeDes = new ArrayList<>();
            List<Integer> safeDesColor = new ArrayList<>();
            JSONArray safeUrlArray = result.getJSONArray("safe");
            for (int i = 0; i < safeUrlArray.length(); i++) {
                JSONObject jsonObject = safeUrlArray.getJSONObject(i);
                safeUrl.add(jsonObject.getString("safeUrl"));
                safeDesUrl.add(jsonObject.getString("safeDesUrl"));
                safeDes.add(jsonObject.getString("safeDes"));
                safeDesColor.add(jsonObject.getInt("safeDesColor"));
            }

            AppInfo appInfo = new AppInfo(id, name, packageName, iconUrl, stars, size, downLoadUrl, des,
                    downloadNum, version, date, author, screen,
                    safeUrl, safeDesUrl, safeDes, safeDesColor);

            return appInfo;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String getKey() {
        return "detail";
    }

    /**
     * 额外带的参数
     *
     * @return
     */
    @Override
    public String getParams() {
        return "&packageName=" + packageName;
    }
}


using System;

namespace Tasks
{
	public interface IConsole
	{
		string ReadLine();

		void Write(string format, params object[] args);

		void WriteLine(string format, params object[] args);

		void WriteLine();
	}
}


package business;

import business.category.CategoryDao;
import business.category.CategoryDaoGuava;
import business.category.CategoryDaoJdbc;
import business.category.CategoryService;
import business.category.DefaultCategoryService;
import business.customer.CustomerDao;
import business.customer.CustomerDaoJdbc;
import business.customer.CustomerService;
import business.customer.DefaultCustomerService;
import business.order.CustomerOrderDao;
import business.order.CustomerOrderDaoJdbc;
import business.order.CustomerOrderLineItemDao;
import business.order.CustomerOrderLineItemDaoJdbc;
import business.order.CustomerOrderService;
import business.order.DefaultCustomerOrderService;
import business.product.DefaultProductService;
import business.product.ProductDao;
import business.product.ProductDaoGuava;
import business.product.ProductDaoJdbc;
import business.product.ProductService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 */
public final class ApplicationContext {

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

    private ProductService productService;

    private CategoryService categoryService;

    private CustomerService customerService;

    private CustomerOrderService customerOrderService;

    private ScheduledExecutorService executorService;

    public static ApplicationContext INSTANCE = new ApplicationContext();

    private ApplicationContext() {

        executorService = new ScheduledThreadPoolExecutor(Runtime.getRuntime().availableProcessors());

        // wire up the business.dao layer "by hand"
        ProductDao productDao = new ProductDaoJdbc();

        ProductDaoGuava cachedProductDao = new ProductDaoGuava(productDao);

        productService = new DefaultProductService();
        ((DefaultProductService) productService).setProductDao(cachedProductDao);

        CategoryDao categoryDao = new CategoryDaoJdbc();

        CategoryDaoGuava cachedCategoryDao = new CategoryDaoGuava(categoryDao);

        categoryService = new DefaultCategoryService();
        ((DefaultCategoryService) categoryService).setCategoryDao(cachedCategoryDao);

        CustomerDao customerDao = new CustomerDaoJdbc();
        customerService = new DefaultCustomerService();
        ((DefaultCustomerService) customerService).setCustomerDao(customerDao);

        CustomerOrderLineItemDao customerOrderLineItemDao = new CustomerOrderLineItemDaoJdbc();
        CustomerOrderDao customerOrderDao = new CustomerOrderDaoJdbc();

        customerOrderService = new DefaultCustomerOrderService();
        DefaultCustomerOrderService service = (DefaultCustomerOrderService) customerOrderService;
        service.setProductDao(cachedProductDao);
        service.setCustomerService(customerService);
        service.setCustomerOrderDao(customerOrderDao);
        service.setCustomerOrderLineItemDao(customerOrderLineItemDao);

        executorService.scheduleWithFixedDelay(() -> {
                try {
                    logger.info("Refreshing category and product caches....commencing");
                    cachedCategoryDao.bulkload();
                    cachedProductDao.clear();
                    logger.info("Refreshing category and product caches....complete!");
                } catch (Throwable t) {
                    logger.error("Encountered trouble refreshing category and product caches.", t);
                }
            }, 10, 60, TimeUnit.MINUTES);
    }

    public ProductService getProductService() {
        return productService;
    }

    public CategoryService getCategoryService() {
        return categoryService;
    }

    public CustomerService getCustomerService() {
        return customerService;
    }

    public CustomerOrderService getCustomerOrderService() {
        return customerOrderService;
    }

    public void shutdown() {
        executorService.shutdown();
    }
}


package org.zstack.sdk.iam2.api;

import java.util.HashMap;
import java.util.Map;
import org.zstack.sdk.*;

public class AddAttributesToIAM2VirtualIDGroupAction extends AbstractAction {

    private static final HashMap<String, Parameter> parameterMap = new HashMap<>();

    private static final HashMap<String, Parameter> nonAPIParameterMap = new HashMap<>();

    public static class Result {
        public ErrorCode error;
        public org.zstack.sdk.iam2.api.AddAttributesToIAM2VirtualIDGroupResult value;

        public Result throwExceptionIfError() {
            if (error != null) {
                throw new ApiException(
                    String.format("error[code: %s, description: %s, details: %s]", error.code, error.description, error.details)
                );
            }

            return this;
        }
    }

    @Param(required = true, nonempty = false, nullElements = false, emptyString = true, noTrim = false)
    public java.lang.String uuid;

    @Param(required = true, nonempty = true, nullElements = false, emptyString = true, noTrim = false)
    public java.util.List attributes;

    @Param(required = false)
    public java.util.List systemTags;

    @Param(required = false)
    public java.util.List userTags;

    @Param(required = false)
    public String sessionId;

    @Param(required = false)
    public String accessKeyId;

    @Param(required = false)
    public String accessKeySecret;

    @Param(required = false)
    public String requestIp;

    @NonAPIParam
    public long timeout = -1;

    @NonAPIParam
    public long pollingInterval = -1;

    private Result makeResult(ApiResult res) {
        Result ret = new Result();
        if (res.error != null) {
            ret.error = res.error;
            return ret;
        }

        org.zstack.sdk.iam2.api.AddAttributesToIAM2VirtualIDGroupResult value = res.getResult(org.zstack.sdk.iam2.api.AddAttributesToIAM2VirtualIDGroupResult.class);
        ret.value = value == null ? new org.zstack.sdk.iam2.api.AddAttributesToIAM2VirtualIDGroupResult() : value;

        return ret;
    }

    public Result call() {
        ApiResult res = ZSClient.call(this);
        return makeResult(res);
    }

    public void call(final Completion<Result> completion) {
        ZSClient.call(this, new InternalCompletion() {
            @Override
            public void complete(ApiResult res) {
                completion.complete(makeResult(res));
            }
        });
    }

    protected Map<String, Parameter> getParameterMap() {
        return parameterMap;
    }

    protected Map<String, Parameter> getNonAPIParameterMap() {
        return nonAPIParameterMap;
    }

    protected RestInfo getRestInfo() {
        RestInfo info = new RestInfo();
        info.httpMethod = "POST";
        info.path = "/iam2/projects/groups/{uuid}/attributes";
        info.needSession = true;
        info.needPoll = true;
        info.parameterName = "params";
        return info;
    }

}


FROM balenalib/surface-go-fedora:32-build

# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8

RUN dnf install -y \
		python-pip \
		python-dbus \
	&& dnf clean all

# install "virtualenv", since the vast majority of users of this image will want it
RUN pip install -U --no-cache-dir --ignore-installed pip setuptools \
	&& pip install --no-cache-dir virtualenv

RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'As of January 1st, 2020, Python 2 was end-of-life, we will change the latest tag for Balenalib Python base image to Python 3.x and drop support for Python 2 soon. So after 1st July, 2020, all the balenalib Python latest tag will point to the latest Python 3 version and no changes, or fixes will be made to balenalib Python 2 base image. If you are using Python 2 for your application, please upgrade to Python 3 before 1st July.' > /.balena/messages/python-deprecation-warning

CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]

 RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \
  && echo "Running test-stack@python" \
  && chmod +x test-stack@python.sh \
  && bash test-stack@python.sh \
  && rm -rf test-stack@python.sh

RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: Intel 64-bit (x86-64) \nOS: Fedora 32 \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v2.7.18, Pip v21.0.1, Setuptools v56.0.0 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature  (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info

RUN echo $'#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
	&& chmod +x /bin/sh-shim \
	&& cp /bin/sh /bin/sh.real \
	&& mv /bin/sh-shim /bin/sh


/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/generic/memory/lib/utils/omi/gen_omi_traits.H $    */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2019,2022                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file gen_omi_traits.H
/// @brief Generic Traits file for OMI code
///
// *HWP HWP Owner: Geetha Pisapati <Geetha.Pisapati@ibm.com>
// *HWP HWP Backup: Louis Stermole <stermole@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: HB:FSP
// EKB-Mirror-To: hostboot

#ifndef _GEN_OMI_TRAITS_H_
#define _GEN_OMI_TRAITS_H_

#include <fapi2.H>

namespace mss
{
namespace omi
{
///
/// @class omiTraits
/// @tparam MC the mc type
/// @brief A MC to MC_TARGET_TYPE mapping
///
template< mss::mc_type MC >
class omiTraits;

} // end omi ns

} // end mss ns
#endif


<?php

namespace Zend\Form\Annotation;

/**
 * Hydrator annotation
 *
 * Use this annotation to specify a specific hydrator class to use with the form.
 * The value should be a string indicating the fully qualified class name of the
 * hydrator to use.
 *
 * @Annotation
 * @package    Zend_Form
 * @subpackage Annotation
 */
class Hydrator extends AbstractStringAnnotation
{
    /**
     * Retrieve the hydrator class
     *
     * @return null|string
     */
    public function getHydrator()
    {
        return $this->value;
    }
}