text:
#include <zephyr/types.h>

#include <zephyr/bluetooth/hci.h>
#include <zephyr/sys/byteorder.h>
#include <zephyr/sys/slist.h>
#include <zephyr/sys/util.h>

#include "hal/ecb.h"
#include "hal/ccm.h"

#include "util/util.h"
#include "util/mem.h"
#include "util/memq.h"
#include "util/dbuf.h"

#include "pdu.h"
#include "ll.h"
#include "ll_feat.h"
#include "ll_settings.h"

#include "lll.h"
#include "lll/lll_df_types.h"
#include "lll_conn.h"
#include "lll_conn_iso.h"

#include "ull_tx_queue.h"

#include "isoal.h"
#include "ull_iso_types.h"
#include "ull_conn_iso_types.h"
#include "ull_conn_iso_internal.h"

#include "ull_conn_types.h"
#include "ull_internal.h"
#include "ull_llcp.h"
#include "ull_llcp_internal.h"
#include "ull_llcp_features.h"
#include "ull_conn_internal.h"

#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_HCI_DRIVER)
#define LOG_MODULE_NAME bt_ctlr_ull_llcp_enc
#include "common/log.h"
#include <soc.h>
#include "hal/debug.h"

#if defined(CONFIG_BT_CENTRAL)
/* LLCP Local Procedure Encryption FSM states */
enum {
	/* Start Procedure */
	LP_ENC_STATE_UNENCRYPTED,
	LP_ENC_STATE_WAIT_TX_ENC_REQ,
	LP_ENC_STATE_WAIT_RX_ENC_RSP,
	LP_ENC_STATE_WAIT_RX_START_ENC_REQ,
	LP_ENC_STATE_WAIT_TX_START_ENC_RSP,
	LP_ENC_STATE_WAIT_RX_START_ENC_RSP,
	LP_ENC_STATE_WAIT_NTF,
	/* Pause Procedure */
	LP_ENC_STATE_ENCRYPTED,
	LP_ENC_STATE_WAIT_TX_PAUSE_ENC_REQ,
	LP_ENC_STATE_WAIT_RX_PAUSE_ENC_RSP,
	LP_ENC_STATE_WAIT_TX_PAUSE_ENC_RSP,
};

/* LLCP Local Procedure Encryption FSM events */
enum {
	/* Procedure prepared */
	LP_ENC_EVT_RUN,

	/* Response received */
	LP_ENC_EVT_ENC_RSP,

	/* Request received */
	LP_ENC_EVT_START_ENC_REQ,

	/* Response received */
	LP_ENC_EVT_START_ENC_RSP,

	/* Reject response received */
	LP_ENC_EVT_REJECT,

	/* Unknown response received */
	LP_ENC_EVT_UNKNOWN,

	/* Response received */
	LP_ENC_EVT_PAUSE_ENC_RSP,
};
#endif /* CONFIG_BT_CENTRAL */

#if defined(CONFIG_BT_PERIPHERAL)
/* LLCP Remote Procedure Encryption FSM states */
enum {
	/* Start Procedure */
	RP_ENC_STATE_UNENCRYPTED,
	RP_ENC_STATE_WAIT_RX_ENC_REQ,
	RP_ENC_STATE_WAIT_TX_ENC_RSP,
	RP_ENC_STATE_WAIT_NTF_LTK_REQ,
	RP_ENC_STATE_WAIT_LTK_REPLY,
	RP_ENC_STATE_WAIT_TX_START_ENC_REQ,
	RP_ENC_STATE_WAIT_TX_REJECT_IND,
	RP_ENC_STATE_WAIT_RX_START_ENC_RSP,
	RP_ENC_STATE_WAIT_NTF,
	RP_ENC_STATE_WAIT_TX_START_ENC_RSP,
	/* Pause Procedure */
	RP_ENC_STATE_ENCRYPTED,
	RP_ENC_STATE_WAIT_RX_PAUSE_ENC_REQ,
	RP_ENC_STATE_WAIT_TX_PAUSE_ENC_RSP,
	RP_ENC_STATE_WAIT_RX_PAUSE_ENC_RSP,
};

/* LLCP Remote Procedure Encryption FSM events */
enum {
	/* Procedure prepared */
	RP_ENC_EVT_RUN,

	/* Request received */
	RP_ENC_EVT_ENC_REQ,

	/* Response received */
	RP_ENC_EVT_START_ENC_RSP,

	/* LTK request reply */
	RP_ENC_EVT_LTK_REQ_REPLY,

	/* LTK request negative reply */
	RP_ENC_EVT_LTK_REQ_NEG_REPLY,

	/* Reject response received */
	RP_ENC_EVT_REJECT,

	/* Unknown response received */
	RP_ENC_EVT_UNKNOWN,

	/* Request received */
	RP_ENC_EVT_PAUSE_ENC_REQ,

	/* Response received */
	RP_ENC_EVT_PAUSE_ENC_RSP,
};
#endif /* CONFIG_BT_PERIPHERAL */

#if defined(CONFIG_BT_CENTRAL)
/*
 * LLCP Local Procedure Encryption FSM
 */

static struct node_tx *llcp_lp_enc_tx(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t opcode)
{
	struct node_tx *tx;
	struct pdu_data *pdu;

	/* Allocate tx node */
	tx = llcp_tx_alloc(conn, ctx);
	LL_ASSERT(tx);

	pdu = (struct pdu_data *)tx->pdu;

	/* Encode LL Control PDU */
	switch (opcode) {
	case PDU_DATA_LLCTRL_TYPE_ENC_REQ:
		llcp_pdu_encode_enc_req(ctx, pdu);
		break;
	case PDU_DATA_LLCTRL_TYPE_START_ENC_RSP:
		llcp_pdu_encode_start_enc_rsp(pdu);
		break;
	case PDU_DATA_LLCTRL_TYPE_PAUSE_ENC_REQ:
		llcp_pdu_encode_pause_enc_req(pdu);
		break;
	case PDU_DATA_LLCTRL_TYPE_PAUSE_ENC_RSP:
		llcp_pdu_encode_pause_enc_rsp(pdu);
		break;
	default:
		LL_ASSERT(0);
	}

	ctx->tx_opcode = pdu->llctrl.opcode;

	/* Enqueue LL Control PDU towards LLL */
	llcp_tx_enqueue(conn, tx);

	/* Restart procedure response timeout timer */
	llcp_lr_prt_restart(conn);

	return tx;
}

static void lp_enc_ntf(struct ll_conn *conn, struct proc_ctx *ctx)
{
	struct node_rx_pdu *ntf;
	struct pdu_data *pdu;

	/* Allocate ntf node */
	ntf = llcp_ntf_alloc();
	LL_ASSERT(ntf);

	ntf->hdr.type = NODE_RX_TYPE_DC_PDU;
	ntf->hdr.handle = conn->lll.handle;
	pdu = (struct pdu_data *)ntf->pdu;

	if (ctx->data.enc.error == BT_HCI_ERR_SUCCESS) {
		if (ctx->proc == PROC_ENCRYPTION_START) {
			/* Encryption Change Event */
			/* TODO(thoh): is this correct? */
			llcp_pdu_encode_start_enc_rsp(pdu);
		} else if (ctx->proc == PROC_ENCRYPTION_PAUSE) {
			/* Encryption Key Refresh Complete Event */
			ntf->hdr.type = NODE_RX_TYPE_ENC_REFRESH;
		} else {
			/* Should never happen */
			LL_ASSERT(0);
		}
	} else {
		llcp_pdu_encode_reject_ind(pdu, ctx->data.enc.error);
	}

	/* Enqueue notification towards LL */
	ll_rx_put(ntf->hdr.link, ntf);
	ll_rx_sched();
}

static void lp_enc_complete(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt, void *param)
{
	if (!llcp_ntf_alloc_is_available()) {
		ctx->state = LP_ENC_STATE_WAIT_NTF;
	} else {
		lp_enc_ntf(conn, ctx);
		llcp_lr_complete(conn);
		ctx->state = LP_ENC_STATE_UNENCRYPTED;
	}
}

static void lp_enc_store_m(struct ll_conn *conn, struct proc_ctx *ctx, struct pdu_data *pdu)
{
	/* Store SKDm */
	memcpy(&ctx->data.enc.skd[0], pdu->llctrl.enc_req.skdm, sizeof(pdu->llctrl.enc_req.skdm));
	/* Store IVm in the LLL CCM RX
	 * TODO(thoh): Should this be made into a ULL function, as it
	 * interacts with data outside of LLCP?
	 */
	memcpy(&conn->lll.ccm_rx.iv[0], pdu->llctrl.enc_req.ivm, sizeof(pdu->llctrl.enc_req.ivm));
}

static void lp_enc_send_enc_req(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt,
				void *param)
{
	struct node_tx *tx;

	if (!llcp_tx_alloc_peek(conn, ctx)) {
		ctx->state = LP_ENC_STATE_WAIT_TX_ENC_REQ;
	} else {
		tx = llcp_lp_enc_tx(conn, ctx, PDU_DATA_LLCTRL_TYPE_ENC_REQ);
		lp_enc_store_m(conn, ctx, (struct pdu_data *)tx->pdu);
		/* Wait for the LL_ENC_RSP */
		ctx->rx_opcode = PDU_DATA_LLCTRL_TYPE_ENC_RSP;
		ctx->state = LP_ENC_STATE_WAIT_RX_ENC_RSP;

		/* Pause possibly ongoing remote procedure */
		llcp_rr_pause(conn);

	}
}

static void lp_enc_send_pause_enc_req(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt,
				      void *param)
{
	if (!llcp_tx_alloc_peek(conn, ctx)) {
		ctx->state = LP_ENC_STATE_WAIT_TX_PAUSE_ENC_REQ;
	} else {
		llcp_lp_enc_tx(conn, ctx, PDU_DATA_LLCTRL_TYPE_PAUSE_ENC_REQ);
		/* Wait for the LL_PAUSE_ENC_RSP */
		ctx->rx_opcode = PDU_DATA_LLCTRL_TYPE_PAUSE_ENC_RSP;
		ctx->state = LP_ENC_STATE_WAIT_RX_PAUSE_ENC_RSP;
	}
}

static void lp_enc_send_pause_enc_rsp(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt,
				      void *param)
{
	if (!llcp_tx_alloc_peek(conn, ctx)) {
		ctx->state = LP_ENC_STATE_WAIT_TX_PAUSE_ENC_RSP;
	} else {
		llcp_lp_enc_tx(conn, ctx, PDU_DATA_LLCTRL_TYPE_PAUSE_ENC_RSP);

		ctx->rx_opcode = PDU_DATA_LLCTRL_TYPE_UNUSED;
		/* Continue with an encapsulated Start Procedure */
		ctx->state = LP_ENC_STATE_UNENCRYPTED;

		/* Tx Encryption disabled */
		conn->lll.enc_tx = 0U;

		/* Rx Decryption disabled */
		conn->lll.enc_rx = 0U;
	}
}

static void lp_enc_setup_lll(struct ll_conn *conn, struct proc_ctx *ctx)
{
	/* TODO(thoh): Move LLL/CCM manipulation to ULL? */

	/* Calculate the Session Key */
	ecb_encrypt(&ctx->data.enc.ltk[0], &ctx->data.enc.skd[0], NULL, &conn->lll.ccm_rx.key[0]);

	/* Copy the Session Key */
	memcpy(&conn->lll.ccm_tx.key[0], &conn->lll.ccm_rx.key[0], sizeof(conn->lll.ccm_tx.key));

	/* Copy the IV */
	memcpy(&conn->lll.ccm_tx.iv[0], &conn->lll.ccm_rx.iv[0], sizeof(conn->lll.ccm_tx.iv));

	/* Reset CCM counter */
	conn->lll.ccm_tx.counter = 0U;
	conn->lll.ccm_rx.counter = 0U;

	/* Set CCM direction:
	 *	periph to central = 0,
	 *	central to periph = 1
	 */
	conn->lll.ccm_tx.direction = 1U;
	conn->lll.ccm_rx.direction = 0U;
}

static void lp_enc_send_start_enc_rsp(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt,
				      void *param)
{
	if (!llcp_tx_alloc_peek(conn, ctx)) {
		ctx->state = LP_ENC_STATE_WAIT_TX_START_ENC_RSP;
	} else {
		lp_enc_setup_lll(conn, ctx);
		llcp_lp_enc_tx(conn, ctx, PDU_DATA_LLCTRL_TYPE_START_ENC_RSP);

		/* Wait for LL_START_ENC_RSP */
		ctx->rx_opcode = PDU_DATA_LLCTRL_TYPE_START_ENC_RSP;
		ctx->state = LP_ENC_STATE_WAIT_RX_START_ENC_RSP;

		/* Tx Encryption enabled */
		conn->lll.enc_tx = 1U;

		/* Rx Decryption enabled */
		conn->lll.enc_rx = 1U;
	}
}

static void lp_enc_st_unencrypted(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt,
				  void *param)
{
	switch (evt) {
	case LP_ENC_EVT_RUN:
		/* Pause Tx data */
		llcp_tx_pause_data(conn, LLCP_TX_QUEUE_PAUSE_DATA_ENCRYPTION);
		lp_enc_send_enc_req(conn, ctx, evt, param);
		break;
	default:
		/* Ignore other evts */
		break;
	}
}

static void lp_enc_st_wait_tx_enc_req(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt,
				      void *param)
{
	switch (evt) {
	case LP_ENC_EVT_RUN:
		lp_enc_send_enc_req(conn, ctx, evt, param);
		break;
	default:
		/* Ignore other evts */
		break;
	}
}

static void lp_enc_store_s(struct ll_conn *conn, struct proc_ctx *ctx, struct pdu_data *pdu)
{
	/* Store SKDs */
	memcpy(&ctx->data.enc.skd[8], pdu->llctrl.enc_rsp.skds, sizeof(pdu->llctrl.enc_rsp.skds));
	/* Store IVs in the LLL CCM RX
	 * TODO(thoh): Should this be made into a ULL function, as it
	 * interacts with data outside of LLCP?
	 */
	memcpy(&conn->lll.ccm_rx.iv[4], pdu->llctrl.enc_rsp.ivs, sizeof(pdu->llctrl.enc_rsp.ivs));
}

static inline uint8_t reject_error_code(struct pdu_data *pdu)
{
	if (pdu->llctrl.opcode == PDU_DATA_LLCTRL_TYPE_REJECT_IND) {
		return pdu->llctrl.reject_ind.error_code;
#if defined(CONFIG_BT_CTLR_EXT_REJ_IND)
	} else if (pdu->llctrl.opcode == PDU_DATA_LLCTRL_TYPE_REJECT_EXT_IND) {
		return pdu->llctrl.reject_ext_ind.error_code;
#endif /* CONFIG_BT_CTLR_EXT_REJ_IND */
	} else {
		/* Called with an invalid PDU */
		LL_ASSERT(0);

		/* Keep compiler happy */
		return BT_HCI_ERR_UNSPECIFIED;
	}
}

static void lp_enc_st_wait_rx_enc_rsp(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt,
				      void *param)
{
	struct pdu_data *pdu = (struct pdu_data *)param;

	switch (evt) {
	case LP_ENC_EVT_ENC_RSP:
		/* Pause Rx data */
		ull_conn_pause_rx_data(conn);
		lp_enc_store_s(conn, ctx, pdu);

		/* After the Central has received the LL_ENC_RSP PDU,
		 * only PDUs related to this procedure are valid, and invalids should
		 * result in disconnect.
		 * to achieve this enable the greedy RX behaviour, such that
		 * all PDU's end up in this FSM.
		 */
		ctx->rx_greedy = 1U;

		/* Wait for LL_START_ENC_REQ */
		ctx->rx_opcode = PDU_DATA_LLCTRL_TYPE_START_ENC_REQ;
		ctx->state = LP_ENC_STATE_WAIT_RX_START_ENC_REQ;
		break;
	case LP_ENC_EVT_REJECT:
		/* Encryption is not supported by the Link Layer of the Peripheral */

		/* Resume Tx data */
		llcp_tx_resume_data(conn, LLCP_TX_QUEUE_PAUSE_DATA_ENCRYPTION);

		/* Store the error reason */
		ctx->data.enc.error = reject_error_code(pdu);

		/* Resume possibly paused remote procedure */
		llcp_rr_resume(conn);

		/* Complete the procedure */
		lp_enc_complete(conn, ctx, evt, param);
		break;
	default:
		/* Ignore other evts */
		break;
	}
}

static void lp_enc_st_wait_rx_start_enc_req(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt,
					    void *param)
{
	struct pdu_data *pdu = (struct pdu_data *)param;

	switch (evt) {
	case LP_ENC_EVT_START_ENC_REQ:
		lp_enc_send_start_enc_rsp(conn, ctx, evt, param);
		break;
	case LP_ENC_EVT_REJECT:
		/* Resume Tx data */
		llcp_tx_resume_data(conn, LLCP_TX_QUEUE_PAUSE_DATA_ENCRYPTION);
		/* Resume Rx data */
		ull_conn_resume_rx_data(conn);

		/* Store the error reason */
		ctx->data.enc.error = reject_error_code(pdu);

		/* Resume possibly paused remote procedure */
		llcp_rr_resume(conn);

		/* Disable the greedy behaviour */
		ctx->rx_greedy = 0U;

		lp_enc_complete(conn, ctx, evt, param);
		break;
	default:
		/* Ignore other evts */
		break;
	}
}

static void lp_enc_st_wait_tx_start_enc_rsp(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt,
					    void *param)
{
	switch (evt) {
	case LP_ENC_EVT_RUN:
		lp_enc_send_start_enc_rsp(conn, ctx, evt, param);
		break;
	default:
		/* Ignore other evts */
		break;
	}
}

static void lp_enc_st_wait_rx_start_enc_rsp(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt,
					    void *param)
{
	switch (evt) {
	case LP_ENC_EVT_START_ENC_RSP:
		/* Resume Tx data */
		llcp_tx_resume_data(conn, LLCP_TX_QUEUE_PAUSE_DATA_ENCRYPTION);
		/* Resume Rx data */
		ull_conn_resume_rx_data(conn);
		ctx->data.enc.error = BT_HCI_ERR_SUCCESS;

		/* Resume possibly paused remote procedure */
		llcp_rr_resume(conn);

		/* Disable the greedy behaviour */
		ctx->rx_greedy = 0U;

		lp_enc_complete(conn, ctx, evt, param);
		break;
	default:
		/* Ignore other evts */
		break;
	}
}

static void lp_enc_st_wait_ntf(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt, void *param)
{
	switch (evt) {
	case LP_ENC_EVT_RUN:
		lp_enc_complete(conn, ctx, evt, param);
		break;
	default:
		/* Ignore other evts */
		break;
	}
}

static void lp_enc_state_encrypted(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt,
				   void *param)
{
	switch (evt) {
	case LP_ENC_EVT_RUN:
		/* Pause Tx data */
		llcp_tx_pause_data(conn, LLCP_TX_QUEUE_PAUSE_DATA_ENCRYPTION);
		lp_enc_send_pause_enc_req(conn, ctx, evt, param);
		break;
	default:
		/* Ignore other evts */
		break;
	}
}

static void lp_enc_state_wait_tx_pause_enc_req(struct ll_conn *conn, struct proc_ctx *ctx,
					       uint8_t evt, void *param)
{
	switch (evt) {
	case LP_ENC_EVT_RUN:
		lp_enc_send_pause_enc_req(conn, ctx, evt, param);
		break;
	default:
		/* Ignore other evts */
		break;
	}
}

static void lp_enc_state_wait_rx_pause_enc_rsp(struct ll_conn *conn, struct proc_ctx *ctx,
					       uint8_t evt, void *param)
{
	switch (evt) {
	case LP_ENC_EVT_PAUSE_ENC_RSP:
		/*
		 * Pause Rx data; will be resumed when the encapsulated
		 * Start Procedure is done.
		 */
		ull_conn_pause_rx_data(conn);
		lp_enc_send_pause_enc_rsp(conn, ctx, evt, param);
		break;
	default:
		/* Ignore other evts */
		break;
	}
}

static void lp_enc_state_wait_tx_pause_enc_rsp(struct ll_conn *conn, struct proc_ctx *ctx,
					       uint8_t evt, void *param)
{
	switch (evt) {
	case LP_ENC_EVT_RUN:
		lp_enc_send_pause_enc_rsp(conn, ctx, evt, param);
		break;
	default:
		/* Ignore other evts */
		break;
	}
}

static void lp_enc_execute_fsm(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt, void *param)
{
	switch (ctx->state) {
	/* Start Procedure */
	case LP_ENC_STATE_UNENCRYPTED:
		lp_enc_st_unencrypted(conn, ctx, evt, param);
		break;
	case LP_ENC_STATE_WAIT_TX_ENC_REQ:
		lp_enc_st_wait_tx_enc_req(conn, ctx, evt, param);
		break;
	case LP_ENC_STATE_WAIT_RX_ENC_RSP:
		lp_enc_st_wait_rx_enc_rsp(conn, ctx, evt, param);
		break;
	case LP_ENC_STATE_WAIT_RX_START_ENC_REQ:
		lp_enc_st_wait_rx_start_enc_req(conn, ctx, evt, param);
		break;
	case LP_ENC_STATE_WAIT_TX_START_ENC_RSP:
		lp_enc_st_wait_tx_start_enc_rsp(conn, ctx, evt, param);
		break;
	case LP_ENC_STATE_WAIT_RX_START_ENC_RSP:
		lp_enc_st_wait_rx_start_enc_rsp(conn, ctx, evt, param);
		break;
	case LP_ENC_STATE_WAIT_NTF:
		lp_enc_st_wait_ntf(conn, ctx, evt, param);
		break;
	/* Pause Procedure */
	case LP_ENC_STATE_ENCRYPTED:
		lp_enc_state_encrypted(conn, ctx, evt, param);
		break;
	case LP_ENC_STATE_WAIT_TX_PAUSE_ENC_REQ:
		lp_enc_state_wait_tx_pause_enc_req(conn, ctx, evt, param);
		break;
	case LP_ENC_STATE_WAIT_RX_PAUSE_ENC_RSP:
		lp_enc_state_wait_rx_pause_enc_rsp(conn, ctx, evt, param);
		break;
	case LP_ENC_STATE_WAIT_TX_PAUSE_ENC_RSP:
		lp_enc_state_wait_tx_pause_enc_rsp(conn, ctx, evt, param);
		break;
	default:
		/* Unknown state */
		LL_ASSERT(0);
	}
}

void llcp_lp_enc_rx(struct ll_conn *conn, struct proc_ctx *ctx, struct node_rx_pdu *rx)
{
	struct pdu_data *pdu = (struct pdu_data *)rx->pdu;

	switch (pdu->llctrl.opcode) {
	case PDU_DATA_LLCTRL_TYPE_ENC_RSP:
		lp_enc_execute_fsm(conn, ctx, LP_ENC_EVT_ENC_RSP, pdu);
		break;
	case PDU_DATA_LLCTRL_TYPE_START_ENC_REQ:
		lp_enc_execute_fsm(conn, ctx, LP_ENC_EVT_START_ENC_REQ, pdu);
		break;
	case PDU_DATA_LLCTRL_TYPE_START_ENC_RSP:
		lp_enc_execute_fsm(conn, ctx, LP_ENC_EVT_START_ENC_RSP, pdu);
		break;
	case PDU_DATA_LLCTRL_TYPE_REJECT_IND:
	case PDU_DATA_LLCTRL_TYPE_REJECT_EXT_IND:
		lp_enc_execute_fsm(conn, ctx, LP_ENC_EVT_REJECT, pdu);
		break;
	case PDU_DATA_LLCTRL_TYPE_PAUSE_ENC_RSP:
		lp_enc_execute_fsm(conn, ctx, LP_ENC_EVT_PAUSE_ENC_RSP, pdu);
		break;
	default:
		/* Unknown opcode */

		/*
		 * BLUETOOTH CORE SPECIFICATION Version 5.3
		 * Vol 6, Part B, 5.1.3.1 Encryption Start procedure
		 *
		 * [...]
		 *
		 * If, at any time during the encryption start procedure after the Peripheral has
		 * received the LL_ENC_REQ PDU or the Central has received the
		 * LL_ENC_RSP PDU, the Link Layer of the Central or the Peripheral receives an
		 * unexpected Data Physical Channel PDU from the peer Link Layer, it shall
		 * immediately exit the Connection state, and shall transition to the Standby state.
		 * The Host shall be notified that the link has been disconnected with the error
		 * code Connection Terminated Due to MIC Failure (0x3D).
		 */

		conn->llcp_terminate.reason_final = BT_HCI_ERR_TERM_DUE_TO_MIC_FAIL;
	}
}

void llcp_lp_enc_init_proc(struct proc_ctx *ctx)
{
	switch (ctx->proc) {
	case PROC_ENCRYPTION_START:
		ctx->state = LP_ENC_STATE_UNENCRYPTED;
		break;
	case PROC_ENCRYPTION_PAUSE:
		ctx->state = LP_ENC_STATE_ENCRYPTED;
		break;
	default:
		LL_ASSERT(0);
	}
}

void llcp_lp_enc_run(struct ll_conn *conn, struct proc_ctx *ctx, void *param)
{
	lp_enc_execute_fsm(conn, ctx, LP_ENC_EVT_RUN, param);
}

#endif /* CONFIG_BT_CENTRAL */

#if defined(CONFIG_BT_PERIPHERAL)
/*
 * LLCP Remote Procedure Encryption FSM
 */

static struct node_tx *llcp_rp_enc_tx(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t opcode)
{
	struct node_tx *tx;
	struct pdu_data *pdu;

	/* Allocate tx node */
	tx = llcp_tx_alloc(conn, ctx);
	LL_ASSERT(tx);

	pdu = (struct pdu_data *)tx->pdu;

	/* Encode LL Control PDU */
	switch (opcode) {
	case PDU_DATA_LLCTRL_TYPE_ENC_RSP:
		llcp_pdu_encode_enc_rsp(pdu);
		break;
	case PDU_DATA_LLCTRL_TYPE_START_ENC_REQ:
		llcp_pdu_encode_start_enc_req(pdu);
		break;
	case PDU_DATA_LLCTRL_TYPE_START_ENC_RSP:
		llcp_pdu_encode_start_enc_rsp(pdu);
		break;
	case PDU_DATA_LLCTRL_TYPE_PAUSE_ENC_RSP:
		llcp_pdu_encode_pause_enc_rsp(pdu);
		break;
	case PDU_DATA_LLCTRL_TYPE_REJECT_IND:
		if (conn->llcp.fex.valid && feature_ext_rej_ind(conn)) {
			llcp_pdu_encode_reject_ext_ind(pdu, PDU_DATA_LLCTRL_TYPE_ENC_REQ,
						       BT_HCI_ERR_PIN_OR_KEY_MISSING);
		} else {
			llcp_pdu_encode_reject_ind(pdu, BT_HCI_ERR_PIN_OR_KEY_MISSING);
		}
		break;
	default:
		LL_ASSERT(0);
	}

	ctx->tx_opcode = pdu->llctrl.opcode;

	/* Enqueue LL Control PDU towards LLL */
	llcp_tx_enqueue(conn, tx);

	/* Restart procedure response timeout timer */
	llcp_rr_prt_restart(conn);

	return tx;
}

static void rp_enc_ntf_ltk(struct ll_conn *conn, struct proc_ctx *ctx)
{
	struct node_rx_pdu *ntf;
	struct pdu_data *pdu;

	/* Allocate ntf node */
	ntf = llcp_ntf_alloc();
	LL_ASSERT(ntf);

	ntf->hdr.type = NODE_RX_TYPE_DC_PDU;
	ntf->hdr.handle = conn->lll.handle;
	pdu = (struct pdu_data *)ntf->pdu;

	llcp_ntf_encode_enc_req(ctx, pdu);

	/* Enqueue notification towards LL */
	ll_rx_put(ntf->hdr.link, ntf);
	ll_rx_sched();
}

static void rp_enc_ntf(struct ll_conn *conn, struct proc_ctx *ctx)
{
	struct node_rx_pdu *ntf;
	struct pdu_data *pdu;

	/* Allocate ntf node */
	ntf = llcp_ntf_alloc();
	LL_ASSERT(ntf);

	ntf->hdr.type = NODE_RX_TYPE_DC_PDU;
	ntf->hdr.handle = conn->lll.handle;
	pdu = (struct pdu_data *)ntf->pdu;

	if (ctx->proc == PROC_ENCRYPTION_START) {
		/* Encryption Change Event */
		/* TODO(thoh): is this correct? */
		llcp_pdu_encode_start_enc_rsp(pdu);
	} else if (ctx->proc == PROC_ENCRYPTION_PAUSE) {
		/* Encryption Key Refresh Complete Event */
		ntf->hdr.type = NODE_RX_TYPE_ENC_REFRESH;
	} else {
		/* Should never happen */
		LL_ASSERT(0);
	}

	/* Enqueue notification towards LL */
	ll_rx_put(ntf->hdr.link, ntf);
	ll_rx_sched();
}

static void rp_enc_send_start_enc_rsp(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt,
				      void *param);

static void rp_enc_complete(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt, void *param)
{
	if (!llcp_ntf_alloc_is_available()) {
		ctx->state = RP_ENC_STATE_WAIT_NTF;
	} else {
		rp_enc_ntf(conn, ctx);
		rp_enc_send_start_enc_rsp(conn, ctx, evt, param);
	}
}

static void rp_enc_send_ltk_ntf(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt,
				void *param)
{
	if (!llcp_ntf_alloc_is_available()) {
		ctx->state = RP_ENC_STATE_WAIT_NTF_LTK_REQ;
	} else {
		rp_enc_ntf_ltk(conn, ctx);
		ctx->state = RP_ENC_STATE_WAIT_LTK_REPLY;
	}
}

static void rp_enc_store_s(struct ll_conn *conn, struct proc_ctx *ctx, struct pdu_data *pdu)
{
	/* Store SKDs */
	memcpy(&ctx->data.enc.skds, pdu->llctrl.enc_rsp.skds, sizeof(pdu->llctrl.enc_rsp.skds));
	/* Store IVs in the LLL CCM RX
	 * TODO(thoh): Should this be made into a ULL function, as it
	 * interacts with data outside of LLCP?
	 */
	memcpy(&conn->lll.ccm_rx.iv[4], pdu->llctrl.enc_rsp.ivs, sizeof(pdu->llctrl.enc_rsp.ivs));
}

static void rp_enc_send_enc_rsp(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt,
				void *param)
{
	struct node_tx *tx;

	if (!llcp_tx_alloc_peek(conn, ctx)) {
		ctx->state = RP_ENC_STATE_WAIT_TX_ENC_RSP;
	} else {
		tx = llcp_rp_enc_tx(conn, ctx, PDU_DATA_LLCTRL_TYPE_ENC_RSP);
		rp_enc_store_s(conn, ctx, (struct pdu_data *)tx->pdu);
		rp_enc_send_ltk_ntf(conn, ctx, evt, param);
	}
}

static void rp_enc_setup_lll(struct ll_conn *conn, struct proc_ctx *ctx)
{
	/* TODO(thoh): Move LLL/CCM manipulation to ULL? */

	/* Calculate the Session Key */
	ecb_encrypt(&ctx->data.enc.ltk[0], &ctx->data.enc.skd[0], NULL, &conn->lll.ccm_rx.key[0]);

	/* Copy the Session Key */
	memcpy(&conn->lll.ccm_tx.key[0], &conn->lll.ccm_rx.key[0], sizeof(conn->lll.ccm_tx.key));

	/* Copy the IV */
	memcpy(&conn->lll.ccm_tx.iv[0], &conn->lll.ccm_rx.iv[0], sizeof(conn->lll.ccm_tx.iv));

	/* Reset CCM counter */
	conn->lll.ccm_tx.counter = 0U;
	conn->lll.ccm_rx.counter = 0U;

	/* Set CCM direction:
	 *	periph to central = 0,
	 *	central to periph = 1
	 */
	conn->lll.ccm_tx.direction = 0U;
	conn->lll.ccm_rx.direction = 1U;
}

static void rp_enc_send_start_enc_req(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt,
				      void *param)
{
	if (!llcp_tx_alloc_peek(conn, ctx)) {
		ctx->state = RP_ENC_STATE_WAIT_TX_START_ENC_REQ;
	} else {
		rp_enc_setup_lll(conn, ctx);
		llcp_rp_enc_tx(conn, ctx, PDU_DATA_LLCTRL_TYPE_START_ENC_REQ);
		/* Wait for the LL_START_ENC_RSP */
		ctx->rx_opcode = PDU_DATA_LLCTRL_TYPE_START_ENC_RSP;
		ctx->state = RP_ENC_STATE_WAIT_RX_START_ENC_RSP;

		/* Rx Decryption enabled */
		conn->lll.enc_rx = 1U;
	}
}

static void rp_enc_send_reject_ind(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt,
				   void *param)
{
	if (!llcp_tx_alloc_peek(conn, ctx)) {
		ctx->state = RP_ENC_STATE_WAIT_TX_REJECT_IND;
	} else {
		llcp_rp_enc_tx(conn, ctx, PDU_DATA_LLCTRL_TYPE_REJECT_IND);
		llcp_rr_complete(conn);
		ctx->state = RP_ENC_STATE_UNENCRYPTED;

		/* Resume Tx data */
		llcp_tx_resume_data(conn, LLCP_TX_QUEUE_PAUSE_DATA_ENCRYPTION);
		/* Resume Rx data */
		ull_conn_resume_rx_data(conn);
		/* Resume possibly paused local procedure */
		llcp_lr_resume(conn);
	}
}

static void rp_enc_send_start_enc_rsp(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt,
				      void *param)
{
	if (!llcp_tx_alloc_peek(conn, ctx)) {
		ctx->state = RP_ENC_STATE_WAIT_TX_START_ENC_RSP;
	} else {
		llcp_rp_enc_tx(conn, ctx, PDU_DATA_LLCTRL_TYPE_START_ENC_RSP);
		llcp_rr_complete(conn);
		ctx->state = RP_ENC_STATE_UNENCRYPTED;

		/* Resume Tx data */
		llcp_tx_resume_data(conn, LLCP_TX_QUEUE_PAUSE_DATA_ENCRYPTION);
		/* Resume Rx data */
		ull_conn_resume_rx_data(conn);

		/* Resume possibly paused local procedure */
		llcp_lr_resume(conn);

		/* Tx Encryption enabled */
		conn->lll.enc_tx = 1U;
	}
}

static void rp_enc_send_pause_enc_rsp(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt,
				      void *param)
{
	if (!llcp_tx_alloc_peek(conn, ctx)) {
		ctx->state = RP_ENC_STATE_WAIT_TX_PAUSE_ENC_RSP;
	} else {
		llcp_rp_enc_tx(conn, ctx, PDU_DATA_LLCTRL_TYPE_PAUSE_ENC_RSP);
		/* Wait for the LL_PAUSE_ENC_RSP */
		ctx->rx_opcode = PDU_DATA_LLCTRL_TYPE_PAUSE_ENC_RSP;
		ctx->state = RP_ENC_STATE_WAIT_RX_PAUSE_ENC_RSP;

		/* Rx Decryption disabled */
		conn->lll.enc_rx = 0U;
	}
}

static void rp_enc_state_unencrypted(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt,
				     void *param)
{
	switch (evt) {
	case RP_ENC_EVT_RUN:
		ctx->state = RP_ENC_STATE_WAIT_RX_ENC_REQ;
		break;
	default:
		/* Ignore other evts */
		break;
	}
}

static void rp_enc_store_m(struct ll_conn *conn, struct proc_ctx *ctx, struct pdu_data *pdu)
{
	/* Store Rand */
	memcpy(ctx->data.enc.rand, pdu->llctrl.enc_req.rand, sizeof(ctx->data.enc.rand));

	/* Store EDIV */
	ctx->data.enc.ediv[0] = pdu->llctrl.enc_req.ediv[0];
	ctx->data.enc.ediv[1] = pdu->llctrl.enc_req.ediv[1];

	/* Store SKDm */
	memcpy(&ctx->data.enc.skdm, pdu->llctrl.enc_req.skdm, sizeof(ctx->data.enc.skdm));

	/* Store IVm in the LLL CCM RX
	 * TODO(thoh): Should this be made into a ULL function, as it
	 * interacts with data outside of LLCP?
	 */
	memcpy(&conn->lll.ccm_rx.iv[0], pdu->llctrl.enc_req.ivm, sizeof(pdu->llctrl.enc_req.ivm));
}

static void rp_enc_state_wait_rx_enc_req(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt,
					 void *param)
{
	switch (evt) {
	case RP_ENC_EVT_ENC_REQ:
		/* Pause Tx data */
		llcp_tx_pause_data(conn, LLCP_TX_QUEUE_PAUSE_DATA_ENCRYPTION);
		/* Pause Rx data */
		ull_conn_pause_rx_data(conn);

		/* Pause possibly paused local procedure */
		llcp_lr_pause(conn);

		rp_enc_store_m(conn, ctx, param);
		rp_enc_send_enc_rsp(conn, ctx, evt, param);
		break;
	default:
		/* Ignore other evts */
		break;
	}
}

static void rp_enc_state_wait_tx_enc_rsp(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt,
					 void *param)
{
	switch (evt) {
	case RP_ENC_EVT_RUN:
		rp_enc_send_enc_rsp(conn, ctx, evt, param);
		break;
	default:
		/* Ignore other evts */
		break;
	}
}

static void rp_enc_state_wait_ntf_ltk_req(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt,
					  void *param)
{
	switch (evt) {
	case RP_ENC_EVT_RUN:
		rp_enc_send_ltk_ntf(conn, ctx, evt, param);
		break;
	default:
		/* Ignore other evts */
		break;
	}
}

static void rp_enc_state_wait_ltk_reply(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt,
					void *param)
{
	switch (evt) {
	case RP_ENC_EVT_LTK_REQ_REPLY:
		rp_enc_send_start_enc_req(conn, ctx, evt, param);
		break;
	case RP_ENC_EVT_LTK_REQ_NEG_REPLY:
		rp_enc_send_reject_ind(conn, ctx, evt, param);
		break;
	default:
		/* Ignore other evts */
		break;
	}
}

static void rp_enc_state_wait_tx_start_enc_req(struct ll_conn *conn, struct proc_ctx *ctx,
					       uint8_t evt, void *param)
{
	switch (evt) {
	case RP_ENC_EVT_RUN:
		rp_enc_send_start_enc_req(conn, ctx, evt, param);
		break;
	default:
		/* Ignore other evts */
		break;
	}
}

static void rp_enc_state_wait_tx_reject_ind(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt,
					    void *param)
{
	switch (evt) {
	case RP_ENC_EVT_RUN:
		rp_enc_send_reject_ind(conn, ctx, evt, param);
		break;
	default:
		/* Ignore other evts */
		break;
	}
}

static void rp_enc_state_wait_rx_start_enc_rsp(struct ll_conn *conn, struct proc_ctx *ctx,
					       uint8_t evt, void *param)
{
	switch (evt) {
	case RP_ENC_EVT_START_ENC_RSP:
		rp_enc_complete(conn, ctx, evt, param);
		break;
	default:
		/* Ignore other evts */
		break;
	}
}

static void rp_enc_state_wait_ntf(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt,
				  void *param)
{
	switch (evt) {
	case RP_ENC_EVT_RUN:
		rp_enc_complete(conn, ctx, evt, param);
		break;
	default:
		/* Ignore other evts */
		break;
	}
}

static void rp_enc_state_wait_tx_start_enc_rsp(struct ll_conn *conn, struct proc_ctx *ctx,
					       uint8_t evt, void *param)
{
	switch (evt) {
	case RP_ENC_EVT_RUN:
		rp_enc_send_start_enc_rsp(conn, ctx, evt, param);
		break;
	default:
		/* Ignore other evts */
		break;
	}
}

static void rp_enc_state_encrypted(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt,
				   void *param)
{
	switch (evt) {
	case RP_ENC_EVT_RUN:
		ctx->state = RP_ENC_STATE_WAIT_RX_PAUSE_ENC_REQ;
		break;
	default:
		/* Ignore other evts */
		break;
	}
}

static void rp_enc_state_wait_rx_pause_enc_req(struct ll_conn *conn, struct proc_ctx *ctx,
					       uint8_t evt, void *param)
{
	switch (evt) {
	case RP_ENC_EVT_PAUSE_ENC_REQ:
		/* Pause Tx data */
		llcp_tx_pause_data(conn, LLCP_TX_QUEUE_PAUSE_DATA_ENCRYPTION);
		/*
		 * Pause Rx data; will be resumed when the encapsulated
		 * Start Procedure is done.
		 */
		ull_conn_pause_rx_data(conn);
		rp_enc_send_pause_enc_rsp(conn, ctx, evt, param);
		break;
	default:
		/* Ignore other evts */
		break;
	}
}

static void rp_enc_state_wait_tx_pause_enc_rsp(struct ll_conn *conn, struct proc_ctx *ctx,
					       uint8_t evt, void *param)
{
	switch (evt) {
	case RP_ENC_EVT_RUN:
		rp_enc_send_pause_enc_rsp(conn, ctx, evt, param);
		break;
	default:
		/* Ignore other evts */
		break;
	}
}

static void rp_enc_state_wait_rx_pause_enc_rsp(struct ll_conn *conn, struct proc_ctx *ctx,
					       uint8_t evt, void *param)
{
	switch (evt) {
	case RP_ENC_EVT_PAUSE_ENC_RSP:
		/* Continue with an encapsulated Start Procedure */
		/* Wait for the LL_ENC_REQ */
		ctx->rx_opcode = PDU_DATA_LLCTRL_TYPE_ENC_REQ;
		ctx->state = RP_ENC_STATE_WAIT_RX_ENC_REQ;

		/* Tx Encryption disabled */
		conn->lll.enc_tx = 0U;
		break;
	default:
		/* Ignore other evts */
		break;
	}
}

static void rp_enc_execute_fsm(struct ll_conn *conn, struct proc_ctx *ctx, uint8_t evt, void *param)
{
	switch (ctx->state) {
	/* Start Procedure */
	case RP_ENC_STATE_UNENCRYPTED:
		rp_enc_state_unencrypted(conn, ctx, evt, param);
		break;
	case RP_ENC_STATE_WAIT_RX_ENC_REQ:
		rp_enc_state_wait_rx_enc_req(conn, ctx, evt, param);
		break;
	case RP_ENC_STATE_WAIT_TX_ENC_RSP:
		rp_enc_state_wait_tx_enc_rsp(conn, ctx, evt, param);
		break;
	case RP_ENC_STATE_WAIT_NTF_LTK_REQ:
		rp_enc_state_wait_ntf_ltk_req(conn, ctx, evt, param);
		break;
	case RP_ENC_STATE_WAIT_LTK_REPLY:
		rp_enc_state_wait_ltk_reply(conn, ctx, evt, param);
		break;
	case RP_ENC_STATE_WAIT_TX_START_ENC_REQ:
		rp_enc_state_wait_tx_start_enc_req(conn, ctx, evt, param);
		break;
	case RP_ENC_STATE_WAIT_TX_REJECT_IND:
		rp_enc_state_wait_tx_reject_ind(conn, ctx, evt, param);
		break;
	case RP_ENC_STATE_WAIT_RX_START_ENC_RSP:
		rp_enc_state_wait_rx_start_enc_rsp(conn, ctx, evt, param);
		break;
	case RP_ENC_STATE_WAIT_NTF:
		rp_enc_state_wait_ntf(conn, ctx, evt, param);
		break;
	case RP_ENC_STATE_WAIT_TX_START_ENC_RSP:
		rp_enc_state_wait_tx_start_enc_rsp(conn, ctx, evt, param);
		break;
	/* Pause Procedure */
	case RP_ENC_STATE_ENCRYPTED:
		rp_enc_state_encrypted(conn, ctx, evt, param);
		break;
	case RP_ENC_STATE_WAIT_RX_PAUSE_ENC_REQ:
		rp_enc_state_wait_rx_pause_enc_req(conn, ctx, evt, param);
		break;
	case RP_ENC_STATE_WAIT_TX_PAUSE_ENC_RSP:
		rp_enc_state_wait_tx_pause_enc_rsp(conn, ctx, evt, param);
		break;
	case RP_ENC_STATE_WAIT_RX_PAUSE_ENC_RSP:
		rp_enc_state_wait_rx_pause_enc_rsp(conn, ctx, evt, param);
		break;
	default:
		/* Unknown state */
		LL_ASSERT(0);
	}
}

void llcp_rp_enc_rx(struct ll_conn *conn, struct proc_ctx *ctx, struct node_rx_pdu *rx)
{
	struct pdu_data *pdu = (struct pdu_data *)rx->pdu;

	switch (pdu->llctrl.opcode) {
	case PDU_DATA_LLCTRL_TYPE_ENC_REQ:
		rp_enc_execute_fsm(conn, ctx, RP_ENC_EVT_ENC_REQ, pdu);
		break;
	case PDU_DATA_LLCTRL_TYPE_START_ENC_RSP:
		rp_enc_execute_fsm(conn, ctx, RP_ENC_EVT_START_ENC_RSP, pdu);
		break;
	case PDU_DATA_LLCTRL_TYPE_PAUSE_ENC_REQ:
		rp_enc_execute_fsm(conn, ctx, RP_ENC_EVT_PAUSE_ENC_REQ, pdu);
		break;
	case PDU_DATA_LLCTRL_TYPE_PAUSE_ENC_RSP:
		rp_enc_execute_fsm(conn, ctx, RP_ENC_EVT_PAUSE_ENC_RSP, pdu);
		break;
	default:
		/* Unknown opcode */

		/*
		 * BLUETOOTH CORE SPECIFICATION Version 5.3
		 * Vol 6, Part B, 5.1.3.1 Encryption Start procedure
		 *
		 * [...]
		 *
		 * If, at any time during the encryption start procedure after the Peripheral has
		 * received the LL_ENC_REQ PDU or the Central has received the
		 * LL_ENC_RSP PDU, the Link Layer of the Central or the Peripheral receives an
		 * unexpected Data Physical Channel PDU from the peer Link Layer, it shall
		 * immediately exit the Connection state, and shall transition to the Standby state.
		 * The Host shall be notified that the link has been disconnected with the error
		 * code Connection Terminated Due to MIC Failure (0x3D).
		 */

		conn->llcp_terminate.reason_final = BT_HCI_ERR_TERM_DUE_TO_MIC_FAIL;
	}
}

void llcp_rp_enc_init_proc(struct proc_ctx *ctx)
{
	switch (ctx->proc) {
	case PROC_ENCRYPTION_START:
		ctx->state = RP_ENC_STATE_UNENCRYPTED;
		break;
	case PROC_ENCRYPTION_PAUSE:
		ctx->state = RP_ENC_STATE_ENCRYPTED;
		break;
	default:
		LL_ASSERT(0);
	}
}

void llcp_rp_enc_ltk_req_reply(struct ll_conn *conn, struct proc_ctx *ctx)
{
	rp_enc_execute_fsm(conn, ctx, RP_ENC_EVT_LTK_REQ_REPLY, NULL);
}

void llcp_rp_enc_ltk_req_neg_reply(struct ll_conn *conn, struct proc_ctx *ctx)
{
	rp_enc_execute_fsm(conn, ctx, RP_ENC_EVT_LTK_REQ_NEG_REPLY, NULL);
}

bool llcp_rp_enc_ltk_req_reply_allowed(struct ll_conn *conn, struct proc_ctx *ctx)
{
	return (ctx->state == RP_ENC_STATE_WAIT_LTK_REPLY);
}

void llcp_rp_enc_run(struct ll_conn *conn, struct proc_ctx *ctx, void *param)
{
	rp_enc_execute_fsm(conn, ctx, RP_ENC_EVT_RUN, param);
}
#endif /* CONFIG_BT_PERIPHERAL */


text:
package main

/*

import (
    "fmt"
    "net/http"

	// Qor
    "github.com/qor/qor"
	"github.com/qor/l10n"
	"github.com/qor/media"
	"github.com/qor/publish2"
	"github.com/qor/sorting"
	"github.com/qor/validations"

	// Gorm / RDB
    "github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	_ "github.com/jinzhu/gorm/dialects/postgres"
	_ "github.com/jinzhu/gorm/dialects/sqlite"

	// Qor Admin
    "github.com/qor/admin"
)

// Create a GORM-backend model
type User struct {
  gorm.Model
  Name string
}

// Create another GORM-backend model
type Product struct {
  gorm.Model
  Name        string
  Description string
}

func main() {
  DB, _ := gorm.Open("sqlite3", "demo.db")
  DB.AutoMigrate(&User{}, &Product{})

  // Initalize
  Admin := admin.New(&qor.Config{DB: DB})

  // Create resources from GORM-backend model
  Admin.AddResource(&User{})
  Admin.AddResource(&Product{})

  // Register route
  mux := http.NewServeMux()
  // amount to /admin, so visit `/admin` to view the admin interface
  Admin.MountTo("/admin", mux)

  fmt.Println("Listening on: 9000")
  http.ListenAndServe(":9000", mux)
}

*/

/*
	// Beego
	mux := http.NewServeMux()
	Admin.MountTo("/admin", mux)

	beego.Handler("/admin/*", mux)
	beego.Run()
*/

/*
	// Gin
	mux := http.NewServeMux()
	Admin.MountTo("/admin", mux)

	r := gin.Default()
	r.Any("/admin/*w", gin.WrapH(mux))
	r.Run()
*/

redpajama_set_name: RedPajamaGithub


text:
- [Throttling Management]({url}/throttling/manage)
    - [Disable Throttling](#disable-the-throttling-feature)
    - [Enable Throttling](#enable-the-throttling-feature)
    - [Check Throttling Status](#check-the-throttling-feature-status)
- [User Throttling]({url}/throttling/user-throttling)
    - [Ban user(s)](#ban-users)
    - [Unban user(s)](#unban-users)
    - [Check if User is Banned](#check-if-a-user-is-banned)
    - [Suspend user(s)](#suspend-users)
    - [Unsuspend user(s)](#unsuspend-users)
    - [Check if User is Suspended](#check-if-a-user-is-suspended)
    - [Set Suspension Time](#set-the-user-suspension-time)
    - [Get User Suspension Time](#get-the-user-suspension-time)
    - [User Login](#add-a-login-attempt)
    - [Add Login Attempt](#add-a-login-attempt)
    - [Get Login Attempts](#get-login-attempts)
    - [Clear Login Attempts](#clear-login-attempts)
    - [Check User Throttle Status](#check-the-user-throttle-status)
    - [Set Attempt Limit](#set-attempt-limit)
    - [Get Attempt Limit](#get-attempt-limit)
- [Find User(s)]({url}/throttling/find)
    - [Find a user by Id](#find-a-user-by-their-id)
    - [Find a user by Login](#find-a-user-by-their-login)


text:
"""Constants for the Switcher integration."""
DOMAIN = "switcher_kis"

CONF_DEVICE_PASSWORD = "device_password"
CONF_PHONE_ID = "phone_id"

DATA_BRIDGE = "bridge"
DATA_DEVICE = "device"
DATA_DISCOVERY = "discovery"

DISCOVERY_TIME_SEC = 6

SIGNAL_DEVICE_ADD = "switcher_device_add"

# Services
CONF_AUTO_OFF = "auto_off"
CONF_TIMER_MINUTES = "timer_minutes"
SERVICE_SET_AUTO_OFF_NAME = "set_auto_off"
SERVICE_TURN_ON_WITH_TIMER_NAME = "turn_on_with_timer"

# Defines the maximum interval device must send an update before it marked unavailable
MAX_UPDATE_INTERVAL_SEC = 20


text:
layout: page
title: Norton Precinct Media Seminar
date: 2016-05-24
author: Katherine Brock
tags: weekly links, java
status: published
summary: Phasellus sit amet porttitor eros.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 10/17/2018
  endDate: 10/18/2018
  ctyhocn: PKBWVHX
  groupCode: NPMS
published: true
---
Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nulla posuere et purus pulvinar venenatis. In mattis, velit vel mollis vehicula, tortor dolor condimentum mi, ut dapibus nibh leo non sem. Etiam gravida rutrum ultrices. Vivamus consectetur ut magna eu tristique. Suspendisse feugiat facilisis tincidunt. Donec scelerisque fringilla leo. Fusce maximus elit eu ante ullamcorper lacinia.

* Cras sit amet est at elit dictum aliquet
* Curabitur pretium urna vel arcu tincidunt, eu sodales ipsum fermentum
* Vestibulum a massa mollis, dictum ipsum id, tristique sem
* Vivamus porta lectus gravida urna condimentum, in pellentesque justo congue.

Curabitur et iaculis justo. Integer tincidunt suscipit magna. Nulla congue arcu a leo congue, vel bibendum felis dictum. Nunc feugiat feugiat felis eget malesuada. Morbi et neque porttitor sem pulvinar pharetra. Etiam a nibh laoreet, aliquet leo et, fringilla ex. Ut dictum suscipit odio, nec ullamcorper orci pretium lacinia. Donec aliquet placerat arcu ac elementum. Phasellus et posuere augue, non gravida mauris. Vivamus eget interdum tellus. Proin non leo ipsum. Integer mattis quam id purus luctus, quis blandit orci tempor. Vestibulum posuere at ipsum eget consectetur. Aenean ligula nisl, maximus eget commodo sit amet, hendrerit quis nunc. Vestibulum cursus rhoncus purus, nec semper lorem dapibus a. Cras turpis augue, varius vel ullamcorper at, lacinia id lectus.


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
HamletSpec._Head (hadoop-yarn-common 2.3.0 API)
</TITLE>

<META NAME="date" CONTENT="2015-03-06">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.hadoop.yarn.webapp.hamlet

Interface HamletSpec._Head

All Superinterfaces:
HamletSpec._Object, HamletSpec._Script, HamletSpec.HeadMisc

All Known Subinterfaces:
HamletSpec._Html, HamletSpec.HEAD, HamletSpec.HTML

All Known Implementing Classes:
Hamlet, Hamlet.HEAD, Hamlet.HTML, HtmlBlock.Block, HtmlPage.Page

Enclosing class:
HamletSpec

public static interface HamletSpec._Head
extends HamletSpec.HeadMisc

Method Summary

 HamletSpec.BASE
base()

          Add a BASE element.

 HamletSpec._Head
base(String uri)

          Add a complete BASE element.

 HamletSpec.TITLE
title()

          Add a TITLE element.

 HamletSpec._Head
title(String cdata)

          Add a TITLE element.

Methods inherited from interface org.apache.hadoop.yarn.webapp.hamlet.HamletSpec.HeadMisc

link, link, meta_http, meta, meta, style, style

Methods inherited from interface org.apache.hadoop.yarn.webapp.hamlet.HamletSpec._Script

script, script

Methods inherited from interface org.apache.hadoop.yarn.webapp.hamlet.HamletSpec._Object

object, object

Method Detail

title

HamletSpec.TITLE title()

Add a TITLE element.

Returns:
a new TITLE element builder

title

HamletSpec._Head title(String cdata)

Add a TITLE element.

Parameters:
cdata - the content

Returns:
the current element builder

base

HamletSpec.BASE base()

Add a BASE element.

Returns:
a new BASE element builder

base

HamletSpec._Head base(String uri)

Add a complete BASE element.

Parameters:
uri -

Returns:
the current element builder

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2015 Apache Software Foundation. All Rights Reserved.


text:
require 'spec_helper'

RSpec.describe Projects::ParticipantsService do
  describe '#groups' do
    let_it_be(:user) { create(:user) }
    let_it_be(:project) { create(:project, :public) }
    let(:service) { described_class.new(project, user) }

    it 'avoids N+1 queries' do
      group_1 = create(:group)
      group_1.add_owner(user)

      service.groups # Run general application warmup queries
      control_count = ActiveRecord::QueryRecorder.new { service.groups }.count

      group_2 = create(:group)
      group_2.add_owner(user)

      expect { service.groups }.not_to exceed_query_limit(control_count)
    end

    it 'returns correct user counts for groups' do
      group_1 = create(:group)
      group_1.add_owner(user)
      group_1.add_owner(create(:user))

      group_2 = create(:group)
      group_2.add_owner(user)
      create(:group_member, :access_request, group: group_2, user: create(:user))

      expect(service.groups).to contain_exactly(
        a_hash_including(name: group_1.full_name, count: 2),
        a_hash_including(name: group_2.full_name, count: 1)
      )
    end

    describe 'avatar_url' do
      let(:group) { create(:group, avatar: fixture_file_upload('spec/fixtures/dk.png')) }

      before do
        group.add_owner(user)
      end

      it 'returns an url for the avatar' do
        expect(service.groups.size).to eq 1
        expect(service.groups.first[:avatar_url]).to eq("/uploads/-/system/group/avatar/#{group.id}/dk.png")
      end

      it 'returns an url for the avatar with relative url' do
        stub_config_setting(relative_url_root: '/gitlab')
        stub_config_setting(url: Settings.send(:build_gitlab_url))

        expect(service.groups.size).to eq 1
        expect(service.groups.first[:avatar_url]).to eq("/gitlab/uploads/-/system/group/avatar/#{group.id}/dk.png")
      end
    end
  end

  describe '#project_members' do
    subject(:usernames) { service.project_members.map { |member| member[:username] } }

    context 'when there is a project in group namespace' do
      let_it_be(:public_group) { create(:group, :public) }
      let_it_be(:public_project) { create(:project, :public, namespace: public_group)}

      let_it_be(:public_group_owner) { create(:user) }

      let(:service) { described_class.new(public_project, create(:user)) }

      before do
        public_group.add_owner(public_group_owner)
      end

      it 'returns members of a group' do
        expect(usernames).to include(public_group_owner.username)
      end
    end

    context 'when there is a private group and a public project' do
      let_it_be(:public_group) { create(:group, :public) }
      let_it_be(:private_group) { create(:group, :private, :nested) }
      let_it_be(:public_project) { create(:project, :public, namespace: public_group)}

      let_it_be(:project_issue) { create(:issue, project: public_project)}

      let_it_be(:public_group_owner) { create(:user) }
      let_it_be(:private_group_member) { create(:user) }
      let_it_be(:public_project_maintainer) { create(:user) }
      let_it_be(:private_group_owner) { create(:user) }

      let_it_be(:group_ancestor_owner) { create(:user) }

      before_all do
        public_group.add_owner public_group_owner
        private_group.add_developer private_group_member
        public_project.add_maintainer public_project_maintainer

        private_group.add_owner private_group_owner
        private_group.parent.add_owner group_ancestor_owner
      end

      context 'when the private group is invited to the public project' do
        before_all do
          create(:project_group_link, group: private_group, project: public_project)
        end

        context 'when a user who is outside the public project and the private group is signed in' do
          let(:service) { described_class.new(public_project, create(:user)) }

          it 'does not return the private group' do
            expect(usernames).not_to include(private_group.name)
          end

          it 'does not return private group members' do
            expect(usernames).not_to include(private_group_member.username)
          end

          it 'returns the project maintainer' do
            expect(usernames).to include(public_project_maintainer.username)
          end

          it 'returns project members from an invited public group' do
            invited_public_group = create(:group, :public)
            invited_public_group.add_owner create(:user)

            create(:project_group_link, group: invited_public_group, project: public_project)

            expect(usernames).to include(invited_public_group.users.first.username)
          end

          it 'does not return ancestors of the private group' do
            expect(usernames).not_to include(group_ancestor_owner.username)
          end
        end

        context 'when private group owner is signed in' do
          let(:service) { described_class.new(public_project, private_group_owner) }

          it 'returns private group members' do
            expect(usernames).to include(private_group_member.username)
          end

          it 'returns ancestors of the the private group' do
            expect(usernames).to include(group_ancestor_owner.username)
          end
        end

        context 'when the namespace owner of the public project is signed in' do
          let(:service) { described_class.new(public_project, public_group_owner) }

          it 'returns private group members' do
            expect(usernames).to include(private_group_member.username)
          end

          it 'does not return members of the ancestral groups of the private group' do
            expect(usernames).to include(group_ancestor_owner.username)
          end
        end
      end
    end
  end
end


text:
<?php

namespace CodeIgniter\Exceptions;

use Throwable;

/**
 * This trait provides framework exceptions the ability to pinpoint
 * accurately where the exception was raised rather than instantiated.
 *
 * This is used primarily for factory-instantiated exceptions.
 */
trait DebugTraceableTrait
{
	/**
	 * Tweaks the exception's constructor to assign the file/line to where
	 * it is actually raised rather than were it is instantiated.
	 *
	 * @param string         $message
	 * @param integer        $code
	 * @param Throwable|null $previous
	 */
	final public function __construct(string $message = '', int $code = 0, Throwable $previous = null)
	{
		parent::__construct($message, $code, $previous);

		$trace = $this->getTrace()[0];

		if (isset($trace['class']) && $trace['class'] === static::class)
		{
			[
				'line' => $this->line,
				'file' => $this->file,
			] = $trace;
		}
	}
}


text:
<?php

declare(strict_types=1);

/**
 * This file is part of Narrowspark Framework.
 *
 * (c) Daniel Bannert <d.bannert@anolilab.de>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Viserio\Component\Container\Tests\Fixture\Invoke;

use Viserio\Component\Container\Tests\Fixture\EmptyClass;

class InvokeParameterAndConstructorParameterClass
{
    public function __construct(EmptyClass $class)
    {
    }

    public function __invoke(InvokeCallableClass $invokeCallableClass): InvokeCallableClass
    {
        return $invokeCallableClass;
    }
}


text:
import unittest

from slackrest.command import Visibility, Method, UnknownMethodException, CommandParser

class FooCommand:
    pattern = '!foo'
    url_format = '/foo'
    visibility = Visibility.Any
    body = None
    method = Method.GET

class FooWithParameter:
    pattern = '!foo {bar}'
    url_format = '/foo/bar'
    visibility = Visibility.Any
    body = None
    method = Method.GET

class TestCommand(unittest.TestCase):
    def test_ChannelVisibility_ChannelStartingWithC_ChannelIsPublic(self):
        self.assertEqual(Visibility.Public, Visibility.parse("C0123456"))

    def test_ChannelVisibility_ChannelStartingWithD_ChannelIsPrivate(self):
        self.assertEqual(Visibility.Private, Visibility.parse("D0123456"))

    def test_ParseMethod_GET_MethodIsGET(self):
        self.assertEqual(Method.GET, Method.parse("GET"))

    def test_ParseMethod_POST_MethodIsPOST(self):
        self.assertEqual(Method.POST, Method.parse("POST"))

    def test_ParseMethod_PUT_MethodIsPUT(self):
        self.assertEqual(Method.PUT, Method.parse("PUT"))

    def test_ParseMethod_DELETE_MethodIsDELETE(self):
        self.assertEqual(Method.DELETE, Method.parse("DELETE"))

    def test_ParseMethod_UnknownMethod_RaisesException(self):
        self.assertRaises(UnknownMethodException, Method.parse, "NOTAMETHOD")

    def test_SerializeMethod_GET_ReturnsString(self):
        self.assertEqual('GET', Method.serialize(Method.GET))

    def test_SerializeMethod_POST_ReturnsString(self):
        self.assertEqual('POST', Method.serialize(Method.POST))

    def test_ParseCommand_CommandHasTrailingWhitespace_CommandIsFound(self):
        command_parser = CommandParser([FooCommand])
        text_with_trailing_whitespace = "!foo "
        channel_id = "C1"
        user_id = "U1"
        user_name = "user"
        self_name = "mybotname"
        command = command_parser.parse(text_with_trailing_whitespace, channel_id, user_id, user_name, self_name, Visibility.Public)
        self.assertIsNotNone(command)

    def test_ParseCommand_CommandHasNoParameter_NonParameterVersionIsFound(self):
        command_parser = CommandParser([FooWithParameter, FooCommand])
        no_param_text = "!foo"
        channel_id = "C1"
        user_id = "U1"
        user_name = "user"
        self_name = "mybotname"
        command = command_parser.parse(no_param_text, channel_id, user_id, user_name, self_name, Visibility.Public)
        self.assertEqual(command.url, "/foo")


text:
<?php

namespace ondrs\ApiBase\Services;

use Nette\Neon\Neon;
use Nette\Utils\Json;
use ondrs\ApiBase\ApiPresenter;

class ExampleResponse
{

    /** @var  FakeResponse */
    private $fakeResponse;

    public function __construct(FakeResponse $fakeResponse)
    {
        $this->fakeResponse = $fakeResponse;
    }

    /**
     * @param ApiPresenter $presenter
     * @param string $what
     * @param string $actionName
     * @return mixed|\stdClass
     */
    public function generate(ApiPresenter $presenter, $what, $actionName)
    {
        $schemaFile = SchemaProvider::getSchemaFile($presenter, $what, $actionName);
        $exampleFile = SchemaProvider::getSchemaExampleFile($presenter, $what, $actionName);

        if ($exampleFile) {
            $example = @file_get_contents($exampleFile);  // TODO: validate content
            $example = Neon::decode($example);
            return Json::decode(Json::encode($example));
        }

        return $this->fakeResponse->generate($schemaFile);
    }

}


text:
var express = require('express');
var fs = require('fs');
var router = require('express').Router();
var jsonfile = require('jsonfile')
var yaml = require('js-yaml');

const BASE_DIR = 'templates/'

const getTemplate = (file) => {
  if (fs.existsSync(BASE_DIR + file + '.json')) {
    return jsonfile.readFileSync(BASE_DIR + file + '.json');
  } else if (fs.existsSync(BASE_DIR + file + '.yaml')) {
    return yaml.safeLoad(fs.readFileSync(BASE_DIR + file + '.yaml', {encoding: 'utf-8'}));
  }
    throw new Error("Template '" + file + "' not found")
}

const sendResponse = (request, response, data) => {
  let result;
  response.setHeader('charset', 'utf8');

  response.setHeader("Content-Type", "application/json; charset=utf-8")
  result = JSON.stringify(data);

  const buffer = new Buffer(result)
  response.setHeader('Content-Length', buffer.length)
  response.end(buffer.toString('utf-8'))
}

router.route('/templates').get(function (req, res) {
  const templates = fs.readdirSync(BASE_DIR);
  sendResponse(req, res, {"success": true, "templates":
    templates.map(function(f) {
      return f.split('.')[0];
    }
  )})
})

const getActionList = (template) => {
  var keys = [];
  for(var k in template.texts) {
    keys.push(k)
  }

  return keys
}

router.route('/:file/actions').get(function (req, res) {
  try {
    const template = getTemplate(req.params.file), actions = getActionList(template)

    sendResponse(req, res, {"success": true, "file": req.params.action, "actions": actions})
  } catch (e) {
    console.log(e)

    sendResponse(req, res, {"success": false, "text": e.message})
    return
  }
})

router.route('/:file/:action*?')
  .get(function(req, res) {
  try {
    const template = getTemplate(req.params.file),
    actions = getActionList(template)
    let action
    if (req.params.action) {
      action = req.params.action;

      if (actions.indexOf(action) === -1) {
        throw "Action '" + action + "' does not exist in " + actions.join(', ')
      }
    } else {
      action = actions[Math.floor(Math.random() * actions.length)];
    }

    var text = template.texts[action], orgtext = text

    let valueList = JSON.parse(JSON.stringify(template.values)), i = 0

    while (text.match(/{(\w+)}/)) {
      i++
      if (i > 10) {
        throw "Too many loops while parsing placeholders for " + orgtext
      }

      text = text.replace(/{(\w+)}/g, function (w, m) {
        if (valueList[m] == undefined) {
          throw "Could not match placeholder " + m
        }
        let values = valueList[m]

        if (values.length == 0) {
          throw "No more unique values left for '" + m + "'. Please add more choices to the template"
        }

        let index = Math.floor(Math.random() * values.length)
        const item = values[index];
        values.splice(index, 1)
        return item;
      });
    }
  } catch (e) {
    console.log(e)

    sendResponse(req, res, {"success": false, "text": e.message})
    return
  }

  console.log("Result: " + text);
  sendResponse(req, res, {"success": true, "text": text})
})

module.exports = router;


text:
{% extends "templates/layout-question.html" %}

{% block body_classes %}version-4{% endblock %}

{% block page_title %}
  How can we contact you?
{% endblock %}

{% block question_number %}3{% endblock %}
{% block previous_url %}name{% endblock %}
{% block next_url %}how-often-contact{% endblock %}

{% block question_content %}

We'll only use this information to contact you with research opportunities relevant to you. We won't share it with
anyone else
  and you can leave the panel at any time.

    Email address
    <input type="text" class="form-control form-control-1-1" id="email">

    Phone number
    <input type="text" class="form-control form-control-1-2" id="tel">

  How would you prefer to be contacted?

      <input type="radio" id="preferred-contact-1" name="preferred-contact" value="preferred-contact-1">
      Email

      <input type="radio" id="preferred-contact-2" name="preferred-contact" value="preferred-contact-2">
      Phone

{% endblock %}


text:
module I18n
  module Transformers
    class Collection
      class Generic < Base
        def initialize(name: nil, **options, &block)
          super options, &block
          @name = name ? name.to_s : to_s
          raise ArgumentError, 'block is missing' unless @block
        end

        def transform(key, value)
          @block.call(key, value)
        end
      end
    end
  end
end


text:
static void
CheckBoxPaint(tWidget *psWidget, bool bClick)
{
    tCheckBoxWidget *pCheck;
    tRectangle i16Rect;
    tContext sCtx;
    int32_t i32Y;

    //
    // Check the arguments.
    //
    ASSERT(psWidget);

    //
    // Convert the generic widget pointer into a check box widget pointer.
    //
    pCheck = (tCheckBoxWidget *)psWidget;

    //
    // Initialize a drawing context.
    //
    GrContextInit(&sCtx, psWidget->psDisplay);

    //
    // Initialize the clipping region based on the extents of this check box.
    //
    GrContextClipRegionSet(&sCtx, &(psWidget->sPosition));

    //
    // See if the check box fill style is selected.
    //
    if((pCheck->ui16Style & CB_STYLE_FILL) && !bClick)
    {
        //
        // Fill the check box with the fill color.
        //
        GrContextForegroundSet(&sCtx, pCheck->ui32FillColor);
        GrRectFill(&sCtx, &(psWidget->sPosition));
    }

    //
    // See if the check box outline style is selected.
    //
    if((pCheck->ui16Style & CB_STYLE_OUTLINE) && !bClick)
    {
        //
        // Outline the check box with the outline color.
        //
        GrContextForegroundSet(&sCtx, pCheck->ui32OutlineColor);
        GrRectDraw(&sCtx, &(psWidget->sPosition));
    }

    //
    // Draw the check box.
    //
    i16Rect.i16XMin = psWidget->sPosition.i16XMin + 2;
    i16Rect.i16YMin = (psWidget->sPosition.i16YMin +
                   ((psWidget->sPosition.i16YMax - psWidget->sPosition.i16YMin -
                     pCheck->ui16BoxSize + 1) / 2));
    i16Rect.i16XMax = i16Rect.i16XMin + pCheck->ui16BoxSize - 1;
    i16Rect.i16YMax = i16Rect.i16YMin + pCheck->ui16BoxSize - 1;
    if(!bClick)
    {
        GrContextForegroundSet(&sCtx, pCheck->ui32OutlineColor);
        GrRectDraw(&sCtx, &i16Rect);
    }

    //
    // Select the foreground color based on whether or not the check box is
    // selected.
    //
    if(pCheck->ui16Style & CB_STYLE_SELECTED)
    {
        GrContextForegroundSet(&sCtx, pCheck->ui32OutlineColor);
    }
    else
    {
        GrContextForegroundSet(&sCtx, pCheck->ui32FillColor);
    }

    //
    // Draw an "X" in the check box.
    //
    GrLineDraw(&sCtx, i16Rect.i16XMin + 1, i16Rect.i16YMin + 1,
               i16Rect.i16XMax - 1, i16Rect.i16YMax - 1);
    GrLineDraw(&sCtx, i16Rect.i16XMin + 1, i16Rect.i16YMax - 1,
               i16Rect.i16XMax - 1, i16Rect.i16YMin + 1);

    //
    // See if the check box text or image style is selected.
    //
    if((pCheck->ui16Style & (CB_STYLE_TEXT | CB_STYLE_IMG)) && !bClick)
    {
        //
        // Shrink the clipping region by the size of the check box so that it
        // is not overwritten by further "decorative" portions of the widget.
        //
        sCtx.sClipRegion.i16XMin += pCheck->ui16BoxSize + 4;

        //
        // If the check box outline style is selected then shrink the clipping
        // region by one pixel on each side so that the outline is not
        // overwritten by the text or image.
        //
        if(pCheck->ui16Style & CB_STYLE_OUTLINE)
        {
            sCtx.sClipRegion.i16YMin++;
            sCtx.sClipRegion.i16XMax--;
            sCtx.sClipRegion.i16YMax--;
        }

        //
        // See if the check box image style is selected.
        //
        if(pCheck->ui16Style & CB_STYLE_IMG)
        {
            //
            // Determine where along the Y extent of the widget to draw the
            // image.  It is drawn at the top if it takes all (or more than
            // all) of the Y extent of the widget, and it is drawn centered if
            // it takes less than the Y extent.
            //
            if(GrImageHeightGet(pCheck->pui8Image) >
               (sCtx.sClipRegion.i16YMax - sCtx.sClipRegion.i16YMin))
            {
                i32Y = sCtx.sClipRegion.i16YMin;
            }
            else
            {
                i32Y = (sCtx.sClipRegion.i16YMin +
                      ((sCtx.sClipRegion.i16YMax - sCtx.sClipRegion.i16YMin -
                        GrImageHeightGet(pCheck->pui8Image) + 1) / 2));
            }

            //
            // Set the foreground and background colors to use for 1 BPP
            // images.
            //
            GrContextForegroundSet(&sCtx, pCheck->ui32TextColor);
            GrContextBackgroundSet(&sCtx, pCheck->ui32FillColor);

            //
            // Draw the image next to the check box.
            //
            GrImageDraw(&sCtx, pCheck->pui8Image, sCtx.sClipRegion.i16XMin,
                        i32Y);
        }

        //
        // See if the check box text style is selected.
        //
        if(pCheck->ui16Style & CB_STYLE_TEXT)
        {
            //
            // Determine where along the Y extent of the widget to draw the
            // string.  It is drawn at the top if it takes all (or more than
            // all) of the Y extent of the widget, and it is drawn centered if
            // it takes less than the Y extent.
            //
            if(GrFontHeightGet(pCheck->psFont) >
               (sCtx.sClipRegion.i16YMax - sCtx.sClipRegion.i16YMin))
            {
                i32Y = sCtx.sClipRegion.i16YMin;
            }
            else
            {
                i32Y = (sCtx.sClipRegion.i16YMin +
                      ((sCtx.sClipRegion.i16YMax - sCtx.sClipRegion.i16YMin -
                        GrFontHeightGet(pCheck->psFont) + 1) / 2));
            }

            //
            // Draw the text next to the check box.
            //
            GrContextFontSet(&sCtx, pCheck->psFont);
            GrContextForegroundSet(&sCtx, pCheck->ui32TextColor);
            GrContextBackgroundSet(&sCtx, pCheck->ui32FillColor);
            GrStringDraw(&sCtx, pCheck->pcText, -1, sCtx.sClipRegion.i16XMin,
                         i32Y, pCheck->ui16Style & CB_STYLE_TEXT_OPAQUE);
        }
    }
}

//*****************************************************************************
//
//! Handles pointer events for a check box.
//!
//! \param psWidget is a pointer to the check box widget.
//! \param ui32Msg is the pointer event message.
//! \param i32X is the X coordinate of the pointer event.
//! \param i32Y is the Y coordinate of the pointer event.
//!
//! This function processes pointer event messages for a check box.  This is
//! called in response to a \b #WIDGET_MSG_PTR_DOWN, \b #WIDGET_MSG_PTR_MOVE,
//! and \b #WIDGET_MSG_PTR_UP messages.
//!
//! If the \b #WIDGET_MSG_PTR_UP message is received with a position within the
//! extents of the check box, the check box's selected state will be toggled
//! and its OnChange function is called.
//!
//! \return Returns 1 if the coordinates are within the extents of the check
//! box and 0 otherwise.
//
//*****************************************************************************
static int32_t
CheckBoxClick(tWidget *psWidget, uint32_t ui32Msg, int32_t i32X, int32_t i32Y)
{
    tCheckBoxWidget *pCheck;

    //
    // Check the arguments.
    //
    ASSERT(psWidget);

    //
    // Convert the generic widget pointer into a check box widget pointer.
    //
    pCheck = (tCheckBoxWidget *)psWidget;

    //
    // See if the given coordinates are within the extents of the check box.
    //
    if((i32X >= psWidget->sPosition.i16XMin) &&
       (i32X <= psWidget->sPosition.i16XMax) &&
       (i32Y >= psWidget->sPosition.i16YMin) &&
       (i32Y <= psWidget->sPosition.i16YMax))
    {
        //
        // See if the pointer was just raised.
        //
        if(ui32Msg == WIDGET_MSG_PTR_UP)
        {
            //
            // Toggle the selected state of this check box.
            //
            pCheck->ui16Style ^= CB_STYLE_SELECTED;

            //
            // Redraw the check box based on the new selected state.
            //
            CheckBoxPaint(psWidget, 1);

            //
            // If there is an OnChange callback for this widget then call the
            // callback.
            //
            if(pCheck->pfnOnChange)
            {
                pCheck->pfnOnChange(psWidget,
                                    pCheck->ui16Style & CB_STYLE_SELECTED);
            }
        }

        //
        // These coordinates are within the extents of the check box widget.
        //
        return(1);
    }

    //
    // These coordinates are not within the extents of the check box widget.
    //
    return(0);
}

//*****************************************************************************
//
//! Handles messages for a check box widget.
//!
//! \param psWidget is a pointer to the check box widget.
//! \param ui32Msg is the message.
//! \param ui32Param1 is the first parameter to the message.
//! \param ui32Param2 is the second parameter to the message.
//!
//! This function receives messages intended for this check box widget and
//! processes them accordingly.  The processing of the message varies based on
//! the message in question.
//!
//! Unrecognized messages are handled by calling WidgetDefaultMsgProc().
//!
//! \return Returns a value appropriate to the supplied message.
//
//*****************************************************************************
int32_t
CheckBoxMsgProc(tWidget *psWidget, uint32_t ui32Msg, uint32_t ui32Param1,
                uint32_t ui32Param2)
{
    //
    // Check the arguments.
    //
    ASSERT(psWidget);

    //
    // Determine which message is being sent.
    //
    switch(ui32Msg)
    {
        //
        // The widget paint request has been sent.
        //
        case WIDGET_MSG_PAINT:
        {
            //
            // Handle the widget paint request.
            //
            CheckBoxPaint(psWidget, 0);

            //
            // Return one to indicate that the message was successfully
            // processed.
            //
            return(1);
        }

        //
        // One of the pointer requests has been sent.
        //
        case WIDGET_MSG_PTR_DOWN:
        case WIDGET_MSG_PTR_MOVE:
        case WIDGET_MSG_PTR_UP:
        {
            //
            // Handle the pointer request, returning the appropriate value.
            //
            return(CheckBoxClick(psWidget, ui32Msg, ui32Param1, ui32Param2));
        }

        //
        // An unknown request has been sent.
        //
        default:
        {
            //
            // Let the default message handler process this message.
            //
            return(WidgetDefaultMsgProc(psWidget, ui32Msg, ui32Param1,
                                        ui32Param2));
        }
    }
}

//*****************************************************************************
//
//! Initializes a check box widget.
//!
//! \param psWidget is a pointer to the check box widget to initialize.
//! \param psDisplay is a pointer to the display on which to draw the check box.
//! \param i32X is the X coordinate of the upper left corner of the check box.
//! \param i32Y is the Y coordinate of the upper left corner of the check box.
//! \param i32Width is the width of the check box.
//! \param i32Height is the height of the check box.
//!
//! This function initializes the provided check box widget.
//!
//! \return None.
//
//*****************************************************************************
void
CheckBoxInit(tCheckBoxWidget *psWidget, const tDisplay *psDisplay, int32_t i32X,
             int32_t i32Y, int32_t i32Width, int32_t i32Height)
{
    uint32_t ui32Idx;

    //
    // Check the arguments.
    //
    ASSERT(psWidget);
    ASSERT(psDisplay);

    //
    // Clear out the widget structure.
    //
    for(ui32Idx = 0; ui32Idx < sizeof(tCheckBoxWidget); ui32Idx += 4)
    {
        ((uint32_t *)psWidget)[ui32Idx / 4] = 0;
    }

    //
    // Set the size of the check box widget structure.
    //
    psWidget->sBase.i32Size = sizeof(tCheckBoxWidget);

    //
    // Mark this widget as fully disconnected.
    //
    psWidget->sBase.psParent = 0;
    psWidget->sBase.psNext = 0;
    psWidget->sBase.psChild = 0;

    //
    // Save the display pointer.
    //
    psWidget->sBase.psDisplay = psDisplay;

    //
    // Set the extents of this check box.
    //
    psWidget->sBase.sPosition.i16XMin = i32X;
    psWidget->sBase.sPosition.i16YMin = i32Y;
    psWidget->sBase.sPosition.i16XMax = i32X + i32Width - 1;
    psWidget->sBase.sPosition.i16YMax = i32Y + i32Height - 1;

    //
    // Use the check box message handler to processage messages to this check
    // box.
    //
    psWidget->sBase.pfnMsgProc = CheckBoxMsgProc;
}

//*****************************************************************************
//
// Close the Doxygen group.
//! @}
//
//*****************************************************************************


text:
package org.hawkular.apm.api.model.analytics;

import com.fasterxml.jackson.annotation.JsonInclude;

/**
 * This class represents a set of statistical values.
 *
 * @author gbrown
 */
public class TimeseriesStatistics {

    /**
     * Timestamp in microseconds
     */
    @JsonInclude
    private long timestamp = 0;

    @JsonInclude
    private long count = 0;

    @JsonInclude
    private long faultCount = 0;

    /**
     * Minimal duration in microseconds
     */
    @JsonInclude
    private long min = 0;

    /**
     * Average duration in microseconds
     */
    @JsonInclude
    private long average = 0;

    /**
     * Maximal duration in microseconds
     */
    @JsonInclude
    private long max = 0;

    /**
     * @return the timestamp
     */
    public long getTimestamp() {
        return timestamp;
    }

    /**
     * @param timestamp the timestamp to set
     */
    public void setTimestamp(long timestamp) {
        this.timestamp = timestamp;
    }

    /**
     * @return the count
     */
    public long getCount() {
        return count;
    }

    /**
     * @param count the count to set
     */
    public void setCount(long count) {
        this.count = count;
    }

    /**
     * @return the faultCount
     */
    public long getFaultCount() {
        return faultCount;
    }

    /**
     * @param faultCount the faultCount to set
     */
    public void setFaultCount(long faultCount) {
        this.faultCount = faultCount;
    }

    /**
     * @return the min
     */
    public long getMin() {
        return min;
    }

    /**
     * @param min the min to set
     */
    public void setMin(long min) {
        this.min = min;
    }

    /**
     * @return the average
     */
    public long getAverage() {
        return average;
    }

    /**
     * @param average the average to set
     */
    public void setAverage(long average) {
        this.average = average;
    }

    /**
     * @return the max
     */
    public long getMax() {
        return max;
    }

    /**
     * @param max the max to set
     */
    public void setMax(long max) {
        this.max = max;
    }

    @Override
    public String toString() {
        return "TimeseriesStatistics [timestamp=" + timestamp + ", count=" + count + ", faultCount="
                + faultCount + ", min=" + min + ", average=" + average + ", max=" + max + "]";
    }

}


text:
layout: default
title: Not found
---

Not Found

Sorry we couldn't find that page!


text:
package org.jkiss.dbeaver.model.impl.jdbc.data;

import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.model.DBPDataSource;
import org.jkiss.dbeaver.model.DBValueFormatting;
import org.jkiss.dbeaver.model.data.DBDContentCached;
import org.jkiss.dbeaver.model.data.DBDContentStorage;
import org.jkiss.dbeaver.model.data.DBDDisplayFormat;
import org.jkiss.dbeaver.model.exec.DBCException;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCPreparedStatement;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.struct.DBSTypedObject;
import org.jkiss.dbeaver.utils.ContentUtils;
import org.jkiss.dbeaver.utils.MimeTypes;
import org.jkiss.utils.CommonUtils;

import java.io.*;
import java.sql.SQLException;

/**
 * JDBCContentChars
 *
 * @author Serge Rider
 */
public class JDBCContentChars extends JDBCContentAbstract implements DBDContentStorage, DBDContentCached {

    private String originalData;
    protected String data;

    public JDBCContentChars(DBPDataSource dataSource, String data) {
        super(dataSource);
        this.data = this.originalData = data;
    }

    @Override
    public InputStream getContentStream()
        throws IOException
    {
        if (data == null) {
            // Empty content
            return new ByteArrayInputStream(new byte[0]);
        } else {
            return new ByteArrayInputStream(data.getBytes(getCharset()));
        }
    }

    @Override
    public Reader getContentReader()
        throws IOException
    {
        if (data == null) {
            // Empty content
            return new StringReader(""); //$NON-NLS-1$
        } else {
            return new StringReader(data);
        }
    }

    @Override
    public long getContentLength() {
        if (data == null) {
            return 0;
        }
        return data.length();
    }

    @NotNull
    @Override
    public String getContentType()
    {
        return MimeTypes.TEXT_PLAIN;
    }

    @Override
    public DBDContentStorage getContents(DBRProgressMonitor monitor)
        throws DBCException
    {
        return this;
    }

    @Override
    public boolean updateContents(
        DBRProgressMonitor monitor,
        DBDContentStorage storage)
        throws DBException
    {
        if (storage == null) {
            data = null;
        } else {
            try {
                Reader reader = storage.getContentReader();
                try {
                    StringWriter sw = new StringWriter((int)storage.getContentLength());
                    ContentUtils.copyStreams(reader, storage.getContentLength(), sw, monitor);
                    data = sw.toString();
                }
                finally {
                    ContentUtils.close(reader);
                }
            }
            catch (IOException e) {
                throw new DBCException("IO error while reading content", e);
            }
        }
        this.modified = true;
        return false;
    }

    @Override
    public void resetContents()
    {
        this.data = this.originalData;
        this.modified = false;
    }

    @Override
    public String getCharset()
    {
        return DBValueFormatting.getDefaultBinaryFileEncoding(dataSource);
    }

    @Override
    public JDBCContentChars cloneStorage(DBRProgressMonitor monitor)
    {
        return cloneValue(monitor);
    }

    @Override
    public void bindParameter(JDBCSession session, JDBCPreparedStatement preparedStatement,
                              DBSTypedObject columnType, int paramIndex)
        throws DBCException
    {
        try {
            if (data != null) {
                preparedStatement.setString(paramIndex, data);
            } else {
                preparedStatement.setNull(paramIndex, columnType.getTypeID());
            }
        }
        catch (SQLException e) {
            throw new DBCException(e, dataSource);
        }
    }

    @Override
    public Object getRawValue() {
        return data;
    }

    @Override
    public boolean isNull()
    {
        return data == null;
    }

    @Override
    public void release()
    {
        this.data = this.originalData;
    }

    @Override
    public boolean equals(Object obj)
    {
        return
            obj instanceof JDBCContentChars &&
            CommonUtils.equalObjects(data, ((JDBCContentChars) obj).data);
    }

    @Override
    public String getDisplayString(DBDDisplayFormat format) {
        return data;
    }

    @Override
    public JDBCContentChars cloneValue(DBRProgressMonitor monitor)
    {
        return new JDBCContentChars(dataSource, data);
    }

    @Override
    public Object getCachedValue()
    {
        return data;
    }

}


text:
/**
 * ExtensionSettingErrorReason.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
 */

package com.google.api.ads.adwords.axis.v201502.cm;

public class ExtensionSettingErrorReason implements java.io.Serializable {
    private java.lang.String _value_;
    private static java.util.HashMap _table_ = new java.util.HashMap();

    // Constructor
    protected ExtensionSettingErrorReason(java.lang.String value) {
        _value_ = value;
        _table_.put(_value_,this);
    }

    public static final java.lang.String _EXTENSIONS_REQUIRED = "EXTENSIONS_REQUIRED";
    public static final java.lang.String _FEED_TYPE_EXTENSION_TYPE_MISMATCH = "FEED_TYPE_EXTENSION_TYPE_MISMATCH";
    public static final java.lang.String _INVALID_FEED_TYPE = "INVALID_FEED_TYPE";
    public static final java.lang.String _INVALID_FEED_TYPE_FOR_CUSTOMER_EXTENSION_SETTING = "INVALID_FEED_TYPE_FOR_CUSTOMER_EXTENSION_SETTING";
    public static final java.lang.String _CANNOT_CHANGE_FEED_ITEM_ON_ADD = "CANNOT_CHANGE_FEED_ITEM_ON_ADD";
    public static final java.lang.String _NO_EXISTING_AD_GROUP_EXTENSION_SETTING_FOR_TYPE = "NO_EXISTING_AD_GROUP_EXTENSION_SETTING_FOR_TYPE";
    public static final java.lang.String _NO_EXISTING_CAMPAIGN_EXTENSION_SETTING_FOR_TYPE = "NO_EXISTING_CAMPAIGN_EXTENSION_SETTING_FOR_TYPE";
    public static final java.lang.String _NO_EXISTING_CUSTOMER_EXTENSION_SETTING_FOR_TYPE = "NO_EXISTING_CUSTOMER_EXTENSION_SETTING_FOR_TYPE";
    public static final java.lang.String _AD_GROUP_EXTENSION_SETTING_ALREADY_EXISTS = "AD_GROUP_EXTENSION_SETTING_ALREADY_EXISTS";
    public static final java.lang.String _CAMPAIGN_EXTENSION_SETTING_ALREADY_EXISTS = "CAMPAIGN_EXTENSION_SETTING_ALREADY_EXISTS";
    public static final java.lang.String _CUSTOMER_EXTENSION_SETTING_ALREADY_EXISTS = "CUSTOMER_EXTENSION_SETTING_ALREADY_EXISTS";
    public static final java.lang.String _AD_GROUP_FEED_ALREADY_EXISTS_FOR_PLACEHOLDER_TYPE = "AD_GROUP_FEED_ALREADY_EXISTS_FOR_PLACEHOLDER_TYPE";
    public static final java.lang.String _CAMPAIGN_FEED_ALREADY_EXISTS_FOR_PLACEHOLDER_TYPE = "CAMPAIGN_FEED_ALREADY_EXISTS_FOR_PLACEHOLDER_TYPE";
    public static final java.lang.String _CUSTOMER_FEED_ALREADY_EXISTS_FOR_PLACEHOLDER_TYPE = "CUSTOMER_FEED_ALREADY_EXISTS_FOR_PLACEHOLDER_TYPE";
    public static final java.lang.String _VALUE_OUT_OF_RANGE = "VALUE_OUT_OF_RANGE";
    public static final java.lang.String _URL_LIST_TOO_LONG = "URL_LIST_TOO_LONG";
    public static final java.lang.String _CANNOT_SET_WITH_FINAL_URLS = "CANNOT_SET_WITH_FINAL_URLS";
    public static final java.lang.String _CANNOT_SET_WITHOUT_FINAL_URLS = "CANNOT_SET_WITHOUT_FINAL_URLS";
    public static final java.lang.String _INVALID_PHONE_NUMBER = "INVALID_PHONE_NUMBER";
    public static final java.lang.String _PHONE_NUMBER_NOT_SUPPORTED_FOR_COUNTRY = "PHONE_NUMBER_NOT_SUPPORTED_FOR_COUNTRY";
    public static final java.lang.String _CARRIER_SPECIFIC_SHORT_NUMBER_NOT_ALLOWED = "CARRIER_SPECIFIC_SHORT_NUMBER_NOT_ALLOWED";
    public static final java.lang.String _PREMIUM_RATE_NUMBER_NOT_ALLOWED = "PREMIUM_RATE_NUMBER_NOT_ALLOWED";
    public static final java.lang.String _DISALLOWED_NUMBER_TYPE = "DISALLOWED_NUMBER_TYPE";
    public static final java.lang.String _INVALID_DOMESTIC_PHONE_NUMBER_FORMAT = "INVALID_DOMESTIC_PHONE_NUMBER_FORMAT";
    public static final java.lang.String _VANITY_PHONE_NUMBER_NOT_ALLOWED = "VANITY_PHONE_NUMBER_NOT_ALLOWED";
    public static final java.lang.String _INVALID_COUNTRY_CODE = "INVALID_COUNTRY_CODE";
    public static final java.lang.String _INVALID_CALL_CONVERSION_TYPE_ID = "INVALID_CALL_CONVERSION_TYPE_ID";
    public static final java.lang.String _CUSTOMER_NOT_WHITELISTED_FOR_CALLTRACKING = "CUSTOMER_NOT_WHITELISTED_FOR_CALLTRACKING";
    public static final java.lang.String _CALLTRACKING_NOT_SUPPORTED_FOR_COUNTRY = "CALLTRACKING_NOT_SUPPORTED_FOR_COUNTRY";
    public static final java.lang.String _INVALID_APP_ID = "INVALID_APP_ID";
    public static final java.lang.String _QUOTES_IN_REVIEW_EXTENSION_SNIPPET = "QUOTES_IN_REVIEW_EXTENSION_SNIPPET";
    public static final java.lang.String _HYPHENS_IN_REVIEW_EXTENSION_SNIPPET = "HYPHENS_IN_REVIEW_EXTENSION_SNIPPET";
    public static final java.lang.String _REVIEW_EXTENSION_SOURCE_INELIGIBLE = "REVIEW_EXTENSION_SOURCE_INELIGIBLE";
    public static final java.lang.String _SOURCE_NAME_IN_REVIEW_EXTENSION_TEXT = "SOURCE_NAME_IN_REVIEW_EXTENSION_TEXT";
    public static final java.lang.String _MISSING_FIELD = "MISSING_FIELD";
    public static final java.lang.String _INVALID_DEVICE_PREFERENCE = "INVALID_DEVICE_PREFERENCE";
    public static final java.lang.String _INVALID_SCHEDULE_END = "INVALID_SCHEDULE_END";
    public static final java.lang.String _DATE_TIME_MUST_BE_IN_ACCOUNT_TIME_ZONE = "DATE_TIME_MUST_BE_IN_ACCOUNT_TIME_ZONE";
    public static final java.lang.String _OVERLAPPING_SCHEDULES = "OVERLAPPING_SCHEDULES";
    public static final java.lang.String _SCHEDULE_END_NOT_AFTER_START = "SCHEDULE_END_NOT_AFTER_START";
    public static final java.lang.String _TOO_MANY_SCHEDULES_PER_DAY = "TOO_MANY_SCHEDULES_PER_DAY";
    public static final java.lang.String _UNKNOWN = "UNKNOWN";
    public static final ExtensionSettingErrorReason EXTENSIONS_REQUIRED = new ExtensionSettingErrorReason(_EXTENSIONS_REQUIRED);
    public static final ExtensionSettingErrorReason FEED_TYPE_EXTENSION_TYPE_MISMATCH = new ExtensionSettingErrorReason(_FEED_TYPE_EXTENSION_TYPE_MISMATCH);
    public static final ExtensionSettingErrorReason INVALID_FEED_TYPE = new ExtensionSettingErrorReason(_INVALID_FEED_TYPE);
    public static final ExtensionSettingErrorReason INVALID_FEED_TYPE_FOR_CUSTOMER_EXTENSION_SETTING = new ExtensionSettingErrorReason(_INVALID_FEED_TYPE_FOR_CUSTOMER_EXTENSION_SETTING);
    public static final ExtensionSettingErrorReason CANNOT_CHANGE_FEED_ITEM_ON_ADD = new ExtensionSettingErrorReason(_CANNOT_CHANGE_FEED_ITEM_ON_ADD);
    public static final ExtensionSettingErrorReason NO_EXISTING_AD_GROUP_EXTENSION_SETTING_FOR_TYPE = new ExtensionSettingErrorReason(_NO_EXISTING_AD_GROUP_EXTENSION_SETTING_FOR_TYPE);
    public static final ExtensionSettingErrorReason NO_EXISTING_CAMPAIGN_EXTENSION_SETTING_FOR_TYPE = new ExtensionSettingErrorReason(_NO_EXISTING_CAMPAIGN_EXTENSION_SETTING_FOR_TYPE);
    public static final ExtensionSettingErrorReason NO_EXISTING_CUSTOMER_EXTENSION_SETTING_FOR_TYPE = new ExtensionSettingErrorReason(_NO_EXISTING_CUSTOMER_EXTENSION_SETTING_FOR_TYPE);
    public static final ExtensionSettingErrorReason AD_GROUP_EXTENSION_SETTING_ALREADY_EXISTS = new ExtensionSettingErrorReason(_AD_GROUP_EXTENSION_SETTING_ALREADY_EXISTS);
    public static final ExtensionSettingErrorReason CAMPAIGN_EXTENSION_SETTING_ALREADY_EXISTS = new ExtensionSettingErrorReason(_CAMPAIGN_EXTENSION_SETTING_ALREADY_EXISTS);
    public static final ExtensionSettingErrorReason CUSTOMER_EXTENSION_SETTING_ALREADY_EXISTS = new ExtensionSettingErrorReason(_CUSTOMER_EXTENSION_SETTING_ALREADY_EXISTS);
    public static final ExtensionSettingErrorReason AD_GROUP_FEED_ALREADY_EXISTS_FOR_PLACEHOLDER_TYPE = new ExtensionSettingErrorReason(_AD_GROUP_FEED_ALREADY_EXISTS_FOR_PLACEHOLDER_TYPE);
    public static final ExtensionSettingErrorReason CAMPAIGN_FEED_ALREADY_EXISTS_FOR_PLACEHOLDER_TYPE = new ExtensionSettingErrorReason(_CAMPAIGN_FEED_ALREADY_EXISTS_FOR_PLACEHOLDER_TYPE);
    public static final ExtensionSettingErrorReason CUSTOMER_FEED_ALREADY_EXISTS_FOR_PLACEHOLDER_TYPE = new ExtensionSettingErrorReason(_CUSTOMER_FEED_ALREADY_EXISTS_FOR_PLACEHOLDER_TYPE);
    public static final ExtensionSettingErrorReason VALUE_OUT_OF_RANGE = new ExtensionSettingErrorReason(_VALUE_OUT_OF_RANGE);
    public static final ExtensionSettingErrorReason URL_LIST_TOO_LONG = new ExtensionSettingErrorReason(_URL_LIST_TOO_LONG);
    public static final ExtensionSettingErrorReason CANNOT_SET_WITH_FINAL_URLS = new ExtensionSettingErrorReason(_CANNOT_SET_WITH_FINAL_URLS);
    public static final ExtensionSettingErrorReason CANNOT_SET_WITHOUT_FINAL_URLS = new ExtensionSettingErrorReason(_CANNOT_SET_WITHOUT_FINAL_URLS);
    public static final ExtensionSettingErrorReason INVALID_PHONE_NUMBER = new ExtensionSettingErrorReason(_INVALID_PHONE_NUMBER);
    public static final ExtensionSettingErrorReason PHONE_NUMBER_NOT_SUPPORTED_FOR_COUNTRY = new ExtensionSettingErrorReason(_PHONE_NUMBER_NOT_SUPPORTED_FOR_COUNTRY);
    public static final ExtensionSettingErrorReason CARRIER_SPECIFIC_SHORT_NUMBER_NOT_ALLOWED = new ExtensionSettingErrorReason(_CARRIER_SPECIFIC_SHORT_NUMBER_NOT_ALLOWED);
    public static final ExtensionSettingErrorReason PREMIUM_RATE_NUMBER_NOT_ALLOWED = new ExtensionSettingErrorReason(_PREMIUM_RATE_NUMBER_NOT_ALLOWED);
    public static final ExtensionSettingErrorReason DISALLOWED_NUMBER_TYPE = new ExtensionSettingErrorReason(_DISALLOWED_NUMBER_TYPE);
    public static final ExtensionSettingErrorReason INVALID_DOMESTIC_PHONE_NUMBER_FORMAT = new ExtensionSettingErrorReason(_INVALID_DOMESTIC_PHONE_NUMBER_FORMAT);
    public static final ExtensionSettingErrorReason VANITY_PHONE_NUMBER_NOT_ALLOWED = new ExtensionSettingErrorReason(_VANITY_PHONE_NUMBER_NOT_ALLOWED);
    public static final ExtensionSettingErrorReason INVALID_COUNTRY_CODE = new ExtensionSettingErrorReason(_INVALID_COUNTRY_CODE);
    public static final ExtensionSettingErrorReason INVALID_CALL_CONVERSION_TYPE_ID = new ExtensionSettingErrorReason(_INVALID_CALL_CONVERSION_TYPE_ID);
    public static final ExtensionSettingErrorReason CUSTOMER_NOT_WHITELISTED_FOR_CALLTRACKING = new ExtensionSettingErrorReason(_CUSTOMER_NOT_WHITELISTED_FOR_CALLTRACKING);
    public static final ExtensionSettingErrorReason CALLTRACKING_NOT_SUPPORTED_FOR_COUNTRY = new ExtensionSettingErrorReason(_CALLTRACKING_NOT_SUPPORTED_FOR_COUNTRY);
    public static final ExtensionSettingErrorReason INVALID_APP_ID = new ExtensionSettingErrorReason(_INVALID_APP_ID);
    public static final ExtensionSettingErrorReason QUOTES_IN_REVIEW_EXTENSION_SNIPPET = new ExtensionSettingErrorReason(_QUOTES_IN_REVIEW_EXTENSION_SNIPPET);
    public static final ExtensionSettingErrorReason HYPHENS_IN_REVIEW_EXTENSION_SNIPPET = new ExtensionSettingErrorReason(_HYPHENS_IN_REVIEW_EXTENSION_SNIPPET);
    public static final ExtensionSettingErrorReason REVIEW_EXTENSION_SOURCE_INELIGIBLE = new ExtensionSettingErrorReason(_REVIEW_EXTENSION_SOURCE_INELIGIBLE);
    public static final ExtensionSettingErrorReason SOURCE_NAME_IN_REVIEW_EXTENSION_TEXT = new ExtensionSettingErrorReason(_SOURCE_NAME_IN_REVIEW_EXTENSION_TEXT);
    public static final ExtensionSettingErrorReason MISSING_FIELD = new ExtensionSettingErrorReason(_MISSING_FIELD);
    public static final ExtensionSettingErrorReason INVALID_DEVICE_PREFERENCE = new ExtensionSettingErrorReason(_INVALID_DEVICE_PREFERENCE);
    public static final ExtensionSettingErrorReason INVALID_SCHEDULE_END = new ExtensionSettingErrorReason(_INVALID_SCHEDULE_END);
    public static final ExtensionSettingErrorReason DATE_TIME_MUST_BE_IN_ACCOUNT_TIME_ZONE = new ExtensionSettingErrorReason(_DATE_TIME_MUST_BE_IN_ACCOUNT_TIME_ZONE);
    public static final ExtensionSettingErrorReason OVERLAPPING_SCHEDULES = new ExtensionSettingErrorReason(_OVERLAPPING_SCHEDULES);
    public static final ExtensionSettingErrorReason SCHEDULE_END_NOT_AFTER_START = new ExtensionSettingErrorReason(_SCHEDULE_END_NOT_AFTER_START);
    public static final ExtensionSettingErrorReason TOO_MANY_SCHEDULES_PER_DAY = new ExtensionSettingErrorReason(_TOO_MANY_SCHEDULES_PER_DAY);
    public static final ExtensionSettingErrorReason UNKNOWN = new ExtensionSettingErrorReason(_UNKNOWN);
    public java.lang.String getValue() { return _value_;}
    public static ExtensionSettingErrorReason fromValue(java.lang.String value)
          throws java.lang.IllegalArgumentException {
        ExtensionSettingErrorReason enumeration = (ExtensionSettingErrorReason)
            _table_.get(value);
        if (enumeration==null) throw new java.lang.IllegalArgumentException();
        return enumeration;
    }
    public static ExtensionSettingErrorReason fromString(java.lang.String value)
          throws java.lang.IllegalArgumentException {
        return fromValue(value);
    }
    public boolean equals(java.lang.Object obj) {return (obj == this);}
    public int hashCode() { return toString().hashCode();}
    public java.lang.String toString() { return _value_;}
    public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);}
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new org.apache.axis.encoding.ser.EnumSerializer(
            _javaType, _xmlType);
    }
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new org.apache.axis.encoding.ser.EnumDeserializer(
            _javaType, _xmlType);
    }
    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(ExtensionSettingErrorReason.class);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201502", "ExtensionSettingError.Reason"));
    }
    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

}


text:
package org.apache.hadoop.hbase.security;

import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.hbase.classification.InterfaceStability;

/**
 * Security related generic utility methods.
 */
@InterfaceAudience.Private
@InterfaceStability.Evolving
public class SecurityUtil {

  /**
   * Get the user name from a principal
   */
  public static String getUserFromPrincipal(final String principal) {
    int i = principal.indexOf("/");
    if (i == -1) {
      i = principal.indexOf("@");
    }
    return (i > -1) ? principal.substring(0, i) : principal;
  }

  /**
   * Get the user name from a principal
   */
  public static String getPrincipalWithoutRealm(final String principal) {
    int i = principal.indexOf("@");
    return (i > -1) ? principal.substring(0, i) : principal;
  }
}


text:
package org.optaplanner.examples.projectjobscheduling.domain;

import java.util.List;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import org.optaplanner.osgi.common.domain.AbstractPersistable;
import org.optaplanner.examples.projectjobscheduling.domain.resource.LocalResource;

@XStreamAlias("PjsProject")
public class Project extends AbstractPersistable {

	/**
	 *
	 */
	private static final long serialVersionUID = -6254251957471654072L;
	private int releaseDate;
	private int criticalPathDuration;

	private List<LocalResource> localResourceList;
	private List<Job> jobList;

	public int getReleaseDate() {
		return releaseDate;
	}

	public void setReleaseDate(int releaseDate) {
		this.releaseDate = releaseDate;
	}

	public int getCriticalPathDuration() {
		return criticalPathDuration;
	}

	public void setCriticalPathDuration(int criticalPathDuration) {
		this.criticalPathDuration = criticalPathDuration;
	}

	public List<LocalResource> getLocalResourceList() {
		return localResourceList;
	}

	public void setLocalResourceList(List<LocalResource> localResourceList) {
		this.localResourceList = localResourceList;
	}

	public List<Job> getJobList() {
		return jobList;
	}

	public void setJobList(List<Job> jobList) {
		this.jobList = jobList;
	}

	// ************************************************************************
	// Complex methods
	// ************************************************************************

	public int getCriticalPathEndDate() {
		return releaseDate + criticalPathDuration;
	}

	public String getLabel() {
		return "Project " + id;
	}

}


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Latermoon.Web
{
	public class PageScript
	{
		private const string SCRIPT_START = "<script type=\"text/javascript\">\r\n";
		private const string SCRIPT_END = "</script>\r\n";

		/// <summary>
		/// 弹出信息提示框
		/// </summary>
		/// <param name="obj">任意可以转换为JSON文本的对象</param>
		/// <returns></returns>
		public static string Alert(object obj)
		{
			StringBuilder sb = new StringBuilder();
			sb.Append(SCRIPT_START);
			sb.Append("alert(");
			//sb.Append(JsonUtil.ToJson(obj));
			sb.Append(");\r\n");
			sb.Append(SCRIPT_END);
			return sb.ToString();
		}

		/// <summary>
		/// 用script标签包裹代码
		/// </summary>
		/// <param name="obj"></param>
		/// <returns></returns>
		public static string Wrap(object obj)
		{
			StringBuilder sb = new StringBuilder();
			sb.Append(SCRIPT_START);
			sb.Append(obj);
			sb.Append(SCRIPT_END);
			return sb.ToString();
		}

		/// <summary>
		/// 窗口跳转
		/// </summary>
		/// <param name="url"></param>
		/// <returns></returns>
		public static string Redirect(string url)
		{
			return Redirect(url, 0);
		}

		/// <summary>
		/// 延时窗口跳转
		/// </summary>
		/// <param name="url"></param>
		/// <param name="timeout"></param>
		/// <returns></returns>
		public static string Redirect(string url, int timeout)
		{
			StringBuilder sb = new StringBuilder();
			sb.Append(SCRIPT_START);
			if (timeout <= 0)
			{
				sb.Append("window.location='");
				sb.Append(url);
				sb.Append("';\r\n");
			}
			else
			{
				sb.Append("window.setTimeout(function(){window.location='");
				sb.Append(url);
				sb.Append("';},");
				sb.Append(timeout);
				sb.Append(");\r\n");
			}
			sb.Append(SCRIPT_END);
			return sb.ToString();
		}

		/// <summary>
		/// 立即后退
		/// </summary>
		/// <returns></returns>
		public static string GoBack()
		{
			return GoBack(0);
		}

		/// <summary>
		/// 延时后退
		/// </summary>
		/// <param name="timeout"></param>
		/// <returns></returns>
		public static string GoBack(int timeout)
		{
			StringBuilder sb = new StringBuilder();
			sb.Append(SCRIPT_START);
			if (timeout <= 0)
			{
				sb.Append("history.go(-1);\r\n");
			}
			else
			{
				sb.Append("window.setTimeout('history.go(-1)', ");
				sb.Append(timeout);
				sb.Append(");\r\n");
			}
			sb.Append(SCRIPT_END);
			return sb.ToString();
		}

		/// <summary>
		/// 立即关闭窗口
		/// </summary>
		/// <returns></returns>
		public static string CloseWindow()
		{
			return CloseWindow(0);
		}

		/// <summary>
		/// 定时关闭窗口
		/// </summary>
		/// <param name="timeout">毫秒数</param>
		/// <returns></returns>
		public static string CloseWindow(int timeout)
		{
			StringBuilder sb = new StringBuilder();
			sb.Append(SCRIPT_START);
			if (timeout <= 0)
			{
				sb.Append("window.close();\r\n");
			}
			else
			{
				sb.Append("window.setTimeout('window.close()', ");
				sb.Append(timeout);
				sb.Append(");\r\n");
			}
			sb.Append(SCRIPT_END);
			return sb.ToString();
		}

		/// <summary>
		/// 执行iframe里面的函数
		/// </summary>
		/// <param name="framename"></param>
		/// <param name="function">如:showImage(1)</param>
		/// <returns></returns>
		public static string CallFrameFunction(string framename, string function)
		{
			StringBuilder sb = new StringBuilder();
			sb.Append(SCRIPT_START);
			sb.Append("window.frames['");
			sb.Append(framename);
			sb.Append("'].");
			sb.Append(function);
			sb.Append(";\r\n");
			sb.Append(SCRIPT_END);
			return sb.ToString();
		}

		//执行父窗口里面的函数
		public static string CallParentFunction(string function)
		{
			StringBuilder sb = new StringBuilder();
			sb.Append(SCRIPT_START);
			sb.Append("window.parent.");
			sb.Append(function);
			sb.Append(";\r\n");
			sb.Append(SCRIPT_END);
			return sb.ToString();
		}
	}
}


text:
namespace apl
{
struct MockResponse {
	MockResponse(const apl::CommandResponse& aResponse, int aSequence) :
		Response(aResponse),
		Sequence(aSequence)
	{}

	apl::CommandResponse Response;
	int Sequence;
};

class MockResponseAcceptor : public apl::IResponseAcceptor
{
public:

	void AcceptResponse(const apl::CommandResponse& aResponse, int aSequence);

	MockResponse PopResponse();
	size_t NumResponses();

private:
	apl::SigLock mLock;
	std::deque<MockResponse> mResponses;
};
}

#endif


text:
class FriendshipsController < ApplicationController

  def create
    current_user.friendships.create( friend_id: friendship_params[:friend_id] )
    render json: friendship_params[:friend_id]
  end

  def destroy
    Friendship.find_and_destroy( params[:friend_id], current_user.id )
    render json: params[:friend_id]
  end

  private

  def friendship_params
    params.permit( :user_id, :friend_id )
  end

end