text:
#ifndef __FSL_FLEXSPI_H_
#define __FSL_FLEXSPI_H_

#include <stddef.h>
#include "fsl_device_registers.h"
#include "fsl_common.h"

/*!
 * @addtogroup flexspi
 * @{
 */

/*******************************************************************************
 * Definitions
 ******************************************************************************/

/*! @name Driver version */
/*@{*/
/*! @brief FLEXSPI driver version 2.0.3. */
#define FSL_FLEXSPI_DRIVER_VERSION (MAKE_VERSION(2, 0, 3))
/*@}*/

#define FSL_FEATURE_FLEXSPI_AHB_BUFFER_COUNT FSL_FEATURE_FLEXSPI_AHB_BUFFER_COUNTn(0)

/*! @breif Formula to form FLEXSPI instructions in LUT table. */
#define FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1)                                                              \
    (FLEXSPI_LUT_OPERAND0(op0) | FLEXSPI_LUT_NUM_PADS0(pad0) | FLEXSPI_LUT_OPCODE0(cmd0) | FLEXSPI_LUT_OPERAND1(op1) | \
     FLEXSPI_LUT_NUM_PADS1(pad1) | FLEXSPI_LUT_OPCODE1(cmd1))

/*! @brief Status structure of FLEXSPI.*/
enum _flexspi_status
{
    kStatus_FLEXSPI_Busy = MAKE_STATUS(kStatusGroup_FLEXSPI, 0),                     /*!< FLEXSPI is busy */
    kStatus_FLEXSPI_SequenceExecutionTimeout = MAKE_STATUS(kStatusGroup_FLEXSPI, 1), /*!< Sequence execution timeout
                                                                            error occurred during FLEXSPI transfer. */
    kStatus_FLEXSPI_IpCommandSequenceError = MAKE_STATUS(kStatusGroup_FLEXSPI, 2),   /*!< IP command Sequence execution
                                                                     timeout error occurred during FLEXSPI transfer. */
    kStatus_FLEXSPI_IpCommandGrantTimeout = MAKE_STATUS(kStatusGroup_FLEXSPI, 3),    /*!< IP command grant timeout error
                                                                                occurred during FLEXSPI transfer. */
};

/*! @brief CMD definition of FLEXSPI, use to form LUT instruction. */
enum _flexspi_command
{
    kFLEXSPI_Command_STOP = 0x00U,           /*!< Stop execution, deassert CS. */
    kFLEXSPI_Command_SDR = 0x01U,            /*!< Transmit Command code to Flash, using SDR mode. */
    kFLEXSPI_Command_RADDR_SDR = 0x02U,      /*!< Transmit Row Address to Flash, using SDR mode. */
    kFLEXSPI_Command_CADDR_SDR = 0x03U,      /*!< Transmit Column Address to Flash, using SDR mode. */
    kFLEXSPI_Command_MODE1_SDR = 0x04U,      /*!< Transmit 1-bit Mode bits to Flash, using SDR mode. */
    kFLEXSPI_Command_MODE2_SDR = 0x05U,      /*!< Transmit 2-bit Mode bits to Flash, using SDR mode. */
    kFLEXSPI_Command_MODE4_SDR = 0x06U,      /*!< Transmit 4-bit Mode bits to Flash, using SDR mode. */
    kFLEXSPI_Command_MODE8_SDR = 0x07U,      /*!< Transmit 8-bit Mode bits to Flash, using SDR mode. */
    kFLEXSPI_Command_WRITE_SDR = 0x08U,      /*!< Transmit Programming Data to Flash, using SDR mode. */
    kFLEXSPI_Command_READ_SDR = 0x09U,       /*!< Receive Read Data from Flash, using SDR mode. */
    kFLEXSPI_Command_LEARN_SDR = 0x0AU,      /*!< Receive Read Data or Preamble bit from Flash, SDR mode. */
    kFLEXSPI_Command_DATSZ_SDR = 0x0BU,      /*!< Transmit Read/Program Data size (byte) to Flash, SDR mode. */
    kFLEXSPI_Command_DUMMY_SDR = 0x0CU,      /*!< Leave data lines undriven by FlexSPI controller.*/
    kFLEXSPI_Command_DUMMY_RWDS_SDR = 0x0DU, /*!< Leave data lines undriven by FlexSPI controller,
                                                  dummy cycles decided by RWDS. */
    kFLEXSPI_Command_DDR = 0x21U,            /*!< Transmit Command code to Flash, using DDR mode. */
    kFLEXSPI_Command_RADDR_DDR = 0x22U,      /*!< Transmit Row Address to Flash, using DDR mode. */
    kFLEXSPI_Command_CADDR_DDR = 0x23U,      /*!< Transmit Column Address to Flash, using DDR mode. */
    kFLEXSPI_Command_MODE1_DDR = 0x24U,      /*!< Transmit 1-bit Mode bits to Flash, using DDR mode. */
    kFLEXSPI_Command_MODE2_DDR = 0x25U,      /*!< Transmit 2-bit Mode bits to Flash, using DDR mode. */
    kFLEXSPI_Command_MODE4_DDR = 0x26U,      /*!< Transmit 4-bit Mode bits to Flash, using DDR mode. */
    kFLEXSPI_Command_MODE8_DDR = 0x27U,      /*!< Transmit 8-bit Mode bits to Flash, using DDR mode. */
    kFLEXSPI_Command_WRITE_DDR = 0x28U,      /*!< Transmit Programming Data to Flash, using DDR mode. */
    kFLEXSPI_Command_READ_DDR = 0x29U,       /*!< Receive Read Data from Flash, using DDR mode. */
    kFLEXSPI_Command_LEARN_DDR = 0x2AU,      /*!< Receive Read Data or Preamble bit from Flash, DDR mode. */
    kFLEXSPI_Command_DATSZ_DDR = 0x2BU,      /*!< Transmit Read/Program Data size (byte) to Flash, DDR mode. */
    kFLEXSPI_Command_DUMMY_DDR = 0x2CU,      /*!< Leave data lines undriven by FlexSPI controller.*/
    kFLEXSPI_Command_DUMMY_RWDS_DDR = 0x2DU, /*!< Leave data lines undriven by FlexSPI controller,
                                               dummy cycles decided by RWDS. */
    kFLEXSPI_Command_JUMP_ON_CS = 0x1FU,     /*!< Stop execution, deassert CS and save operand[7:0] as the
                                               instruction start pointer for next sequence */
};

/*! @brief pad definition of FLEXSPI, use to form LUT instruction. */
enum _flexspi_pad
{
    kFLEXSPI_1PAD = 0x00U, /*!< Transmit command/address and transmit/receive data only through DATA0/DATA1. */
    kFLEXSPI_2PAD = 0x01U, /*!< Transmit command/address and transmit/receive data only through DATA[1:0]. */
    kFLEXSPI_4PAD = 0x02U, /*!< Transmit command/address and transmit/receive data only through DATA[3:0]. */
    kFLEXSPI_8PAD = 0x03U, /*!< Transmit command/address and transmit/receive data only through DATA[7:0]. */
};

/*! @brief FLEXSPI interrupt status flags.*/
typedef enum _flexspi_flags
{
    kFLEXSPI_SequenceExecutionTimeoutFlag = FLEXSPI_INTEN_SEQTIMEOUTEN_MASK, /*!< Sequence execution timeout. */
    kFLEXSPI_AhbBusTimeoutFlag = FLEXSPI_INTEN_AHBBUSTIMEOUTEN_MASK,         /*!< AHB Bus timeout. */
    kFLEXSPI_SckStoppedBecauseTxEmptyFlag =
        FLEXSPI_INTEN_SCKSTOPBYWREN_MASK, /*!< SCK is stopped during command
                                               sequence because Async TX FIFO empty. */
    kFLEXSPI_SckStoppedBecauseRxFullFlag =
        FLEXSPI_INTEN_SCKSTOPBYRDEN_MASK, /*!< SCK is stopped during command
                                               sequence because Async RX FIFO full. */
#if !((defined(FSL_FEATURE_FLEXSPI_HAS_NO_DATA_LEARN)) && (FSL_FEATURE_FLEXSPI_HAS_NO_DATA_LEARN))
    kFLEXSPI_DataLearningFailedFlag = FLEXSPI_INTEN_DATALEARNFAILEN_MASK, /*!< Data learning failed. */
#endif
    kFLEXSPI_IpTxFifoWatermarkEmpltyFlag = FLEXSPI_INTEN_IPTXWEEN_MASK,    /*!< IP TX FIFO WaterMark empty. */
    kFLEXSPI_IpRxFifoWatermarkAvailableFlag = FLEXSPI_INTEN_IPRXWAEN_MASK, /*!< IP RX FIFO WaterMark available. */
    kFLEXSPI_AhbCommandSequenceErrorFlag =
        FLEXSPI_INTEN_AHBCMDERREN_MASK,                                  /*!< AHB triggered Command Sequences Error. */
    kFLEXSPI_IpCommandSequenceErrorFlag = FLEXSPI_INTEN_IPCMDERREN_MASK, /*!< IP triggered Command Sequences Error. */
    kFLEXSPI_AhbCommandGrantTimeoutFlag =
        FLEXSPI_INTEN_AHBCMDGEEN_MASK, /*!< AHB triggered Command Sequences Grant Timeout. */
    kFLEXSPI_IpCommandGrantTimeoutFlag =
        FLEXSPI_INTEN_IPCMDGEEN_MASK, /*!< IP triggered Command Sequences Grant Timeout. */
    kFLEXSPI_IpCommandExcutionDoneFlag =
        FLEXSPI_INTEN_IPCMDDONEEN_MASK,  /*!< IP triggered Command Sequences Execution finished. */
    kFLEXSPI_AllInterruptFlags = 0xFFFU, /*!< All flags. */
} flexspi_flags_t;

/*! @brief FLEXSPI sample clock source selection for Flash Reading.*/
typedef enum _flexspi_read_sample_clock
{
    kFLEXSPI_ReadSampleClkLoopbackInternally = 0x0U,      /*!< Dummy Read strobe generated by FlexSPI Controller
                                                               and loopback internally. */
    kFLEXSPI_ReadSampleClkLoopbackFromDqsPad = 0x1U,      /*!< Dummy Read strobe generated by FlexSPI Controller
                                                               and loopback from DQS pad. */
    kFLEXSPI_ReadSampleClkLoopbackFromSckPad = 0x2U,      /*!< SCK output clock and loopback from SCK pad. */
    kFLEXSPI_ReadSampleClkExternalInputFromDqsPad = 0x3U, /*!< Flash provided Read strobe and input from DQS pad. */
} flexspi_read_sample_clock_t;

/*! @brief FLEXSPI interval unit for flash device select.*/
typedef enum _flexspi_cs_interval_cycle_unit
{
    kFLEXSPI_CsIntervalUnit1SckCycle = 0x0U,   /*!< Chip selection interval: CSINTERVAL * 1 serial clock cycle. */
    kFLEXSPI_CsIntervalUnit256SckCycle = 0x1U, /*!< Chip selection interval: CSINTERVAL * 256 serial clock cycle. */
} flexspi_cs_interval_cycle_unit_t;

/*! @brief FLEXSPI AHB wait interval unit for writting.*/
typedef enum _flexspi_ahb_write_wait_unit
{
    kFLEXSPI_AhbWriteWaitUnit2AhbCycle = 0x0U,     /*!< AWRWAIT unit is 2 ahb clock cycle. */
    kFLEXSPI_AhbWriteWaitUnit8AhbCycle = 0x1U,     /*!< AWRWAIT unit is 8 ahb clock cycle. */
    kFLEXSPI_AhbWriteWaitUnit32AhbCycle = 0x2U,    /*!< AWRWAIT unit is 32 ahb clock cycle. */
    kFLEXSPI_AhbWriteWaitUnit128AhbCycle = 0x3U,   /*!< AWRWAIT unit is 128 ahb clock cycle. */
    kFLEXSPI_AhbWriteWaitUnit512AhbCycle = 0x4U,   /*!< AWRWAIT unit is 512 ahb clock cycle. */
    kFLEXSPI_AhbWriteWaitUnit2048AhbCycle = 0x5U,  /*!< AWRWAIT unit is 2048 ahb clock cycle. */
    kFLEXSPI_AhbWriteWaitUnit8192AhbCycle = 0x6U,  /*!< AWRWAIT unit is 8192 ahb clock cycle. */
    kFLEXSPI_AhbWriteWaitUnit32768AhbCycle = 0x7U, /*!< AWRWAIT unit is 32768 ahb clock cycle. */
} flexspi_ahb_write_wait_unit_t;

/*! @brief Error Code when IP command Error detected.*/
typedef enum _flexspi_ip_error_code
{
    kFLEXSPI_IpCmdErrorNoError = 0x0U,                  /*!< No error. */
    kFLEXSPI_IpCmdErrorJumpOnCsInIpCmd = 0x2U,          /*!< IP command with JMP_ON_CS instruction used. */
    kFLEXSPI_IpCmdErrorUnknownOpCode = 0x3U,            /*!< Unknown instruction opcode in the sequence. */
    kFLEXSPI_IpCmdErrorSdrDummyInDdrSequence = 0x4U,    /*!< Instruction DUMMY_SDR/DUMMY_RWDS_SDR
                                                             used in DDR sequence. */
    kFLEXSPI_IpCmdErrorDdrDummyInSdrSequence = 0x5U,    /*!< Instruction DUMMY_DDR/DUMMY_RWDS_DDR
                                                             used in SDR sequence. */
    kFLEXSPI_IpCmdErrorInvalidAddress = 0x6U,           /*!< Flash access start address exceed the whole
                                                            flash address range (A1/A2/B1/B2). */
    kFLEXSPI_IpCmdErrorSequenceExecutionTimeout = 0xEU, /*!< Sequence execution timeout. */
    kFLEXSPI_IpCmdErrorFlashBoundaryAcrosss = 0xFU,     /*!< Flash boundary crossed. */
} flexspi_ip_error_code_t;

/*! @brief Error Code when AHB command Error detected.*/
typedef enum _flexspi_ahb_error_code
{
    kFLEXSPI_AhbCmdErrorNoError = 0x0U,               /*!< No error. */
    kFLEXSPI_AhbCmdErrorJumpOnCsInWriteCmd = 0x2U,    /*!< AHB Write command with JMP_ON_CS instruction
                                                           used in the sequence. */
    kFLEXSPI_AhbCmdErrorUnknownOpCode = 0x3U,         /*!< Unknown instruction opcode in the sequence. */
    kFLEXSPI_AhbCmdErrorSdrDummyInDdrSequence = 0x4U, /*!< Instruction DUMMY_SDR/DUMMY_RWDS_SDR used
                                                           in DDR sequence. */
    kFLEXSPI_AhbCmdErrorDdrDummyInSdrSequence = 0x5U, /*!< Instruction DUMMY_DDR/DUMMY_RWDS_DDR
                                                           used in SDR sequence. */
    kFLEXSPI_AhbCmdSequenceExecutionTimeout = 0x6U,   /*!< Sequence execution timeout. */
} flexspi_ahb_error_code_t;

/*! @brief FLEXSPI operation port select.*/
typedef enum _flexspi_port
{
    kFLEXSPI_PortA1 = 0x0U, /*!< Access flash on A1 port. */
    kFLEXSPI_PortA2 = 0x1U, /*!< Access flash on A2 port. */
    kFLEXSPI_PortB1 = 0x2U, /*!< Access flash on B1 port. */
    kFLEXSPI_PortB2 = 0x3U, /*!< Access flash on B2 port. */
} flexspi_port_t;

/*! @brief Trigger source of current command sequence granted by arbitrator.*/
typedef enum _flexspi_arb_command_source
{
    kFLEXSPI_AhbReadCommand = 0x0U,
    kFLEXSPI_AhbWriteCommand = 0x1U,
    kFLEXSPI_IpCommand = 0x2U,
    kFLEXSPI_SuspendedCommand = 0x3U,
} flexspi_arb_command_source_t;

typedef enum _flexspi_command_type
{
    kFLEXSPI_Command, /*!< FlexSPI operation: Only command, both TX and Rx buffer are ignored. */
    kFLEXSPI_Config,  /*!< FlexSPI operation: Configure device mode, the TX fifo size is fixed in LUT. */
    kFLEXSPI_Read,    /* /!< FlexSPI operation: Read, only Rx Buffer is effective. */
    kFLEXSPI_Write,   /* /!< FlexSPI operation: Read, only Tx Buffer is effective. */
} flexspi_command_type_t;

typedef struct _flexspi_ahbBuffer_config
{
    uint8_t priority;    /*!< This priority for AHB Master Read which this AHB RX Buffer is assigned. */
    uint8_t masterIndex; /*!< AHB Master ID the AHB RX Buffer is assigned. */
    uint16_t bufferSize; /*!< AHB buffer size in byte. */
    bool enablePrefetch; /*!< AHB Read Prefetch Enable for current AHB RX Buffer corresponding Master, allows
                          prefetch disable/enable seperately for each master. */
} flexspi_ahbBuffer_config_t;

/*! @brief FLEXSPI configuration structure. */
typedef struct _flexspi_config
{
    flexspi_read_sample_clock_t rxSampleClock; /*!< Sample Clock source selection for Flash Reading. */
    bool enableSckFreeRunning;                 /*!< Enable/disable SCK output free-running. */
    bool enableCombination;                    /*!< Enable/disable combining PORT A and B Data Pins
                                               (SIOA[3:0] and SIOB[3:0]) to support Flash Octal mode. */
    bool enableDoze;                           /*!< Enable/disable doze mode support. */
    bool enableHalfSpeedAccess;                /*!< Enable/disable divide by 2 of the clock for half
                                                speed commands. */
    bool enableSckBDiffOpt;                    /*!< Enable/disable SCKB pad use as SCKA differential clock
                                                output, when enable, Port B flash access is not available. */
    bool enableSameConfigForAll;               /*!< Enable/disable same configuration for all connected devices
                                                when enabled, same configuration in FLASHA1CRx is applied to all. */
    uint16_t seqTimeoutCycle;                  /*!< Timeout wait cycle for command sequence execution,
                                               timeout after ahbGrantTimeoutCyle*1024 serial root clock cycles. */
    uint8_t ipGrantTimeoutCycle;               /*!< Timeout wait cycle for IP command grant, timeout after
                                                ipGrantTimeoutCycle*1024 AHB clock cycles. */
    uint8_t txWatermark;                       /*!< FLEXSPI IP transmit watermark value. */
    uint8_t rxWatermark;                       /*!< FLEXSPI receive watermark value. */
    struct
    {
        bool enableAHBWriteIpTxFifo;  /*!< Enable AHB bus write access to IP TX FIFO. */
        bool enableAHBWriteIpRxFifo;  /*!< Enable AHB bus write access to IP RX FIFO. */
        uint8_t ahbGrantTimeoutCycle; /*!< Timeout wait cycle for AHB command grant,
                                       timeout after ahbGrantTimeoutCyle*1024 AHB clock cycles. */
        uint16_t ahbBusTimeoutCycle;  /*!< Timeout wait cycle for AHB read/write access,
                                      timeout after ahbBusTimeoutCycle*1024 AHB clock cycles. */
        uint8_t resumeWaitCycle;      /*!< Wait cycle for idle state before suspended command sequence
                                       resume, timeout after ahbBusTimeoutCycle AHB clock cycles. */
        flexspi_ahbBuffer_config_t buffer[FSL_FEATURE_FLEXSPI_AHB_BUFFER_COUNT]; /*!< AHB buffer size. */
        bool enableClearAHBBufferOpt; /*!< Enable/disable automatically clean AHB RX Buffer and TX Buffer
                                       when FLEXSPI returns STOP mode ACK. */
        bool enableReadAddressOpt;    /*!< Enable/disable remove AHB read burst start address alignment limitation.
                                       when eanble, there is no AHB read burst start address alignment limitation. */
        bool enableAHBPrefetch;       /*!< Enable/disable AHB read prefetch feature, when enabled, FLEXSPI
                                       will fetch more data than current AHB burst. */
        bool enableAHBBufferable;     /*!< Enable/disable AHB bufferable write access support, when enabled,
                                       FLEXSPI return before waiting for command excution finished. */
        bool enableAHBCachable;       /*!< Enable AHB bus cachable read access support. */
    } ahbConfig;
} flexspi_config_t;

/*! @brief External device configuration items. */
typedef struct _flexspi_device_config
{
    uint32_t flexspiRootClk;                         /*!< FLEXSPI serial root clock. */
    bool isSck2Enabled;                              /*!< FLEXSPI use SCK2. */
    uint32_t flashSize;                              /*!< Flash size in KByte. */
    flexspi_cs_interval_cycle_unit_t CSIntervalUnit; /*!< CS interval unit, 1 or 256 cycle. */
    uint16_t CSInterval;                             /*!< CS line assert interval, mutiply CS interval unit to
                                                      get the CS line assert interval cycles. */
    uint8_t CSHoldTime;                              /*!< CS line hold time. */
    uint8_t CSSetupTime;                             /*!< CS line setup time. */
    uint8_t dataValidTime;                           /*!< Data valid time for external device. */
    uint8_t columnspace;                             /*!< Column space size. */
    bool enableWordAddress;                          /*!< If enable word address.*/
    uint8_t AWRSeqIndex;                             /*!< Sequence ID for AHB write command. */
    uint8_t AWRSeqNumber;                            /*!< Sequence number for AHB write command. */
    uint8_t ARDSeqIndex;                             /*!< Sequence ID for AHB read command. */
    uint8_t ARDSeqNumber;                            /*!< Sequence number for AHB read command. */
    flexspi_ahb_write_wait_unit_t AHBWriteWaitUnit;  /*!< AHB write wait unit. */
    uint16_t AHBWriteWaitInterval;                   /*!< AHB write wait interval, mutiply AHB write interval
                                                      unit to get the AHB write wait cycles. */
    bool enableWriteMask;                            /*!< Enable/Disable FLEXSPI drive DQS pin as write mask
                                                      when writing to external device. */
} flexspi_device_config_t;

/*! @brief Transfer structure for FLEXSPI. */
typedef struct _flexspi_transfer
{
    uint32_t deviceAddress;         /*!< Operation device address. */
    flexspi_port_t port;            /*!< Operation port. */
    flexspi_command_type_t cmdType; /*!< Execution command type. */
    uint8_t seqIndex;               /*!< Sequence ID for command. */
    uint8_t SeqNumber;              /*!< Sequence number for command. */
    uint32_t *data;                 /*!< Data buffer. */
    size_t dataSize;                /*!< Data size in bytes. */
} flexspi_transfer_t;

/* Forward declaration of the handle typedef. */
typedef struct _flexspi_handle flexspi_handle_t;

/*! @brief FLEXSPI transfer callback function. */
typedef void (*flexspi_transfer_callback_t)(FLEXSPI_Type *base,
                                            flexspi_handle_t *handle,
                                            status_t status,
                                            void *userData);

/*! @brief Transfer handle structure for FLEXSPI. */
struct _flexspi_handle
{
    uint32_t state;                                 /*!< Internal state for FLEXSPI transfer */
    uint32_t *data;                                 /*!< Data buffer. */
    size_t dataSize;                                /*!< Remaining Data size in bytes. */
    size_t transferTotalSize;                       /*!< Total Data size in bytes. */
    flexspi_transfer_callback_t completionCallback; /*!< Callback for users while transfer finish or error occurred */
    void *userData;                                 /*!< FLEXSPI callback function parameter.*/
};

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

#if defined(__cplusplus)
extern "C" {
#endif /*_cplusplus. */

/*!
 * @name Initialization and deinitialization
 * @{
 */
/*!
 * @brief Initializes the FLEXSPI module and internal state.
 *
 * This function enables the clock for FLEXSPI and also configures the FLEXSPI with the
 * input configure parameters. Users should call this function before any FLEXSPI operations.
 *
 * @param base FLEXSPI peripheral base address.
 * @param config FLEXSPI configure structure.
 */
void FLEXSPI_Init(FLEXSPI_Type *base, const flexspi_config_t *config);

/*!
 * @brief Gets default settings for FLEXSPI.
 *
 * @param config FLEXSPI configuration structure.
 */
void FLEXSPI_GetDefaultConfig(flexspi_config_t *config);

/*!
 * @brief Deinitializes the FLEXSPI module.
 *
 * Clears the FLEXSPI state and  FLEXSPI module registers.
 * @param base FLEXSPI peripheral base address.
 */
void FLEXSPI_Deinit(FLEXSPI_Type *base);

/*!
 * @brief Configures the connected device parameter.
 *
 * This function configures the connected device relevant parameters, such as the size, command, and so on.
 * The flash configuration value cannot have a default value. The user needs to configure it according to the
 * connected device.
 *
 * @param base FLEXSPI peripheral base address.
 * @param config Flash configuration parameters.
 * @param port FLEXSPI Operation port.
 */
void FLEXSPI_SetFlashConfig(FLEXSPI_Type *base, flexspi_device_config_t *config, flexspi_port_t port);

/*!
 * @brief Software reset for the FLEXSPI logic.
 *
 * This function sets the software reset flags for both AHB and buffer domain and
 * resets both AHB buffer and also IP FIFOs.
 *
 * @param base FLEXSPI peripheral base address.
 */
static inline void FLEXSPI_SoftwareReset(FLEXSPI_Type *base)
{
    base->MCR0 |= FLEXSPI_MCR0_SWRESET_MASK;
    while (base->MCR0 & FLEXSPI_MCR0_SWRESET_MASK)
    {
    }
}

/*!
 * @brief Enables or disables the FLEXSPI module.
 *
 * @param base FLEXSPI peripheral base address.
 * @param enable True means enable FLEXSPI, false means disable.
 */
static inline void FLEXSPI_Enable(FLEXSPI_Type *base, bool enable)
{
    if (enable)
    {
        base->MCR0 &= ~FLEXSPI_MCR0_MDIS_MASK;
    }
    else
    {
        base->MCR0 |= FLEXSPI_MCR0_MDIS_MASK;
    }
}

/* @} */

/*!
 * @name Interrupts
 * @{
 */
/*!
 * @brief Enables the FLEXSPI interrupts.
 *
 * @param base FLEXSPI peripheral base address.
 * @param mask FLEXSPI interrupt source.
 */
static inline void FLEXSPI_EnableInterrupts(FLEXSPI_Type *base, uint32_t mask)
{
    base->INTEN |= mask;
}

/*!
 * @brief Disable the FLEXSPI interrupts.
 *
 * @param base FLEXSPI peripheral base address.
 * @param mask FLEXSPI interrupt source.
 */
static inline void FLEXSPI_DisableInterrupts(FLEXSPI_Type *base, uint32_t mask)
{
    base->INTEN &= ~mask;
}

/* @} */

/*! @name DMA control */
/*@{*/

/*!
 * @brief Enables or disables FLEXSPI IP Tx FIFO DMA requests.
 *
 * @param base FLEXSPI peripheral base address.
 * @param enable Enable flag for transmit DMA request. Pass true for enable, false for disable.
 */
static inline void FLEXSPI_EnableTxDMA(FLEXSPI_Type *base, bool enable)
{
    if (enable)
    {
        base->IPTXFCR |= FLEXSPI_IPTXFCR_TXDMAEN_MASK;
    }
    else
    {
        base->IPTXFCR &= ~FLEXSPI_IPTXFCR_TXDMAEN_MASK;
    }
}

/*!
 * @brief Enables or disables FLEXSPI IP Rx FIFO DMA requests.
 *
 * @param base FLEXSPI peripheral base address.
 * @param enable Enable flag for receive DMA request. Pass true for enable, false for disable.
 */
static inline void FLEXSPI_EnableRxDMA(FLEXSPI_Type *base, bool enable)
{
    if (enable)
    {
        base->IPRXFCR |= FLEXSPI_IPRXFCR_RXDMAEN_MASK;
    }
    else
    {
        base->IPRXFCR &= ~FLEXSPI_IPRXFCR_RXDMAEN_MASK;
    }
}

/*!
 * @brief Gets FLEXSPI IP tx fifo address for DMA transfer.
 *
 * @param base FLEXSPI peripheral base address.
 * @retval The tx fifo address.
 */
static inline uint32_t FLEXSPI_GetTxFifoAddress(FLEXSPI_Type *base)
{
    return (uint32_t)&base->TFDR[0];
}

/*!
 * @brief Gets FLEXSPI IP rx fifo address for DMA transfer.
 *
 * @param base FLEXSPI peripheral base address.
 * @retval The rx fifo address.
 */
static inline uint32_t FLEXSPI_GetRxFifoAddress(FLEXSPI_Type *base)
{
    return (uint32_t)&base->RFDR[0];
}

/*@}*/

/*! @name FIFO control */
/*@{*/

/*! @brief Clears the FLEXSPI IP FIFO logic.
 *
 * @param base FLEXSPI peripheral base address.
 * @param txFifo Pass true to reset TX FIFO.
 * @param rxFifo Pass true to reset RX FIFO.
 */
static inline void FLEXSPI_ResetFifos(FLEXSPI_Type *base, bool txFifo, bool rxFifo)
{
    if (txFifo)
    {
        base->IPTXFCR |= FLEXSPI_IPTXFCR_CLRIPTXF_MASK;
    }
    if (rxFifo)
    {
        base->IPRXFCR |= FLEXSPI_IPRXFCR_CLRIPRXF_MASK;
    }
}

/*!
 * @brief Gets the valid data entries in the FLEXSPI FIFOs.
 *
 * @param base FLEXSPI peripheral base address.
 * @param[out] txCount Pointer through which the current number of bytes in the transmit FIFO is returned.
 *      Pass NULL if this value is not required.
 * @param[out] rxCount Pointer through which the current number of bytes in the receive FIFO is returned.
 *      Pass NULL if this value is not required.
 */
static inline void FLEXSPI_GetFifoCounts(FLEXSPI_Type *base, size_t *txCount, size_t *rxCount)
{
    if (txCount)
    {
        *txCount = (((base->IPTXFSTS) & FLEXSPI_IPTXFSTS_FILL_MASK) >> FLEXSPI_IPTXFSTS_FILL_SHIFT) * 8U;
    }
    if (rxCount)
    {
        *rxCount = (((base->IPRXFSTS) & FLEXSPI_IPRXFSTS_FILL_MASK) >> FLEXSPI_IPRXFSTS_FILL_SHIFT) * 8U;
    }
}

/*@}*/

/*!
 * @name Status
 * @{
 */
/*!
 * @brief Get the FLEXSPI interrupt status flags.
 *
 * @param base FLEXSPI peripheral base address.
 * @retval interrupt status flag, use status flag to AND #flexspi_flags_t could get the related status.
 */
static inline uint32_t FLEXSPI_GetInterruptStatusFlags(FLEXSPI_Type *base)
{
    return base->INTR;
}

/*!
 * @brief Get the FLEXSPI interrupt status flags.
 *
 * @param base FLEXSPI peripheral base address.
 * @param interrupt status flag.
 */
static inline void FLEXSPI_ClearInterruptStatusFlags(FLEXSPI_Type *base, uint32_t mask)
{
    base->INTR |= mask;
}

#if !((defined(FSL_FEATURE_FLEXSPI_HAS_NO_DATA_LEARN)) && (FSL_FEATURE_FLEXSPI_HAS_NO_DATA_LEARN))
/*! @brief Gets the sampling clock phase selection after Data Learning.
 *
 * @param base FLEXSPI peripheral base address.
 * @param portAPhase Pointer to a uint8_t type variable to receive the selected clock phase on PORTA.
 * @param portBPhase Pointer to a uint8_t type variable to receive the selected clock phase on PORTB.
 */
static inline void FLEXSPI_GetDataLearningPhase(FLEXSPI_Type *base, uint8_t *portAPhase, uint8_t *portBPhase)
{
    if (portAPhase)
    {
        *portAPhase = (base->STS0 & FLEXSPI_STS0_DATALEARNPHASEA_MASK) >> FLEXSPI_STS0_DATALEARNPHASEA_SHIFT;
    }

    if (portBPhase)
    {
        *portBPhase = (base->STS0 & FLEXSPI_STS0_DATALEARNPHASEB_MASK) >> FLEXSPI_STS0_DATALEARNPHASEB_SHIFT;
    }
}
#endif

/*! @brief Gets the trigger source of current command sequence granted by arbitrator.
 *
 * @param base FLEXSPI peripheral base address.
 * @retval trigger source of current command sequence.
 */
static inline flexspi_arb_command_source_t FLEXSPI_GetArbitratorCommandSource(FLEXSPI_Type *base)
{
    return (flexspi_arb_command_source_t)((base->STS0 & FLEXSPI_STS0_ARBCMDSRC_MASK) >> FLEXSPI_STS0_ARBCMDSRC_SHIFT);
}

/*! @brief Gets the error code when IP command error detected.
 *
 * @param base FLEXSPI peripheral base address.
 * @param index Pointer to a uint8_t type variable to receive the sequence index when error detected.
 * @retval error code when IP command error detected.
 */
static inline flexspi_ip_error_code_t FLEXSPI_GetIPCommandErrorCode(FLEXSPI_Type *base, uint8_t *index)
{
    *index = (base->STS1 & FLEXSPI_STS1_IPCMDERRID_MASK) >> FLEXSPI_STS1_IPCMDERRID_SHIFT;
    return (flexspi_ip_error_code_t)((base->STS1 & FLEXSPI_STS1_IPCMDERRCODE_MASK) >> FLEXSPI_STS1_IPCMDERRCODE_SHIFT);
}

/*! @brief Gets the error code when AHB command error detected.
 *
 * @param base FLEXSPI peripheral base address.
 * @param index Pointer to a uint8_t type variable to receive the sequence index when error detected.
 * @retval error code when AHB command error detected.
 */
static inline flexspi_ahb_error_code_t FLEXSPI_GetAHBCommandErrorCode(FLEXSPI_Type *base, uint8_t *index)
{
    *index = (base->STS1 & FLEXSPI_STS1_AHBCMDERRID_MASK) >> FLEXSPI_STS1_AHBCMDERRID_SHIFT;
    return (flexspi_ahb_error_code_t)((base->STS1 & FLEXSPI_STS1_AHBCMDERRCODE_MASK) >>
                                      FLEXSPI_STS1_AHBCMDERRCODE_SHIFT);
}

/*! @brief Returns whether the bus is idle.
 *
 * @param base FLEXSPI peripheral base address.
 * @retval true Bus is idle.
 * @retval false Bus is busy.
 */
static inline bool FLEXSPI_GetBusIdleStatus(FLEXSPI_Type *base)
{
    return (base->STS0 & FLEXSPI_STS0_ARBIDLE_MASK) && (base->STS0 & FLEXSPI_STS0_SEQIDLE_MASK);
}
/*@}*/

/*!
 * @name Bus Operations
 * @{
 */

/*! @brief Enables/disables the FLEXSPI IP command parallel mode.
 *
 * @param base FLEXSPI peripheral base address.
 * @param enable True means enable parallel mode, false means disable parallel mode.
 */
static inline void FLEXSPI_EnableIPParallelMode(FLEXSPI_Type *base, bool enable)
{
    if (enable)
    {
        base->IPCR1 |= FLEXSPI_IPCR1_IPAREN_MASK;
    }
    else
    {
        base->IPCR1 &= ~FLEXSPI_IPCR1_IPAREN_MASK;
    }
}

/*! @brief Enables/disables the FLEXSPI AHB command parallel mode.
 *
 * @param base FLEXSPI peripheral base address.
 * @param enable True means enable parallel mode, false means disable parallel mode.
 */
static inline void FLEXSPI_EnableAHBParallelMode(FLEXSPI_Type *base, bool enable)
{
    if (enable)
    {
        base->AHBCR |= FLEXSPI_AHBCR_APAREN_MASK;
    }
    else
    {
        base->AHBCR &= ~FLEXSPI_AHBCR_APAREN_MASK;
    }
}

/*! @brief Updates the LUT table.
*
* @param base FLEXSPI peripheral base address.
* @param index From which index start to update. It could be any index of the LUT table, which
* also allows user to update command content inside a command. Each command consists of up to
* 8 instructions and occupy 4*32-bit memory.
* @param cmd Command sequence array.
* @param count Number of sequences.
*/
void FLEXSPI_UpdateLUT(FLEXSPI_Type *base, uint32_t index, const uint32_t *cmd, uint32_t count);

/*!
 * @brief Writes data into FIFO.
 *
 * @param base FLEXSPI peripheral base address
 * @param data The data bytes to send
 * @param fifoIndex Destination fifo index.
 */
static inline void FLEXSPI_WriteData(FLEXSPI_Type *base, uint32_t data, uint8_t fifoIndex)
{
    base->TFDR[fifoIndex] = data;
}

/*!
 * @brief Receives data from data FIFO.
 *
 * @param base FLEXSPI peripheral base address
 * @param fifoIndex Source fifo index.
 * @return The data in the FIFO.
 */
static inline uint32_t FLEXSPI_ReadData(FLEXSPI_Type *base, uint8_t fifoIndex)
{
    return base->RFDR[fifoIndex];
}

/*!
 * @brief Sends a buffer of data bytes using blocking method.
 * @note This function blocks via polling until all bytes have been sent.
 * @param base FLEXSPI peripheral base address
 * @param buffer The data bytes to send
 * @param size The number of data bytes to send
 * @retval kStatus_Success write success without error
 * @retval kStatus_FLEXSPI_SequenceExecutionTimeout sequence execution timeout
 * @retval kStatus_FLEXSPI_IpCommandSequenceError IP command sequencen error detected
 * @retval kStatus_FLEXSPI_IpCommandGrantTimeout IP command grant timeout detected
 */
status_t FLEXSPI_WriteBlocking(FLEXSPI_Type *base, uint32_t *buffer, size_t size);

/*!
 * @brief Receives a buffer of data bytes using a blocking method.
 * @note This function blocks via polling until all bytes have been sent.
 * @param base FLEXSPI peripheral base address
 * @param buffer The data bytes to send
 * @param size The number of data bytes to receive
 * @retval kStatus_Success read success without error
 * @retval kStatus_FLEXSPI_SequenceExecutionTimeout sequence execution timeout
 * @retval kStatus_FLEXSPI_IpCommandSequenceError IP command sequencen error detected
 * @retval kStatus_FLEXSPI_IpCommandGrantTimeout IP command grant timeout detected
 */
status_t FLEXSPI_ReadBlocking(FLEXSPI_Type *base, uint32_t *buffer, size_t size);

/*!
 * @brief Execute command to transfer a buffer data bytes using a blocking method.
 * @param base FLEXSPI peripheral base address
 * @param xfer pointer to the transfer structure.
 * @retval kStatus_Success command transfer success without error
 * @retval kStatus_FLEXSPI_SequenceExecutionTimeout sequence execution timeout
 * @retval kStatus_FLEXSPI_IpCommandSequenceError IP command sequencen error detected
 * @retval kStatus_FLEXSPI_IpCommandGrantTimeout IP command grant timeout detected
*/
status_t FLEXSPI_TransferBlocking(FLEXSPI_Type *base, flexspi_transfer_t *xfer);
/*! @} */

/*!
 * @name Transactional
 * @{
 */

/*!
 * @brief Initializes the FLEXSPI handle which is used in transactional functions.
 *
 * @param base FLEXSPI peripheral base address.
 * @param handle pointer to flexspi_handle_t structure to store the transfer state.
 * @param callback pointer to user callback function.
 * @param userData user parameter passed to the callback function.
 */
void FLEXSPI_TransferCreateHandle(FLEXSPI_Type *base,
                                  flexspi_handle_t *handle,
                                  flexspi_transfer_callback_t callback,
                                  void *userData);

/*!
 * @brief Performs a interrupt non-blocking transfer on the FLEXSPI bus.
 *
 * @note Calling the API returns immediately after transfer initiates. The user needs
 * to call FLEXSPI_GetTransferCount to poll the transfer status to check whether
 * the transfer is finished. If the return status is not kStatus_FLEXSPI_Busy, the transfer
 * is finished. For FLEXSPI_Read, the dataSize should be multiple of rx watermark levle, or
 * FLEXSPI could not read data properly.
 *
 * @param base FLEXSPI peripheral base address.
 * @param handle pointer to flexspi_handle_t structure which stores the transfer state.
 * @param xfer pointer to flexspi_transfer_t structure.
 * @retval kStatus_Success Successfully start the data transmission.
 * @retval kStatus_FLEXSPI_Busy Previous transmission still not finished.
 */
status_t FLEXSPI_TransferNonBlocking(FLEXSPI_Type *base, flexspi_handle_t *handle, flexspi_transfer_t *xfer);

/*!
 * @brief Gets the master transfer status during a interrupt non-blocking transfer.
 *
 * @param base FLEXSPI peripheral base address.
 * @param handle pointer to flexspi_handle_t structure which stores the transfer state.
 * @param count Number of bytes transferred so far by the non-blocking transaction.
 * @retval kStatus_InvalidArgument count is Invalid.
 * @retval kStatus_Success Successfully return the count.
 */
status_t FLEXSPI_TransferGetCount(FLEXSPI_Type *base, flexspi_handle_t *handle, size_t *count);

/*!
 * @brief Aborts an interrupt non-blocking transfer early.
 *
 * @note This API can be called at any time when an interrupt non-blocking transfer initiates
 * to abort the transfer early.
 *
 * @param base FLEXSPI peripheral base address.
 * @param handle pointer to flexspi_handle_t structure which stores the transfer state
 */
void FLEXSPI_TransferAbort(FLEXSPI_Type *base, flexspi_handle_t *handle);

/*!
 * @brief Master interrupt handler.
 *
 * @param base FLEXSPI peripheral base address.
 * @param handle pointer to flexspi_handle_t structure.
 */
void FLEXSPI_TransferHandleIRQ(FLEXSPI_Type *base, flexspi_handle_t *handle);
/*! @} */

#if defined(__cplusplus)
}
#endif /*_cplusplus. */
/*@}*/

#endif /* __FSL_FLEXSPI_H_ */


text:
#include "fstorage.h"
#include "fstorage_config.h"
#include "fstorage_internal_defs.h"

#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include "nrf_error.h"
#include "nrf_soc.h"

static uint8_t       m_flags;       // fstorage status flags.
static fs_op_queue_t m_queue;       // Queue of requested operations.
static uint8_t       m_retry_count; // Number of times the last flash operation was retried.

// Sends events to the application.
static void send_event(fs_op_t const * const p_op, fs_ret_t result)
{
    fs_evt_t evt;
    memset(&evt, 0x00, sizeof(fs_evt_t));

    switch (p_op->op_code)
    {
        case FS_OP_STORE:
            evt.id                 = FS_EVT_STORE;
            evt.store.p_data       = p_op->store.p_dest;
            evt.store.length_words = p_op->store.length_words;
            break;

        case FS_OP_ERASE:
            evt.id               = FS_EVT_ERASE;
            evt.erase.first_page = p_op->erase.page - p_op->erase.pages_erased;
            evt.erase.last_page  = p_op->erase.page;
            break;

        default:
            // Should not happen.
            break;
    }

    p_op->p_config->callback(&evt, result);
}

// Checks that a configuration is non-NULL and within section variable bounds.
static bool check_config(fs_config_t const * const config)
{
    if ((config != NULL) &&
        (FS_SECTION_VARS_START_ADDR <= (uint32_t)config) &&
        (FS_SECTION_VARS_END_ADDR   >  (uint32_t)config))
    {
        return true;
    }

    return false;
}

// Executes a store operation.
static uint32_t store_execute(fs_op_t const * const p_op)
{
    uint16_t chunk_len;

    if ((p_op->store.length_words - p_op->store.offset) < FS_MAX_WRITE_SIZE_WORDS)
    {
        chunk_len = p_op->store.length_words - p_op->store.offset;
    }
    else
    {
        chunk_len = FS_MAX_WRITE_SIZE_WORDS;
    }

    return sd_flash_write((uint32_t*)p_op->store.p_dest + p_op->store.offset,
                          (uint32_t*)p_op->store.p_src  + p_op->store.offset,
                          chunk_len);
}

// Executes an erase operation.
static uint32_t erase_execute(fs_op_t const * const p_op)
{
    return sd_flash_page_erase(p_op->erase.page);
}

// Advances the queue, wrapping around if necessary.
// If no elements are left in the queue, clears the FS_FLAG_PROCESSING flag.
static void queue_advance(void)
{
    if (--m_queue.count == 0)
    {
        m_flags &= ~FS_FLAG_PROCESSING;
    }

    if (++m_queue.rp == FS_QUEUE_SIZE)
    {
        m_queue.rp = 0;
    }
}

// Processes the current element in the queue. If the queue is empty, does nothing.
static void queue_process(void)
{
    uint32_t         ret;
    fs_op_t  * const p_op = &m_queue.op[m_queue.rp];

    if (m_queue.count > 0)
    {
        switch (p_op->op_code)
        {
            case FS_OP_STORE:
                ret = store_execute(p_op);
                break;

            case FS_OP_ERASE:
                ret = erase_execute(p_op);
                break;

             default:
                ret = FS_ERR_INTERNAL;
                break;
        }

        // There is a pending flash operation which was not initiated by this module.
        // Stop processing the queue and wait for a system event.
        if (ret == NRF_ERROR_BUSY)
        {
            m_flags &= ~FS_FLAG_PROCESSING;
            m_flags |= FS_FLAG_FLASH_REQ_PENDING;
        }
        else if (ret != NRF_SUCCESS)
        {
            // An error has occurred.
            send_event(p_op, FS_ERR_INTERNAL);
        }
        else
        {
            // Operation is executing.
        }
    }
}

// Starts processing the queue if there are no pending flash operations, both inside and
// outside this module. Returns immediately otherwise.
static void queue_start(void)
{
    if (!(m_flags & FS_FLAG_PROCESSING) &&
        !(m_flags & FS_FLAG_FLASH_REQ_PENDING))
    {
        m_flags |= FS_FLAG_PROCESSING;
        queue_process();
    }
}

// Flash operation success callback handler. Keeps track of the progress of an operation.
// If it has finished, advances the queue and notifies the application.
static void on_operation_success(fs_op_t * const p_op)
{
    m_retry_count = 0;

    switch (p_op->op_code)
    {
        case FS_OP_STORE:
        {
            uint16_t chunk_len;

            if ((p_op->store.length_words - p_op->store.offset) < FS_MAX_WRITE_SIZE_WORDS)
            {
                chunk_len = p_op->store.length_words - p_op->store.offset;
            }
            else
            {
                chunk_len = FS_MAX_WRITE_SIZE_WORDS;
            }

            p_op->store.offset += chunk_len;

            if (p_op->store.offset == p_op->store.length_words)
            {
                // The operation has finished.
                send_event(p_op, FS_SUCCESS);
                queue_advance();
            }
        }
        break;

        case FS_OP_ERASE:
        {
            p_op->erase.page++;
            p_op->erase.pages_erased++;

            if (p_op->erase.pages_erased == p_op->erase.pages_to_erase)
            {
                send_event(p_op, FS_SUCCESS);
                queue_advance();
            }
        }
        break;

        default:
            // Should not happen.
            break;
    }
}

// Flash operation failure callback handler. If the maximum number of retries has
// been reached, notifies the application and advances the queue.
static void on_operation_failure(fs_op_t const * const p_op)
{
    if (++m_retry_count > FS_OP_MAX_RETRIES)
    {
        m_retry_count = 0;

        send_event(p_op, FS_ERR_OPERATION_TIMEOUT);
        queue_advance();
    }
}

// Retrieves a pointer to the next free element in the queue.
// Additionally, increases the number of elements stored in the queue.
static bool queue_get_next_free(fs_op_t ** p_op)
{
    uint32_t idx;

    if (m_queue.count == FS_QUEUE_SIZE)
    {
        return false;
    }

    idx = ((m_queue.rp + m_queue.count) < FS_QUEUE_SIZE) ?
           (m_queue.rp + m_queue.count) : 0;

    m_queue.count++;

    // Zero the element so that unassigned fields will be zero.
    memset(&m_queue.op[idx], 0x00, sizeof(fs_op_t));

    *p_op = &m_queue.op[idx];

    return true;
}

fs_ret_t fs_init(void)
{
    uint32_t const   users         = FS_SECTION_VARS_COUNT;
    uint32_t const * p_current_end = FS_PAGE_END_ADDR;
    uint32_t         index_max     = 0x00;
    uint32_t         index_last    = 0xFFFFFFFF;

    if (m_flags & FS_FLAG_INITIALIZED)
    {
        return FS_SUCCESS;
    }

    #if 0
    // Check for configurations with duplicate priority.
    for (uint32_t i = 0; i < users; i++)
    {
        for (uint32_t j = i + 1; j < users; j++)
        {
            fs_config_t const * const p_config_i = FS_SECTION_VARS_GET(i);
            fs_config_t const * const p_config_j = FS_SECTION_VARS_GET(j);

            if (p_config_i->page_order == p_config_j->page_order)
            {
                // Error.
                return FS_ERR_INVALID_CFG;
            }
        }
    }
    #endif

    // Assign pages to registered users, beginning with the ones with the highest
    // priority, which will be assigned pages with the highest memory address.

    for (uint32_t i = 0; i < users; i++)
    {
        uint8_t max_priority  = 0x00;

        for (uint32_t j = 0; j < users; j++)
        {
            fs_config_t * const p_config = FS_SECTION_VARS_GET(j);

            // Skip the one assigned during last iteration.
            if (j == index_last)
            {
                continue;
            }

            if (p_config->priority >= max_priority)
            {
                max_priority = p_config->priority;
                index_max    = j;
            }
        }

        fs_config_t * const p_config = FS_SECTION_VARS_GET(index_max);

        p_config->p_end_addr   = p_current_end;
        p_config->p_start_addr = p_current_end - (p_config->num_pages * FS_PAGE_SIZE_WORDS);

        p_current_end = p_config->p_start_addr;

        index_last = index_max;
    }

    m_flags |= FS_FLAG_INITIALIZED;

    return FS_SUCCESS;
}

fs_ret_t fs_store(fs_config_t const * const p_config,
                  uint32_t    const * const p_dest,
                  uint32_t    const * const p_src,
                  uint16_t    const         length_words)
{
    fs_op_t * p_op;

    if (!(m_flags & FS_FLAG_INITIALIZED))
    {
        return FS_ERR_NOT_INITIALIZED;
    }

    if (!check_config(p_config))
    {
        return FS_ERR_INVALID_CFG;
    }

    if ((p_src == NULL) || (p_dest == NULL))
    {
        return FS_ERR_NULL_ARG;
    }

    // Check that both pointers are word aligned.
    if (((uint32_t)p_src  & 0x03) ||
        ((uint32_t)p_dest & 0x03))
    {
        return FS_ERR_UNALIGNED_ADDR;
    }

    // Check that the operation doesn't go outside the client's memory boundaries.
    if ((p_config->p_start_addr > p_dest) ||
        (p_config->p_end_addr   < (p_dest + length_words)))
    {
        return FS_ERR_INVALID_ADDR;
    }

    if (length_words == 0)
    {
        return FS_ERR_INVALID_ARG;
    }

    if (!queue_get_next_free(&p_op))
    {
        return FS_ERR_QUEUE_FULL;
    }

    // Initialize the operation.
    p_op->p_config           = p_config;
    p_op->op_code            = FS_OP_STORE;
    p_op->store.p_src        = p_src;
    p_op->store.p_dest       = p_dest;
    p_op->store.length_words = length_words;

    queue_start();

    return FS_SUCCESS;
}

fs_ret_t fs_erase(fs_config_t const * const p_config,
                  uint32_t    const * const p_page_addr,
                  uint16_t    const         num_pages)
{
    fs_op_t * p_op;

    if (!(m_flags & FS_FLAG_INITIALIZED))
    {
        return FS_ERR_NOT_INITIALIZED;
    }

    if (!check_config(p_config))
    {
        return FS_ERR_INVALID_CFG;
    }

    if (p_page_addr == NULL)
    {
        return FS_ERR_NULL_ARG;
    }

    // Check that the page is aligned to a page boundary.
    if (((uint32_t)p_page_addr % FS_PAGE_SIZE) != 0)
    {
        return FS_ERR_UNALIGNED_ADDR;
    }

    // Check that the operation doesn't go outside the client's memory boundaries.
    if ((p_page_addr < p_config->p_start_addr) ||
        (p_page_addr + (FS_PAGE_SIZE_WORDS * num_pages) > p_config->p_end_addr))
    {
        return FS_ERR_INVALID_ADDR;
    }

    if (num_pages == 0)
    {
        return FS_ERR_INVALID_ARG;
    }

    if (!queue_get_next_free(&p_op))
    {
        return FS_ERR_QUEUE_FULL;
    }

    // Initialize the operation.
    p_op->p_config             = p_config;
    p_op->op_code              = FS_OP_ERASE;
    p_op->erase.page           = ((uint32_t)p_page_addr / FS_PAGE_SIZE);
    p_op->erase.pages_to_erase = num_pages;

    queue_start();

    return FS_SUCCESS;
}

fs_ret_t fs_queued_op_count_get(uint32_t * const p_op_count)
{
    if (p_op_count == NULL)
    {
        return FS_ERR_NULL_ARG;
    }

    *p_op_count = m_queue.count;

    return FS_SUCCESS;
}

void fs_sys_event_handler(uint32_t sys_evt)
{
    fs_op_t * const p_op = &m_queue.op[m_queue.rp];

    if (m_flags & FS_FLAG_PROCESSING)
    {
        // A flash operation was initiated by this module. Handle the result.
        switch (sys_evt)
        {
            case NRF_EVT_FLASH_OPERATION_SUCCESS:
                on_operation_success(p_op);
                break;

            case NRF_EVT_FLASH_OPERATION_ERROR:
                on_operation_failure(p_op);
                break;
        }
    }
    else if ((m_flags & FS_FLAG_FLASH_REQ_PENDING))
    {
        // A flash operation was initiated outside this module.
        // A callback which indicates that it has finished was received.
        m_flags &= ~FS_FLAG_FLASH_REQ_PENDING;

        // If there are any elements left in the queue, set FS_FLAG_PROCESSING.
        if (m_queue.count > 0)
        {
           m_flags |= FS_FLAG_PROCESSING;
        }
    }

    // Resume processing the queue, if necessary.
    queue_process();
}

redpajama_set_name: RedPajamaGithub


text:
module UserApis
  module Mdi
    module Tools
      # @api private
      class SubscriberClass < Struct.new(:classes)

        def initialize(apis = nil)
          @user_apis = apis
          self.classes = []
        end

        def user_api
          @user_apis
        end

        def subscribe(user_class)
          self.classes << user_class
        end

        def get_subscribers
          self.classes
        end

      end

    end
  end
end


text:
package hso.autonomy.agent.model.agentmeta.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import hso.autonomy.agent.model.agentmeta.IAgentMetaModel;
import hso.autonomy.agent.model.agentmeta.IBodyPartConfiguration;
import hso.autonomy.agent.model.agentmeta.ICompositeJointConfiguration;
import hso.autonomy.agent.model.agentmeta.IHingeJointConfiguration;
import hso.autonomy.agent.model.agentmeta.ISensorConfiguration;
import hso.autonomy.util.geometry.IPose3D;

/**
 * Agent meta model class
 *
 * @author Stefan Glaser
 */
public abstract class AgentMetaModel implements IAgentMetaModel
{
	protected final String modelName;

	protected List<IBodyPartConfiguration> bodyPartConfig;

	protected final String bodyPartContainingCamera;

	protected final IPose3D cameraOffset;

	private final float height;

	protected Collection<ISensorConfiguration> jointConfigs;

	protected String[] jointNames;

	protected String[] effectorNames;

	/**
	 * Constructor.
	 *
	 * @param modelName - the name of this model
	 * @param bodyPartContainingCamera - the name of the body part containing the
	 *        camera
	 */
	public AgentMetaModel(String modelName, String bodyPartContainingCamera, IPose3D cameraOffset, float height)
	{
		this.modelName = modelName;
		this.bodyPartContainingCamera = bodyPartContainingCamera;
		this.cameraOffset = cameraOffset;
		this.height = height;
		bodyPartConfig = createBodyPartConfigs();
	}

	protected abstract List<IBodyPartConfiguration> createBodyPartConfigs();

	@Override
	public String getName()
	{
		return modelName;
	}

	@Override
	public List<IBodyPartConfiguration> getBodyPartConfigurations()
	{
		return bodyPartConfig;
	}

	@Override
	public String getNameOfCameraBodyPart()
	{
		return bodyPartContainingCamera;
	}

	@Override
	public IPose3D getCameraOffset()
	{
		return cameraOffset;
	}

	@Override
	public List<IBodyPartConfiguration> getChildBodyConfigurations(IBodyPartConfiguration bodyPart)
	{
		List<IBodyPartConfiguration> childBodies = new ArrayList<>();

		if (bodyPart != null) {
			String parentName = bodyPart.getName();

			for (int i = 0; i < bodyPartConfig.size(); i++) {
				if (parentName.equals(bodyPartConfig.get(i).getParent())) {
					childBodies.add(bodyPartConfig.get(i));
				}
			}
		}

		return childBodies;
	}

	@Override
	public IBodyPartConfiguration getRootBodyConfiguration()
	{
		for (int i = 0; i < bodyPartConfig.size(); i++) {
			if (bodyPartConfig.get(i).getParent() == null) {
				return bodyPartConfig.get(i);
			}
		}

		return null;
	}

	@Override
	public Collection<ISensorConfiguration> getAvailableJoints()
	{
		if (jointConfigs == null) {
			ArrayList<ISensorConfiguration> jointConfigsList = new ArrayList<>();

			// Extract joints
			ISensorConfiguration jointConfig;
			for (IBodyPartConfiguration config : bodyPartConfig) {
				jointConfig = config.getJointConfiguration();
				if (jointConfig != null) {
					if (jointConfig instanceof ICompositeJointConfiguration) {
						Collections.addAll(
								jointConfigsList, ((ICompositeJointConfiguration) jointConfig).getHjConfigurations());
					} else {
						jointConfigsList.add(jointConfig);
					}
				}
			}
			jointConfigs = Collections.unmodifiableCollection(jointConfigsList);

			jointNames = new String[jointConfigsList.size()];
			effectorNames = new String[jointConfigsList.size()];
			for (int i = 0; i < jointConfigsList.size(); i++) {
				ISensorConfiguration config = jointConfigsList.get(i);
				jointNames[i] = config.getName();
				effectorNames[i] = ((IHingeJointConfiguration) config).getEffectorName();
			}
		}

		return jointConfigs;
	}

	@Override
	public String[] getAvailableJointNames()
	{
		if (jointNames == null) {
			getAvailableJoints();
		}

		return jointNames;
	}

	@Override
	public String[] getAvailableEffectorNames()
	{
		if (effectorNames == null) {
			getAvailableJoints();
		}

		return effectorNames;
	}

	@Override
	public float getHeight()
	{
		return height;
	}
}


text:
#ifndef __R_PLANE__
#define __R_PLANE__

#include "r_data.h"

#ifdef __GNUG__
#pragma interface
#endif

// Visplane related.
extern  short*		lastopening;

typedef void (*planefunction_t) (int top, int bottom);

extern planefunction_t	floorfunc;
extern planefunction_t	ceilingfunc_t;

extern short		floorclip[SCREENWIDTH];
extern short		ceilingclip[SCREENWIDTH];

extern fixed_t		yslope[SCREENHEIGHT];
extern fixed_t		distscale[SCREENWIDTH];

void R_InitPlanes (void);
void R_ClearPlanes (void);

void
R_MapPlane
( int		y,
  int		x1,
  int		x2 );

void
R_MakeSpans
( int		x,
  int		t1,
  int		b1,
  int		t2,
  int		b2 );

void R_DrawPlanes (void);

visplane_t*
R_FindPlane
( fixed_t	height,
  int		picnum,
  int		lightlevel );

visplane_t*
R_CheckPlane
( visplane_t*	pl,
  int		start,
  int		stop );

#endif


text:
prefixes=(5 6 8)
for p in $prefixes; do
	compctl -g "*.${p}" ${p}l
	compctl -g "*.go" ${p}g
done

# standard go tools
compctl -g "*.go" gofmt

# gccgo
compctl -g "*.go" gccgo

# go tool
__go_tool_complete() {
  typeset -a commands build_flags
  commands+=(
    'build[compile packages and dependencies]'
    'clean[remove object files]'
    'doc[run godoc on package sources]'
    'env[print Go environment information]'
    'fix[run go tool fix on packages]'
    'fmt[run gofmt on package sources]'
    'get[download and install packages and dependencies]'
    'help[display help]'
    'install[compile and install packages and dependencies]'
    'list[list packages]'
    'run[compile and run Go program]'
    'test[test packages]'
    'tool[run specified go tool]'
    'version[print Go version]'
    'vet[run go tool vet on packages]'
  )
  if (( CURRENT == 2 )); then
    # explain go commands
    _values 'go tool commands' ${commands[@]}
    return
  fi
  build_flags=(
    '-a[force reinstallation of packages that are already up-to-date]'
    '-n[print the commands but do not run them]'
    '-p[number of parallel builds]:number'
    '-race[enable data race detection]'
    '-x[print the commands]'
    '-work[print temporary directory name and keep it]'
    '-ccflags[flags for 5c/6c/8c]:flags'
    '-gcflags[flags for 5g/6g/8g]:flags'
    '-ldflags[flags for 5l/6l/8l]:flags'
    '-gccgoflags[flags for gccgo]:flags'
    '-compiler[name of compiler to use]:name'
    '-installsuffix[suffix to add to package directory]:suffix'
    '-tags[list of build tags to consider satisfied]:tags'
  )
  __go_list() {
      local expl importpaths
      declare -a importpaths
      importpaths=($(go list ${words[$CURRENT]}... 2>/dev/null))
      _wanted importpaths expl 'import paths' compadd "$@" - "${importpaths[@]}"
  }
  case ${words[2]} in
  clean|doc)
      _arguments -s -w : '*:importpaths:__go_list'
      ;;
  fix|fmt|list|vet)
      _alternative ':importpaths:__go_list' ':files:_path_files -g "*.go"'
      ;;
  install)
      _arguments -s -w : ${build_flags[@]} \
        "-v[show package names]" \
        '*:importpaths:__go_list'
      ;;
  get)
      _arguments -s -w : \
        ${build_flags[@]}
      ;;
  build)
      _arguments -s -w : \
        ${build_flags[@]} \
        "-v[show package names]" \
        "-o[output file]:file:_files" \
        "*:args:{ _alternative ':importpaths:__go_list' ':files:_path_files -g \"*.go\"' }"
      ;;
  test)
      _arguments -s -w : \
        ${build_flags[@]} \
        "-c[do not run, compile the test binary]" \
        "-i[do not run, install dependencies]" \
        "-v[print test output]" \
        "-x[print the commands]" \
        "-short[use short mode]" \
        "-parallel[number of parallel tests]:number" \
        "-cpu[values of GOMAXPROCS to use]:number list" \
        "-run[run tests and examples matching regexp]:regexp" \
        "-bench[run benchmarks matching regexp]:regexp" \
        "-benchmem[print memory allocation stats]" \
        "-benchtime[run each benchmark until taking this long]:duration" \
        "-blockprofile[write goroutine blocking profile to file]:file" \
        "-blockprofilerate[set sampling rate of goroutine blocking profile]:number" \
        "-timeout[kill test after that duration]:duration" \
        "-cpuprofile[write CPU profile to file]:file:_files" \
        "-memprofile[write heap profile to file]:file:_files" \
        "-memprofilerate[set heap profiling rate]:number" \
        "*:args:{ _alternative ':importpaths:__go_list' ':files:_path_files -g \"*.go\"' }"
      ;;
  help)
      _values "${commands[@]}" \
        'gopath[GOPATH environment variable]' \
        'packages[description of package lists]' \
        'remote[remote import path syntax]' \
        'testflag[description of testing flags]' \
        'testfunc[description of testing functions]'
      ;;
  run)
      _arguments -s -w : \
          ${build_flags[@]} \
          '*:file:_path_files -g "*.go"'
      ;;
  tool)
      if (( CURRENT == 3 )); then
          _values "go tool" $(go tool)
          return
      fi
      case ${words[3]} in
      [568]g)
          _arguments -s -w : \
              '-I[search for packages in DIR]:includes:_path_files -/' \
              '-L[show full path in file:line prints]' \
              '-S[print the assembly language]' \
              '-V[print the compiler version]' \
              '-e[no limit on number of errors printed]' \
              '-h[panic on an error]' \
              '-l[disable inlining]' \
              '-m[print optimization decisions]' \
              '-o[file specify output file]:file' \
              '-p[assumed import path for this code]:importpath' \
              '-u[disable package unsafe]' \
              "*:file:_files -g '*.go'"
          ;;
      [568]l)
          local O=${words[3]%l}
          _arguments -s -w : \
              '-o[file specify output file]:file' \
              '-L[search for packages in DIR]:includes:_path_files -/' \
              "*:file:_files -g '*.[ao$O]'"
          ;;
      dist)
          _values "dist tool" banner bootstrap clean env install version
          ;;
      *)
          # use files by default
          _files
          ;;
      esac
      ;;
  esac
}

compdef __go_tool_complete go

# aliases
alias gfa='go fmt . ./...'


text:
package com.navercorp.pinpoint.web.util;

import com.navercorp.pinpoint.common.service.ServiceTypeRegistryService;
import com.navercorp.pinpoint.common.trace.ServiceType;
import com.navercorp.pinpoint.common.trace.ServiceTypeCategory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * @author Woonduk Kang(emeroad)
 */
public class ServiceTypeRegistryMockFactory {

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

    private final Map<Short, ServiceType> serviceTypeMap = new HashMap<>();

    public void addServiceTypeMock(short typeCode, String typeName) {
        // setup serviceType
        ServiceType mockServiceType = mock(ServiceType.class);
        when(mockServiceType.getCode()).thenReturn(typeCode);
        when(mockServiceType.getName()).thenReturn(typeName);

        if (ServiceTypeCategory.SERVER.contains(typeCode)) {
            logger.debug("mark isWas() {}/{}", mockServiceType.getName(), mockServiceType.getCode());
            when(mockServiceType.isWas()).thenReturn(true);
        }

        this.serviceTypeMap.put(typeCode, mockServiceType);
    }

    public ServiceType getServiceTypeMock(short typeCode) {
        return this.serviceTypeMap.get(typeCode);
    }

    public ServiceTypeRegistryService createMockServiceTypeRegistryService() {

        final ServiceTypeRegistryService serviceTypeRegistryService = mock(ServiceTypeRegistryService.class);
        for (ServiceType serviceType : serviceTypeMap.values()) {
            // setup serviceRegistry
            final String serviceTypeName = serviceType.getName();
            final short serviceTypeCode = serviceType.getCode();
            when(serviceTypeRegistryService.findServiceTypeByName(serviceTypeName)).thenReturn(serviceType);
            when(serviceTypeRegistryService.findServiceType(serviceTypeCode)).thenReturn(serviceType);
            when(serviceTypeRegistryService.findDesc(serviceTypeName)).thenReturn(Collections.singletonList(serviceType));
        }

        return serviceTypeRegistryService;
    }
}


text:
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Threading.Tasks;

//namespace NSS_Koans
//{
//    public class Koan
//    {
//        public static object FILL_ME_IN = new Object();
//    }

//    //This is just used when we need a type
//    public abstract class FillMeIn
//    {

//    }
//}


text:
<!DOCTYPE html>

        <title>Data Jenis Kegiatan</title>

Hapus kategori?

            <form class="form-horizontal" th:object="${jeniskegiatan}" method="post">

                    Kategori Kegiatan

kode

                    Komponen Kegiatan

nama

                    Bukti Kegiatan

bukti

                    Batas Maksimal diakui

batasMaksimal

                    Angka Kredit

angkaKredit

                            Batal

                        <button onclick="return confirm('Yakin ingin menghapus data ?')" type="submit" class="btn btn-danger">Hapus </button>

            </form>


text:
package model403

import (
	"github.com/crabmusket/gosunspec"
	"github.com/crabmusket/gosunspec/smdx"
	"github.com/crabmusket/gosunspec/typelabel"
)

// Block403 - String Combiner (Current) - A basic string combiner model

const (
	ModelID = 403
)

const (
	DCA        = "DCA"
	DCAMax     = "DCAMax"
	DCA_SF     = "DCA_SF"
	DCAhr      = "DCAhr"
	DCAhr_SF   = "DCAhr_SF"
	DCV        = "DCV"
	DCV_SF     = "DCV_SF"
	Evt        = "Evt"
	EvtVnd     = "EvtVnd"
	InDCA      = "InDCA"
	InDCA_SF   = "InDCA_SF"
	InDCAhr    = "InDCAhr"
	InDCAhr_SF = "InDCAhr_SF"
	InEvt      = "InEvt"
	InEvtVnd   = "InEvtVnd"
	InID       = "InID"
	N          = "N"
	Tmp        = "Tmp"
)

type Block403Repeat struct {
	InID     uint16             `sunspec:"offset=0"`
	InEvt    sunspec.Bitfield32 `sunspec:"offset=1"`
	InEvtVnd sunspec.Bitfield32 `sunspec:"offset=3"`
	InDCA    int16              `sunspec:"offset=5,sf=InDCA_SF"`
	InDCAhr  sunspec.Acc32      `sunspec:"offset=6,sf=InDCAhr_SF"`
}

type Block403 struct {
	DCA_SF     sunspec.ScaleFactor `sunspec:"offset=0"`
	DCAhr_SF   sunspec.ScaleFactor `sunspec:"offset=1"`
	DCV_SF     sunspec.ScaleFactor `sunspec:"offset=2"`
	DCAMax     uint16              `sunspec:"offset=3,sf=DCA_SF"`
	N          sunspec.Count       `sunspec:"offset=4"`
	Evt        sunspec.Bitfield32  `sunspec:"offset=5"`
	EvtVnd     sunspec.Bitfield32  `sunspec:"offset=7"`
	DCA        int16               `sunspec:"offset=9,sf=DCA_SF"`
	DCAhr      sunspec.Acc32       `sunspec:"offset=10,sf=DCAhr_SF"`
	DCV        int16               `sunspec:"offset=12,sf=DCV_SF"`
	Tmp        int16               `sunspec:"offset=13"`
	InDCA_SF   sunspec.ScaleFactor `sunspec:"offset=14"`
	InDCAhr_SF sunspec.ScaleFactor `sunspec:"offset=15"`

	Repeats []Block403Repeat
}

func (self *Block403) GetId() sunspec.ModelId {
	return ModelID
}

func init() {
	smdx.RegisterModel(&smdx.ModelElement{
		Id:     ModelID,
		Name:   "string_combiner",
		Length: 24,
		Blocks: []smdx.BlockElement{
			smdx.BlockElement{
				Length: 16,

				Points: []smdx.PointElement{
					smdx.PointElement{Id: DCA_SF, Offset: 0, Type: typelabel.Sunssf, Mandatory: true},
					smdx.PointElement{Id: DCAhr_SF, Offset: 1, Type: typelabel.Sunssf},
					smdx.PointElement{Id: DCV_SF, Offset: 2, Type: typelabel.Sunssf},
					smdx.PointElement{Id: DCAMax, Offset: 3, Type: typelabel.Uint16, ScaleFactor: "DCA_SF", Units: "A", Mandatory: true},
					smdx.PointElement{Id: N, Offset: 4, Type: typelabel.Count, Mandatory: true},
					smdx.PointElement{Id: Evt, Offset: 5, Type: typelabel.Bitfield32, Mandatory: true},
					smdx.PointElement{Id: EvtVnd, Offset: 7, Type: typelabel.Bitfield32},
					smdx.PointElement{Id: DCA, Offset: 9, Type: typelabel.Int16, ScaleFactor: "DCA_SF", Units: "A", Mandatory: true},
					smdx.PointElement{Id: DCAhr, Offset: 10, Type: typelabel.Acc32, ScaleFactor: "DCAhr_SF", Units: "Ah"},
					smdx.PointElement{Id: DCV, Offset: 12, Type: typelabel.Int16, ScaleFactor: "DCV_SF", Units: "V"},
					smdx.PointElement{Id: Tmp, Offset: 13, Type: typelabel.Int16, Units: "C"},
					smdx.PointElement{Id: InDCA_SF, Offset: 14, Type: typelabel.Sunssf},
					smdx.PointElement{Id: InDCAhr_SF, Offset: 15, Type: typelabel.Sunssf},
				},
			},
			smdx.BlockElement{Name: "string",
				Length: 8,
				Type:   "repeating",
				Points: []smdx.PointElement{
					smdx.PointElement{Id: InID, Offset: 0, Type: typelabel.Uint16, Mandatory: true},
					smdx.PointElement{Id: InEvt, Offset: 1, Type: typelabel.Bitfield32, Mandatory: true},
					smdx.PointElement{Id: InEvtVnd, Offset: 3, Type: typelabel.Bitfield32},
					smdx.PointElement{Id: InDCA, Offset: 5, Type: typelabel.Int16, ScaleFactor: "InDCA_SF", Units: "A", Mandatory: true},
					smdx.PointElement{Id: InDCAhr, Offset: 6, Type: typelabel.Acc32, ScaleFactor: "InDCAhr_SF", Units: "Ah"},
				},
			},
		}})
}


text:
module ActiveRecord
  class Base
    def self.clean
      connection.execute("TRUNCATE TABLE #{table_name};")
    end
  end
end


text:
/***************************************************/
/*! \class NRev
    \brief CCRMA's NRev reverberator class.

    This class is derived from the CLM NRev
    function, which is based on the use of
    networks of simple allpass and comb delay
    filters.  This particular arrangement consists
    of 6 comb filters in parallel, followed by 3
    allpass filters, a lowpass filter, and another
    allpass in series, followed by two allpass
    filters in parallel with corresponding right
    and left outputs.

    by Perry R. Cook and Gary P. Scavone, 1995 - 2005.
*/
/***************************************************/

#ifndef STK_NREV_H
#define STK_NREV_H

#include "Effect.h"
#include "Delay.h"

namespace Nyq
{

class NRev : public Effect
{
 public:
  //! Class constructor taking a T60 decay time argument (one second default value).
  NRev( StkFloat T60 = 1.0 );

  //! Class destructor.
  ~NRev();

  //! Reset and clear all internal state.
  void clear();

  //! Set the reverberation T60 decay time.
  void setT60( StkFloat T60 );

 protected:

  StkFloat computeSample( StkFloat input );

  Delay allpassDelays_[8];
  Delay combDelays_[6];
  StkFloat allpassCoefficient_;
  StkFloat combCoefficient_[6];
	StkFloat lowpassState_;

};

} // namespace Nyq

#endif


text:
require 'sinatra'
require 'sinatra/json'
require 'mongo'

module Nightwatch
  class Server < Sinatra::Application
    set :run, false
    set :server, 'thin'

    # TODO: Allow server configuration via command-line or settings file.
    mongo = Mongo::MongoClient.new
    events = mongo['nightwatch']['events']

    get '/' do
      erb :index
    end

    get '/events' do
      json events.find.to_a
    end

    get '/events/summary' do
      json events.find({}, fields: [
        'exception.class',
        'exception.message',
        'host.name',
        'timestamp'
      ]).to_a
    end

    get '/events/:id' do
      json events.find(_id: BSON::ObjectId(params[:id])).first
    end
  end
end


text:
package io.quarkus.rest.client.reactive.error.clientexceptionmapper;

import java.util.concurrent.atomic.AtomicInteger;

public class DummyException extends RuntimeException {

    static final AtomicInteger executionCount = new AtomicInteger(0);

    public DummyException() {
        executionCount.incrementAndGet();
        setStackTrace(new StackTraceElement[0]);
    }
}


text:
package org.mymoney.accountservice.service.impl;

import org.mymoney.accountservice.service.PersonalBankAccountService;
import org.mymoney.accountservice.domain.PersonalBankAccount;
import org.mymoney.accountservice.repository.PersonalBankAccountRepository;
import org.mymoney.accountservice.service.dto.PersonalBankAccountDTO;
import org.mymoney.accountservice.service.mapper.PersonalBankAccountMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;

import javax.inject.Inject;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Service Implementation for managing PersonalBankAccount.
 */
@Service
@Transactional
public class PersonalBankAccountServiceImpl implements PersonalBankAccountService{

    private final Logger log = LoggerFactory.getLogger(PersonalBankAccountServiceImpl.class);

    @Inject
    private PersonalBankAccountRepository personalBankAccountRepository;

    @Inject
    private PersonalBankAccountMapper personalBankAccountMapper;

    /**
     * Save a personalBankAccount.
     *
     * @param personalBankAccountDTO the entity to save
     * @return the persisted entity
     */
    public PersonalBankAccountDTO save(PersonalBankAccountDTO personalBankAccountDTO) {
        log.debug("Request to save PersonalBankAccount : {}", personalBankAccountDTO);
        PersonalBankAccount personalBankAccount = personalBankAccountMapper.personalBankAccountDTOToPersonalBankAccount(personalBankAccountDTO);
        personalBankAccount = personalBankAccountRepository.save(personalBankAccount);
        PersonalBankAccountDTO result = personalBankAccountMapper.personalBankAccountToPersonalBankAccountDTO(personalBankAccount);
        return result;
    }

    /**
     *  Get all the personalBankAccounts.
     *
     *  @return the list of entities
     */
    @Transactional(readOnly = true)
    public List<PersonalBankAccountDTO> findAll() {
        log.debug("Request to get all PersonalBankAccounts");
        List<PersonalBankAccountDTO> result = personalBankAccountRepository.findAll().stream()
            .map(personalBankAccountMapper::personalBankAccountToPersonalBankAccountDTO)
            .collect(Collectors.toCollection(LinkedList::new));

        return result;
    }

    /**
     *  Get one personalBankAccount by id.
     *
     *  @param id the id of the entity
     *  @return the entity
     */
    @Transactional(readOnly = true)
    public PersonalBankAccountDTO findOne(Long id) {
        log.debug("Request to get PersonalBankAccount : {}", id);
        PersonalBankAccount personalBankAccount = personalBankAccountRepository.findOne(id);
        PersonalBankAccountDTO personalBankAccountDTO = personalBankAccountMapper.personalBankAccountToPersonalBankAccountDTO(personalBankAccount);
        return personalBankAccountDTO;
    }

    /**
     *  Delete the  personalBankAccount by id.
     *
     *  @param id the id of the entity
     */
    public void delete(Long id) {
        log.debug("Request to delete PersonalBankAccount : {}", id);
        personalBankAccountRepository.delete(id);
    }
}


text:
//%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements.  Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////

UNIX_ArchitectureCheck::UNIX_ArchitectureCheck(void)
{
}

UNIX_ArchitectureCheck::~UNIX_ArchitectureCheck(void)
{
}

Boolean UNIX_ArchitectureCheck::getInstanceID(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_INSTANCE_ID, getInstanceID());
	return true;
}

String UNIX_ArchitectureCheck::getInstanceID() const
{
	return String ("");
}

Boolean UNIX_ArchitectureCheck::getCaption(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_CAPTION, getCaption());
	return true;
}

String UNIX_ArchitectureCheck::getCaption() const
{
	return String ("");
}

Boolean UNIX_ArchitectureCheck::getDescription(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_DESCRIPTION, getDescription());
	return true;
}

String UNIX_ArchitectureCheck::getDescription() const
{
	return String ("");
}

Boolean UNIX_ArchitectureCheck::getElementName(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_ELEMENT_NAME, getElementName());
	return true;
}

String UNIX_ArchitectureCheck::getElementName() const
{
	return String("ArchitectureCheck");
}

Boolean UNIX_ArchitectureCheck::getName(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_NAME, getName());
	return true;
}

String UNIX_ArchitectureCheck::getName() const
{
	return String ("");
}

Boolean UNIX_ArchitectureCheck::getVersion(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_VERSION, getVersion());
	return true;
}

String UNIX_ArchitectureCheck::getVersion() const
{
	return String ("");
}

Boolean UNIX_ArchitectureCheck::getSoftwareElementState(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_SOFTWARE_ELEMENT_STATE, getSoftwareElementState());
	return true;
}

Uint16 UNIX_ArchitectureCheck::getSoftwareElementState() const
{
	return Uint16(0);
}

Boolean UNIX_ArchitectureCheck::getSoftwareElementID(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_SOFTWARE_ELEMENT_ID, getSoftwareElementID());
	return true;
}

String UNIX_ArchitectureCheck::getSoftwareElementID() const
{
	return String ("");
}

Boolean UNIX_ArchitectureCheck::getTargetOperatingSystem(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_TARGET_OPERATING_SYSTEM, getTargetOperatingSystem());
	return true;
}

Uint16 UNIX_ArchitectureCheck::getTargetOperatingSystem() const
{
	return Uint16(0);
}

Boolean UNIX_ArchitectureCheck::getCheckID(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_CHECK_ID, getCheckID());
	return true;
}

String UNIX_ArchitectureCheck::getCheckID() const
{
	return String ("");
}

Boolean UNIX_ArchitectureCheck::getCheckMode(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_CHECK_MODE, getCheckMode());
	return true;
}

Boolean UNIX_ArchitectureCheck::getCheckMode() const
{
	return Boolean(false);
}

Boolean UNIX_ArchitectureCheck::getArchitectureType(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_ARCHITECTURE_TYPE, getArchitectureType());
	return true;
}

Uint16 UNIX_ArchitectureCheck::getArchitectureType() const
{
	return Uint16(0);
}

Boolean UNIX_ArchitectureCheck::initialize()
{
	return false;
}

Boolean UNIX_ArchitectureCheck::load(int &pIndex)
{
	return false;
}

Boolean UNIX_ArchitectureCheck::finalize()
{
	return false;
}

Boolean UNIX_ArchitectureCheck::find(Array<CIMKeyBinding> &kbArray)
{
	CIMKeyBinding kb;
	String nameKey;
	String versionKey;
	String softwareElementStateKey;
	String softwareElementIDKey;
	String targetOperatingSystemKey;
	String checkIDKey;

	for(Uint32 i = 0; i < kbArray.size(); i++)
	{
		kb = kbArray[i];
		CIMName keyName = kb.getName();
		if (keyName.equal(PROPERTY_NAME)) nameKey = kb.getValue();
		else if (keyName.equal(PROPERTY_VERSION)) versionKey = kb.getValue();
		else if (keyName.equal(PROPERTY_SOFTWARE_ELEMENT_STATE)) softwareElementStateKey = kb.getValue();
		else if (keyName.equal(PROPERTY_SOFTWARE_ELEMENT_ID)) softwareElementIDKey = kb.getValue();
		else if (keyName.equal(PROPERTY_TARGET_OPERATING_SYSTEM)) targetOperatingSystemKey = kb.getValue();
		else if (keyName.equal(PROPERTY_CHECK_ID)) checkIDKey = kb.getValue();
	}

/* EXecute find with extracted keys */

	return false;
}


text:
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// IPC messages for access to MIDI hardware.
// Multiply-included message file, hence no include guard.

#include "base/basictypes.h"
#include "content/common/content_export.h"
#include "ipc/ipc_message_macros.h"
#include "media/midi/midi_port_info.h"
#include "url/gurl.h"

#undef IPC_MESSAGE_EXPORT
#define IPC_MESSAGE_EXPORT CONTENT_EXPORT
#define IPC_MESSAGE_START MIDIMsgStart

IPC_STRUCT_TRAITS_BEGIN(media::MIDIPortInfo)
  IPC_STRUCT_TRAITS_MEMBER(id)
  IPC_STRUCT_TRAITS_MEMBER(manufacturer)
  IPC_STRUCT_TRAITS_MEMBER(name)
  IPC_STRUCT_TRAITS_MEMBER(version)
IPC_STRUCT_TRAITS_END()

// Messages for IPC between MIDIDispatcher and MIDIDispatcherHost.

// Renderer request to browser for using system exclusive messages.
IPC_MESSAGE_CONTROL3(MIDIHostMsg_RequestSysExPermission,
                     int /* routing id */,
                     int /* client id */,
                     GURL /* origin */)

// Renderer request to browser for canceling a previous permission request.
IPC_MESSAGE_CONTROL3(MIDIHostMsg_CancelSysExPermissionRequest,
                     int /* render_view_id */,
                     int /* bridge_id */,
                     GURL /* GURL of the frame */)

// Messages sent from the browser to the renderer.

IPC_MESSAGE_ROUTED2(MIDIMsg_SysExPermissionApproved,
                    int /* client id */,
                    bool /* success */)

// Messages for IPC between MIDIMessageFilter and MIDIHost.

// Renderer request to browser for access to MIDI services.
IPC_MESSAGE_CONTROL1(MIDIHostMsg_StartSession,
                     int /* client id */)

IPC_MESSAGE_CONTROL3(MIDIHostMsg_SendData,
                     uint32 /* port */,
                     std::vector<uint8> /* data */,
                     double /* timestamp */)

// Messages sent from the browser to the renderer.

IPC_MESSAGE_CONTROL4(MIDIMsg_SessionStarted,
                     int /* client id */,
                     bool /* success */,
                     media::MIDIPortInfoList /* input ports */,
                     media::MIDIPortInfoList /* output ports */)

IPC_MESSAGE_CONTROL3(MIDIMsg_DataReceived,
                     uint32 /* port */,
                     std::vector<uint8> /* data */,
                     double /* timestamp */)

IPC_MESSAGE_CONTROL1(MIDIMsg_AcknowledgeSentData,
                     uint32 /* bytes sent */)


text:
package org.ektorp.http;

import static org.junit.Assert.*;

import org.junit.Test;

public class StdHttpClientTest {

	@Test
	public void build_from_url() throws Exception {
		StdHttpClient.Builder b = new StdHttpClient.Builder().url("http://somehost:8989");
		assertEquals("somehost", b.host);
		assertEquals(8989, b.port);
		assertFalse(b.enableSSL);
	}

	@Test
	public void build_from_ssl_url() throws Exception {
		StdHttpClient.Builder b = new StdHttpClient.Builder().url("https://somehost:8989");
		assertTrue(b.enableSSL);
	}
}


text:
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');

var port = process.env.PORT || 3000;
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.text());
app.use(bodyParser.json({ type: "application/vnd.api+json" }));

///////ROUTES////////////

require("./app/routing/api-routes.js")(app);
require("./app/routing/html-routes.js")(app);

////////////////////////////
app.listen(port, function() {
   console.log('Hi. App is listening on PORT: ' + port);
});


text:
namespace Hqub.MusicBrainz.API.Cache
{
    using System.IO;
    using System.Threading.Tasks;

    /// <summary>
    /// A simple cache interface.
    /// </summary>
    public interface IRequestCache
    {
        /// <summary>
        /// Add a request and its response to the cache.
        /// </summary>
        /// <param name="request">The request url used to identify the cache item.</param>
        /// <param name="response">The MusicbBrainz webservice response stream.</param>
        Task Add(string request, Stream response);

        /// <summary>
        /// Try to find the cached response for given request url.
        /// </summary>
        /// <param name="request">The request url used to identify the cache item.</param>
        /// <param name="stream">The response stream read form cache.</param>
        /// <returns>True, if a cache entry matching the request was found.</returns>
        Task<bool> TryGetCachedItem(string request, out Stream stream);
    }
}


text:
module Fluorine
  ( Driver()
  , Process()
  , mainLoop
  ) where

import Control.Monad
import Data.IORef
import Fluorine.Signal
import Fluorine.HTML.Events.Types

-------------------------------------------------------------------------------

type Driver i = i -> IO ()

-- | `runUI` renders a `Component` to the DOM using `virtual-dom`.
-- |
-- | This function is the workhorse of the Halogen library. It can be called in `main`
-- | to set up the application and create the driver function, which can be used to
-- | send inputs to the UI from external components.
-- runUI :: Component (Event (HalogenEffects eff)) req req
--       -> Eff (HalogenEffects eff) (Tuple HTMLElement (Driver req eff))
-- runUI sf = sf `runUIWith` \_ _ _ -> return unit

-- | A variant of `runUI` which supports a _post-render hook_. This allows applications
-- | to support third-party components or other custom behaviors by modifying the DOM after
-- | each update.
-- |
-- | This is considered an advanced feature, and should only be used with an understanding of
-- | the rendering pipeline.
-- runUIWith :: Component (Event (HalogenEffects eff)) req req
--           -> (req -> HTMLElement -> Driver req eff -> Eff (HalogenEffects eff) Unit)
--           -> Eff (HalogenEffects eff) (Tuple HTMLElement (Driver req eff))
-- runUIWith sf postRender = mainLoop (pure <<< componentProcess sf postRender)

-- | A `Process` receives inputs and outputs effectful computations which update the DOM.
type Process req = SF (req, HTMLElement) (IO HTMLElement)

-- | This function provides the low-level implementation of Halogen's DOM update loop.
-- |
-- | The first argument is a function which receives the `Driver` function as an argument and
-- | constructs a `Process` which will update the DOM given an input.
-- |
-- | This function could be reused to create other types of applications based on signal functions
-- | (2D and 3D canvas, text-based, etc.)
mainLoop :: (Driver req -> IO (HTMLElement, Process req))
         -> IO (HTMLElement, Driver req)
mainLoop buildProcess = do
  ref <- newIORef Nothing
  go ref
  where
    go ref = do
      (node, process) <- buildProcess driver
      writeIORef ref $ Just (process, node)
      return (node, driver)
      where
        driver req = void $ {- setTimeout globalWindow 0 $-} do
          ms <- readIORef ref
          case ms of
            Just (process, node) -> do
              let work = runSF process (req, node)
              node' <- result work
              writeIORef ref $ Just (next work, node')
            Nothing -> error "Error: An attempt to re-render was made during the initial render."


text:
package BrickMosaic

import (
	"fmt"
	"testing"
)

type fakeOrig struct{}

func (f fakeOrig) Orientation() ViewOrientation {
	return StudsOut
}
func (f fakeOrig) NumRows() int {
	return 5
}
func (f fakeOrig) NumCols() int {
	return 5
}
func (f fakeOrig) Color(row, col int) BrickColor {
	return BrightRed
}

type fakePlan struct {
	counter int
}

func (f *fakePlan) Orig() Ideal {
	return fakeOrig{}
}

func (f *fakePlan) Pieces() []PlacedBrick {
	var pieces []PlacedBrick
	for row := 0; row < f.Orig().NumRows(); row++ {
		for col := 0; col < f.Orig().NumCols(); col++ {
			pieces = append(pieces, f.Piece(row, col))
		}
	}
	return pieces
}

func (f *fakePlan) Piece(row, col int) PlacedBrick {
	f.counter++
	return PlacedBrick{
		Id: f.counter,
	}
}

func (f *fakePlan) Inventory() Inventory {
	return Inventory{}
}

func TestTerminalRender(t *testing.T) {
	w := WriterRenderer{}
	fmt.Println(w.Render(&fakePlan{}))
}


text:
<TITLE>glslf</TITLE>

<object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e">
</object>

NAME

glslf - OpenGL fragment profile for the OpenGL Shading Lanauge (GLSL)

SYNOPSIS

  glslf

DESCRIPTION

This OpenGL profile corresponds to the per-fragment functionality
introduced by the OpenGL Shading Language.

The compiler output for this profile conforms to the language grammar
defined by the OpenGL Shading Language specification.

3D API DEPENDENCIES

Requires support for OpenGL 2.0.

OpenGL Extension Specifications

 www.opengl.org/documentation/specs/version2.0/glspec20.pdf
 www.opengl.org/documentation/glsl/
 www.opengl.org/registry/doc/GLSLangSpec.Full.1.20.8.pdf

PROFILE OPTIONS

version=val

GLSL version to target.  Supported versions are 100, 110, 120, 130, 140 and 150.

userTexCoord

Use user-defined varying instead of gl_TexCoord.

ATI_draw_buffers

Use ATI_draw_buffers extension for MRT.

EXT_gpu_shader4

Use EXT_gpu_shader4 extension where useful.

DATA TYPES

The Cg half and fixed data types are both mapped to float because GLSL lacks first-class half and fixed data types.

SEMANTICS

VARYING INPUT SEMANTICS

  Binding Semantics Name           Corresponding Data           GLSL Equivalent

  COLOR                            Primary color (float4)       gl_Color
  COLOR0
  COL0
  COL

  COLOR1                           Secondary color (float4)     gl_SecondaryColor
  COL1

  TEXCOORD                         Texture coordinate set 0     gl_TexCoord[0]
  TEXCOORD#                        Texture coordinate set #     gl_TexCoord[#]
  TEX#

  FACE                             Front/back facing (+1/-1)    gl_FrontFacing

UNIFORM INPUT SEMANTICS

Sixteen texture units are supported:

  Binding Semantic Name            Corresponding Data

  TEXUNIT0                         Texture unit 0
  TEXUNIT1                         Texture unit 1
  ...
  TEXUNIT15                        Texture unit 15

The Cg profiles for GLSL provide access to all the uniform constants and variables documented in Section 7.4 (Built-in Constants) and 7.5 (Built-in Uniform State) respectively of the OpenGL Shading Language specification found at:

  www.opengl.org/documentation/glsl/
  www.opengl.org/registry/doc/GLSLangSpec.Full.1.20.8.pdf

Example:

  glslf void main(float4 color : COLOR,
                  out float4 ocol : COLOR)
  {
    ocol.xyz = mul(gl_NormalMatrix, color.xyz);
    ocol.w = 1;
  }

OUTPUT SEMANTICS

The following standard fragment output semantics are supported:

  Binding Semantics Name           Corresponding Data      GLSL Equivalent

  COLOR                            Output color (float4)   gl_FragColor
  COLOR0
  COL0
  COL

  COLOR0-COLOR7                    Output color (float4)   gl_FragData[n]
  COL0-COL7                        for draw buffers 0 to 7

  DEPTH                            Output depth (float)    gl_FragDepth
  DEPR

STANDARD LIBRARY ISSUES

Fragment program Cg standard library routines are available.

SEE ALSO

glslv,
glslg


text:
require 'cask/staged'

class Cask::DSL::UninstallPreflight < Cask::DSL::Base
  include Cask::Staged

  def method_missing(method, *args)
    Cask::Utils.method_missing_message(method, @cask.to_s, 'uninstall_preflight')
    return nil
  end
end