text:
#ifndef __FSL_LPUART_HAL_H__
#define __FSL_LPUART_HAL_H__

#include <stdint.h>
#include <stdbool.h>
#include <assert.h>
#include "fsl_device_registers.h"

/*!
 * @addtogroup lpuart_hal
 * @{
 */

/*******************************************************************************
 * Definitions
 ******************************************************************************/
#define LPUART_SHIFT (16U)
#define LPUART_BAUD_REG_ID (0U)
#define LPUART_STAT_REG_ID (1U)
#define LPUART_CTRL_REG_ID (2U)
#define LPUART_DATA_REG_ID (3U)
#define LPUART_MATCH_REG_ID (4U)
#define LPUART_MODIR_REG_ID (5U)
#define LPUART_FIFO_REG_ID (6U)
#define LPUART_WATER_REG_ID (7U)

/*! @brief Error codes for the LPUART driver.*/
typedef enum _lpuart_status
{
    kStatus_LPUART_Success                  = 0x00U,
    kStatus_LPUART_Fail                     = 0x01U,
    kStatus_LPUART_BaudRateCalculationError = 0x02U,
    kStatus_LPUART_RxStandbyModeError       = 0x03U,
    kStatus_LPUART_ClearStatusFlagError     = 0x04U,
    kStatus_LPUART_TxNotDisabled            = 0x05U,
    kStatus_LPUART_RxNotDisabled            = 0x06U,
    kStatus_LPUART_TxOrRxNotDisabled        = 0x07U,
    kStatus_LPUART_TxBusy                   = 0x08U,
    kStatus_LPUART_RxBusy                   = 0x09U,
    kStatus_LPUART_NoTransmitInProgress     = 0x0AU,
    kStatus_LPUART_NoReceiveInProgress      = 0x0BU,
    kStatus_LPUART_Timeout                  = 0x0CU,
    kStatus_LPUART_Initialized              = 0x0DU,
    kStatus_LPUART_NoDataToDeal             = 0x0EU,
    kStatus_LPUART_RxOverRun                = 0x0FU
} lpuart_status_t;

/*! @brief LPUART number of stop bits*/
typedef enum _lpuart_stop_bit_count {
    kLpuartOneStopBit = 0x0U, /*!< one stop bit @internal gui name="1" */
    kLpuartTwoStopBit = 0x1U, /*!< two stop bits @internal gui name="2" */
} lpuart_stop_bit_count_t;

/*! @brief LPUART parity mode*/
typedef enum _lpuart_parity_mode {
    kLpuartParityDisabled = 0x0U, /*!< parity disabled @internal gui name="Disabled" */
    kLpuartParityEven     = 0x2U, /*!< parity enabled, type even, bit setting: PE|PT = 10 @internal gui name="Even" */
    kLpuartParityOdd      = 0x3U, /*!< parity enabled, type odd,  bit setting: PE|PT = 11 @internal gui name="Odd" */
} lpuart_parity_mode_t;

/*! @brief LPUART number of bits in a character*/
typedef enum  _lpuart_bit_count_per_char {
    kLpuart8BitsPerChar  = 0x0U, /*!< 8-bit data characters @internal gui name="8" */
    kLpuart9BitsPerChar  = 0x1U, /*!< 9-bit data characters @internal gui name="9" */
    kLpuart10BitsPerChar = 0x2U, /*!< 10-bit data characters @internal gui name="10" */
} lpuart_bit_count_per_char_t;

/*! @brief LPUART operation configuration constants*/
typedef enum _lpuart_operation_config {
    kLpuartOperates = 0x0U, /*!< LPUART continues to operate normally.*/
    kLpuartStops    = 0x1U, /*!< LPUART stops operation. */
} lpuart_operation_config_t;

/*! @brief LPUART wakeup from standby method constants*/
typedef enum _lpuart_wakeup_method {
    kLpuartIdleLineWake = 0x0U, /*!< Idle-line wakes the LPUART receiver from standby. */
    kLpuartAddrMarkWake = 0x1U, /*!< Addr-mark wakes LPUART receiver from standby.*/
} lpuart_wakeup_method_t;

/*! @brief LPUART idle line detect selection types*/
typedef enum _lpuart_idle_line_select {
    kLpuartIdleLineAfterStartBit = 0x0U, /*!< LPUART idle character bit count start after start bit */
    kLpuartIdleLineAfterStopBit  = 0x1U, /*!< LPUART idle character bit count start after stop bit */
} lpuart_idle_line_select_t;

/*!
 * @brief LPUART break character length settings for transmit/detect.
 *
 * The actual maximum bit times may vary depending on the LPUART instance.
 */
typedef enum _lpuart_break_char_length {
    kLpuartBreakChar10BitMinimum = 0x0U, /*!< LPUART break char length 10 bit times (if M = 0, SBNS = 0)
                                      or 11 (if M = 1, SBNS = 0 or M = 0, SBNS = 1) or 12 (if M = 1,
                                      SBNS = 1 or M10 = 1, SNBS = 0) or 13 (if M10 = 1, SNBS = 1) */
    kLpuartBreakChar13BitMinimum = 0x1U, /*!< LPUART break char length 13 bit times (if M = 0, SBNS = 0
                                           or M10 = 0, SBNS = 1) or 14 (if M = 1, SBNS = 0 or M = 1,
                                           SBNS = 1) or 15 (if M10 = 1, SBNS = 1 or M10 = 1, SNBS = 0) */
} lpuart_break_char_length_t;

/*! @brief LPUART single-wire mode TX direction*/
typedef enum _lpuart_singlewire_txdir {
    kLpuartSinglewireTxdirIn  = 0x0U, /*!< LPUART Single Wire mode TXDIR input*/
    kLpuartSinglewireTxdirOut = 0x1U, /*!< LPUART Single Wire mode TXDIR output*/
} lpuart_singlewire_txdir_t;

/*! @brief LPUART Configures the match addressing mode used.*/
typedef enum _lpuart_match_config {
    kLpuartAddressMatchWakeup    = 0x0U, /*!< Address Match Wakeup*/
    kLpuartIdleMatchWakeup       = 0x1U, /*!< Idle Match Wakeup*/
    kLpuartMatchOnAndMatchOff    = 0x2U, /*!< Match On and Match Off*/
    kLpuartEnablesRwuOnDataMatch = 0x3U, /*!< Enables RWU on Data Match and Match On/Off for transmitter CTS input*/
} lpuart_match_config_t;

/*! @brief LPUART infra-red transmitter pulse width options*/
typedef enum _lpuart_ir_tx_pulsewidth {
    kLpuartIrThreeSixteenthsWidth  = 0x0U, /*!< 3/16 pulse*/
    kLpuartIrOneSixteenthWidth     = 0x1U, /*!< 1/16 pulse*/
    kLpuartIrOneThirtysecondsWidth = 0x2U, /*!< 1/32 pulse*/
    kLpuartIrOneFourthWidth        = 0x3U, /*!< 1/4 pulse*/
} lpuart_ir_tx_pulsewidth_t;

/*!
 * @brief LPUART Configures the number of idle characters that must be received
 * before the IDLE flag is set.
 */
typedef enum _lpuart_idle_char {
    kLpuart_1_IdleChar   = 0x0U, /*!< 1 idle character*/
    kLpuart_2_IdleChar   = 0x1U, /*!< 2 idle character*/
    kLpuart_4_IdleChar   = 0x2U, /*!< 4 idle character*/
    kLpuart_8_IdleChar   = 0x3U, /*!< 8 idle character*/
    kLpuart_16_IdleChar  = 0x4U, /*!< 16 idle character*/
    kLpuart_32_IdleChar  = 0x5U, /*!< 32 idle character*/
    kLpuart_64_IdleChar  = 0x6U, /*!< 64 idle character*/
    kLpuart_128_IdleChar = 0x7U, /*!< 128 idle character*/
} lpuart_idle_char_t;

/*! @brief LPUART Transmits the CTS Configuration. Configures the source of the CTS input.*/
typedef enum _lpuart_cts_source {
    kLpuartCtsSourcePin = 0x0U,  /*!< CTS input is the LPUART_CTS pin.*/
    kLpuartCtsSourceInvertedReceiverMatch = 0x1U, /*!< CTS input is the inverted Receiver Match result.*/
} lpuart_cts_source_t;

/*!
 * @brief LPUART Transmits CTS Source.Configures if the CTS state is checked at
 * the start of each character or only when the transmitter is idle.
 */
typedef enum _lpuart_cts_config {
    kLpuartCtsSampledOnEachChar = 0x0U, /*!< CTS input is sampled at the start of each character.*/
    kLpuartCtsSampledOnIdle     = 0x1U, /*!< CTS input is sampled when the transmitter is idle.*/
} lpuart_cts_config_t;

/*! @brief Structure for idle line configuration settings*/
typedef struct LpuartIdleLineConfig {
    unsigned idleLineType : 1; /*!< ILT, Idle bit count start: 0 - after start bit (default),
                                    1 - after stop bit */
    unsigned rxWakeIdleDetect : 1; /*!< RWUID, Receiver Wake Up Idle Detect. IDLE status bit
                                        operation during receive standbyControls whether idle
                                        character that wakes up receiver will also set
                                        IDLE status bit 0 - IDLE status bit doesn't
                                        get set (default), 1 - IDLE status bit gets set*/
} lpuart_idle_line_config_t;

/*! @brief LPUART Receiver Idle Empty Enable constants.*/
typedef enum _lpuart_rx_idle_empty_config {
    kLpuartRxidDisabled         = 0x0U,  /*!< Disable RDRF assertion due to partially filled FIFO when receiver is idle.*/
    kLpuartRxidEnabledFor1Char  = 0x1U,  /*!< Enable RDRF assertion due to partially filled FIFO when receiver is idle for 1 character.*/
    kLpuartRxidEnabledFor2Char  = 0x2U,  /*!< Enable RDRF assertion due to partially filled FIFO when receiver is idle for 2 characters.*/
    kLpuartRxidEnabledFor4Char  = 0x3U,  /*!< Enable RDRF assertion due to partially filled FIFO when receiver is idle for 4 characters.*/
    kLpuartRxidEnabledFor8Char  = 0x4U,  /*!< Enable RDRF assertion due to partially filled FIFO when receiver is idle for 8 characters.*/
    kLpuartRxidEnabledFor16Char = 0x5U,  /*!< Enable RDRF assertion due to partially filled FIFO when receiver is idle for 16 characters.*/
    kLpuartRxidEnabledFor32Char = 0x6U,  /*!< Enable RDRF assertion due to partially filled FIFO when receiver is idle for 32 characters.*/
    kLpuartRxidEnabledFor64Char = 0x7U,  /*!< Enable RDRF assertion due to partially filled FIFO when receiver is idle for 64 characters.*/
} lpuart_rx_idle_empty_config_t;

/*!
 * @brief LPUART status flags.
 *
 * This provides constants for the LPUART status flags for use in the UART functions.
 */
typedef enum _lpuart_status_flag {
    kLpuartTxDataRegEmpty         = LPUART_STAT_REG_ID << LPUART_SHIFT | LPUART_STAT_TDRE_SHIFT,    /*!< Transmit data register empty flag, sets when transmit buffer is empty */
    kLpuartTxComplete             = LPUART_STAT_REG_ID << LPUART_SHIFT | LPUART_STAT_TC_SHIFT,      /*!< Transmission complete flag, sets when transmission activity complete */
    kLpuartRxDataRegFull          = LPUART_STAT_REG_ID << LPUART_SHIFT | LPUART_STAT_RDRF_SHIFT,    /*!< Receive data register full flag, sets when the receive data buffer is full */
    kLpuartIdleLineDetect         = LPUART_STAT_REG_ID << LPUART_SHIFT | LPUART_STAT_IDLE_SHIFT,    /*!< Idle line detect flag, sets when idle line detected */
    kLpuartRxOverrun              = LPUART_STAT_REG_ID << LPUART_SHIFT | LPUART_STAT_OR_SHIFT,      /*!< Receive Overrun, sets when new data is received before data is read from receive register */
    kLpuartNoiseDetect            = LPUART_STAT_REG_ID << LPUART_SHIFT | LPUART_STAT_NF_SHIFT,      /*!< Receive takes 3 samples of each received bit.  If any of these samples differ, noise flag sets */
    kLpuartFrameErr               = LPUART_STAT_REG_ID << LPUART_SHIFT | LPUART_STAT_FE_SHIFT,      /*!< Frame error flag, sets if logic 0 was detected where stop bit expected */
    kLpuartParityErr              = LPUART_STAT_REG_ID << LPUART_SHIFT | LPUART_STAT_PF_SHIFT,      /*!< If parity enabled, sets upon parity error detection */
    kLpuartLineBreakDetect        = LPUART_STAT_REG_ID << LPUART_SHIFT | LPUART_STAT_LBKDE_SHIFT,   /*!< LIN break detect interrupt flag, sets when LIN break char detected and LIN circuit enabled */
    kLpuartRxActiveEdgeDetect     = LPUART_STAT_REG_ID << LPUART_SHIFT | LPUART_STAT_RXEDGIF_SHIFT, /*!< Receive pin active edge interrupt flag, sets when active edge detected */
    kLpuartRxActive               = LPUART_STAT_REG_ID << LPUART_SHIFT | LPUART_STAT_RAF_SHIFT,     /*!< Receiver Active Flag (RAF), sets at beginning of valid start bit */
    kLpuartNoiseInCurrentWord     = LPUART_DATA_REG_ID << LPUART_SHIFT | LPUART_DATA_NOISY_SHIFT,     /*!< NOISY bit, sets if noise detected in current data word */
    kLpuartParityErrInCurrentWord = LPUART_DATA_REG_ID << LPUART_SHIFT | LPUART_DATA_PARITYE_SHIFT,   /*!< PARITYE bit, sets if noise detected in current data word */
#if FSL_FEATURE_LPUART_HAS_ADDRESS_MATCHING
    kLpuartMatchAddrOne           = LPUART_STAT_REG_ID << LPUART_SHIFT | LPUART_STAT_MA1F_SHIFT,    /*!< Address one match flag */
    kLpuartMatchAddrTwo           = LPUART_STAT_REG_ID << LPUART_SHIFT | LPUART_STAT_MA2F_SHIFT,    /*!< Address two match flag */
#endif
#if FSL_FEATURE_LPUART_HAS_FIFO
    kLpuartTxBuffEmpty              = LPUART_FIFO_REG_ID << LPUART_SHIFT | LPUART_FIFO_TXEMPT_SHIFT,  /*!< TXEMPT bit, sets if transmit buffer is empty */
    kLpuartRxBuffEmpty              = LPUART_FIFO_REG_ID << LPUART_SHIFT | LPUART_FIFO_RXEMPT_SHIFT,  /*!< RXEMPT bit, sets if receive buffer is empty */
    kLpuartTxBuffOverflow           = LPUART_FIFO_REG_ID << LPUART_SHIFT | LPUART_FIFO_TXOF_SHIFT,    /*!< TXOF bit, sets if transmit buffer overflow occurred */
    kLpuartRxBuffUnderflow          = LPUART_FIFO_REG_ID << LPUART_SHIFT | LPUART_FIFO_RXUF_SHIFT,    /*!< RXUF bit, sets if receive buffer underflow occurred */
#endif
} lpuart_status_flag_t;

/*! @brief LPUART interrupt configuration structure, default settings are 0 (disabled)*/
typedef enum _lpuart_interrupt {
    kLpuartIntLinBreakDetect = LPUART_BAUD_REG_ID << LPUART_SHIFT | LPUART_BAUD_LBKDIE_SHIFT,  /*!< LIN break detect. */
    kLpuartIntRxActiveEdge   = LPUART_BAUD_REG_ID << LPUART_SHIFT | LPUART_BAUD_RXEDGIE_SHIFT, /*!< Receive Active Edge. */
    kLpuartIntTxDataRegEmpty = LPUART_CTRL_REG_ID << LPUART_SHIFT | LPUART_CTRL_TIE_SHIFT,     /*!< Transmit data register empty. */
    kLpuartIntTxComplete     = LPUART_CTRL_REG_ID << LPUART_SHIFT | LPUART_CTRL_TCIE_SHIFT,    /*!< Transmission complete. */
    kLpuartIntRxDataRegFull  = LPUART_CTRL_REG_ID << LPUART_SHIFT | LPUART_CTRL_RIE_SHIFT,     /*!< Receiver data register full. */
    kLpuartIntIdleLine       = LPUART_CTRL_REG_ID << LPUART_SHIFT | LPUART_CTRL_ILIE_SHIFT,    /*!< Idle line. */
    kLpuartIntRxOverrun      = LPUART_CTRL_REG_ID << LPUART_SHIFT | LPUART_CTRL_ORIE_SHIFT,    /*!< Receiver Overrun. */
    kLpuartIntNoiseErrFlag   = LPUART_CTRL_REG_ID << LPUART_SHIFT | LPUART_CTRL_NEIE_SHIFT,    /*!< Noise error flag. */
    kLpuartIntFrameErrFlag   = LPUART_CTRL_REG_ID << LPUART_SHIFT | LPUART_CTRL_FEIE_SHIFT,    /*!< Framing error flag. */
    kLpuartIntParityErrFlag  = LPUART_CTRL_REG_ID << LPUART_SHIFT | LPUART_CTRL_PEIE_SHIFT,    /*!< Parity error flag. */
#if FSL_FEATURE_LPUART_HAS_ADDRESS_MATCHING
    kLpuartIntMatchAddrOne   = LPUART_CTRL_REG_ID << LPUART_SHIFT | LPUART_CTRL_MA1IE_SHIFT,   /*!< Match address one flag. */
    kLpuartIntMatchAddrTwo   = LPUART_CTRL_REG_ID << LPUART_SHIFT | LPUART_CTRL_MA2IE_SHIFT,   /*!< Match address two flag. */
#endif
#if FSL_FEATURE_LPUART_HAS_FIFO
    kLpuartIntTxFifoOverflow  = LPUART_FIFO_REG_ID << LPUART_SHIFT | LPUART_FIFO_TXOFE_SHIFT,   /*!< Transmit FIFO Overflow. */
    kLpuartIntRxFifoUnderflow = LPUART_FIFO_REG_ID << LPUART_SHIFT | LPUART_FIFO_RXUFE_SHIFT,   /*!< Receive FIFO Underflow. */
#endif
} lpuart_interrupt_t;

/*******************************************************************************
 * API
 ******************************************************************************/

#if defined(__cplusplus)
extern "C" {
#endif

/*!
 * @name LPUART Common Configurations
 * @{
 */

/*!
 * @brief Initializes the LPUART controller to known state.
 *
 * @param base LPUART base pointer.
 */
void LPUART_HAL_Init(LPUART_Type * base);

/*!
 * @brief Enables/disables the LPUART transmitter.
 *
 * @param base LPUART base pointer.
 * @param enable Enable(true) or disable(false) transmitter.
 */
static inline void LPUART_HAL_SetTransmitterCmd(LPUART_Type * base, bool enable)
{
    LPUART_BWR_CTRL_TE(base, enable);
}

/*!
 * @brief Gets the LPUART transmitter enabled/disabled configuration.
 *
 * @param base LPUART base pointer
 * @return State of LPUART transmitter enable(true)/disable(false)
 */
static inline bool LPUART_HAL_GetTransmitterCmd(LPUART_Type * base)
{
    return LPUART_BRD_CTRL_TE(base);
}

/*!
 * @brief Enables/disables the LPUART receiver.
 *
 * @param base LPUART base pointer
 * @param enable Enable(true) or disable(false) receiver.
 */
static inline void LPUART_HAL_SetReceiverCmd(LPUART_Type * base, bool enable)
{
    LPUART_BWR_CTRL_RE(base, enable);
}

/*!
 * @brief Gets the LPUART receiver enabled/disabled configuration.
 *
 * @param base LPUART base pointer
 * @return State of LPUART receiver enable(true)/disable(false)
 */
static inline bool LPUART_HAL_GetReceiverCmd(LPUART_Type * base)
{
    return LPUART_BRD_CTRL_RE(base);
}

/*!
 * @brief Configures the LPUART baud rate.
 *
 *  In some LPUART instances the user must disable the transmitter/receiver
 *  before calling this function.
 *  Generally, this may be applied to all LPUARTs to ensure safe operation.
 *
 * @param base LPUART base pointer.
 * @param sourceClockInHz LPUART source input clock in Hz.
 * @param desiredBaudRate LPUART desired baud rate.
 * @return  An error code or kStatus_Success
 */
lpuart_status_t LPUART_HAL_SetBaudRate(LPUART_Type * base,
                                       uint32_t sourceClockInHz,
                                       uint32_t desiredBaudRate);

/*!
 * @brief Sets the LPUART baud rate modulo divisor.
 *
 * @param base LPUART base pointer.
 * @param baudRateDivisor The baud rate modulo division "SBR"
 */
static inline void LPUART_HAL_SetBaudRateDivisor(LPUART_Type * base, uint32_t baudRateDivisor)
{
    assert ((baudRateDivisor < 0x1FFF) && (baudRateDivisor > 1));
    LPUART_BWR_BAUD_SBR(base, baudRateDivisor);
}

#if FSL_FEATURE_LPUART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORT
/*!
 * @brief Sets the LPUART baud rate oversampling ratio. Note that this feature is available on select
 *        LPUART instances used together with baud rate programming.
 *        The oversampling ratio should be set between 4x (00011) and 32x (11111). Writing
 *        an invalid oversampling ratio results in an error and is set to a default
 *        16x (01111) oversampling ratio.
 *        IDisable the transmitter/receiver before calling
 *        this function.
 *
 * @param base LPUART base pointer.
 * @param overSamplingRatio The oversampling ratio "OSR"
 */
static inline void LPUART_HAL_SetOversamplingRatio(LPUART_Type * base, uint32_t overSamplingRatio)
{
    assert(overSamplingRatio < 0x1F);
    LPUART_BWR_BAUD_OSR(base, overSamplingRatio);
}
#endif

#if FSL_FEATURE_LPUART_HAS_BOTH_EDGE_SAMPLING_SUPPORT
/*!
 * @brief Configures the LPUART baud rate both edge sampling. Note that this feature is available on select
 *        LPUART instances used with baud rate programming.
 *        When enabled, the received data is sampled on both edges of the baud rate clock.
 *        This must be set when the oversampling ratio is between 4x and 7x.
 *        This function should only be called when the receiver is disabled.
 *
 * @param base LPUART base pointer.
 * @param enable   Enable (1) or Disable (0) Both Edge Sampling
 * @return An error code or kStatus_Success
 */
static inline void LPUART_HAL_SetBothEdgeSamplingCmd(LPUART_Type * base, bool enable)
{
    LPUART_BWR_BAUD_BOTHEDGE(base, enable);
}
#endif

/*!
 * @brief Configures the number of bits per character in the LPUART controller.
 *
 *  In some LPUART instances, the user should disable the transmitter/receiver
 *  before calling this function.
 *  Generally, this may be applied to all LPUARTs to ensure safe operation.
 *
 * @param base LPUART base pointer.
 * @param bitCountPerChar  Number of bits per char (8, 9, or 10, depending on the LPUART instance)
 */
void LPUART_HAL_SetBitCountPerChar(LPUART_Type * base, lpuart_bit_count_per_char_t bitCountPerChar);

/*!
 * @brief Configures parity mode in the LPUART controller.
 *
 *  In some LPUART instances, the user should disable the transmitter/receiver
 *  before calling this function.
 *  Generally, this may be applied to all LPUARTs to ensure safe operation.
 *
 * @param base LPUART base pointer.
 * @param parityModeType  Parity mode (enabled, disable, odd, even - see parity_mode_t struct)
 */
void LPUART_HAL_SetParityMode(LPUART_Type * base, lpuart_parity_mode_t parityModeType);

/*!
 * @brief Configures the number of stop bits in the LPUART controller.
 *  In some LPUART instances, the user should disable the transmitter/receiver
 *  before calling this function.
 *  Generally, this may be applied to all LPUARTs to ensure safe operation.
 *
 * @param base LPUART base pointer.
 * @param stopBitCount Number of stop bits (1 or 2 - see lpuart_stop_bit_count_t struct)
 * @return  An error code (an unsupported setting in some LPUARTs) or kStatus_Success
 */
static inline void LPUART_HAL_SetStopBitCount(LPUART_Type * base, lpuart_stop_bit_count_t stopBitCount)
{
    LPUART_BWR_BAUD_SBNS(base, stopBitCount);
}

/*!
 * @brief  Gets the LPUART transmit/receive data register address.
 *
 * @param base LPUART base pointer.
 * @return  LPUART transmit/receive data register address.
 */
static inline uint32_t LPUART_HAL_GetDataRegAddr(LPUART_Type * base)
{
    return (uint32_t)(&LPUART_DATA_REG(base));
}

/*@}*/

/*!
 * @name LPUART Interrupts and DMA
 * @{
 */

/*!
 * @brief Configures the LPUART module interrupts to enable/disable various interrupt sources.
 *
 * @param   base LPUART module base pointer.
 * @param   interrupt LPUART interrupt configuration data.
 * @param   enable   true: enable, false: disable.
 */
void LPUART_HAL_SetIntMode(LPUART_Type * base, lpuart_interrupt_t interrupt, bool enable);

/*!
 * @brief Returns whether the LPUART module interrupts is enabled/disabled.
 *
 * @param   base LPUART module base pointer.
 * @param   interrupt LPUART interrupt configuration data.
 * @return  true: enable, false: disable.
 */
bool LPUART_HAL_GetIntMode(LPUART_Type * base, lpuart_interrupt_t interrupt);

#if FSL_FEATURE_LPUART_HAS_DMA_ENABLE
/*!
 * @brief  LPUART configures DMA requests for Transmitter and Receiver.
 *
 * @param base LPUART base pointer
 * @param enable Transmit DMA request configuration (enable:1 /disable: 0)
 */
static inline void LPUART_HAL_SetTxDmaCmd(LPUART_Type * base, bool enable)
{
    LPUART_BWR_BAUD_TDMAE(base, enable);
}

/*!
 * @brief  LPUART configures DMA requests for Transmitter and Receiver.
 *
 * @param base LPUART base pointer
 * @param enable Receive DMA request configuration (enable: 1/disable: 0)
 */
static inline void LPUART_HAL_SetRxDmaCmd(LPUART_Type * base, bool enable)
{
    LPUART_BWR_BAUD_RDMAE(base, enable);
}

/*!
 * @brief  Gets the LPUART Transmit DMA request configuration.
 *
 * @param base LPUART base pointer
 * @return Transmit DMA request configuration (enable: 1/disable: 0)
 */
static inline bool LPUART_HAL_IsTxDmaEnabled(LPUART_Type * base)
{
    return LPUART_BRD_BAUD_TDMAE(base);
}

/*!
 * @brief  Gets the LPUART receive DMA request configuration.
 *
 * @param base LPUART base pointer
 * @return Receives the DMA request configuration (enable: 1/disable: 0).
 */
static inline bool LPUART_HAL_IsRxDmaEnabled(LPUART_Type * base)
{
    return LPUART_BRD_BAUD_RDMAE(base);
}

#endif

/*@}*/

/*!
 * @name LPUART Transfer Functions
 * @{
 */

/*!
 * @brief Sends the LPUART 8-bit character.
 *
 * @param base LPUART Instance
 * @param data     data to send (8-bit)
 */
static inline void LPUART_HAL_Putchar(LPUART_Type * base, uint8_t data)
{
    LPUART_WR_DATA(base, data);
}

/*!
 * @brief Sends the LPUART 9-bit character.
 *
 * @param base LPUART Instance
 * @param data     data to send (9-bit)
 */
void LPUART_HAL_Putchar9(LPUART_Type * base, uint16_t data);

/*!
 * @brief Sends the LPUART 10-bit character. Note that this feature is available on select LPUART instances.
 *
 * @param base LPUART Instance
 * @param data   data to send (10-bit)
 * @return An error code or kStatus_Success
 */
lpuart_status_t LPUART_HAL_Putchar10(LPUART_Type * base, uint16_t data);

/*!
 * @brief Gets the LPUART 8-bit character.
 *
 * @param base LPUART base pointer
 * @param readData Data read from receive (8-bit)
 */
static inline void  LPUART_HAL_Getchar(LPUART_Type * base, uint8_t *readData)
{
    *readData = (uint8_t)LPUART_RD_DATA(base);
}

/*!
 * @brief Gets the LPUART 9-bit character.
 *
 * @param base LPUART base pointer
 * @param readData Data read from receive (9-bit)
 */
void LPUART_HAL_Getchar9(LPUART_Type * base, uint16_t *readData);

/*!
 * @brief Gets the LPUART 10-bit character.
 *
 * @param base LPUART base pointer
 * @param readData Data read from receive (10-bit)
 */
void LPUART_HAL_Getchar10(LPUART_Type * base, uint16_t *readData);

/*!
 * @brief Sends out multiple bytes of data using the polling method.
 *
 * This function only supports 8-bit transaction.
 *
 * @param   base LPUART module base pointer.
 * @param   txBuff The buffer pointer which saves the data to be sent.
 * @param   txSize Size of data to be sent in unit of byte.
 */
void LPUART_HAL_SendDataPolling(LPUART_Type * base, const uint8_t *txBuff, uint32_t txSize);

/*!
 * @brief Receives multiple bytes of data using the polling method.
 *
 * This function only supports 8-bit transaction.
 *
 * @param   base LPUART module base pointer.
 * @param   rxBuff The buffer pointer which saves the data to be received.
 * @param   rxSize Size of data need to be received in unit of byte.
 * @return  Whether the transaction is success or receive overrun.
 */
lpuart_status_t LPUART_HAL_ReceiveDataPolling(LPUART_Type * base, uint8_t *rxBuff, uint32_t rxSize);

/*@}*/

/*!
 * @name LPUART Status Flags
 * @{
 */

/*!
 * @brief  LPUART get status flag.
 *
 * @param base LPUART base pointer
 * @param statusFlag  The status flag to query
 * @return Whether the current status flag is set(true) or not(false).
 */
bool LPUART_HAL_GetStatusFlag(LPUART_Type * base, lpuart_status_flag_t statusFlag);

/*!
 * @brief LPUART clears an individual status flag (see lpuart_status_flag_t for list of status bits).
 *
 * @param base LPUART base pointer
 * @param statusFlag  Desired LPUART status flag to clear
 * @return An error code or kStatus_Success
 */
lpuart_status_t LPUART_HAL_ClearStatusFlag(LPUART_Type * base, lpuart_status_flag_t statusFlag);

/*@}*/

/*!
 * @name LPUART Special Feature Configurations
 * @{
 */

/*!
 * @brief Configures the number of idle characters that must be received before the IDLE flag is set.
 *
 * @param base LPUART base pointer
 * @param idleConfig Idle characters configuration
 */
static inline void LPUART_HAL_SetIdleChar(LPUART_Type * base, lpuart_idle_char_t idleConfig)
{
    LPUART_BWR_CTRL_IDLECFG(base, idleConfig);
}

/*!
 * @brief Gets the configuration of the number of idle characters that must be received
 * before the IDLE flag is set.
 *
 * @param base LPUART base pointer
 * @return  idle characters configuration
 */
static inline lpuart_idle_char_t LPUART_HAL_GetIdleChar(LPUART_Type * base)
{
    return (lpuart_idle_char_t)LPUART_BRD_CTRL_IDLECFG(base);
}

/*!
 * @brief  Checks whether the current data word was received with noise.
 *
 * @param base LPUART base pointer.
 * @return The status of the NOISY bit in the LPUART extended data register
 */
static inline bool LPUART_HAL_IsCurrentDataWithNoise(LPUART_Type * base)
{
    return LPUART_BRD_DATA_NOISY(base);
}

/*!
 * @brief Checks whether the current data word was received with frame error.
 *
 * @param base LPUART base pointer
 * @return The status of the FRETSC bit in the LPUART extended data register
 */
static inline bool LPUART_HAL_IsCurrentDataWithFrameError(LPUART_Type * base)
{
    return LPUART_BRD_DATA_FRETSC(base);
}

/*!
 * @brief Indicates a break or that the idle character is to be transmitted
 *        instead of the contents in DATA[T9:T0].
 *
 * @param base LPUART base pointer
 * @param specialChar T9 is used to indicate a break character when 0 an idle
 * character when 1, the contents of DATA[T8:T0] should be zero.
 */
static inline void LPUART_HAL_SetTxSpecialChar(LPUART_Type * base, uint8_t specialChar)
{
    LPUART_BWR_DATA_FRETSC(base, specialChar);
}

/*!
 * @brief Checks whether the current data word was received with parity error.
 *
 * @param base LPUART base pointer
 * @return The status of the PARITYE bit in the LPUART extended data register
 */
static inline bool LPUART_HAL_IsCurrentDataWithParityError(LPUART_Type * base)
{
    return LPUART_BRD_DATA_PARITYE(base);
}

/*!
 * @brief Checks whether the receive buffer is empty.
 *
 * @param base LPUART base pointer
 * @return TRUE if the receive-buffer is empty, else FALSE.
 */
static inline bool LPUART_HAL_IsReceiveBufferEmpty(LPUART_Type * base)
{
    return LPUART_BRD_DATA_RXEMPT(base);
}

/*!
 * @brief Checks whether the previous BUS state was idle before this byte is received.
 *
 * @param base LPUART base pointer
 * @return TRUE if the previous BUS state was IDLE, else FALSE.
 */
static inline bool LPUART_HAL_WasPreviousReceiverStateIdle(LPUART_Type * base)
{
    return LPUART_BRD_DATA_IDLINE(base);
}

/*!
 * @brief Configures the LPUART operation in wait mode (operates or stops operations in wait mode).
 *
 * In some LPUART instances, the user should disable the transmitter/receiver
 * before calling this function.
 * Generally, this may be applied to all LPUARTs to ensure safe operation.
 *
 * @param base LPUART base pointer
 * @param mode     LPUART wait mode operation - operates or stops to operate in wait mode.
 */
static inline void  LPUART_HAL_SetWaitModeOperation(LPUART_Type * base, lpuart_operation_config_t mode)
{
    /* In CPU wait mode: 0 - LPUART clocks continue to run; 1 - LPUART clocks freeze */
    LPUART_BWR_CTRL_DOZEEN(base, mode);
}

/*!
 * @brief Gets the LPUART operation in wait mode (operates or stops operations in wait mode).
 *
 * @param base LPUART base pointer
 * @return LPUART wait mode operation configuration
 *         - kLpuartOperates or KLpuartStops in wait mode
 */
static inline lpuart_operation_config_t LPUART_HAL_GetWaitModeOperation(LPUART_Type * base)
{
    /* In CPU wait mode: 0 - LPUART clocks continue to run; 1 - LPUART clocks freeze  */
    return (lpuart_operation_config_t)LPUART_BRD_CTRL_DOZEEN(base);
}

/*!
 * @brief Configures the LPUART loopback operation (enables/disables the loopback operation).
 *
 * In some LPUART instances, the user should disable the transmitter/receiver
 * before calling this function.
 * Generally, this may be applied to all LPUARTs to ensure safe operation.
 *
 * @param base LPUART base pointer
 * @param enable   LPUART loopback mode - disabled (0) or enabled (1)
 */
void LPUART_HAL_SetLoopbackCmd(LPUART_Type * base, bool enable);

/*!
 * @brief Configures the LPUART single-wire operation (enables/disables the single-wire mode).
 *
 * In some LPUART instances, the user should disable the transmitter/receiver
 * before calling this function.
 * Generally, this may be applied to all LPUARTs to ensure safe operation.
 *
 * @param base LPUART base pointer
 * @param enable   LPUART loopback mode - disabled (0) or enabled (1)
 */
void LPUART_HAL_SetSingleWireCmd(LPUART_Type * base, bool enable);

/*!
 * @brief Configures the LPUART transmit direction while in single-wire mode.
 *
 * @param base LPUART base pointer
 * @param direction LPUART single-wire transmit direction - input or output
 */
static inline void LPUART_HAL_SetTxdirInSinglewireMode(LPUART_Type * base,
                                                 lpuart_singlewire_txdir_t direction)
{
    LPUART_BWR_CTRL_TXDIR(base, direction);
}

/*!
 * @brief  Places the LPUART receiver in standby mode.
 *
 * @param base LPUART base pointer
 * @return Error code or kStatus_Success
 */
lpuart_status_t LPUART_HAL_SetReceiverInStandbyMode(LPUART_Type * base);

/*!
 * @brief  Places the LPUART receiver in a normal mode (disable standby mode operation).
 *
 * @param base LPUART base pointer
 */
static inline void LPUART_HAL_PutReceiverInNormalMode(LPUART_Type * base)
{
    LPUART_BWR_CTRL_RWU(base, 0);
}

/*!
 * @brief  Checks whether the LPUART receiver is in a standby mode.
 *
 * @param base LPUART base pointer
 * @return LPUART in normal more (0) or standby (1)
 */
static inline bool LPUART_HAL_IsReceiverInStandby(LPUART_Type * base)
{
    return LPUART_BRD_CTRL_RWU(base);
}

/*!
 * @brief  LPUART receiver wakeup method (idle line or addr-mark) from standby mode.
 *
 * @param base LPUART base pointer
 * @param method   LPUART wakeup method: 0 - Idle-line wake (default), 1 - addr-mark wake
 */
static inline void LPUART_HAL_SetReceiverWakeupMode(LPUART_Type * base,
                                                    lpuart_wakeup_method_t method)
{
    LPUART_BWR_CTRL_WAKE(base, method);
}

/*!
 * @brief  Gets the LPUART receiver wakeup method (idle line or addr-mark) from standby mode.
 *
 * @param base LPUART base pointer
 * @return  LPUART wakeup method: kLpuartIdleLineWake: 0 - Idle-line wake (default),
 *          kLpuartAddrMarkWake: 1 - addr-mark wake
 */
static inline lpuart_wakeup_method_t LPUART_HAL_GetReceiverWakeupMode(LPUART_Type * base)
{
    return (lpuart_wakeup_method_t)LPUART_BRD_CTRL_WAKE(base);
}

/*!
 * @brief  LPUART idle-line detect operation configuration (idle line bit-count start and wake
 *         up affect on IDLE status bit).
 *
 * In some LPUART instances, the user should disable the transmitter/receiver
 * before calling this function.
 * Generally, this may be applied to all LPUARTs to ensure safe operation.
 *
 * @param base LPUART base pointer
 * @param config   LPUART configuration data for idle line detect operation
 */
void LPUART_HAL_SetIdleLineDetect(LPUART_Type * base,
                                  const lpuart_idle_line_config_t *config);

/*!
 * @brief  LPUART break character transmit length configuration.
 *
 * In some LPUART instances, the user should disable the transmitter before calling
 * this function. Generally, this may be applied to all LPUARTs to ensure safe operation.
 *
 * @param base LPUART base pointer
 * @param length   LPUART break character length setting: 0 - minimum 10-bit times (default),
 *                   1 - minimum 13-bit times
 */
static inline void LPUART_HAL_SetBreakCharTransmitLength(LPUART_Type * base,
                                             lpuart_break_char_length_t length)
{
    LPUART_BWR_STAT_BRK13(base, length);
}

/*!
 * @brief  LPUART break character detect length configuration.
 *
 * @param base LPUART base pointer
 * @param length  LPUART break character length setting: 0 - minimum 10-bit times (default),
 *                  1 - minimum 13-bit times
 */
static inline void LPUART_HAL_SetBreakCharDetectLength(LPUART_Type * base,
                                           lpuart_break_char_length_t length)
{
    LPUART_BWR_STAT_LBKDE(base, length);
}

/*!
 * @brief  LPUART transmit sends break character configuration.
 *
 * @param base LPUART base pointer
 * @param enable LPUART normal/queue break char - disabled (normal mode, default: 0) or
 *                 enabled (queue break char: 1)
 */
static inline void LPUART_HAL_QueueBreakCharToSend(LPUART_Type * base, bool enable)
{
    LPUART_BWR_CTRL_SBK(base, enable);
}

/*!
 * @brief LPUART configures match address mode control.
 *
 * @param base LPUART base pointer
 * @param config MATCFG: Configures the match addressing mode used.
 */
static inline void LPUART_HAL_SetMatchAddressMode(LPUART_Type * base, lpuart_match_config_t config)
{
    LPUART_BWR_BAUD_MATCFG(base, config);
}

/*!
 * @brief Configures address match register 1.
 *
 * The MAEN bit must be cleared before configuring the MA value. Therefore, the enable/disable
 * and set value must be included inside one function.
 *
 * @param base LPUART base pointer
 * @param enable Match address model enable (true)/disable (false)
 * @param value Match address value to program into match address register 1
 */
void LPUART_HAL_SetMatchAddressReg1(LPUART_Type * base, bool enable, uint8_t value);

/*!
 * @brief Configures address match register 2.
 *
 * The MAEN bit must be cleared before configuring MA value. Therefore, the enable/disable
 * and set value must be included inside one function.
 *
 * @param base LPUART base pointer
 * @param enable Match address model enable (true)/disable (false)
 * @param value Match address value to program into match address register 2
 */
void LPUART_HAL_SetMatchAddressReg2(LPUART_Type * base, bool enable, uint8_t value);

/*!
 * @brief LPUART sends the MSB first configuration.
 *
 * In some LPUART instances, the user should disable the transmitter/receiver
 * before calling this function.
 * Generally, this may be applied to all LPUARTs to ensure safe operation.
 *
 * @param base LPUART base pointer
 * @param enable  false - LSB (default, disabled), true - MSB (enabled)
 */
static inline void LPUART_HAL_SetSendMsbFirstCmd(LPUART_Type * base, bool enable)
{
    LPUART_BWR_STAT_MSBF(base, enable);
}

/*!
 * @brief  LPUART enable/disable re-sync of received data configuration.
 *
 * @param base LPUART base pointer
 * @param enable  re-sync of received data word configuration:
 *                true - re-sync of received data word (default)
 *                false - disable the re-sync
 */
static inline void LPUART_HAL_SetReceiveResyncCmd(LPUART_Type * base, bool enable)
{
    /* When disabled, the resynchronization of the received data word when a data
     * one followed by data zero transition is detected. This bit should only be
     * changed when the receiver is disabled. */
    LPUART_BWR_BAUD_RESYNCDIS(base, enable);
}

#if FSL_FEATURE_LPUART_HAS_MODEM_SUPPORT
/*!
 * @brief  Transmits the CTS source configuration.
 *
 * @param base LPUART base pointer
 * @param source   LPUART CTS source
 */
static inline void LPUART_HAL_SetCtsSource(LPUART_Type * base,
                                           lpuart_cts_source_t source)
{
    LPUART_BWR_MODIR_TXCTSSRC(base, source);
}

/*!
 * @brief  Transmits the CTS configuration.
 *
 * Note: configures if the CTS state is checked at the start of each character
 * or only when the transmitter is idle.
 *
 * @param base LPUART base pointer
 * @param mode     LPUART CTS configuration
 */
static inline void LPUART_HAL_SetCtsMode(LPUART_Type * base, lpuart_cts_config_t mode)
{
    LPUART_BWR_MODIR_TXCTSC(base, mode);
}

/*!
 * @brief Enables/disables the transmitter clear-to-send.
 *
 * @param base LPUART base pointer
 * @param enable  disable(0)/enable(1) transmitter CTS.
 */
static inline void LPUART_HAL_SetTxCtsCmd(LPUART_Type * base, bool enable)
{
    LPUART_BWR_MODIR_TXCTSE(base, enable);
}

/*!
 * @brief  Enables/disables the receiver request-to-send.
 *
 * Note: do not enable both Receiver RTS (RXRTSE) and Transmit RTS (TXRTSE).
 *
 * @param base LPUART base pointer
 * @param enable  disable(0)/enable(1) receiver RTS.
 */
static inline void LPUART_HAL_SetRxRtsCmd(LPUART_Type * base, bool enable)
{
    LPUART_BWR_MODIR_RXRTSE(base, enable);
}

/*!
 * @brief  Enables/disables the transmitter request-to-send.
 * Note: do not enable both Receiver RTS (RXRTSE) and Transmit RTS (TXRTSE).
 *
 * @param base LPUART base pointer
 * @param enable  disable(0)/enable(1) transmitter RTS.
 */
static inline void LPUART_HAL_SetTxRtsCmd(LPUART_Type * base, bool enable)
{
    LPUART_BWR_MODIR_TXRTSE(base, enable);
}

/*!
 * @brief Configures the transmitter RTS polarity.
 *
 * @param base LPUART base pointer
 * @param polarity Settings to choose RTS polarity (0=active low, 1=active high)
 */
static inline void LPUART_HAL_SetTxRtsPolarityMode(LPUART_Type * base, bool polarity)
{
    LPUART_BWR_MODIR_TXRTSPOL(base, polarity);
}

#endif  /* FSL_FEATURE_LPUART_HAS_MODEM_SUPPORT */

#if FSL_FEATURE_LPUART_HAS_IR_SUPPORT
/*!
 * @brief  Configures the LPUART infrared operation.
 *
 * @param base LPUART base pointer
 * @param enable    Enable (1) or disable (0) the infrared operation
 * @param pulseWidth The transmit narrow pulse width of type lpuart_ir_tx_pulsewidth_t
 */
void LPUART_HAL_SetInfrared(LPUART_Type * base, bool enable,
                            lpuart_ir_tx_pulsewidth_t pulseWidth);
#endif  /* FSL_FEATURE_LPUART_HAS_IR_SUPPORT */

/*!
 * @name LPUART FIFO Configurations
 * @{
 */

#if FSL_FEATURE_LPUART_HAS_FIFO
/*!
 * @brief  Enables or disable the LPUART transmit FIFO.
 *
 * This function allows the user to enable or disable the LPUART transmit FIFO.
 * It is required that the transmitter/receiver be disabled before calling this function
 * when the FIFO is empty.
 * Additionally, TXFLUSH and RXFLUSH commands should be issued after calling this function.
 *
 * @param base LPUART module base pointer.
 * @param enable Enable or disable Tx FIFO.
 * @return Error code if it is detected that the transmitter or receiver is enabled or
 *         kStatus_LPUART_Success.
 */
lpuart_status_t LPUART_HAL_SetTxFifoCmd(LPUART_Type * base, bool enable);

/*!
 * @brief  Enables or disables the LPUART receive FIFO.
 *
 * This function allows the user to enable or disable the LPUART receive FIFO.
 * It is required that the transmitter/receiver be disabled before calling this function
 * when the FIFO is empty.
 * Additionally, TXFLUSH and RXFLUSH commands should be issued after calling this function.
 *
 * @param base LPUART module base pointer.
 * @param enable Enable or disable Rx FIFO.
 * @return Error code if it is detected that the transmitter or receiver is enabled or
 *         kStatus_LPUART_Success.
 */
lpuart_status_t LPUART_HAL_SetRxFifoCmd(LPUART_Type * base, bool enable);

/*!
 * @brief  Gets the size of the LPUART transmit FIFO.
 *
 * This function returns the size (number of entries) supported in the LPUART transmit FIFO for
 * a particular module base.
 *
 * @param base LPUART module base pointer.
 * @return  The LPUART transmit FIFO size as follows:
 *    0x0: 1 data word; 0x1: 4 data words; 0x2: 8 data words; 0x3: 16 data words
 *    0x4: 32 data words; 0x5: 64 data words; 0x6: 128 data words; 0x7: 256 data words
 */
static inline uint8_t LPUART_HAL_GetTxFifoSize(LPUART_Type * base)
{
    return LPUART_BRD_FIFO_TXFIFOSIZE(base);
}

/*!
 * @brief  Gets the size of the LPUART receive FIFO.
 *
 * This function returns the size (number of entries) supported in the LPUART receive FIFO for
 * a particular module base.
 *
 * @param   base LPUART module base pointer.
 * @return  The receive FIFO size as follows:
 *    0x0: 1 data word; 0x1: 4 data words; 0x2: 8 data words; 0x3: 16 data words
 *    0x4: 32 data words; 0x5: 64 data words; 0x6: 128 data words; 0x7: 256 data words
 */
static inline uint8_t LPUART_HAL_GetRxFifoSize(LPUART_Type * base)
{
    return LPUART_BRD_FIFO_RXFIFOSIZE(base);
}

/*!
 * @brief  Flushes the LPUART transmit FIFO.
 *
 * This function allows the user to flush the LPUART transmit FIFO for a particular module base.
 * Flushing the FIFO may result in data loss.
 * It is recommended that the transmitter be disabled before calling this function.
 *
 * @param base LPUART module base pointer.
 * @return Error code if it is detected that the transmitter or receiver is enabled or
 *         kStatus_LPUART_Success.
 */
lpuart_status_t LPUART_HAL_FlushTxFifo(LPUART_Type * base);

/*!
 * @brief  Flushes the LPUART receive FIFO.
 *
 * This function allows the user to flush the LPUART receive FIFO for a particular module base.
 * Flushing the FIFO may result in data loss.
 * It is recommended that the receiver be disabled before calling this function.
 *
 * @param base LPUART module base pointer.
 * @return Error code if it is detected that the transmitter or receiver is enabled or
 *         kStatus_LPUART_Success.
 */
lpuart_status_t LPUART_HAL_FlushRxFifo(LPUART_Type * base);

/*!
 * @brief  Gets the LPUART transmit FIFO empty status state.
 *
 * The function returns the state of the transmit FIFO empty status state, but does not take into
 * account data in the shift register.
 *
 * @param   base LPUART module base pointer.
 * @return  The LPUART transmit FIFO empty status: true=empty; false=not-empty.
 */
static inline bool LPUART_HAL_IsTxFifoEmpty(LPUART_Type * base)
{
    return LPUART_BRD_FIFO_TXEMPT(base);
}

/*!
 * @brief  Gets the LPUART receive FIFO empty status state.
 *
 * The function returns the state of the receive FIFO empty status state, but does not take into
 * account data in the shift register.
 *
 * @param   base LPUART module base pointer.
 * @return  The LPUART receive FIFO empty status: true=empty; false=not-empty.
 */
static inline bool LPUART_HAL_IsRxFifoEmpty(LPUART_Type * base)
{
    return LPUART_BRD_FIFO_RXEMPT(base);
}

/*!
 * @brief  Configures the LPUART receiver idle empty enable value.
 *
 * The function enables configuration of the assertion of RDRF when the receiver is idle for a number of idle characters and the
 * FIFO is not empty.
 *
 * @param   base LPUART module base pointer.
 * @param   config Configures the number of idle characters that asserts RDRF.
 * @return  Error code if transmitter is enabled or kStatus_LPUART_Success.
 */
lpuart_status_t LPUART_HAL_SetRxIdleEmpty(LPUART_Type * base, lpuart_rx_idle_empty_config_t config);

/*!
 * @brief  Gets the LPUART receiver idle empty enable value.
 *
 * @param   base LPUART module base pointer.
 * @return  Current number of idle characters that asserts RDRF.
 */
static inline lpuart_rx_idle_empty_config_t LPUART_HAL_GetRxIdleEmpty(LPUART_Type * base)
{
    return (lpuart_rx_idle_empty_config_t)LPUART_BRD_FIFO_RXIDEN(base);
}

/*!
 * @brief  Sets the LPUART transmit FIFO watermark value.
 *
 * Programming the transmit watermark should be done when LPUART the transmitter is disabled
 * and the value must be set less than the size obtained from LPUART_HAL_GetTxFifoSize.
 *
 * @param   base LPUART module base pointer.
 * @param   watermark  The LPUART transmit watermark value to be programmed.
 * @return  Error code if transmitter is enabled or kStatus_LPUART_Success.
 */
lpuart_status_t LPUART_HAL_SetTxFifoWatermark(LPUART_Type * base, uint8_t watermark);

/*!
 * @brief  Gets the LPUART transmit FIFO watermark value.
 *
 * @param   base LPUART module base pointer.
 * @return  The value currently programmed for the LPUART transmit watermark.
 */
static inline uint8_t LPUART_HAL_GetTxFifoWatermark(LPUART_Type * base)
{
    return LPUART_BRD_WATER_TXWATER(base);
}

/*!
 * @brief  Gets the LPUART transmit FIFO data word count (number of words in the transmit FIFO).
 *
 * The function LPUART_HAL_GetTxDatawordCountInFifo excludes any data that may
 * be in the LPUART transmit shift register.
 *
 * @param   base LPUART module base pointer.
 * @return  The number of data words currently in the LPUART transmit FIFO.
 */
static inline uint8_t LPUART_HAL_GetTxDatawordCountInFifo(LPUART_Type * base)
{
    return LPUART_BRD_WATER_TXCOUNT(base);
}

/*!
 * @brief  Sets the LPUART receive FIFO watermark value.
 *
 * Programming the receive watermark should be done when the receiver is disabled
 * and the value must be set less than the size obtained from LPUART_HAL_GetRxFifoSize and
 * greater than zero.
 *
 * @param   base LPUART module base pointer.
 * @param  watermark  The LPUART receive watermark value to be programmed.
 * @return  Error code if receiver is enabled or kStatus_LPUART_Success.
 */
lpuart_status_t LPUART_HAL_SetRxFifoWatermark(LPUART_Type * base, uint8_t watermark);

/*!
 * @brief  Gets the LPUART receive FIFO data word count (number of words in the receive FIFO).
 *
 * The function LPUART_HAL_GetRxDatawordCountInFifo excludes any data that may be
 * in the receive shift register.
 *
 * @param   base LPUART module base pointer.
 * @return  The number of data words currently in the LPUART receive FIFO.
 */
static inline uint8_t LPUART_HAL_GetRxDatawordCountInFifo(LPUART_Type * base)
{
    return LPUART_BRD_WATER_RXCOUNT(base);
}

/*!
 * @brief  Gets the LPUART receive FIFO watermark value.
 *
 * @param   base LPUART module base pointer.
 * @return  The value currently programmed for the LPUART receive watermark.
 */
static inline uint8_t LPUART_HAL_GetRxFifoWatermark(LPUART_Type * base)
{
    return LPUART_BRD_WATER_RXWATER(base);
}

#endif  /* FSL_FEATURE_LPUART_HAS_FIFO*/

/*@}*/

#if defined(__cplusplus)
}
#endif

/*! @}*/

#endif /* __FSL_LPUART_HAL_H__ */
/*******************************************************************************
 * EOF
 ******************************************************************************/


text:
from __future__ import absolute_import
import theano
import theano.tensor as T
import numpy as np

from .. import activations, initializations
from ..utils.theano_utils import shared_zeros, alloc_zeros_matrix
from ..layers.core import Layer
from .. import regularizers

from six.moves import range

class BLSTM(Layer):
    def __init__(self, input_dim, output_dim,
        init='glorot_uniform', inner_init='orthogonal',
        activation='tanh', inner_activation='hard_sigmoid',
        weights=None, truncate_gradient=-1, return_sequences=False,
        is_entity=False, regularize=False):

        self.is_entity = is_entity
        self.input_dim = input_dim
        self.output_dim = output_dim
        self.truncate_gradient = truncate_gradient
        self.return_sequences = return_sequences

        self.init = initializations.get(init)
        self.inner_init = initializations.get(inner_init)
        self.activation = activations.get(activation)
        self.inner_activation = activations.get(inner_activation)
        self.input = T.tensor3()

        self.W_if = self.init((self.input_dim, self.output_dim))
        self.W_ib = self.init((self.input_dim, self.output_dim))
        self.U_if = self.inner_init((self.output_dim, self.output_dim))
        self.U_ib = self.inner_init((self.output_dim, self.output_dim))
        self.b_if = shared_zeros((self.output_dim))
        self.b_ib = shared_zeros((self.output_dim))

        self.W_ff = self.init((self.input_dim, self.output_dim))
        self.W_fb = self.init((self.input_dim, self.output_dim))
        self.U_ff = self.inner_init((self.output_dim, self.output_dim))
        self.U_fb = self.inner_init((self.output_dim, self.output_dim))
        self.b_ff = shared_zeros((self.output_dim))
        self.b_fb = shared_zeros((self.output_dim))

        self.W_cf = self.init((self.input_dim, self.output_dim))
        self.W_cb = self.init((self.input_dim, self.output_dim))
        self.U_cf = self.inner_init((self.output_dim, self.output_dim))
        self.U_cb = self.inner_init((self.output_dim, self.output_dim))
        self.b_cf = shared_zeros((self.output_dim))
        self.b_cb = shared_zeros((self.output_dim))

        self.W_of = self.init((self.input_dim, self.output_dim))
        self.W_ob = self.init((self.input_dim, self.output_dim))
        self.U_of = self.inner_init((self.output_dim, self.output_dim))
        self.U_ob = self.inner_init((self.output_dim, self.output_dim))
        self.b_of = shared_zeros((self.output_dim))
        self.b_ob = shared_zeros((self.output_dim))

        self.W_yf = self.init((self.output_dim, self.output_dim))
        self.W_yb = self.init((self.output_dim, self.output_dim))
        #self.W_y = self.init((self.output_dim, self.output_dim))
        self.b_y = shared_zeros((self.output_dim))

        self.params = [
            self.W_if, self.U_if, self.b_if,
            self.W_ib, self.U_ib, self.b_ib,

            self.W_cf, self.U_cf, self.b_cf,
            self.W_cb, self.U_cb, self.b_cb,

            self.W_ff, self.U_ff, self.b_ff,
            self.W_fb, self.U_fb, self.b_fb,

            self.W_of, self.U_of, self.b_of,
            self.W_ob, self.U_ob, self.b_ob,

            self.W_yf, self.W_yb, self.b_y
            #self.W_y, self.b_y
        ]
        if regularize:
            self.regularizers = []
            for i in self.params:
                self.regularizers.append(regularizers.my_l2)

        if weights is not None:
            self.set_weights(weights)

    def _step(self,
        xi_t, xf_t, xo_t, xc_t,
        h_tm1, c_tm1,
        u_i, u_f, u_o, u_c):
        i_t = self.inner_activation(xi_t + T.dot(h_tm1, u_i))
        f_t = self.inner_activation(xf_t + T.dot(h_tm1, u_f))
        c_t = f_t * c_tm1 + i_t * self.activation(xc_t + T.dot(h_tm1, u_c))
        o_t = self.inner_activation(xo_t + T.dot(h_tm1, u_o))
        h_t = o_t * self.activation(c_t)
        return h_t, c_t

    def output(self, train):
        X = self.get_input(train)
        X = X.dimshuffle((1,0,2))

        if self.is_entity:
            Entity = X[-1:].dimshuffle(1,0,2)
            X = X[:-1]

        b_y = self.b_y
        b_yn = T.repeat(T.repeat(b_y.reshape((1,self.output_dim)),X.shape[0],axis=0).reshape((1,X.shape[0],self.output_dim)), X.shape[1], axis=0)

        xif = T.dot(X, self.W_if) + self.b_if
        xib = T.dot(X, self.W_ib) + self.b_ib

        xff = T.dot(X, self.W_ff) + self.b_ff
        xfb = T.dot(X, self.W_fb) + self.b_fb

        xcf = T.dot(X, self.W_cf) + self.b_cf
        xcb = T.dot(X, self.W_cb) + self.b_cb

        xof = T.dot(X, self.W_of) + self.b_of
        xob = T.dot(X, self.W_ob) + self.b_ob

        [outputs_f, memories_f], updates_f = theano.scan(
            self._step,
            sequences=[xif, xff, xof, xcf],
            outputs_info=[
                alloc_zeros_matrix(X.shape[1], self.output_dim),
                alloc_zeros_matrix(X.shape[1], self.output_dim)
            ],
            non_sequences=[self.U_if, self.U_ff, self.U_of, self.U_cf],
            truncate_gradient=self.truncate_gradient
        )
        [outputs_b, memories_b], updates_b = theano.scan(
            self._step,
            sequences=[xib, xfb, xob, xcb],
            outputs_info=[
                alloc_zeros_matrix(X.shape[1], self.output_dim),
                alloc_zeros_matrix(X.shape[1], self.output_dim)
            ],
            non_sequences=[self.U_ib, self.U_fb, self.U_ob, self.U_cb],
            truncate_gradient=self.truncate_gradient
        )
        if self.return_sequences:
            y = T.add(T.add(
                    T.tensordot(outputs_f.dimshuffle((1,0,2)), self.W_yf, [[2],[0]]),
                    T.tensordot(outputs_b[::-1].dimshuffle((1,0,2)), self.W_yb, [[2],[0]])),
                b_yn)
            # y = T.add(T.tensordot(
            #     T.add(outputs_f.dimshuffle((1, 0, 2)),
            #           outputs_b[::-1].dimshuffle((1,0,2))),
            #     self.W_y,[[2],[0]]),b_yn)
            if self.is_entity:
                return T.concatenate([y, Entity], axis=1)
            else:
                return y
        return T.concatenate((outputs_f[-1], outputs_b[0]))

    def get_config(self):
        return {"name":self.__class__.__name__,
            "input_dim":self.input_dim,
            "output_dim":self.output_dim,
            "init":self.init.__name__,
            "inner_init":self.inner_init.__name__,
            "activation":self.activation.__name__,
            "truncate_gradient":self.truncate_gradient,
            "return_sequences":self.return_sequences}

class BRNN(Layer):
    '''
        Fully connected Bi-directional RNN where:
            Output at time=t is fed back to input for time=t+1 in a forward pass
            Output at time=t is fed back to input for time=t-1 in a backward pass
    '''
    def __init__(self, input_dim, output_dim,
        init='uniform', inner_init='orthogonal', activation='sigmoid', weights=None,
        truncate_gradient=-1,  return_sequences=False, is_entity=False, regularize=False):
        #whyjay
        self.is_entity = is_entity

        self.init = initializations.get(init)
        self.inner_init = initializations.get(inner_init)
        self.input_dim = input_dim
        self.output_dim = output_dim
        self.truncate_gradient = truncate_gradient
        self.activation = activations.get(activation)
        self.return_sequences = return_sequences
        self.input = T.tensor3()
        self.W_o  =  self.init((self.input_dim, self.output_dim))
        self.W_if = self.init((self.input_dim, self.output_dim))    # Input -> Forward
        self.W_ib = self.init((self.input_dim, self.output_dim))    # Input -> Backward
        self.W_ff = self.init((self.output_dim, self.output_dim))   # Forward tm1 -> Forward t
        self.W_bb = self.init((self.output_dim, self.output_dim))   # Backward t -> Backward tm1
        self.b_if = shared_zeros((self.output_dim))
        self.b_ib = shared_zeros((self.output_dim))
        self.b_f = shared_zeros((self.output_dim))
        self.b_b = shared_zeros((self.output_dim))
        self.b_o =  shared_zeros((self.output_dim))
        self.params = [self.W_o,self.W_if,self.W_ib, self.W_ff, self.W_bb,self.b_if,self.b_ib, self.b_f, self.b_b, self.b_o]

        if regularize:
            self.regularizers = []
            for i in self.params:
                self.regularizers.append(regularizers.my_l2)

        if weights is not None:
            self.set_weights(weights)

    def _step(self, x_t, h_tm1, u,b):
        return self.activation(x_t + T.dot(h_tm1, u)+b)

    def output(self, train):
        X = self.get_input(train) # shape: (nb_samples, time (padded with zeros at the end), input_dim)
        # new shape: (time, nb_samples, input_dim) -> because theano.scan iterates over main dimension
        X = X.dimshuffle((1, 0, 2))

        if self.is_entity:
            lenX=X.shape[0]
            Entity=X[lenX-1:].dimshuffle(1,0,2)
            X=X[:lenX-1]

        xf = self.activation(T.dot(X, self.W_if) + self.b_if)
        xb = self.activation(T.dot(X, self.W_ib) + self.b_ib)
        b_o=self.b_o
        b_on= T.repeat(T.repeat(b_o.reshape((1,self.output_dim)),X.shape[0],axis=0).reshape((1,X.shape[0],self.output_dim)),X.shape[1],axis=0)

        # Iterate forward over the first dimension of the x array (=time).
        outputs_f, updates_f = theano.scan(
            self._step,  # this will be called with arguments (sequences[i], outputs[i-1], non_sequences[i])
            sequences=xf,  # tensors to iterate over, inputs to _step
            # initialization of the output. Input to _step with default tap=-1.
            outputs_info=alloc_zeros_matrix(X.shape[1], self.output_dim),
            non_sequences=[self.W_ff,self.b_f],  # static inputs to _step
            truncate_gradient=self.truncate_gradient
        )
        # Iterate backward over the first dimension of the x array (=time).
        outputs_b, updates_b = theano.scan(
            self._step,  # this will be called with arguments (sequences[i], outputs[i-1], non_sequences[i])
            sequences=xb,  # tensors to iterate over, inputs to _step
            # initialization of the output. Input to _step with default tap=-1.
            outputs_info=alloc_zeros_matrix(X.shape[1], self.output_dim),
            non_sequences=[self.W_bb,self.b_b],  # static inputs to _step
            truncate_gradient=self.truncate_gradient,
            go_backwards=True  # Iterate backwards through time
        )
        #return outputs_f.dimshuffle((1, 0, 2))
        if self.return_sequences:
            if self.is_entity:
                return T.concatenate([T.add(T.tensordot(T.add(outputs_f.dimshuffle((1, 0, 2)), outputs_b[::-1].dimshuffle((1,0,2))),self.W_o,[[2],[0]]),b_on),Entity],axis=1)
            else:
                return T.add(T.tensordot(T.add(outputs_f.dimshuffle((1, 0, 2)), outputs_b[::-1].dimshuffle((1,0,2))),self.W_o,[[2],[0]]),b_on)

        return T.concatenate((outputs_f[-1], outputs_b[0]))

    def get_config(self):
        return {"name":self.__class__.__name__,
            "input_dim":self.input_dim,
            "output_dim":self.output_dim,
            "init":self.init.__name__,
            "inner_init":self.inner_init.__name__,
            "activation":self.activation.__name__,
            "truncate_gradient":self.truncate_gradient,
            "return_sequences":self.return_sequences}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace DoS\ResourceBundle\Provider;

use Sylius\Component\Resource\Model\ResourceInterface;

interface ProviderInterface
{
    /**
     * @return ResourceInterface
     */
    public function createNew();

    /**
     * @param ResourceInterface $resource
     */
    public function persist(ResourceInterface $resource);

    /**
     * @param ResourceInterface|null $resource
     */
    public function flush(ResourceInterface $resource = null);

    /**
     * @param ResourceInterface $resource
     * @param bool $single
     */
    public function save(ResourceInterface $resource, $single = false);

    /**
     * @param $id
     *
     * @return ResourceInterface
     */
    public function find($id);

    /**
     * @return ResourceInterface[]
     */
    public function findAll();

    /**
     * @param array $criteria
     * @param array|null $orderBy
     * @param null $limit
     * @param null $offset
     *
     * @return ResourceInterface[]
     */
    public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null);

    /**
     * @param array $criteria
     *
     * @return ResourceInterface[]
     */
    public function findOneBy(array $criteria);
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
J. Dept. Agric. Porto Rico 14(4): 226 (1930)

#### Original name
Belonopsis ingae Seaver

### Remarks
null


text:
layout: default
---

		Posted on {{ page.date | date: "%B %-d, %Y" }}

{{ page.title }}

		{{ content }}

  {% include share-page.html %}

		Do you want to get organized?

	 MyEmbroids is a desktop application which let's you view designs on
	  your computer without having to open each file individually. Just download the app and get organized :)

		More info

		{% if page.next.url %}

			Next entry
			{{ page.next.title }}

		{% endif %}

		{% if page.previous.url %}

			Previous entry
			{{ page.previous.title }}

		{% endif %}


text:
/* Adapted from Paul Furgale Schweizer Messer sm_timing */

#ifndef VOXBLOX_FAST_UTILS_TIMING_H_
#define VOXBLOX_FAST_UTILS_TIMING_H_

#include <algorithm>
#include <chrono>
#include <limits>
#include <map>
#include <string>
#include <vector>

namespace voxblox_fast {

namespace timing {

template <typename T, typename Total, int N>
class Accumulator {
 public:
  Accumulator()
      : window_samples_(0),
        totalsamples_(0),
        window_sum_(0),
        sum_(0),
        min_(std::numeric_limits<T>::max()),
        max_(std::numeric_limits<T>::min()) {}

  void Add(T sample) {
    if (window_samples_ < N) {
      samples_[window_samples_++] = sample;
      window_sum_ += sample;
    } else {
      T& oldest = samples_[window_samples_++ % N];
      window_sum_ += sample - oldest;
      oldest = sample;
    }
    sum_ += sample;
    ++totalsamples_;
    if (sample > max_) {
      max_ = sample;
    }
    if (sample < min_) {
      min_ = sample;
    }
  }

  int TotalSamples() const { return totalsamples_; }

  double Sum() const { return sum_; }

  double Mean() const { return sum_ / totalsamples_; }

  double RollingMean() const {
    return window_sum_ / std::min(window_samples_, N);
  }

  double Max() const { return max_; }

  double Min() const { return min_; }

  double LazyVariance() const {
    if (window_samples_ == 0) {
      return 0.0;
    }
    double var = 0;
    double mean = RollingMean();
    for (int i = 0; i < std::min(window_samples_, N); ++i) {
      var += (samples_[i] - mean) * (samples_[i] - mean);
    }
    var /= std::min(window_samples_, N);
    return var;
  }

 private:
  int window_samples_;
  int totalsamples_;
  Total window_sum_;
  Total sum_;
  T min_;
  T max_;
  T samples_[N];
};

struct TimerMapValue {
  TimerMapValue() {}

  // Create an accumulator with specified window size.
  Accumulator<double, double, 50> acc_;
};

// A class that has the timer interface but does nothing. Swapping this in in
// place of the Timer class (say with a typedef) should allow one to disable
// timing. Because all of the functions are inline, they should just disappear.
class DummyTimer {
 public:
  DummyTimer(size_t /*handle*/, bool /*constructStopped*/ = false) {}
  DummyTimer(std::string const& /*tag*/, bool /*constructStopped*/ = false) {}
  ~DummyTimer() {}

  void Start() {}
  void Stop() {}
  bool IsTiming() { return false; }
};

class Timer {
 public:
  Timer(size_t handle, bool constructStopped = false);
  Timer(std::string const& tag, bool constructStopped = false);
  ~Timer();

  void Start();
  void Stop();
  bool IsTiming() const;

 private:
  std::chrono::time_point<std::chrono::system_clock> time_;

  bool timing_;
  size_t handle_;
};

class Timing {
 public:
  typedef std::map<std::string, size_t> map_t;
  friend class Timer;
  // Definition of static functions to query the timers.
  static size_t GetHandle(std::string const& tag);
  static std::string GetTag(size_t handle);
  static double GetTotalSeconds(size_t handle);
  static double GetTotalSeconds(std::string const& tag);
  static double GetMeanSeconds(size_t handle);
  static double GetMeanSeconds(std::string const& tag);
  static size_t GetNumSamples(size_t handle);
  static size_t GetNumSamples(std::string const& tag);
  static double GetVarianceSeconds(size_t handle);
  static double GetVarianceSeconds(std::string const& tag);
  static double GetMinSeconds(size_t handle);
  static double GetMinSeconds(std::string const& tag);
  static double GetMaxSeconds(size_t handle);
  static double GetMaxSeconds(std::string const& tag);
  static double GetHz(size_t handle);
  static double GetHz(std::string const& tag);
  static void Print(std::ostream& out);
  static std::string Print();
  static std::string SecondsToTimeString(double seconds);
  static void Reset();
  static const map_t& GetTimers() { return Instance().tagMap_; }

 private:
  void AddTime(size_t handle, double seconds);

  static Timing& Instance();

  Timing();
  ~Timing();

  typedef std::vector<TimerMapValue> list_t;

  list_t timers_;
  map_t tagMap_;
  size_t maxTagLength_;
};

#if ENABLE_MSF_TIMING
typedef Timer DebugTimer;
#else
typedef DummyTimer DebugTimer;
#endif

}  // namespace timing
}  // namespace voxblox

#endif  // VOXBLOX_FAST_UTILS_TIMING_H_


text:
require 'test_helper'

class ConfigurationsControllerTest < ActionDispatch::IntegrationTest
  setup do
    @configuration = configurations(:one)
  end

  test "should get index" do
    get configurations_url
    assert_response :success
  end

  test "should get new" do
    get new_configuration_url
    assert_response :success
  end

  test "should create configuration" do
    assert_difference('Configuration.count') do
      post configurations_url, params: { configuration: { authentication_type: @configuration.authentication_type, create_artifacts_on_the_fly: @configuration.create_artifacts_on_the_fly, http_password_digest: @configuration.http_password_digest, http_user: @configuration.http_user, use_authentication: @configuration.use_authentication } }
    end

    assert_redirected_to configuration_url(Configuration.last)
  end

  test "should show configuration" do
    get configuration_url(@configuration)
    assert_response :success
  end

  test "should get edit" do
    get edit_configuration_url(@configuration)
    assert_response :success
  end

  test "should update configuration" do
    patch configuration_url(@configuration), params: { configuration: { authentication_type: @configuration.authentication_type, create_artifacts_on_the_fly: @configuration.create_artifacts_on_the_fly, http_password_digest: @configuration.http_password_digest, http_user: @configuration.http_user, use_authentication: @configuration.use_authentication } }
    assert_redirected_to configuration_url(@configuration)
  end

  test "should destroy configuration" do
    assert_difference('Configuration.count', -1) do
      delete configuration_url(@configuration)
    end

    assert_redirected_to configurations_url
  end
end


text:
package com.logitags.cibet.actuator.owner;

import java.util.List;

import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import org.apache.log4j.Logger;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import com.cibethelper.base.DBHelper;
import com.cibethelper.entities.owner.Company;
import com.cibethelper.entities.owner.Merchant;
import com.cibethelper.entities.owner.Merchant2;
import com.cibethelper.entities.owner.Product;
import com.logitags.cibet.context.Context;

public class OwnerIntegrationTest extends DBHelper {

   private static Logger log = Logger.getLogger(OwnerIntegrationTest.class);

   public static String testString;

   @BeforeClass
   public static void beforeClassOwnerIntegrationTest() throws Exception {
      log.debug("OwnerIntegrationTest beforeClass");
      Merchant m1 = new Merchant();
      m1.setId(1);
      m1.setTenant("Ralf");

      Merchant m2 = new Merchant();
      m2.setId(2);
      m2.setParent(m1);
      m2.setTenant("Ralf");

      Product p1 = new Product();
      p1.setId("pp3");
      p1.setTenant("Ralf");

      Company c = new Company();
      c.setId("c1");
      c.setTenant("Ralf");

      Merchant2 m1a = new Merchant2();
      m1a.setId(3);
      m1a.setTenant("Ralf");
      m1a.setCompany(c);

      Merchant2 m2a = new Merchant2();
      m2a.setId(4);
      m2a.setParent(m1a);
      m2a.setTenant("Ralf");

      Merchant2 m3 = new Merchant2();
      m3.setId(5);
      m3.setParent(m2a);
      m3.setTenant("Ralf");
      m3.setCompany(c);

      Merchant mm1 = new Merchant();
      mm1.setId(10);
      mm1.setTenant("Werner");

      Merchant mm2 = new Merchant();
      mm2.setId(12);
      mm2.setParent(mm1);
      mm2.setTenant("Werner");

      Product pp1 = new Product();
      pp1.setId("pp30");
      pp1.setTenant("Werner");

      Company cc = new Company();
      cc.setId("c10");
      cc.setTenant("Werner");

      Merchant2 mm1a = new Merchant2();
      mm1a.setId(13);
      mm1a.setTenant("Werner");
      mm1a.setCompany(cc);

      Merchant2 mm2a = new Merchant2();
      mm2a.setId(14);
      mm2a.setParent(mm1a);
      mm2a.setTenant("Werner");

      Merchant2 mm3 = new Merchant2();
      mm3.setId(15);
      mm3.setParent(mm2a);
      mm3.setTenant("Werner");
      mm3.setCompany(cc);

      applEman.getTransaction().begin();
      applEman.persist(m1);
      applEman.persist(m2);
      applEman.persist(p1);
      applEman.persist(c);
      applEman.persist(m1a);
      applEman.persist(m2a);
      applEman.persist(mm1);
      applEman.persist(mm2);
      applEman.persist(pp1);
      applEman.persist(cc);
      applEman.persist(mm1a);
      applEman.persist(mm2a);
      applEman.getTransaction().commit();

      initConfiguration("cibet-config-owner.xml");
   }

   @AfterClass
   public static void doAfterOwnerIntegrationTest() throws Exception {
      log.debug("OwnerIntegrationTest: doAfter()");

      applEman.clear();
      applEman.getTransaction().begin();

      Query q = applEman.createQuery("delete from Company a");
      q.executeUpdate();

      q = applEman.createQuery("delete from Merchant a");
      q.executeUpdate();

      q = applEman.createQuery("delete from Merchant2 a");
      q.executeUpdate();

      q = applEman.createQuery("delete from Product a");
      q.executeUpdate();

      q = applEman.createQuery("delete from Product2 a");
      q.executeUpdate();

      applEman.getTransaction().commit();
   }

   @Test
   public void insert() {
      log.debug("call insert()");
      Context.sessionScope().setTenant("Ralf");
      Product p1 = new Product();
      p1.setId("np1");
      p1.setTenant("no");
      applEman.persist(p1);
      applEman.flush();

      TypedQuery<Company> q = applEman.createQuery("select a from Company a", Company.class);
      List<Company> list = q.getResultList();
      Assert.assertEquals(1, list.size());

      Context.sessionScope().setTenant(null);
      TypedQuery<Product> q1 = applEman.createQuery("select a from Product a", Product.class);
      List<Product> list1 = q1.getResultList();
      Assert.assertEquals(2, list1.size());
   }

   @Test
   public void insert2() {
      log.debug("call insert2()");
      Context.sessionScope().setTenant("Werner");
      Product p1 = new Product();
      p1.setId("np1");
      p1.setTenant("no");
      try {
         applEman.persist(p1);
         Assert.fail();
      } catch (WrongOwnerException e) {
      }

      applEman.clear();
      TypedQuery<Company> q = applEman.createQuery("select a from Company a", Company.class);
      try {
         q.getResultList();
         Assert.fail();
      } catch (WrongOwnerException e) {
      }
   }

   @Test
   public void findAndMerge() {
      log.debug("call findAndMerge()");
      Context.sessionScope().setTenant("Ralf");
      Product p1 = applEman.find(Product.class, "pp3");
      p1.setProductName("Wanze");
      applEman.merge(p1);

      applEman.getTransaction().commit();
      applEman.getTransaction().begin();
      applEman.clear();

      TypedQuery<Product> q1 = applEman.createQuery("select a from Product a where a.tenant = 'Ralf' and a.id = 'pp3'",
            Product.class);
      Product p = q1.getSingleResult();
      Assert.assertEquals("Wanze", p.getProductName());
   }

   @Test
   public void findAndMergeErr() {
      log.debug("call findAndMergeErr()");
      Context.sessionScope().setTenant("Werner");
      Product p1 = applEman.find(Product.class, "pp30");
      Context.sessionScope().setTenant("Ralf");
      p1.setProductName("Wanze");
      applEman.merge(p1);

      applEman.getTransaction().commit();
      applEman.getTransaction().begin();
      applEman.clear();

      TypedQuery<Product> q1 = applEman.createQuery("select a from Product a where a.id = 'pp30'", Product.class);
      Product p;
      try {
         p = q1.getSingleResult();
         Assert.fail();
      } catch (NoResultException e) {
      }

      Context.sessionScope().setTenant("Werner");
      p = q1.getSingleResult();
      Assert.assertNull(p.getProductName());
   }

   @Test
   public void deleteErr() {
      log.debug("call deleteErr()");
      Context.sessionScope().setTenant("Werner");
      Product p1 = applEman.find(Product.class, "pp30");
      Context.sessionScope().setTenant("Ralf");

      applEman.remove(p1);

      applEman.getTransaction().commit();
      applEman.getTransaction().begin();
      applEman.clear();

      Context.sessionScope().setTenant("Werner");
      TypedQuery<Product> q1 = applEman.createQuery("select a from Product a where a.id = 'pp30'", Product.class);
      Product p = q1.getSingleResult();
   }

   @Test(expected = WrongOwnerException.class)
   public void deleteErr2() {
      log.debug("call deleteErr2()");
      Context.sessionScope().setTenant("Ralf");
      Product p1 = applEman.find(Product.class, "pp3");
      Context.sessionScope().setTenant("Werner");

      applEman.remove(p1);
   }

   @Test(expected = WrongOwnerException.class)
   public void deleteErr3() {
      log.debug("call deleteErr3()");
      Context.sessionScope().setTenant("Werner");
      applEman.find(Product.class, "pp3");
   }

   @Test
   public void findMerchant() {
      log.debug("call findMerchant()");
      Context.sessionScope().setTenant("Werner|c10");
      Merchant2 m = applEman.find(Merchant2.class, 14L);
      Assert.assertNotNull(m);

      Context.sessionScope().setTenant("Werner|xx");
      try {
         applEman.find(Merchant2.class, 14L);
      } catch (WrongOwnerException e) {
      }
   }

   @Test
   public void findMerchant2() {
      log.debug("call findMerchant2()");
      Context.sessionScope().setTenant("Ralf|c1");
      Merchant2 m = applEman.find(Merchant2.class, 3L);
      Assert.assertNotNull(m);

      Context.sessionScope().setTenant("Ralf|xx");
      m = applEman.find(Merchant2.class, 3L);
      Assert.assertNull(m);
   }

   @Test
   public void findMerchant3() {
      log.debug("call findMerchant3()");
      Context.sessionScope().setTenant("Heinz");
      Merchant2 m = applEman.find(Merchant2.class, 3L);
      Assert.assertNull(m);
      Assert.assertNotNull(testString);

      testString = null;
   }

}


text:
package models.test

case class Test(id: String, run: () => Any = () => ()) {
  def toTree = Tree(this)
}


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

  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <title>View Vicnum table</title>

<?php
$table = $_GET["table"];
?>

<?php
   $connection = mysql_connect("localhost","root","vicnum");

   mysql_select_db("vicnum", $connection);

   $result = mysql_query ("SELECT name,guess,count,tod FROM
                          $table where count > 0 order by count,tod asc", $connection);
   $cnt = mysql_num_rows($result);

print "
Below please find all $cnt Vicnum players in table $table\n
" ;

   while ($row = mysql_fetch_array($result, MYSQL_NUM))
   {

     print "$row[0] has guessed $row[1] in $row[2] guess(es) on $row[3] \n";
   }

?>

The Vicnum project was developed for educational purposes to demonstrate common web vulnerabilities.

For comments please visit the OWASP project page.


text:
by Stephane Bedard, sbedard.code@gmail.com

## Introduction

The Relay (as the Simple Multi-Protocol TCP Relay is hence forth referred to) allows two TCP networked applications to
communicate with each other when a direct communication is not possible, for example if the two applications are hosted
on different NAT sub-networks.

The Relay supports 3 basic modes of operation:
- One to One Mode
- One to Many Mode
- Clients/Server with simple Server Adapter
- Client(s)/Server(s) mode with Multiplexing Server Adapter

#
## Supported OS
- Compiled: Windows 10 64 bit
- Compiled and provided binary: Ubuntu 16.04.3 LTS (should work with most flavors of Linux)

#
## Glossary

Client: A connection that connects to the port assigned to a Host for the purpose of communicating with the Host.

Host: A networked connection that simulates listening for other connections. Any commands to the relay must come from
this connection. This is also the connection that a server adapter application would connect to.

Server Adapter: An application with an outbound connection to the Relay that can forward requests to outside servers
and multiplex the response back to the Relay for the client that made the original request. In theory the
Server Adapter allows communication between a traditional server and a client with no modifications.
More details about the Server Adapter specifications can be found in the designated section of this document.

SBRP: The Relay protocol that the Relay uses to send messages to the Host and that the Host can use to send commands
to the Relay (Quit, Rename Host, List all Hosts, etc.). More details on the SBRP protocol under the designated section
of this document.

#
## One to One Mode

One to One mode allows for traditional peer to peer communication between two applications. What one application
transmits, the other receives and vice versa.

This is the default behavior when a single client connects to the assigned port of a single host. An example use
could be for example for a Telnet chat.

#
## One to Many Mode

One to Many mode allows a Host connection to broadcast to all connected clients and for all the Clients to message the
Host connection. The clients do not see each others messages.

This is the default behavior when a multiple clients connects to the assigned port of a single host. An example use
could be the host logging all data from multiple clients, with the capability of sending commands back to the clients.

#
## One to One Client/Server with simple Server Adapter

Allows client/server TCP communication.

The single Host in this scenario is the Server Adapter application connected to the Relay.
The Client is a traditional client such as a web browser or SSH client. The Server Adapter
would be configured to be able to forward requests to a single IP address and port per connection to the Relay.

- The Relay forwards the unaltered Client request to the Server Adapter.
- If the message is not an SBRP message, the Server Adapter makes a request to a redetermined IP.
- Upon a response, the Server Adapter will forward to the Relay the unaltered response.
- If more than one Client is connected to the Host, all clients will receive the response, whether they made the request
or not.

More details can be found in the Server Adapter specifications.

#
## Client(s)/Server(s) mode with Multiplexing Server Adapter

Allows client/server TCP communication.

The Hosts in this scenario are multiple Server Adapter application that have multiplexing capabilities,
connected to the Relay. The Clients are traditional clients such as web browsers or SSH clients. The Server Adapter
would be configured to be able to forward requests to a single IP address and port per connection to the Relay.

- It works by the Server Adapter sending a SBRP command to the Relay.
- The Relay will then prepend all Client->Host communication with a client identifier.
- The Server Adapter will strip the identifier before making any outbound requests to a redetermined IP.
- Upon a response, the Server Adapter will once again prepend the client identifier.
- The Relay will route the data to the correct Client, stripping the client identifier before sending.
- The Server Adapter would also not forward any SBRP protocol messages originating from the Relay to the server.

More details can be found in the Server Adapter specifications.

#
## Supported Protocols

These protocols have been tested (or will be tested before release).

- Raw TCP communication peer to peer
- Telnet
- SSH
- HTTP
- Modbus
- SMTP
- FTP

#
## Unsupported Protocols
- HTTPS
- TLS
- UDP

#
## Limitations
- TCP packets containing more than 512 bytes of data in their data field will be split into multiple packets.
- The Relay has no support for partial packet transmission, it will forward what it receives, even if it is corrupted.
This is an unlikely scenario on Windows or Linux where there is a well implemented TCP stack.

#
## Compiling the Relay from GitHub source

TODO

#
## Running Automated Tests

TODO

#
## Starting the Relay

TODO Windows
TODO Linux

#
## Starting the Relay for client(s)/server(s) communication

TODO Simple Server Adapter Application
TODO Multiplexing Server Adapter Application

#
##Using the provided test Server Adapter Application

TODO Windows
TODO Linux

#
## Server Adapter Specification
TODO more details
#### Simple:

#### Multiplexing:
In short, the first 8 bytes of the TCP message, if the Server Adapter is active, are used as a client identifier.
These identifying bytes are only "on the wire" between the Relay and the Server Adapter.

For simplification of testing purposes, the identifier is an 8 character numeral ranging from 00,000,000 to 99,999,999
(without the commas of course).

#
## SBRP Protocol

The SBRP protocol is designed to use the same syntax both for incoming and outgoing messages.

The SBRP message starts with the identifier "SBRP 1.0 " followed by a 10 character command identifier and
a trailing space. Anything after the trailing space is considered the message body. In other words, the 21st character
until the last character is the message body.

The message body only supports alphanumeric characters from ASCII[32] to ASCII[125]

#
## Host SBRP Messages to the Relay
```
SBRP 1.0 LIST_CONNS HOSTS
SBRP 1.0 LIST_CONNS CLIENTS
SBRP 1.0 LIST_CONNS ALL
SBRP 1.0 LIST_CONNS ME
```
- Returns an unformatted list of connections to the Relay and the ports used
- The ME option returns the information about the connected host the message comes from, as well
as information about any Clients connected to that Host's assigned port.

```
SBRP 1.0 RENAME_CON My_New_Name
```

- Gives a human readable name to the Host connection, useful for identifying a specific host in the list

```
SBRP 1.0 RELAY_PORT GET
```

- Returns the relay port used by the host in this format "SBRP 1.0 RELAY_PORT 8081"

```
SBRP 1.0 QUIT_RELAY
```

#
## Relay SBRP Messages to the Host

If the const USE_RELAY_PROTOCOL is set to true, messages will be sent to the Host and the console.

If the const USE_RELAY_PROTOCOL is set to false, SBRP messages and errors will only be sent to the console.

```
SBRP 1.0 RELAY_PORT 8081
```

- The first message sent to the Host after connection. As well as the return format of the RELAY_PORT GET command

```
SBRP 1.0 ERROR_MSG Some_Error_String_Goes_Here
```

- Informs the Host of a Relay generated error.

#
## Configuration settings

TODO

#
## Future Improvements

- If required, a future version of the Relay and Server Adapter could use something more akin to NAT, but research would
be required to see if this is possible entirely from the application layer in Go.
- Not only having a minimum and maximum port number assignment for Clients in the configuration but also
having a blacklist of ports that the Relay should not use even within said range.
- Moving all configurations from global const variables in the main.go file to a config.cfg file.


text:
// Header for ptrvector template class

#ifndef __PTRVECTOR__MULBERRY__
#define __PTRVECTOR__MULBERRY__

#include <cstddef>
#include <vector>

// Classes

#ifdef MSIPL_USING_NAMESPACE
	namespace std {
#endif

template <class T> class ptrvector : public std::vector<T*>
{
public:
		typedef typename std::vector<T*>::iterator           iterator;
		typedef typename std::vector<T*>::size_type         size_type;

		ptrvector() {_delete_data = true;};
		ptrvector(const ptrvector& copy)
			{ _copy(copy); };
	~ptrvector()
		{ _tidy(); };											// Force object deletion

    ptrvector<T>& operator= (const ptrvector<T>& copy)
    	{ if (this != &copy) { _tidy(); _copy(copy); } return *this; }

	void set_delete_data(bool delete_data)
		{ _delete_data = delete_data; }

	// Special to delete objects
	void resize(size_type sz, T* c = NULL);
	void pop_back ();									// Delete address as well
	iterator erase(iterator position);						// Delete address as well
    iterator erase(iterator first, iterator last);			// Delete addresses as well
	void  clear();

private:
	bool _delete_data;

	void _copy(const ptrvector& copy);
	void _tidy()
		{ erase(this->begin(), this->end()); }
};

// Copy construct
template <class T> void ptrvector<T>::_copy(const ptrvector<T>& copy)
{
	// Since we're creating new ones we must delete them
	_delete_data = true;

	// Copy all objects
	for(typename ptrvector<T>::const_iterator iter = copy.begin(); iter != copy.end(); iter++)
		this->push_back(new T(**iter));
}

template <class T>
inline
bool
operator==(const ptrvector<T>& x, const ptrvector<T>& y)
{
    if (x.size() != y.size())
    	return false;

    // Compare each object
    typename ptrvector<T>::const_iterator iter1 = x.begin();
    typename ptrvector<T>::const_iterator iter2 = y.begin();
	for(; iter1 != x.end(); iter1++, iter2++)
	   if (!(**iter1 == **iter2)) return false;

	return true;
}

template <class T>
inline
bool
operator!=(const ptrvector<T>& x, const ptrvector<T>& y)
{
   	return !(x == y);
}

template <class T> void ptrvector<T>::resize(size_type sz, T* c)
{
	if (sz > this->size())
		insert(this->end(), sz - this->size(), c);
	else if (sz < this->size())
		erase(this->begin() + sz, this->end());
}

// Delete object as well
template <class T> void ptrvector<T>::pop_back()
{
	if (_delete_data)
		delete this->back();
	std::vector<T*>::pop_back();
}

// Delete object as well
template <class T> typename ptrvector<T>::iterator ptrvector<T>::erase(iterator position)
{
	if (_delete_data)
		delete *position;
	return std::vector<T*>::erase(position);
}

// Delete object as well
template <class T> typename ptrvector<T>::iterator ptrvector<T>::erase(iterator first, iterator last)
{
	if (_delete_data)
	{
		for(iterator iter = first; iter != last; iter++)
			delete *iter;
	}

	return std::vector<T*>::erase(first, last);
}

// Delete objects as well
template <class T> void ptrvector<T>::clear()
{
	erase(this->begin(), this->end());
}

#ifdef MSIPL_USING_NAMESPACE
	} // namespace std
#endif

#endif


text:
create user test identified by 'vertica';
create schema test authorization test;

drop schema sugarcrm;
drop user sugarcrm;
create user sugarcrm identified by 'vertica';
create schema sugarcrm authorization sugarcrm;

create user dwhstage identified by 'vertica';
create schema dwhstage authorization dwhstage;

create user dwhreport identified by 'vertica';
create schema dwhreport authorization dwhreport;


text:
from django.shortcuts import render,render_to_response
from django.http import HttpResponseRedirect
from django import forms
from django.contrib.auth.forms import UserCreationForm
from main.forms import ContactForm, UserProfileForm

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        pform = UserProfileForm(request.POST)
        if form.is_valid() and pform.is_valid():
            import logging
            logger = logging.getLogger('django.request')
            logger.info('New registered user\n'+str(request).replace('\n','\n\t'))
            new_user = form.save()
            pform.instance.user = new_user
            pform.save()
            if pform.instance.fladRequest:
                from django.core.mail import send_mail
                send_mail('FLAD request',
                          '{} requested to use FLAD.'.format(new_user.username),
                          'root@forensic.ugent.be',
                          ['itfbt@ugent.be'],
                          fail_silently=True)
            #Set FLAD test configuration for all new users
            from myflq.models import FLADconfig
            fc=FLADconfig(user=new_user,FLAD="forensic.ugent.be/flax",
                          FLADname="testname",FLADkey="testkey")
            fc.save()
            return HttpResponseRedirect("/")
    else:
        form = UserCreationForm()
        pform = UserProfileForm()
    return render(request, "registration/register.html", {
        'form': form,
        'pform': pform,
    })

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            topic = form.cleaned_data['topic']
            message = form.cleaned_data['message']
            sender = form.cleaned_data.get('sender', 'noreply@example.com')

            from django.core.mail import send_mail
            send_mail(
                'Feedback from your site, topic: {}'.format(topic),
                message, sender,
                ['christophe.vanneste@ugent.be']
            )
            return HttpResponseRedirect('/contact/thanks/')
    else:
        form = ContactForm()
    return render(request,'main/contact.html', {'form': form,
                                                'widgets': [{'img':'images/contact.png','style':'margin-top:50px;'}]})


text:
<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
    xmlns:rim="http://www.blackberry.com/ns/widgets"
    id="com.endare.push"
    version="1.0.1">

    <js-module src="www/PushNotification.js" name="PushNotification">
        <clobbers target="PushNotification" />
    </js-module>

    <js-module src="www/Base64.js" name="Base64" />

    <dependency id="com.blackberry.invoked" />
    <dependency id="com.blackberry.push" />
    <dependency id="com.blackberry.notification" />
    <dependency id="com.blackberry.app" />

    <platform name="blackberry10">
        <source-file src="src/blackberry10/index.js" target-dir="PushNotification" />

        <config-file target="www/config.xml" parent="/widget">
            <feature name="com.endare.push" value="com.endare.push" />

            <access origin="https://urbanairship.com" subdomains="true" />
        </config-file>

        <config-file target="www/config.xml" parent="/widget/rim:permissions">
            <rim:permit system="true">_sys_use_consumer_push</rim:permit>
        </config-file>
    </platform>
</plugin>


text:
var username = "";

function setup_user_admin(userprofile_username) {
    username = userprofile_username;

    document.getElementById("toggle-adminpanel-button").addEventListener('click', function(e) {
        $("#adminpanel").toggle();
        var button = document.getElementById("toggle-adminpanel-button");
        if ($('#adminpanel').is(':visible')) {
            button.innerHTML = 'Admin Panel ';
        } else {
            button.innerHTML = 'Admin Panel ';
        }
    }, false);
    document.getElementById("set-admin-button").addEventListener('click', function(e) {
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/api/v1/user/' + username + '/setadmin');
        xhr.onload = function() {
            window.location = window.location;
        };
        if(confirm("Make " + username + " an admin?"))
        {
            xhr.send();
        }
    }, false);
    document.getElementById("remove-admin-button").addEventListener('click', function(e) {
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/api/v1/user/' + username + '/removeadmin');
        xhr.onload = function() {
            window.location = window.location;
        };
        if(confirm("Remove " + username + " as admin?"))
        {
            xhr.send();
        }
    }, false);

    document.getElementById("confirm-user-button").addEventListener('click', function(e) {
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/api/v1/user/' + username + '/confirm/ADMIN');
        xhr.onload = function() {
            window.location = window.location;
        };
        if(confirm("Confirm " + username + "?"))
        {
            xhr.send();
        }
    }, false);
        document.getElementById("unconfirm-user-button").addEventListener('click', function(e) {
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/api/v1/user/' + username +'/unconfirm');
        xhr.onload = function() {
            window.location = window.location;
        };
        if(confirm("Unconfirm " + username + "?"))
        {
            xhr.send();
        }
    }, false);
}


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

describe "Fixnum#+" do
  it "returns self plus the given Integer" do
    (491 + 2).should == 493
    (90210 + 10).should == 90220

    (9 + bignum_value).should == 9223372036854775817
    (1001 + 5.219).should == 1006.219
  end

  it "raises a TypeError when given a non-Integer" do
    lambda {
      (obj = mock('10')).should_receive(:to_int).any_number_of_times.and_return(10)
      13 + obj
    }.should raise_error(TypeError)
    lambda { 13 + "10"    }.should raise_error(TypeError)
    lambda { 13 + :symbol }.should raise_error(TypeError)
  end

  it "overflows to Bignum when the result does not fit in Fixnum" do
    (5 + 10).should be_an_instance_of Fixnum
    (1 + bignum_value).should be_an_instance_of Bignum

    bignum_zero = bignum_value.coerce(0).first
    (1 + bignum_zero).should be_an_instance_of Fixnum
    (fixnum_max + 1).should be_an_instance_of(Bignum)
  end
end


text:
package com.indielist.domain;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.usertype.UserType;

import java.io.Serializable;
import java.sql.*;
import java.time.Instant;

/**
 * @author jsingh on 15-01-10.
 */
public class InstantAsTimestampUserType implements UserType {

    private static final int[] SQL_TYPES = new int[]{Types.TIMESTAMP};

    @Override
    public int[] sqlTypes() {
        return SQL_TYPES;
    }

    @Override
    public Class returnedClass() {
        return Instant.class;
    }

    @Override
    public boolean equals(Object x, Object y) throws HibernateException {
        if (x == y) {
            return true;
        }
        if (x == null || y == null) {
            return false;
        }
        Instant dtx = (Instant) x;
        Instant dty = (Instant) y;
        return dtx.equals(dty);
    }

    @Override
    public int hashCode(Object x) throws HibernateException {
        return x.hashCode();
    }

    @Override
    public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException {
        Timestamp ts = (Timestamp) StandardBasicTypes.TIMESTAMP.nullSafeGet(rs, names, session, owner);
        if (ts == null) {
            return null;
        }
        Instant instant = ts.toInstant();
        return instant;
    }

    @Override
    public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException, SQLException {
        if (value != null){
            Timestamp ts = Timestamp.from((Instant) value);
            StandardBasicTypes.TIMESTAMP.nullSafeSet(st, ts, index, session);
        } else {
            st.setNull(index, Types.TIMESTAMP);
        }
    }

    @Override
    public Object deepCopy(Object value) throws HibernateException {
        return value;
    }

    @Override
    public boolean isMutable() {
        return false;
    }

    @Override
    public Serializable disassemble(Object value) throws HibernateException {
        return (Instant) value;
    }

    @Override
    public Object assemble(Serializable cached, Object owner) throws HibernateException {
        return cached;
    }

    @Override
    public Object replace(Object original, Object target, Object owner) throws HibernateException {
        return original;
    }
}


text:
Given /^a request that has a notification URL$/ do
  key = 'bobbyjpeg'

  put key, File.open('features/camels.jpg').read

  message = {
    :bucket => Ungulate.configuration.test_bucket,
    :key => key,
    :notification_url => 'http://127.0.0.1:4567/bob',
    :versions => {
      :medium => [
        [:resize_to_fill, 100, 100],
      ]
    }
  }.to_yaml

  queue.push(message)

  File.unlink('/tmp/ungulate_put_test') rescue

  # start sinatra app
  @sinatra_pid = fork do
    TestApp.run!
  end
end

Then /^the notification URL should receive a PUT$/ do
  File.read('/tmp/ungulate_put_test').should == 'received, loud and clear!'
  Process.kill('KILL', @sinatra_pid)
  File.unlink('/tmp/ungulate_put_test')
end