text:
/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_hal.h"

/** @addtogroup STM32F4xx_HAL_Driver
  * @{
  */
/** @defgroup DCMI DCMI
  * @brief DCMI HAL module driver
  * @{
  */

#ifdef HAL_DCMI_MODULE_ENABLED

#if defined(STM32F407xx) || defined(STM32F417xx) || defined(STM32F427xx) || defined(STM32F437xx) ||\
    defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F446xx) || defined(STM32F469xx) ||\
    defined(STM32F479xx)
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
#define HAL_TIMEOUT_DCMI_STOP    ((uint32_t)1000U)  /* 1s  */
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
static void       DCMI_DMAXferCplt(DMA_HandleTypeDef *hdma);
static void       DCMI_DMAError(DMA_HandleTypeDef *hdma);

/* Exported functions --------------------------------------------------------*/

/** @defgroup DCMI_Exported_Functions DCMI Exported Functions
  * @{
  */

/** @defgroup DCMI_Exported_Functions_Group1 Initialization and Configuration functions
  *  @brief   Initialization and Configuration functions
  *
@verbatim
 ===============================================================================
                ##### Initialization and Configuration functions #####
 ===============================================================================
    [..]  This section provides functions allowing to:
      (+) Initialize and configure the DCMI
      (+) De-initialize the DCMI

@endverbatim
  * @{
  */

/**
  * @brief  Initializes the DCMI according to the specified
  *         parameters in the DCMI_InitTypeDef and create the associated handle.
  * @param  hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
  *                the configuration information for DCMI.
  * @retval HAL status
  */
__weak HAL_StatusTypeDef HAL_DCMI_Init(DCMI_HandleTypeDef *hdcmi)
{
  /* Check the DCMI peripheral state */
  if(hdcmi == NULL)
  {
     return HAL_ERROR;
  }

  /* Check function parameters */
  assert_param(IS_DCMI_ALL_INSTANCE(hdcmi->Instance));
  assert_param(IS_DCMI_PCKPOLARITY(hdcmi->Init.PCKPolarity));
  assert_param(IS_DCMI_VSPOLARITY(hdcmi->Init.VSPolarity));
  assert_param(IS_DCMI_HSPOLARITY(hdcmi->Init.HSPolarity));
  assert_param(IS_DCMI_SYNCHRO(hdcmi->Init.SynchroMode));
  assert_param(IS_DCMI_CAPTURE_RATE(hdcmi->Init.CaptureRate));
  assert_param(IS_DCMI_EXTENDED_DATA(hdcmi->Init.ExtendedDataMode));
  assert_param(IS_DCMI_MODE_JPEG(hdcmi->Init.JPEGMode));

  if(hdcmi->State == HAL_DCMI_STATE_RESET)
  {
    /* Allocate lock resource and initialize it */
    hdcmi->Lock = HAL_UNLOCKED;
    /* Init the low level hardware */
    HAL_DCMI_MspInit(hdcmi);
  }

  /* Change the DCMI state */
  hdcmi->State = HAL_DCMI_STATE_BUSY;
  /* Configures the HS, VS, DE and PC polarity */
  hdcmi->Instance->CR &= ~(DCMI_CR_PCKPOL | DCMI_CR_HSPOL  | DCMI_CR_VSPOL  | DCMI_CR_EDM_0 |
                           DCMI_CR_EDM_1  | DCMI_CR_FCRC_0 | DCMI_CR_FCRC_1 | DCMI_CR_JPEG  |
                           DCMI_CR_ESS);
  hdcmi->Instance->CR |=  (uint32_t)(hdcmi->Init.SynchroMode | hdcmi->Init.CaptureRate | \
                                     hdcmi->Init.VSPolarity  | hdcmi->Init.HSPolarity  | \
                                     hdcmi->Init.PCKPolarity | hdcmi->Init.ExtendedDataMode | \
                                     hdcmi->Init.JPEGMode);

  if(hdcmi->Init.SynchroMode == DCMI_SYNCHRO_EMBEDDED)
  {
    DCMI->ESCR = (((uint32_t)hdcmi->Init.SyncroCode.FrameStartCode)    |
                  ((uint32_t)hdcmi->Init.SyncroCode.LineStartCode << 8U)|
                  ((uint32_t)hdcmi->Init.SyncroCode.LineEndCode << 16U) |
                  ((uint32_t)hdcmi->Init.SyncroCode.FrameEndCode << 24U));

  }

  /* Enable DCMI by setting DCMIEN bit */
  __HAL_DCMI_ENABLE(hdcmi);

  /* Update error code */
  hdcmi->ErrorCode = HAL_DCMI_ERROR_NONE;

  /* Initialize the DCMI state*/
  hdcmi->State  = HAL_DCMI_STATE_READY;

  return HAL_OK;
}

/**
  * @brief  Deinitializes the DCMI peripheral registers to their default reset
  *         values.
  * @param  hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
  *                the configuration information for DCMI.
  * @retval HAL status
  */

HAL_StatusTypeDef HAL_DCMI_DeInit(DCMI_HandleTypeDef *hdcmi)
{
  /* DeInit the low level hardware */
  HAL_DCMI_MspDeInit(hdcmi);

  /* Update error code */
  hdcmi->ErrorCode = HAL_DCMI_ERROR_NONE;

  /* Initialize the DCMI state*/
  hdcmi->State = HAL_DCMI_STATE_RESET;

  /* Release Lock */
  __HAL_UNLOCK(hdcmi);

  return HAL_OK;
}

/**
  * @brief  Initializes the DCMI MSP.
  * @param  hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
  *                the configuration information for DCMI.
  * @retval None
  */
__weak void HAL_DCMI_MspInit(DCMI_HandleTypeDef* hdcmi)
{
  /* Prevent unused argument(s) compilation warning */
  UNUSED(hdcmi);
  /* NOTE : This function Should not be modified, when the callback is needed,
            the HAL_DCMI_MspInit could be implemented in the user file
   */
}

/**
  * @brief  DeInitializes the DCMI MSP.
  * @param  hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
  *                the configuration information for DCMI.
  * @retval None
  */
__weak void HAL_DCMI_MspDeInit(DCMI_HandleTypeDef* hdcmi)
{
  /* Prevent unused argument(s) compilation warning */
  UNUSED(hdcmi);
  /* NOTE : This function Should not be modified, when the callback is needed,
            the HAL_DCMI_MspDeInit could be implemented in the user file
   */
}

/**
  * @}
  */
/** @defgroup DCMI_Exported_Functions_Group2 IO operation functions
  *  @brief   IO operation functions
  *
@verbatim
 ===============================================================================
                      #####  IO operation functions  #####
 ===============================================================================
    [..]  This section provides functions allowing to:
      (+) Configure destination address and data length and
          Enables DCMI DMA request and enables DCMI capture
      (+) Stop the DCMI capture.
      (+) Handles DCMI interrupt request.

@endverbatim
  * @{
  */

/**
  * @brief  Enables DCMI DMA request and enables DCMI capture
  * @param  hdcmi:     pointer to a DCMI_HandleTypeDef structure that contains
  *                    the configuration information for DCMI.
  * @param  DCMI_Mode: DCMI capture mode snapshot or continuous grab.
  * @param  pData:     The destination memory Buffer address (LCD Frame buffer).
  * @param  Length:    The length of capture to be transferred.
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_DCMI_Start_DMA(DCMI_HandleTypeDef* hdcmi, uint32_t DCMI_Mode, uint32_t pData, uint32_t Length)
{
  /* Initialize the second memory address */
  uint32_t SecondMemAddress = 0U;

  /* Check function parameters */
  assert_param(IS_DCMI_CAPTURE_MODE(DCMI_Mode));

  /* Process Locked */
  __HAL_LOCK(hdcmi);

  /* Enable the Line, Vsync, Error and Overrun interrupts */
  __HAL_DCMI_ENABLE_IT(hdcmi, DCMI_IT_LINE | DCMI_IT_VSYNC | DCMI_IT_ERR | DCMI_IT_OVF);

  /* Disable the End of Frame interrupt */
  __HAL_DCMI_DISABLE_IT(hdcmi, DCMI_IT_FRAME);

  /* Lock the DCMI peripheral state */
  hdcmi->State = HAL_DCMI_STATE_BUSY;

  /* Check the parameters */
  assert_param(IS_DCMI_CAPTURE_MODE(DCMI_Mode));

  /* Configure the DCMI Mode */
  hdcmi->Instance->CR &= ~(DCMI_CR_CM);
  hdcmi->Instance->CR |=  (uint32_t)(DCMI_Mode);

  /* Set the DMA memory0 conversion complete callback */
  hdcmi->DMA_Handle->XferCpltCallback = DCMI_DMAXferCplt;

  /* Set the DMA error callback */
  hdcmi->DMA_Handle->XferErrorCallback = DCMI_DMAError;

  if(Length <= 0xFFFFU)
  {
    /* Enable the DMA Stream */
    HAL_DMA_Start_IT(hdcmi->DMA_Handle, (uint32_t)&hdcmi->Instance->DR, (uint32_t)pData, Length);
  }
  else /* DCMI_DOUBLE_BUFFER Mode */
  {
    /* Set the DMA memory1 conversion complete callback */
    hdcmi->DMA_Handle->XferM1CpltCallback = DCMI_DMAXferCplt;

    /* Initialize transfer parameters */
    hdcmi->XferCount = 1U;
    hdcmi->XferSize = Length;
    hdcmi->pBuffPtr = pData;

    /* Get the number of buffer */
    while(hdcmi->XferSize > 0xFFFFU)
    {
      hdcmi->XferSize = (hdcmi->XferSize/2U);
      hdcmi->XferCount = hdcmi->XferCount*2U;
    }

    /* Update DCMI counter  and transfer number*/
    hdcmi->XferCount = (hdcmi->XferCount - 2U);
    hdcmi->XferTransferNumber = hdcmi->XferCount;

    /* Update second memory address */
    SecondMemAddress = (uint32_t)(pData + (4U*hdcmi->XferSize));

    /* Start DMA multi buffer transfer */
    HAL_DMAEx_MultiBufferStart_IT(hdcmi->DMA_Handle, (uint32_t)&hdcmi->Instance->DR, (uint32_t)pData, SecondMemAddress, hdcmi->XferSize);
  }

  /* Enable Capture */
  DCMI->CR |= DCMI_CR_CAPTURE;

  /* Return function status */
  return HAL_OK;
}

/**
  * @brief  Disable DCMI DMA request and Disable DCMI capture
  * @param  hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
  *                the configuration information for DCMI.
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_DCMI_Stop(DCMI_HandleTypeDef* hdcmi)
{
  uint32_t tickstart = 0U;

  /* Lock the DCMI peripheral state */
  hdcmi->State = HAL_DCMI_STATE_BUSY;

  __HAL_DCMI_DISABLE(hdcmi);

  /* Disable Capture */
  DCMI->CR &= ~(DCMI_CR_CAPTURE);

  /* Get tick */
  tickstart = HAL_GetTick();

  /* Check if the DCMI capture effectively disabled */
  while((hdcmi->Instance->CR & DCMI_CR_CAPTURE) != 0U)
  {
    if((HAL_GetTick() - tickstart ) > HAL_TIMEOUT_DCMI_STOP)
    {
      /* Process Unlocked */
      __HAL_UNLOCK(hdcmi);

      /* Update error code */
      hdcmi->ErrorCode |= HAL_DCMI_ERROR_TIMEOUT;

      /* Change DCMI state */
      hdcmi->State = HAL_DCMI_STATE_TIMEOUT;

      return HAL_TIMEOUT;
    }
  }

  /* Disable the DMA */
  HAL_DMA_Abort(hdcmi->DMA_Handle);

  /* Update error code */
  hdcmi->ErrorCode |= HAL_DCMI_ERROR_NONE;

  /* Change DCMI state */
  hdcmi->State = HAL_DCMI_STATE_READY;

  /* Process Unlocked */
  __HAL_UNLOCK(hdcmi);

  /* Return function status */
  return HAL_OK;
}

/**
  * @brief  Handles DCMI interrupt request.
  * @param  hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
  *                the configuration information for the DCMI.
  * @retval None
  */
void HAL_DCMI_IRQHandler(DCMI_HandleTypeDef *hdcmi)
{
  /* Synchronization error interrupt management *******************************/
  if(__HAL_DCMI_GET_FLAG(hdcmi, DCMI_FLAG_ERRRI) != RESET)
  {
    if(__HAL_DCMI_GET_IT_SOURCE(hdcmi, DCMI_IT_ERR) != RESET)
    {
      /* Clear the Synchronization error flag */
      __HAL_DCMI_CLEAR_FLAG(hdcmi, DCMI_FLAG_ERRRI);

      /* Update error code */
      hdcmi->ErrorCode |= HAL_DCMI_ERROR_SYNC;

      /* Change DCMI state */
      hdcmi->State = HAL_DCMI_STATE_ERROR;

      /* Process Unlocked */
      __HAL_UNLOCK(hdcmi);

      /* Abort the DMA Transfer */
      HAL_DMA_Abort(hdcmi->DMA_Handle);

      /* Synchronization error Callback */
      HAL_DCMI_ErrorCallback(hdcmi);
    }
  }
  /* Overflow interrupt management ********************************************/
  if(__HAL_DCMI_GET_FLAG(hdcmi, DCMI_FLAG_OVFRI) != RESET)
  {
    if(__HAL_DCMI_GET_IT_SOURCE(hdcmi, DCMI_IT_OVF) != RESET)
    {
      /* Clear the Overflow flag */
      __HAL_DCMI_CLEAR_FLAG(hdcmi, DCMI_FLAG_OVFRI);

      /* Update error code */
      hdcmi->ErrorCode |= HAL_DCMI_ERROR_OVF;

      /* Change DCMI state */
      hdcmi->State = HAL_DCMI_STATE_ERROR;

      /* Process Unlocked */
      __HAL_UNLOCK(hdcmi);

      /* Abort the DMA Transfer */
      HAL_DMA_Abort(hdcmi->DMA_Handle);

      /* Overflow Callback */
      HAL_DCMI_ErrorCallback(hdcmi);
    }
  }
  /* Line Interrupt management ************************************************/
  if(__HAL_DCMI_GET_FLAG(hdcmi, DCMI_FLAG_LINERI) != RESET)
  {
    if(__HAL_DCMI_GET_IT_SOURCE(hdcmi, DCMI_IT_LINE) != RESET)
    {
      /* Clear the Line interrupt flag */
      __HAL_DCMI_CLEAR_FLAG(hdcmi, DCMI_FLAG_LINERI);

      /* Process Unlocked */
      __HAL_UNLOCK(hdcmi);

      /* Line interrupt Callback */
      HAL_DCMI_LineEventCallback(hdcmi);
    }
  }
  /* VSYNC interrupt management ***********************************************/
  if(__HAL_DCMI_GET_FLAG(hdcmi, DCMI_FLAG_VSYNCRI) != RESET)
  {
    if(__HAL_DCMI_GET_IT_SOURCE(hdcmi, DCMI_IT_VSYNC) != RESET)
    {
      /* Clear the VSYNC flag */
      __HAL_DCMI_CLEAR_FLAG(hdcmi, DCMI_FLAG_VSYNCRI);

      /* Process Unlocked */
      __HAL_UNLOCK(hdcmi);

      /* VSYNC Callback */
      HAL_DCMI_VsyncEventCallback(hdcmi);
    }
  }
  /* End of Frame interrupt management ****************************************/
  if(__HAL_DCMI_GET_FLAG(hdcmi, DCMI_FLAG_FRAMERI) != RESET)
  {
    if(__HAL_DCMI_GET_IT_SOURCE(hdcmi, DCMI_IT_FRAME) != RESET)
    {
      /* Disable the Line interrupt when using snapshot mode */
      if ((hdcmi->Instance->CR & DCMI_CR_CM) == DCMI_MODE_SNAPSHOT)
      {
        __HAL_DCMI_DISABLE_IT(hdcmi, DCMI_IT_LINE);
      }
      /* Disable the End of frame, Vsync, Error and Overrun interrupts */
      __HAL_DCMI_DISABLE_IT(hdcmi, DCMI_IT_FRAME | DCMI_IT_VSYNC | DCMI_IT_ERR | DCMI_IT_OVF);

      /* Clear the End of Frame flag */
      __HAL_DCMI_CLEAR_FLAG(hdcmi, DCMI_FLAG_FRAMERI);

      /* Process Unlocked */
      __HAL_UNLOCK(hdcmi);

      /* End of Frame Callback */
      HAL_DCMI_FrameEventCallback(hdcmi);
    }
  }
}

/**
* @brief  Error DCMI callback.
  * @param  hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
  *                the configuration information for DCMI.
  * @retval None
  */
__weak void HAL_DCMI_ErrorCallback(DCMI_HandleTypeDef *hdcmi)
{
  /* Prevent unused argument(s) compilation warning */
  UNUSED(hdcmi);
  /* NOTE : This function Should not be modified, when the callback is needed,
            the HAL_DCMI_ErrorCallback could be implemented in the user file
   */
}

/**
  * @brief  Line Event callback.
  * @param  hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
  *                the configuration information for DCMI.
  * @retval None
  */
__weak void HAL_DCMI_LineEventCallback(DCMI_HandleTypeDef *hdcmi)
{
  /* Prevent unused argument(s) compilation warning */
  UNUSED(hdcmi);
  /* NOTE : This function Should not be modified, when the callback is needed,
            the HAL_DCMI_LineEventCallback could be implemented in the user file
   */
}

/**
  * @brief  VSYNC Event callback.
  * @param  hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
  *                the configuration information for DCMI.
  * @retval None
  */
__weak void HAL_DCMI_VsyncEventCallback(DCMI_HandleTypeDef *hdcmi)
{
  /* Prevent unused argument(s) compilation warning */
  UNUSED(hdcmi);
  /* NOTE : This function Should not be modified, when the callback is needed,
            the HAL_DCMI_VsyncEventCallback could be implemented in the user file
   */
}

/**
  * @brief  Frame Event callback.
  * @param  hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
  *                the configuration information for DCMI.
  * @retval None
  */
__weak void HAL_DCMI_FrameEventCallback(DCMI_HandleTypeDef *hdcmi)
{
  /* Prevent unused argument(s) compilation warning */
  UNUSED(hdcmi);
  /* NOTE : This function Should not be modified, when the callback is needed,
            the HAL_DCMI_FrameEventCallback could be implemented in the user file
   */
}

/**
  * @}
  */

/** @defgroup DCMI_Exported_Functions_Group3 Peripheral Control functions
  *  @brief    Peripheral Control functions
  *
@verbatim
 ===============================================================================
                    ##### Peripheral Control functions #####
 ===============================================================================
[..]  This section provides functions allowing to:
      (+) Configure the CROP feature.
      (+) Enable/Disable the CROP feature.

@endverbatim
  * @{
  */

/**
  * @brief  Configure the DCMI CROP coordinate.
  * @param  hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
  *                the configuration information for DCMI.
  * @param  X0:    DCMI window X offset
  * @param  Y0:    DCMI window Y offset
  * @param  XSize: DCMI Pixel per line
  * @param  YSize: DCMI Line number
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_DCMI_ConfigCROP(DCMI_HandleTypeDef *hdcmi, uint32_t X0, uint32_t Y0, uint32_t XSize, uint32_t YSize)
{
  /* Process Locked */
  __HAL_LOCK(hdcmi);

  /* Lock the DCMI peripheral state */
  hdcmi->State = HAL_DCMI_STATE_BUSY;

  /* Check the parameters */
  assert_param(IS_DCMI_WINDOW_COORDINATE(X0));
  assert_param(IS_DCMI_WINDOW_COORDINATE(YSize));
  assert_param(IS_DCMI_WINDOW_COORDINATE(XSize));
  assert_param(IS_DCMI_WINDOW_HEIGHT(Y0));

  /* Configure CROP */
  DCMI->CWSIZER = (XSize | (YSize << 16U));
  DCMI->CWSTRTR = (X0 | (Y0 << 16U));

  /* Initialize the DCMI state*/
  hdcmi->State  = HAL_DCMI_STATE_READY;

  /* Process Unlocked */
  __HAL_UNLOCK(hdcmi);

  return HAL_OK;
}

/**
  * @brief  Disable the Crop feature.
  * @param  hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
  *                the configuration information for DCMI.
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_DCMI_DisableCROP(DCMI_HandleTypeDef *hdcmi)
{
  /* Process Locked */
  __HAL_LOCK(hdcmi);

  /* Lock the DCMI peripheral state */
  hdcmi->State = HAL_DCMI_STATE_BUSY;

  /* Disable DCMI Crop feature */
  DCMI->CR &= ~(uint32_t)DCMI_CR_CROP;

  /* Change the DCMI state*/
  hdcmi->State = HAL_DCMI_STATE_READY;

  /* Process Unlocked */
  __HAL_UNLOCK(hdcmi);

  return HAL_OK;
}

/**
  * @brief  Enable the Crop feature.
  * @param  hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
  *                the configuration information for DCMI.
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_DCMI_EnableCROP(DCMI_HandleTypeDef *hdcmi)
{
  /* Process Locked */
  __HAL_LOCK(hdcmi);

  /* Lock the DCMI peripheral state */
  hdcmi->State = HAL_DCMI_STATE_BUSY;

  /* Enable DCMI Crop feature */
  DCMI->CR |= (uint32_t)DCMI_CR_CROP;

  /* Change the DCMI state*/
  hdcmi->State = HAL_DCMI_STATE_READY;

  /* Process Unlocked */
  __HAL_UNLOCK(hdcmi);

  return HAL_OK;
}

/**
  * @}
  */

/** @defgroup DCMI_Exported_Functions_Group4 Peripheral State functions
  *  @brief    Peripheral State functions
  *
@verbatim
 ===============================================================================
               ##### Peripheral State and Errors functions #####
 ===============================================================================
    [..]
    This subsection provides functions allowing to
      (+) Check the DCMI state.
      (+) Get the specific DCMI error flag.

@endverbatim
  * @{
  */

/**
  * @brief  Return the DCMI state
  * @param  hdcmi: pointer to a DCMI_HandleTypeDef structure that contains
  *                the configuration information for DCMI.
  * @retval HAL state
  */
HAL_DCMI_StateTypeDef HAL_DCMI_GetState(DCMI_HandleTypeDef *hdcmi)
{
  return hdcmi->State;
}

/**
  * @brief  Return the DCMI error code
  * @param  hdcmi : pointer to a DCMI_HandleTypeDef structure that contains
  *               the configuration information for DCMI.
  * @retval DCMI Error Code
  */
uint32_t HAL_DCMI_GetError(DCMI_HandleTypeDef *hdcmi)
{
  return hdcmi->ErrorCode;
}
/**
  * @}
  */

/* Private functions ---------------------------------------------------------*/
/** @defgroup DCMI_Private_Functions DCMI Private Functions
  * @{
  */

/**
  * @brief  DMA conversion complete callback.
  * @param  hdma: pointer to a DMA_HandleTypeDef structure that contains
  *                the configuration information for the specified DMA module.
  * @retval None
  */
static void DCMI_DMAXferCplt(DMA_HandleTypeDef *hdma)
{
  uint32_t tmp = 0U;

  DCMI_HandleTypeDef* hdcmi = ( DCMI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
  hdcmi->State= HAL_DCMI_STATE_READY;

  if(hdcmi->XferCount != 0U)
  {
    /* Update memory 0 address location */
    tmp = ((hdcmi->DMA_Handle->Instance->CR) & DMA_SxCR_CT);
    if(((hdcmi->XferCount % 2U) == 0U) && (tmp != 0U))
    {
      tmp = hdcmi->DMA_Handle->Instance->M0AR;
      HAL_DMAEx_ChangeMemory(hdcmi->DMA_Handle, (tmp + (8U*hdcmi->XferSize)), MEMORY0);
      hdcmi->XferCount--;
    }
    /* Update memory 1 address location */
    else if((hdcmi->DMA_Handle->Instance->CR & DMA_SxCR_CT) == 0U)
    {
      tmp = hdcmi->DMA_Handle->Instance->M1AR;
      HAL_DMAEx_ChangeMemory(hdcmi->DMA_Handle, (tmp + (8U*hdcmi->XferSize)), MEMORY1);
      hdcmi->XferCount--;
    }
  }
  /* Update memory 0 address location */
  else if((hdcmi->DMA_Handle->Instance->CR & DMA_SxCR_CT) != 0U)
  {
    hdcmi->DMA_Handle->Instance->M0AR = hdcmi->pBuffPtr;
  }
  /* Update memory 1 address location */
  else if((hdcmi->DMA_Handle->Instance->CR & DMA_SxCR_CT) == 0U)
  {
    tmp = hdcmi->pBuffPtr;
    hdcmi->DMA_Handle->Instance->M1AR = (tmp + (4U*hdcmi->XferSize));
    hdcmi->XferCount = hdcmi->XferTransferNumber;
  }

  /* Enable the Frame interrupt */
  __HAL_DCMI_ENABLE_IT(hdcmi, DCMI_IT_FRAME);
}

/**
  * @brief  DMA error callback
  * @param  hdma: pointer to a DMA_HandleTypeDef structure that contains
  *                the configuration information for the specified DMA module.
  * @retval None
  */
static void DCMI_DMAError(DMA_HandleTypeDef *hdma)
{
  DCMI_HandleTypeDef* hdcmi = ( DCMI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
  hdcmi->State= HAL_DCMI_STATE_READY;
  HAL_DCMI_ErrorCallback(hdcmi);
}
/**
  * @}
  */

/**
  * @}
  */
#endif /* STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx ||\
          STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx ||\
          STM32F479xx */
#endif /* HAL_DCMI_MODULE_ENABLED */
/**
  * @}
  */

/**
  * @}
  */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/


text:
Writing a story ? Find an expert.

        <input ng-change="doSearch()" style="width:500px; margin: 0 auto;" placeholder="Search for an expert in ..." class="search" ng-model="search" type="text">

{{ search }} experts in your area

{{expert.profile.name}}

{{expert.description}}

{{expert.expertise}}

Writing an article?

An expert can enrich your story and give you input.

Find an expert

Search for skills and find a matching influencer near you.

Connect & Meet

Send an enquiry to the expert. Connect, meet & write an awesome story.

Sign up as an expert

              Register

redpajama_set_name: RedPajamaGithub


text:
package com.dropbox.djinni.ideaplugin;

import com.dropbox.djinni.ideaplugin.psi.DjinniConstReference;
import com.dropbox.djinni.ideaplugin.psi.DjinniExternStatement;
import com.dropbox.djinni.ideaplugin.psi.DjinniImportStatement;
import com.dropbox.djinni.ideaplugin.psi.DjinniTypeReference;
import com.intellij.openapi.util.TextRange;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.*;
import com.intellij.util.ProcessingContext;
import org.jetbrains.annotations.NotNull;

/**
 * Created by jaetzold on 7/28/15.
 */
public class DjinniReferenceContributor extends PsiReferenceContributor {
  @Override
  public void registerReferenceProviders(@NotNull PsiReferenceRegistrar registrar) {
    registrar.registerReferenceProvider(PlatformPatterns.psiElement(DjinniTypeReference.class), new PsiReferenceProvider() {
      @NotNull
      @Override
      public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {
        DjinniTypeReference typeReference = (DjinniTypeReference)element;
        String text = typeReference.getText();
        if(text != null && text.length() > 0) {
          return new PsiReference[] {new DjinniReference(element, new TextRange(0, text.length()))};
        }
        return new PsiReference[0];
      }

    });
    registrar.registerReferenceProvider(PlatformPatterns.psiElement(DjinniConstReference.class), new PsiReferenceProvider() {
      @NotNull
      @Override
      public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {
        DjinniConstReference constReference = (DjinniConstReference)element;
        String name = constReference.getName();
        if(name != null && name.length() > 0) {
          return new PsiReference[] {new DjinniValueReference(constReference, new TextRange(0, name.length()))};
        }
        return new PsiReference[0];
      }

    });
    registrar.registerReferenceProvider(PlatformPatterns.psiElement(DjinniImportStatement.class), new PsiReferenceProvider() {
      @NotNull
      @Override
      public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {
        DjinniImportStatement importStatement = (DjinniImportStatement)element;
        TextRange importRange = importStatement.getTextRange();
        TextRange pathRange = importStatement.getStringLiteral().getTextRange();
        if(pathRange.getLength() > 2) {
          TextRange rangeInElement = new TextRange((pathRange.getStartOffset() - importRange.getStartOffset()) + 1,
                                                   (pathRange.getEndOffset() - importRange.getStartOffset()) - 1);
          DjinniImportReference djinniImportReference = new DjinniImportReference(element, rangeInElement);
          return new PsiReference[] {djinniImportReference};
        }
        return new PsiReference[0];
      }
    });
    registrar.registerReferenceProvider(PlatformPatterns.psiElement(DjinniExternStatement.class), new PsiReferenceProvider() {
      @NotNull
      @Override
      public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {
        DjinniExternStatement externStatement = (DjinniExternStatement)element;
        TextRange importRange = externStatement.getTextRange();
        TextRange pathRange = externStatement.getStringLiteral().getTextRange();
        if(pathRange.getLength() > 2) {
          TextRange rangeInElement = new TextRange((pathRange.getStartOffset() - importRange.getStartOffset()) + 1,
                                                   (pathRange.getEndOffset() - importRange.getStartOffset()) - 1);
          DjinniExternReference djinniExternReference = new DjinniExternReference(element, rangeInElement);
          return new PsiReference[] {djinniExternReference};
        }
        return new PsiReference[0];
      }
    });
  }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Swagger UI</title>

    <link href='libs/swagger-ui/dist/css/typography.css' media='screen' rel='stylesheet' type='text/css'/>
    <link href='libs/swagger-ui/dist/css/reset.css' media='screen' rel='stylesheet' type='text/css'/>
    <link href='libs/swagger-ui/dist/css/screen.css' media='screen' rel='stylesheet' type='text/css'/>
    <link href='libs/swagger-ui/dist/css/reset.css' media='print' rel='stylesheet' type='text/css'/>
    <link href='libs/swagger-ui/dist/css/print.css' media='print' rel='stylesheet' type='text/css'/>


text:
#include <aws/core/utils/Outcome.h>
#include <aws/core/auth/AWSAuthSigner.h>
#include <aws/core/client/CoreErrors.h>
#include <aws/core/client/RetryStrategy.h>
#include <aws/core/http/HttpClient.h>
#include <aws/core/http/HttpResponse.h>
#include <aws/core/http/HttpClientFactory.h>
#include <aws/core/auth/AWSCredentialsProviderChain.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <aws/core/utils/threading/Executor.h>
#include <aws/core/utils/DNS.h>
#include <aws/core/utils/logging/LogMacros.h>
#include <aws/core/utils/logging/ErrorMacros.h>

#include <aws/sagemaker-featurestore-runtime/SageMakerFeatureStoreRuntimeClient.h>
#include <aws/sagemaker-featurestore-runtime/SageMakerFeatureStoreRuntimeErrorMarshaller.h>
#include <aws/sagemaker-featurestore-runtime/SageMakerFeatureStoreRuntimeEndpointProvider.h>
#include <aws/sagemaker-featurestore-runtime/model/BatchGetRecordRequest.h>
#include <aws/sagemaker-featurestore-runtime/model/DeleteRecordRequest.h>
#include <aws/sagemaker-featurestore-runtime/model/GetRecordRequest.h>
#include <aws/sagemaker-featurestore-runtime/model/PutRecordRequest.h>

using namespace Aws;
using namespace Aws::Auth;
using namespace Aws::Client;
using namespace Aws::SageMakerFeatureStoreRuntime;
using namespace Aws::SageMakerFeatureStoreRuntime::Model;
using namespace Aws::Http;
using namespace Aws::Utils::Json;
using ResolveEndpointOutcome = Aws::Endpoint::ResolveEndpointOutcome;

const char* SageMakerFeatureStoreRuntimeClient::SERVICE_NAME = "sagemaker";
const char* SageMakerFeatureStoreRuntimeClient::ALLOCATION_TAG = "SageMakerFeatureStoreRuntimeClient";

SageMakerFeatureStoreRuntimeClient::SageMakerFeatureStoreRuntimeClient(const SageMakerFeatureStoreRuntime::SageMakerFeatureStoreRuntimeClientConfiguration& clientConfiguration,
                                                                       std::shared_ptr<SageMakerFeatureStoreRuntimeEndpointProviderBase> endpointProvider) :
  BASECLASS(clientConfiguration,
            Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG,
                                             Aws::MakeShared<DefaultAWSCredentialsProviderChain>(ALLOCATION_TAG),
                                             SERVICE_NAME,
                                             Aws::Region::ComputeSignerRegion(clientConfiguration.region)),
            Aws::MakeShared<SageMakerFeatureStoreRuntimeErrorMarshaller>(ALLOCATION_TAG)),
  m_clientConfiguration(clientConfiguration),
  m_executor(clientConfiguration.executor),
  m_endpointProvider(std::move(endpointProvider))
{
  init(m_clientConfiguration);
}

SageMakerFeatureStoreRuntimeClient::SageMakerFeatureStoreRuntimeClient(const AWSCredentials& credentials,
                                                                       std::shared_ptr<SageMakerFeatureStoreRuntimeEndpointProviderBase> endpointProvider,
                                                                       const SageMakerFeatureStoreRuntime::SageMakerFeatureStoreRuntimeClientConfiguration& clientConfiguration) :
  BASECLASS(clientConfiguration,
            Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG,
                                             Aws::MakeShared<SimpleAWSCredentialsProvider>(ALLOCATION_TAG, credentials),
                                             SERVICE_NAME,
                                             Aws::Region::ComputeSignerRegion(clientConfiguration.region)),
            Aws::MakeShared<SageMakerFeatureStoreRuntimeErrorMarshaller>(ALLOCATION_TAG)),
    m_clientConfiguration(clientConfiguration),
    m_executor(clientConfiguration.executor),
    m_endpointProvider(std::move(endpointProvider))
{
  init(m_clientConfiguration);
}

SageMakerFeatureStoreRuntimeClient::SageMakerFeatureStoreRuntimeClient(const std::shared_ptr<AWSCredentialsProvider>& credentialsProvider,
                                                                       std::shared_ptr<SageMakerFeatureStoreRuntimeEndpointProviderBase> endpointProvider,
                                                                       const SageMakerFeatureStoreRuntime::SageMakerFeatureStoreRuntimeClientConfiguration& clientConfiguration) :
  BASECLASS(clientConfiguration,
            Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG,
                                             credentialsProvider,
                                             SERVICE_NAME,
                                             Aws::Region::ComputeSignerRegion(clientConfiguration.region)),
            Aws::MakeShared<SageMakerFeatureStoreRuntimeErrorMarshaller>(ALLOCATION_TAG)),
    m_clientConfiguration(clientConfiguration),
    m_executor(clientConfiguration.executor),
    m_endpointProvider(std::move(endpointProvider))
{
  init(m_clientConfiguration);
}

    /* Legacy constructors due deprecation */
  SageMakerFeatureStoreRuntimeClient::SageMakerFeatureStoreRuntimeClient(const Client::ClientConfiguration& clientConfiguration) :
  BASECLASS(clientConfiguration,
            Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG,
                                             Aws::MakeShared<DefaultAWSCredentialsProviderChain>(ALLOCATION_TAG),
                                             SERVICE_NAME,
                                             Aws::Region::ComputeSignerRegion(clientConfiguration.region)),
            Aws::MakeShared<SageMakerFeatureStoreRuntimeErrorMarshaller>(ALLOCATION_TAG)),
  m_clientConfiguration(clientConfiguration),
  m_executor(clientConfiguration.executor),
  m_endpointProvider(Aws::MakeShared<SageMakerFeatureStoreRuntimeEndpointProvider>(ALLOCATION_TAG))
{
  init(m_clientConfiguration);
}

SageMakerFeatureStoreRuntimeClient::SageMakerFeatureStoreRuntimeClient(const AWSCredentials& credentials,
                                                                       const Client::ClientConfiguration& clientConfiguration) :
  BASECLASS(clientConfiguration,
            Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG,
                                             Aws::MakeShared<SimpleAWSCredentialsProvider>(ALLOCATION_TAG, credentials),
                                             SERVICE_NAME,
                                             Aws::Region::ComputeSignerRegion(clientConfiguration.region)),
            Aws::MakeShared<SageMakerFeatureStoreRuntimeErrorMarshaller>(ALLOCATION_TAG)),
    m_clientConfiguration(clientConfiguration),
    m_executor(clientConfiguration.executor),
    m_endpointProvider(Aws::MakeShared<SageMakerFeatureStoreRuntimeEndpointProvider>(ALLOCATION_TAG))
{
  init(m_clientConfiguration);
}

SageMakerFeatureStoreRuntimeClient::SageMakerFeatureStoreRuntimeClient(const std::shared_ptr<AWSCredentialsProvider>& credentialsProvider,
                                                                       const Client::ClientConfiguration& clientConfiguration) :
  BASECLASS(clientConfiguration,
            Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG,
                                             credentialsProvider,
                                             SERVICE_NAME,
                                             Aws::Region::ComputeSignerRegion(clientConfiguration.region)),
            Aws::MakeShared<SageMakerFeatureStoreRuntimeErrorMarshaller>(ALLOCATION_TAG)),
    m_clientConfiguration(clientConfiguration),
    m_executor(clientConfiguration.executor),
    m_endpointProvider(Aws::MakeShared<SageMakerFeatureStoreRuntimeEndpointProvider>(ALLOCATION_TAG))
{
  init(m_clientConfiguration);
}

    /* End of legacy constructors due deprecation */
SageMakerFeatureStoreRuntimeClient::~SageMakerFeatureStoreRuntimeClient()
{
}

std::shared_ptr<SageMakerFeatureStoreRuntimeEndpointProviderBase>& SageMakerFeatureStoreRuntimeClient::accessEndpointProvider()
{
  return m_endpointProvider;
}

void SageMakerFeatureStoreRuntimeClient::init(const SageMakerFeatureStoreRuntime::SageMakerFeatureStoreRuntimeClientConfiguration& config)
{
  AWSClient::SetServiceClientName("SageMaker FeatureStore Runtime");
  AWS_CHECK_PTR(SERVICE_NAME, m_endpointProvider);
  m_endpointProvider->InitBuiltInParameters(config);
}

void SageMakerFeatureStoreRuntimeClient::OverrideEndpoint(const Aws::String& endpoint)
{
  AWS_CHECK_PTR(SERVICE_NAME, m_endpointProvider);
  m_endpointProvider->OverrideEndpoint(endpoint);
}

BatchGetRecordOutcome SageMakerFeatureStoreRuntimeClient::BatchGetRecord(const BatchGetRecordRequest& request) const
{
  AWS_OPERATION_CHECK_PTR(m_endpointProvider, BatchGetRecord, CoreErrors, CoreErrors::ENDPOINT_RESOLUTION_FAILURE);
  ResolveEndpointOutcome endpointResolutionOutcome = m_endpointProvider->ResolveEndpoint(request.GetEndpointContextParams());
  AWS_OPERATION_CHECK_SUCCESS(endpointResolutionOutcome, BatchGetRecord, CoreErrors, CoreErrors::ENDPOINT_RESOLUTION_FAILURE, endpointResolutionOutcome.GetError().GetMessage());
  endpointResolutionOutcome.GetResult().AddPathSegments("/BatchGetRecord");
  return BatchGetRecordOutcome(MakeRequest(request, endpointResolutionOutcome.GetResult(), Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER));
}

BatchGetRecordOutcomeCallable SageMakerFeatureStoreRuntimeClient::BatchGetRecordCallable(const BatchGetRecordRequest& request) const
{
  auto task = Aws::MakeShared< std::packaged_task< BatchGetRecordOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->BatchGetRecord(request); } );
  auto packagedFunction = [task]() { (*task)(); };
  m_executor->Submit(packagedFunction);
  return task->get_future();
}

void SageMakerFeatureStoreRuntimeClient::BatchGetRecordAsync(const BatchGetRecordRequest& request, const BatchGetRecordResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
  m_executor->Submit( [this, request, handler, context]()
    {
      handler(this, request, BatchGetRecord(request), context);
    } );
}

DeleteRecordOutcome SageMakerFeatureStoreRuntimeClient::DeleteRecord(const DeleteRecordRequest& request) const
{
  AWS_OPERATION_CHECK_PTR(m_endpointProvider, DeleteRecord, CoreErrors, CoreErrors::ENDPOINT_RESOLUTION_FAILURE);
  if (!request.FeatureGroupNameHasBeenSet())
  {
    AWS_LOGSTREAM_ERROR("DeleteRecord", "Required field: FeatureGroupName, is not set");
    return DeleteRecordOutcome(Aws::Client::AWSError<SageMakerFeatureStoreRuntimeErrors>(SageMakerFeatureStoreRuntimeErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [FeatureGroupName]", false));
  }
  if (!request.RecordIdentifierValueAsStringHasBeenSet())
  {
    AWS_LOGSTREAM_ERROR("DeleteRecord", "Required field: RecordIdentifierValueAsString, is not set");
    return DeleteRecordOutcome(Aws::Client::AWSError<SageMakerFeatureStoreRuntimeErrors>(SageMakerFeatureStoreRuntimeErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [RecordIdentifierValueAsString]", false));
  }
  if (!request.EventTimeHasBeenSet())
  {
    AWS_LOGSTREAM_ERROR("DeleteRecord", "Required field: EventTime, is not set");
    return DeleteRecordOutcome(Aws::Client::AWSError<SageMakerFeatureStoreRuntimeErrors>(SageMakerFeatureStoreRuntimeErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [EventTime]", false));
  }
  ResolveEndpointOutcome endpointResolutionOutcome = m_endpointProvider->ResolveEndpoint(request.GetEndpointContextParams());
  AWS_OPERATION_CHECK_SUCCESS(endpointResolutionOutcome, DeleteRecord, CoreErrors, CoreErrors::ENDPOINT_RESOLUTION_FAILURE, endpointResolutionOutcome.GetError().GetMessage());
  endpointResolutionOutcome.GetResult().AddPathSegments("/FeatureGroup/");
  endpointResolutionOutcome.GetResult().AddPathSegment(request.GetFeatureGroupName());
  return DeleteRecordOutcome(MakeRequest(request, endpointResolutionOutcome.GetResult(), Aws::Http::HttpMethod::HTTP_DELETE, Aws::Auth::SIGV4_SIGNER));
}

DeleteRecordOutcomeCallable SageMakerFeatureStoreRuntimeClient::DeleteRecordCallable(const DeleteRecordRequest& request) const
{
  auto task = Aws::MakeShared< std::packaged_task< DeleteRecordOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteRecord(request); } );
  auto packagedFunction = [task]() { (*task)(); };
  m_executor->Submit(packagedFunction);
  return task->get_future();
}

void SageMakerFeatureStoreRuntimeClient::DeleteRecordAsync(const DeleteRecordRequest& request, const DeleteRecordResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
  m_executor->Submit( [this, request, handler, context]()
    {
      handler(this, request, DeleteRecord(request), context);
    } );
}

GetRecordOutcome SageMakerFeatureStoreRuntimeClient::GetRecord(const GetRecordRequest& request) const
{
  AWS_OPERATION_CHECK_PTR(m_endpointProvider, GetRecord, CoreErrors, CoreErrors::ENDPOINT_RESOLUTION_FAILURE);
  if (!request.FeatureGroupNameHasBeenSet())
  {
    AWS_LOGSTREAM_ERROR("GetRecord", "Required field: FeatureGroupName, is not set");
    return GetRecordOutcome(Aws::Client::AWSError<SageMakerFeatureStoreRuntimeErrors>(SageMakerFeatureStoreRuntimeErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [FeatureGroupName]", false));
  }
  if (!request.RecordIdentifierValueAsStringHasBeenSet())
  {
    AWS_LOGSTREAM_ERROR("GetRecord", "Required field: RecordIdentifierValueAsString, is not set");
    return GetRecordOutcome(Aws::Client::AWSError<SageMakerFeatureStoreRuntimeErrors>(SageMakerFeatureStoreRuntimeErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [RecordIdentifierValueAsString]", false));
  }
  ResolveEndpointOutcome endpointResolutionOutcome = m_endpointProvider->ResolveEndpoint(request.GetEndpointContextParams());
  AWS_OPERATION_CHECK_SUCCESS(endpointResolutionOutcome, GetRecord, CoreErrors, CoreErrors::ENDPOINT_RESOLUTION_FAILURE, endpointResolutionOutcome.GetError().GetMessage());
  endpointResolutionOutcome.GetResult().AddPathSegments("/FeatureGroup/");
  endpointResolutionOutcome.GetResult().AddPathSegment(request.GetFeatureGroupName());
  return GetRecordOutcome(MakeRequest(request, endpointResolutionOutcome.GetResult(), Aws::Http::HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER));
}

GetRecordOutcomeCallable SageMakerFeatureStoreRuntimeClient::GetRecordCallable(const GetRecordRequest& request) const
{
  auto task = Aws::MakeShared< std::packaged_task< GetRecordOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetRecord(request); } );
  auto packagedFunction = [task]() { (*task)(); };
  m_executor->Submit(packagedFunction);
  return task->get_future();
}

void SageMakerFeatureStoreRuntimeClient::GetRecordAsync(const GetRecordRequest& request, const GetRecordResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
  m_executor->Submit( [this, request, handler, context]()
    {
      handler(this, request, GetRecord(request), context);
    } );
}

PutRecordOutcome SageMakerFeatureStoreRuntimeClient::PutRecord(const PutRecordRequest& request) const
{
  AWS_OPERATION_CHECK_PTR(m_endpointProvider, PutRecord, CoreErrors, CoreErrors::ENDPOINT_RESOLUTION_FAILURE);
  if (!request.FeatureGroupNameHasBeenSet())
  {
    AWS_LOGSTREAM_ERROR("PutRecord", "Required field: FeatureGroupName, is not set");
    return PutRecordOutcome(Aws::Client::AWSError<SageMakerFeatureStoreRuntimeErrors>(SageMakerFeatureStoreRuntimeErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [FeatureGroupName]", false));
  }
  ResolveEndpointOutcome endpointResolutionOutcome = m_endpointProvider->ResolveEndpoint(request.GetEndpointContextParams());
  AWS_OPERATION_CHECK_SUCCESS(endpointResolutionOutcome, PutRecord, CoreErrors, CoreErrors::ENDPOINT_RESOLUTION_FAILURE, endpointResolutionOutcome.GetError().GetMessage());
  endpointResolutionOutcome.GetResult().AddPathSegments("/FeatureGroup/");
  endpointResolutionOutcome.GetResult().AddPathSegment(request.GetFeatureGroupName());
  return PutRecordOutcome(MakeRequest(request, endpointResolutionOutcome.GetResult(), Aws::Http::HttpMethod::HTTP_PUT, Aws::Auth::SIGV4_SIGNER));
}

PutRecordOutcomeCallable SageMakerFeatureStoreRuntimeClient::PutRecordCallable(const PutRecordRequest& request) const
{
  auto task = Aws::MakeShared< std::packaged_task< PutRecordOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->PutRecord(request); } );
  auto packagedFunction = [task]() { (*task)(); };
  m_executor->Submit(packagedFunction);
  return task->get_future();
}

void SageMakerFeatureStoreRuntimeClient::PutRecordAsync(const PutRecordRequest& request, const PutRecordResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
  m_executor->Submit( [this, request, handler, context]()
    {
      handler(this, request, PutRecord(request), context);
    } );
}


text:
using System.Reflection;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.

// Review the values of the assembly attributes
[assembly: AssemblyTitle("CKEditor Provider")]
[assembly: AssemblyCompany("WatchersNET")]
[assembly: AssemblyProduct("CKEditor Provider")]
[assembly: AssemblyCopyright("© Ingo Herbote")]
[assembly: AssemblyTrademark("")]

[assembly: ComVisible(false)]

[assembly: AssemblyVersion("2.01.0.0")]
[assembly: AssemblyFileVersion("2.01.0.0")]


text:
#ifndef CJET_LINUX_EVENTLOOP_H
#define CJET_LINUX_EVENTLOOP_H

#ifdef __cplusplus
extern "C" {
#endif

#include "generated/os_config.h"

/**
 * @brief The eventloop_return enum defines the allowed return values of eventloop callback functions.
 */
enum eventloop_return {
	EL_ABORT_LOOP,    /**< The eventloop will be aborted. */
	EL_CONTINUE_LOOP, /**< The eventloop will continue to run. */
	EL_EVENT_REMOVED, /**< The event was removed from the eventloop in the callback.
	                    The eventloop will continue but will not process further events on the signaled IO channel. */
};

struct eventloop;
struct io_event;

typedef enum eventloop_return (*eventloop_function)(struct io_event *ev);

struct io_event {
	socket_type sock;
	eventloop_function read_function;
	eventloop_function write_function;
	eventloop_function error_function;
	struct eventloop *loop;
};

struct eventloop {
	void *this_ptr;
	int (*init)(void *this_ptr);
	void (*destroy)(const void *this_ptr);
	int (*run)(void *this_ptr, const int *go_ahead);
	enum eventloop_return (*add)(const void *this_ptr, const struct io_event *ev);
	void (*remove)(void *this_ptr, const struct io_event *ev);
};

#ifdef __cplusplus
}
#endif

#endif


text:
<?php
/**
 * REST API WC Payment gateways controller
 *
 * Handles requests to the /payment_gateways endpoint.
 *
 * @author   WooThemes
 * @category API
 * @package  WooCommerce/API
 * @since    3.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * @package WooCommerce/API
 * @extends WC_REST_Controller
 */
class WC_REST_Payment_Gateways_Controller extends WC_REST_Controller {

	/**
	 * Endpoint namespace.
	 *
	 * @var string
	 */
	protected $namespace = 'wc/v2';

	/**
	 * Route base.
	 *
	 * @var string
	 */
	protected $rest_base = 'payment_gateways';

	/**
	 * Register the route for /payment_gateways and /payment_gateways/<id>
	 */
	public function register_routes() {
		register_rest_route( $this->namespace, '/' . $this->rest_base, array(
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_items' ),
				'permission_callback' => array( $this, 'get_items_permissions_check' ),
				'args'                => $this->get_collection_params(),
			),
			'schema' => array( $this, 'get_public_item_schema' ),
		) );
		register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[\w-]+)', array(
			'args' => array(
				'id' => array(
					'description' => __( 'Unique identifier for the resource.', 'woocommerce' ),
					'type'        => 'string',
				),
			),
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_item' ),
				'permission_callback' => array( $this, 'get_item_permissions_check' ),
				'args'                => array(
					'context' => $this->get_context_param( array( 'default' => 'view' ) ),
				),
			),
			array(
				'methods'             => WP_REST_Server::EDITABLE,
				'callback'            => array( $this, 'update_item' ),
				'permission_callback' => array( $this, 'update_items_permissions_check' ),
				'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
			),
			'schema' => array( $this, 'get_public_item_schema' ),
		) );
	}

	/**
	 * Check whether a given request has permission to view payment gateways.
	 *
	 * @param  WP_REST_Request $request Full details about the request.
	 * @return WP_Error|boolean
	 */
	public function get_items_permissions_check( $request ) {
		if ( ! wc_rest_check_manager_permissions( 'payment_gateways', 'read' ) ) {
			return new WP_Error( 'woocommerce_rest_cannot_view', __( 'Sorry, you cannot list resources.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
		}
		return true;
	}

	/**
	 * Check if a given request has access to read a payment gateway.
	 *
	 * @param  WP_REST_Request $request Full details about the request.
	 * @return WP_Error|boolean
	 */
	public function get_item_permissions_check( $request ) {
		if ( ! wc_rest_check_manager_permissions( 'payment_gateways', 'read' ) ) {
			return new WP_Error( 'woocommerce_rest_cannot_view', __( 'Sorry, you cannot view this resource.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
		}
		return true;
	}

	/**
	 * Check whether a given request has permission to edit payment gateways.
	 *
	 * @param  WP_REST_Request $request Full details about the request.
	 * @return WP_Error|boolean
	 */
	public function update_items_permissions_check( $request ) {
		if ( ! wc_rest_check_manager_permissions( 'payment_gateways', 'edit' ) ) {
			return new WP_Error( 'woocommerce_rest_cannot_edit', __( 'Sorry, you are not allowed to edit this resource.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
		}
		return true;
	}

	/**
	 * Get payment gateways.
	 *
	 * @param WP_REST_Request $request Full details about the request.
	 * @return WP_Error|WP_REST_Response
	 */
	public function get_items( $request ) {
		$payment_gateways = WC()->payment_gateways->payment_gateways();
		$response         = array();
		foreach ( $payment_gateways as $payment_gateway_id => $payment_gateway ) {
			$payment_gateway->id = $payment_gateway_id;
			$gateway             = $this->prepare_item_for_response( $payment_gateway, $request );
			$gateway             = $this->prepare_response_for_collection( $gateway );
			$response[]          = $gateway;
		}
		return rest_ensure_response( $response );
	}

	/**
	 * Get a single payment gateway.
	 *
	 * @param WP_REST_Request $request
	 * @return WP_REST_Response|WP_Error
	 */
	public function get_item( $request ) {
		$gateway = $this->get_gateway( $request );

		if ( is_null( $gateway ) ) {
			return new WP_Error( 'woocommerce_rest_payment_gateway_invalid', __( 'Resource does not exist.', 'woocommerce' ), array( 'status' => 404 ) );
		}

		$gateway = $this->prepare_item_for_response( $gateway, $request );
		return rest_ensure_response( $gateway );
	}

	/**
	 * Update A Single Shipping Zone Method.
	 *
	 * @param WP_REST_Request $request
	 * @return WP_REST_Response|WP_Error
	 */
	public function update_item( $request ) {
		$gateway = $this->get_gateway( $request );

		if ( is_null( $gateway ) ) {
			return new WP_Error( 'woocommerce_rest_payment_gateway_invalid', __( 'Resource does not exist.', 'woocommerce' ), array( 'status' => 404 ) );
		}

		// Get settings.
		$gateway->init_form_fields();
		$settings = $gateway->settings;

		// Update settings.
		if ( isset( $request['settings'] ) ) {
			$errors_found = false;
			foreach ( $gateway->form_fields as $key => $field ) {
				if ( isset( $request['settings'][ $key ] ) ) {
					if ( is_callable( array( $this, 'validate_setting_' . $field['type'] . '_field' ) ) ) {
						$value = $this->{'validate_setting_' . $field['type'] . '_field'}( $request['settings'][ $key ], $field );
					} else {
						$value = $this->validate_setting_text_field( $request['settings'][ $key ], $field );
					}
					if ( is_wp_error( $value ) ) {
						$errors_found = true;
						break;
					}
					$settings[ $key ] = $value;
				}
			}

			if ( $errors_found ) {
				return new WP_Error( 'rest_setting_value_invalid', __( 'An invalid setting value was passed.', 'woocommerce' ), array( 'status' => 400 ) );
			}
		}

		// Update if this method is enabled or not.
		if ( isset( $request['enabled'] ) ) {
			$gateway->enabled = $settings['enabled'] = wc_bool_to_string( $request['enabled'] );
		}

		// Update title.
		if ( isset( $request['title'] ) ) {
			$gateway->title = $settings['title'] = $request['title'];
		}

		// Update description.
		if ( isset( $request['description'] ) ) {
			$gateway->description = $settings['description'] = $request['description'];
		}

		// Update options.
		$gateway->settings = $settings;
		update_option( $gateway->get_option_key(), apply_filters( 'woocommerce_gateway_' . $gateway->id . '_settings_values', $settings, $gateway ) );

		// Update order
		if ( isset( $request['order'] ) ) {
			$order  = (array) get_option( 'woocommerce_gateway_order' );
			$order[ $gateway->id ] = $request['order'];
			update_option( 'woocommerce_gateway_order', $order );
			$gateway->order = absint( $request['order'] );
		}

		$gateway = $this->prepare_item_for_response( $gateway, $request );
		return rest_ensure_response( $gateway );
	}

	/**
	 * Get a gateway based on the current request object.
	 *
	 * @param WP_REST_Request $request
	 * @return WP_REST_Response|null
	 */
	public function get_gateway( $request ) {
		$gateway          = null;
		$payment_gateways = WC()->payment_gateways->payment_gateways();
		foreach ( $payment_gateways as $payment_gateway_id => $payment_gateway ) {
			if ( $request['id'] !== $payment_gateway_id ) {
				continue;
			}
			$payment_gateway->id = $payment_gateway_id;
			$gateway             = $payment_gateway;
		}
		return $gateway;
	}

	/**
	 * Prepare a payment gateway for response.
	 *
	 * @param  WC_Payment_Gateway $gateway    Payment gateway object.
	 * @param  WP_REST_Request    $request    Request object.
	 * @return WP_REST_Response   $response   Response data.
	 */
	public function prepare_item_for_response( $gateway, $request ) {
		$order  = (array) get_option( 'woocommerce_gateway_order' );
		$item = array(
			'id'                 => $gateway->id,
			'title'              => $gateway->title,
			'description'        => $gateway->description,
			'order'              => isset( $order[ $gateway->id ] ) ? $order[ $gateway->id ] : '',
			'enabled'            => ( 'yes' === $gateway->enabled ),
			'method_title'       => $gateway->get_method_title(),
			'method_description' => $gateway->get_method_description(),
			'settings'           => $this->get_settings( $gateway ),
		);

		$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
		$data    = $this->add_additional_fields_to_object( $item, $request );
		$data    = $this->filter_response_by_context( $data, $context );

		$response = rest_ensure_response( $data );
		$response->add_links( $this->prepare_links( $gateway, $request ) );

		/**
		 * Filter payment gateway objects returned from the REST API.
		 *
		 * @param WP_REST_Response   $response The response object.
		 * @param WC_Payment_Gateway $gateway  Payment gateway object.
		 * @param WP_REST_Request    $request  Request object.
		 */
		return apply_filters( 'woocommerce_rest_prepare_payment_gateway', $response, $gateway, $request );
	}

	/**
	 * Return settings associated with this payment gateway.
	 */
	public function get_settings( $gateway ) {
		$settings = array();
		$gateway->init_form_fields();
		foreach ( $gateway->form_fields as $id => $field ) {
			// Make sure we at least have a title and type
			if ( empty( $field['title'] ) || empty( $field['type'] ) ) {
				continue;
			}
			// Ignore 'title' settings/fields -- they are UI only
			if ( 'title' === $field['type'] ) {
				continue;
			}
			// Ignore 'enabled' and 'description' which get included elsewhere.
			if ( in_array( $id, array( 'enabled', 'description' ) ) ) {
				continue;
			}
			$data = array(
				'id'          => $id,
				'label'       => empty( $field['label'] ) ? $field['title'] : $field['label'],
				'description' => empty( $field['description'] ) ? '' : $field['description'],
				'type'        => $field['type'],
				'value'       => empty( $gateway->settings[ $id ] ) ? '' : $gateway->settings[ $id ],
				'default'     => empty( $field['default'] ) ? '' : $field['default'],
				'tip'         => empty( $field['description'] ) ? '' : $field['description'],
				'placeholder' => empty( $field['placeholder'] ) ? '' : $field['placeholder'],
			);
			if ( ! empty( $field['options'] ) ) {
				$data['options'] = $field['options'];
			}
			$settings[ $id ] = $data;
		}
		return $settings;
	}

	/**
	 * Prepare links for the request.
	 *
	 * @param  WC_Payment_Gateway $gateway    Payment gateway object.
	 * @param  WP_REST_Request    $request    Request object.
	 * @return array
	 */
	protected function prepare_links( $gateway, $request ) {
		$links      = array(
			'self' => array(
				'href' => rest_url( sprintf( '/%s/%s/%s', $this->namespace, $this->rest_base, $gateway->id ) ),
			),
			'collection' => array(
				'href' => rest_url( sprintf( '/%s/%s', $this->namespace, $this->rest_base ) ),
			),
		);

		return $links;
	}

    /**
	 * Get the payment gateway schema, conforming to JSON Schema.
	 *
	 * @return array
	 */
	public function get_item_schema() {
		$schema = array(
			'$schema'    => 'http://json-schema.org/draft-04/schema#',
			'title'      => 'payment_gateway',
			'type'       => 'object',
			'properties' => array(
				'id' => array(
					'description' => __( 'Payment gateway ID.', 'woocommerce' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
					'readonly'    => true,
				),
				'title' => array(
					'description' => __( 'Payment gateway title on checkout.', 'woocommerce' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
				),
				'description' => array(
					'description' => __( 'Payment gateway description on checkout.', 'woocommerce' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
				),
				'order' => array(
					'description' => __( 'Payment gateway sort order.', 'woocommerce' ),
					'type'        => 'integer',
					'context'     => array( 'view', 'edit' ),
					'arg_options' => array(
						'sanitize_callback' => 'absint',
					),
				),
				'enabled' => array(
					'description' => __( 'Payment gateway enabled status.', 'woocommerce' ),
					'type'        => 'boolean',
					'context'     => array( 'view', 'edit' ),
				),
				'method_title' => array(
					'description' => __( 'Payment gateway method title.', 'woocommerce' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
					'readonly'    => true,
				),
				'method_description' => array(
					'description' => __( 'Payment gateway method description.', 'woocommerce' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
					'readonly'    => true,
				),
				'settings' => array(
					'description' => __( 'Payment gateway settings.', 'woocommerce' ),
					'type'        => 'object',
					'context'     => array( 'view', 'edit' ),
					'properties' => array(
						'id' => array(
							'description' => __( 'A unique identifier for the setting.', 'woocommerce' ),
							'type'        => 'string',
							'context'     => array( 'view', 'edit' ),
							'readonly'    => true,
						),
						'label' => array(
							'description' => __( 'A human readable label for the setting used in interfaces.', 'woocommerce' ),
							'type'        => 'string',
							'context'     => array( 'view', 'edit' ),
							'readonly'    => true,
						),
						'description' => array(
							'description' => __( 'A human readable description for the setting used in interfaces.', 'woocommerce' ),
							'type'        => 'string',
							'context'     => array( 'view', 'edit' ),
							'readonly'    => true,
						),
						'type' => array(
							'description' => __( 'Type of setting.', 'woocommerce' ),
							'type'        => 'string',
							'context'     => array( 'view', 'edit' ),
							'enum'        => array( 'text', 'email', 'number', 'color', 'password', 'textarea', 'select', 'multiselect', 'radio', 'image_width', 'checkbox' ),
							'readonly'    => true,
						),
						'value' => array(
							'description' => __( 'Setting value.', 'woocommerce' ),
							'type'        => 'string',
							'context'     => array( 'view', 'edit' ),
						),
						'default' => array(
							'description' => __( 'Default value for the setting.', 'woocommerce' ),
							'type'        => 'string',
							'context'     => array( 'view', 'edit' ),
							'readonly'    => true,
						),
						'tip' => array(
							'description' => __( 'Additional help text shown to the user about the setting.', 'woocommerce' ),
							'type'        => 'string',
							'context'     => array( 'view', 'edit' ),
							'readonly'    => true,
						),
						'placeholder' => array(
							'description' => __( 'Placeholder text to be displayed in text inputs.', 'woocommerce' ),
							'type'        => 'string',
							'context'     => array( 'view', 'edit' ),
							'readonly'    => true,
						),
					),
				),
			),
		);

		return $this->add_additional_fields_schema( $schema );
	}

	/**
	 * Get any query params needed.
	 *
	 * @return array
	 */
	public function get_collection_params() {
		return array(
			'context' => $this->get_context_param( array( 'default' => 'view' ) ),
		);
	}

}


text:
package com.moodstocks.phonegap.plugin;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Color;
import android.util.Log;

import com.moodstocks.android.MoodstocksError;
import com.moodstocks.android.Scanner;

public class MoodstocksPlugin extends CordovaPlugin implements
		Scanner.SyncListener {

	public static final String TAG = "MoodstocksPlugin";

	public static final String OPEN = "open";
	public static final String SYNC = "sync";
	public static final String SCAN = "scan";
	public static final String PAUSE = "pause";
	public static final String RESUME = "resume";
	public static final String DISMISS = "dismiss";

	public static final String PLUGINACTION = "com.moodstocks.phonegap.plugin.action";
	public static final String MESSAGE = "message";
	public static final String STATUS = "status";
	public static final String PROGRESS = "progress";

	private CallbackContext syncCallback;
	private static CallbackContext scanCallback;
	private static CordovaWebView overlay;

	private boolean scannerStarted = false;
	public boolean compatible = false;
	private Scanner scanner = null;

	// --------------------------------
	// Moodstocks API key/secret pair
	// --------------------------------
	private static final String API_KEY = "ApIkEy";
	private static final String API_SECRET = "ApIsEcReT";

	public boolean execute(String action, JSONArray args,
			CallbackContext callbackContext) throws JSONException {

		if (action.equals(OPEN)) {
			this.open(callbackContext);

			return true;
		} else if (action.equals(SYNC)) {
			this.syncCallback = callbackContext;
			this.sync();

			return true;
		} else if (action.equals(SCAN)) {
			MoodstocksPlugin.setOverlay(this.webView);
			MoodstocksPlugin.overlay.setBackgroundColor(Color.TRANSPARENT);

			MoodstocksPlugin.setScanCallback(callbackContext);
			this.scan(args);

			return true;
		} else if (action.equals(PAUSE)) {
			this.pause(callbackContext);

			return true;
		} else if (action.equals(RESUME)) {
			this.resume(callbackContext);

			return true;
		} else if (action.equals(DISMISS)) {
			this.dismiss(callbackContext);

			return true;
		}

		return false;
	}

	private void open(CallbackContext callbackContext) {
		compatible = Scanner.isCompatible();
		if (compatible) {
			try {
				this.scanner = Scanner.get();
				scanner.open(
						this.cordova.getActivity().getApplicationContext(),
						API_KEY, API_SECRET);
				callbackContext.success();

			} catch (MoodstocksError e) {
				if (e.getErrorCode() == MoodstocksError.Code.CREDMISMATCH) {
					String errmsg = "There is a problem with your key/secret pair: "
							+ "the current pair does NOT match with the one recorded within the on-disk datastore. "
							+ "This could happen if:
"
							+ " * you have first build & run the app without replacing the default"
							+ " \"ApIkEy\" and \"ApIsEcReT\" pair, and later on replaced with your real key/secret,
"
							+ " * or, you have first made a typo on the key/secret pair, build & run the"
							+ " app, and later on fixed the typo and re-deployed.
"
							+ "
"
							+ "To solve your problem:
"
							+ " 1) uninstall the app from your device,
"
							+ " 2) make sure to properly configure your key/secret pair within Scanner.java
"
							+ " 3) re-build & run
";
					MoodstocksError err = new MoodstocksError(errmsg,
							MoodstocksError.Code.CREDMISMATCH);
					err.log();
					callbackContext.error(errmsg);
				} else {
					e.log();
					callbackContext.error(e.getErrorCode());
				}
			}
		} else {
			/* device is not compatible */
			// error callback with message to display on web view
			callbackContext.error("DEVICE NOT COMPATIBLE");
		}
	}

	private void sync() {
		scanner.sync(this);
	}

	public void scan(JSONArray args) throws JSONException {
		Intent scanIntent = new Intent(cordova.getActivity(),
				MoodstocksScanActivity.class);
		scanIntent.putExtra("com.moodstocks.phonegap.plugin",
				"MoodstocksScanActivity");
		scanIntent.putExtra("scanOptions", args.getInt(0));
		scanIntent.putExtra("useDeviceOrientation", args.getBoolean(1));
		scanIntent.putExtra("noPartialMatching", args.getBoolean(2));
		scanIntent.putExtra("smallTargetSupport", args.getBoolean(3));

		// NOTE: the original startActivityForResult() will pause PhoneGap app's
		// js code. Here we use the one we override
		this.cordova.startActivityForResult(this, scanIntent, 1);

		scannerStarted = true;
	}

	public void pause(CallbackContext callbackContext) {
		if (scannerStarted) {
			Intent pauseIntent = new Intent(PLUGINACTION);
			pauseIntent.putExtra(PLUGINACTION, PAUSE);

			this.cordova.getActivity().sendBroadcast(pauseIntent);
			callbackContext.success();
		}
	}

	public void resume(CallbackContext callbackContext) {
		if (scannerStarted) {
			Intent resumeIntent = new Intent(PLUGINACTION);
			resumeIntent.putExtra(PLUGINACTION, RESUME);

			this.cordova.getActivity().sendBroadcast(resumeIntent);
			callbackContext.success();
		}
	}

	public void dismiss(CallbackContext callbackContext) {
		if (scannerStarted) {
			Intent dismissIntent = new Intent(PLUGINACTION);
			dismissIntent.putExtra(PLUGINACTION, DISMISS);

			this.cordova.getActivity().sendBroadcast(dismissIntent);
			callbackContext.success();
		}
	}

	// Sync Listener

	@Override
	public void onSyncStart() {
		Log.d(TAG, "[SYNC] Starting...");

		JSONObject obj = new JSONObject();

		try {
			obj.put(MESSAGE, "Sync starts.");
			obj.put(STATUS, 1);
			obj.put(PROGRESS, 0);
		} catch (JSONException e) {
			e.printStackTrace();
		}

		PluginResult r = new PluginResult(PluginResult.Status.OK, obj);
		r.setKeepCallback(true);
		this.syncCallback.sendPluginResult(r);
	}

	@Override
	public void onSyncComplete() {
		Log.d(TAG, "[SYNC] Complete!");

		JSONObject obj = new JSONObject();

		try {
			obj.put(MESSAGE, "Sync completed.");
			obj.put(STATUS, 3);
			obj.put(PROGRESS, 100);
		} catch (JSONException e) {
			e.printStackTrace();
		}

		PluginResult r = new PluginResult(PluginResult.Status.OK, obj);
		r.setKeepCallback(false);
		this.syncCallback.sendPluginResult(r);
	}

	@Override
	public void onSyncFailed(MoodstocksError e) {
		e.log();

		JSONObject obj = new JSONObject();

		try {
			obj.put(MESSAGE, "Sync failed with error code " + e.getErrorCode());
			obj.put(STATUS, 0);
			obj.put(PROGRESS, 0);
		} catch (JSONException e1) {
			e1.printStackTrace();
		}

		PluginResult r = new PluginResult(PluginResult.Status.ERROR, obj);
		r.setKeepCallback(false);
		this.syncCallback.sendPluginResult(r);
	}

	@Override
	public void onSyncProgress(int total, int current) {
		Log.d(TAG, "[SYNC] " + current + "/" + total);

		JSONObject obj = new JSONObject();

		try {
			obj.put(MESSAGE, "Sync is progressing.");
			obj.put(STATUS, 2);
			obj.put(PROGRESS, 100 * (current / total));
		} catch (JSONException e) {
			e.printStackTrace();
		}

		PluginResult r = new PluginResult(PluginResult.Status.OK, obj);
		r.setKeepCallback(true);
		this.syncCallback.sendPluginResult(r);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (compatible) {
			try {
				/* you must close the scanner before exiting */
				scanner.close();
			} catch (MoodstocksError e) {
				e.log();
			}
		}
	}

	public static MoodstocksWebView getOverlay() {
		return (MoodstocksWebView) overlay;
	}

	private static void setOverlay(CordovaWebView webView) {
		MoodstocksPlugin.overlay = webView;
	}

	public static CallbackContext getScanCallback() {
		return scanCallback;
	}

	public static void setScanCallback(CallbackContext scanCallback) {
		MoodstocksPlugin.scanCallback = scanCallback;
	}
}


text:
require 'spec_helper'

describe RomanNumeralTokenizer do
  class FakeCharacterClass
    def self.value_for(character)
      case character
      when 'I'
        1
      when 'V'
        5
      else
        42
      end
    end
  end

  class FakeConverterClass
    def character_map
      FakeCharacterClass
    end
  end

  it "groups single character as segment" do
    tokens = RomanNumeralTokenizer.call("I", FakeConverterClass.new)
    expect(tokens.length).to eq(1)
    expect(tokens).to eq([["I"]])
  end

  it "groups separate arrays if characters are of greater or equal value" do
    tokens = RomanNumeralTokenizer.call("III", FakeConverterClass.new)
    expect(tokens.length).to eq(3)
    expect(tokens).to eq([["I"], ["I"], ["I"]])
  end

  it "groups characters that form indicate subtractive relationship" do
    tokens = RomanNumeralTokenizer.call("IV", FakeConverterClass.new)
    expect(tokens.length).to eq(1)
    expect(tokens).to eq([["I", "V"]])
  end

  it "groups characters in parenthesis as 1 unit" do
    tokens = RomanNumeralTokenizer.call("(V)", FakeConverterClass.new)
    expect(tokens.length).to eq(1)
    expect(tokens).to eq([['(V)']])
  end

  it "groups multiple characters in parenthesis as 1 unit" do
    tokens = RomanNumeralTokenizer.call("(CCCX)MMMM", FakeConverterClass.new)
    expect(tokens.length).to eq(5)
    expect(tokens).to eq([["(CCCX)"], ["M"], ["M"], ["M"], ["M"]])
  end
end


text:
'use strict'

four51.app.config(['$locationProvider', function($locationProvider) {
		$locationProvider.html5Mode(false);
}]);

four51.app.config(function($provide) {
	$provide.decorator('$exceptionHandler', function($delegate, $injector) {
		return function $broadcastingExceptionHandler(ex, cause) {
			$delegate(ex, cause);
			$injector.get('$rootScope').$broadcast('exception', ex, cause);
		}
	});
});


text:
Returns the length of its last collection argument or
the length of the incoming f.ret

```
length [ 0 1 2 3 ]
  # f.ret ==> 4

{ a: 'A', b: 'B', c: 'C' }
length _
  # f.ret ==> 3
```

It will fail unless "length" receives a (non-attribute) argument
that has a length.

Has the "size" alias.

* [source](https://github.com/floraison/flor/tree/master/lib/flor/pcore/length.rb)
* [length spec](https://github.com/floraison/flor/tree/master/spec/pcore/length_spec.rb)


text:
<?php

class Diff_SequenceMatcher
{
	/**
	 * @var string|array Either a string or an array containing a callback function to determine if a line is "junk" or not.
	 */
	private $junkCallback = null;

	/**
	 * @var array The first sequence to compare against.
	 */
	private $a = null;

	/**
	 * @var array The second sequence.
	 */
	private $b = null;

	/**
	 * @var array Array of characters that are considered junk from the second sequence. Characters are the array key.
	 */
	private $junkDict = array();

	/**
	 * @var array Array of indices that do not contain junk elements.
	 */
	private $b2j = array();

	private $options = array();

	private $defaultOptions = array(
		'ignoreNewLines' => false,
		'ignoreWhitespace' => false,
		'ignoreCase' => false
	);

	/**
	 * The constructor. With the sequences being passed, they'll be set for the
	 * sequence matcher and it will perform a basic cleanup & calculate junk
	 * elements.
	 *
	 * @param string|array $a A string or array containing the lines to compare against.
	 * @param string|array $b A string or array containing the lines to compare.
	 * @param string|array $junkCallback Either an array or string that references a callback function (if there is one) to determine 'junk' characters.
	 * @param array $options
	 */
	public function __construct($a, $b, $junkCallback=null, $options)
	{
		$this->a = null;
		$this->b = null;
		$this->junkCallback = $junkCallback;
		$this->setOptions($options);
		$this->setSequences($a, $b);
	}

	/**
	 * Set new options
	 *
	 * @param array $options
	 */
	public function setOptions($options)
	{
		$this->options = array_merge($this->defaultOptions, $options);
	}

	/**
	 * Set the first and second sequences to use with the sequence matcher.
	 *
	 * @param string|array $a A string or array containing the lines to compare against.
	 * @param string|array $b A string or array containing the lines to compare.
	 */
	public function setSequences($a, $b)
	{
		$this->setSeq1($a);
		$this->setSeq2($b);
	}

	/**
	 * Set the first sequence ($a) and reset any internal caches to indicate that
	 * when calling the calculation methods, we need to recalculate them.
	 *
	 * @param string|array $a The sequence to set as the first sequence.
	 */
	public function setSeq1($a)
	{
		if(!is_array($a)) {
			$a = str_split($a);
		}
		if($a == $this->a) {
			return;
		}

		$this->a= $a;
		$this->matchingBlocks = null;
		$this->opCodes = null;
	}

	/**
	 * Set the second sequence ($b) and reset any internal caches to indicate that
	 * when calling the calculation methods, we need to recalculate them.
	 *
	 * @param string|array $b The sequence to set as the second sequence.
	 */
	public function setSeq2($b)
	{
		if(!is_array($b)) {
			$b = str_split($b);
		}
		if($b == $this->b) {
			return;
		}

		$this->b = $b;
		$this->matchingBlocks = null;
		$this->opCodes = null;
		$this->fullBCount = null;
		$this->chainB();
	}

	/**
	 * Generate the internal arrays containing the list of junk and non-junk
	 * characters for the second ($b) sequence.
	 */
	private function chainB()
	{
		$length = count ($this->b);
		$this->b2j = array();
		$popularDict = array();

		for($i = 0; $i < $length; ++$i) {
			$char = $this->b[$i];
			if(isset($this->b2j[$char])) {
				if($length >= 200 && count($this->b2j[$char]) * 100 > $length) {
					$popularDict[$char] = 1;
					unset($this->b2j[$char]);
				}
				else {
					$this->b2j[$char][] = $i;
				}
			}
			else {
				$this->b2j[$char] = array(
					$i
				);
			}
		}

		// Remove leftovers
		foreach(array_keys($popularDict) as $char) {
			unset($this->b2j[$char]);
		}

		$this->junkDict = array();
		if(is_callable($this->junkCallback)) {
			foreach(array_keys($popularDict) as $char) {
				if(call_user_func($this->junkCallback, $char)) {
					$this->junkDict[$char] = 1;
					unset($popularDict[$char]);
				}
			}

			foreach(array_keys($this->b2j) as $char) {
				if(call_user_func($this->junkCallback, $char)) {
					$this->junkDict[$char] = 1;
					unset($this->b2j[$char]);
				}
			}
		}
	}

	/**
	 * Checks if a particular character is in the junk dictionary
	 * for the list of junk characters.
	 * @param $b
	 * @return boolean True if the character is considered junk. False if not.
	 */
	private function isBJunk($b)
	{
		if(isset($this->juncDict[$b])) {
			return true;
		}

		return false;
	}

	/**
	 * Find the longest matching block in the two sequences, as defined by the
	 * lower and upper constraints for each sequence. (for the first sequence,
	 * $alo - $ahi and for the second sequence, $blo - $bhi)
	 *
	 * Essentially, of all of the maximal matching blocks, return the one that
	 * startest earliest in $a, and all of those maximal matching blocks that
	 * start earliest in $a, return the one that starts earliest in $b.
	 *
	 * If the junk callback is defined, do the above but with the restriction
	 * that the junk element appears in the block. Extend it as far as possible
	 * by matching only junk elements in both $a and $b.
	 *
	 * @param int $alo The lower constraint for the first sequence.
	 * @param int $ahi The upper constraint for the first sequence.
	 * @param int $blo The lower constraint for the second sequence.
	 * @param int $bhi The upper constraint for the second sequence.
	 * @return array Array containing the longest match that includes the starting position in $a, start in $b and the length/size.
	 */
	public function findLongestMatch($alo, $ahi, $blo, $bhi)
	{
		$a = $this->a;
		$b = $this->b;

		$bestI = $alo;
		$bestJ = $blo;
		$bestSize = 0;

		$j2Len = array();
		$nothing = array();

		for($i = $alo; $i < $ahi; ++$i) {
			$newJ2Len = array();
			$jDict = $this->arrayGetDefault($this->b2j, $a[$i], $nothing);
			foreach($jDict as $jKey => $j) {
				if($j < $blo) {
					continue;
				}
				else if($j >= $bhi) {
					break;
				}

				$k = $this->arrayGetDefault($j2Len, $j -1, 0) + 1;
				$newJ2Len[$j] = $k;
				if($k > $bestSize) {
					$bestI = $i - $k + 1;
					$bestJ = $j - $k + 1;
					$bestSize = $k;
				}
			}

			$j2Len = $newJ2Len;
		}

		while($bestI > $alo && $bestJ > $blo && !$this->isBJunk($b[$bestJ - 1]) &&
			!$this->linesAreDifferent($bestI - 1, $bestJ - 1)) {
				--$bestI;
				--$bestJ;
				++$bestSize;
		}

		while($bestI + $bestSize < $ahi && ($bestJ + $bestSize) < $bhi &&
			!$this->isBJunk($b[$bestJ + $bestSize]) && !$this->linesAreDifferent($bestI + $bestSize, $bestJ + $bestSize)) {
				++$bestSize;
		}

		while($bestI > $alo && $bestJ > $blo && $this->isBJunk($b[$bestJ - 1]) &&
			!$this->isLineDifferent($bestI - 1, $bestJ - 1)) {
				--$bestI;
				--$bestJ;
				++$bestSize;
		}

		while($bestI + $bestSize < $ahi && $bestJ + $bestSize < $bhi &&
			$this->isBJunk($b[$bestJ + $bestSize]) && !$this->linesAreDifferent($bestI + $bestSize, $bestJ + $bestSize)) {
					++$bestSize;
		}

		return array(
			$bestI,
			$bestJ,
			$bestSize
		);
	}

	/**
	 * Check if the two lines at the given indexes are different or not.
	 *
	 * @param int $aIndex Line number to check against in a.
	 * @param int $bIndex Line number to check against in b.
	 * @return boolean True if the lines are different and false if not.
	 */
	public function linesAreDifferent($aIndex, $bIndex)
	{
		$lineA = $this->a[$aIndex];
		$lineB = $this->b[$bIndex];

		if($this->options['ignoreWhitespace']) {
			$replace = array("\t", ' ');
			$lineA = str_replace($replace, '', $lineA);
			$lineB = str_replace($replace, '', $lineB);
		}

		if($this->options['ignoreCase']) {
			$lineA = strtolower($lineA);
			$lineB = strtolower($lineB);
		}

		if($lineA != $lineB) {
			return true;
		}

		return false;
	}

	/**
	 * Return a nested set of arrays for all of the matching sub-sequences
	 * in the strings $a and $b.
	 *
	 * Each block contains the lower constraint of the block in $a, the lower
	 * constraint of the block in $b and finally the number of lines that the
	 * block continues for.
	 *
	 * @return array Nested array of the matching blocks, as described by the function.
	 */
	public function getMatchingBlocks()
	{
		if(!empty($this->matchingBlocks)) {
			return $this->matchingBlocks;
		}

		$aLength = count($this->a);
		$bLength = count($this->b);

		$queue = array(
			array(
				0,
				$aLength,
				0,
				$bLength
			)
		);

		$matchingBlocks = array();
		while(!empty($queue)) {
			list($alo, $ahi, $blo, $bhi) = array_pop($queue);
			$x = $this->findLongestMatch($alo, $ahi, $blo, $bhi);
			list($i, $j, $k) = $x;
			if($k) {
				$matchingBlocks[] = $x;
				if($alo < $i && $blo < $j) {
					$queue[] = array(
						$alo,
						$i,
						$blo,
						$j
					);
				}

				if($i + $k < $ahi && $j + $k < $bhi) {
					$queue[] = array(
						$i + $k,
						$ahi,
						$j + $k,
						$bhi
					);
				}
			}
		}

		usort($matchingBlocks, array($this, 'tupleSort'));

		$i1 = 0;
		$j1 = 0;
		$k1 = 0;
		$nonAdjacent = array();
		foreach($matchingBlocks as $block) {
			list($i2, $j2, $k2) = $block;
			if($i1 + $k1 == $i2 && $j1 + $k1 == $j2) {
				$k1 += $k2;
			}
			else {
				if($k1) {
					$nonAdjacent[] = array(
						$i1,
						$j1,
						$k1
					);
				}

				$i1 = $i2;
				$j1 = $j2;
				$k1 = $k2;
			}
		}

		if($k1) {
			$nonAdjacent[] = array(
				$i1,
				$j1,
				$k1
			);
		}

		$nonAdjacent[] = array(
			$aLength,
			$bLength,
			0
		);

		$this->matchingBlocks = $nonAdjacent;
		return $this->matchingBlocks;
	}

	/**
	 * Return a list of all of the opcodes for the differences between the
	 * two strings.
	 *
	 * The nested array returned contains an array describing the opcode
	 * which includes:
	 * 0 - The type of tag (as described below) for the opcode.
	 * 1 - The beginning line in the first sequence.
	 * 2 - The end line in the first sequence.
	 * 3 - The beginning line in the second sequence.
	 * 4 - The end line in the second sequence.
	 *
	 * The different types of tags include:
	 * replace - The string from $i1 to $i2 in $a should be replaced by
	 *           the string in $b from $j1 to $j2.
	 * delete -  The string in $a from $i1 to $j2 should be deleted.
	 * insert -  The string in $b from $j1 to $j2 should be inserted at
	 *           $i1 in $a.
	 * equal  -  The two strings with the specified ranges are equal.
	 *
	 * @return array Array of the opcodes describing the differences between the strings.
	 */
	public function getOpCodes()
	{
		if(!empty($this->opCodes)) {
			return $this->opCodes;
		}

		$i = 0;
		$j = 0;
		$this->opCodes = array();

		$blocks = $this->getMatchingBlocks();
		foreach($blocks as $block) {
			list($ai, $bj, $size) = $block;
			$tag = '';
			if($i < $ai && $j < $bj) {
				$tag = 'replace';
			}
			else if($i < $ai) {
				$tag = 'delete';
			}
			else if($j < $bj) {
				$tag = 'insert';
			}

			if($tag) {
				$this->opCodes[] = array(
					$tag,
					$i,
					$ai,
					$j,
					$bj
				);
			}

			$i = $ai + $size;
			$j = $bj + $size;

			if($size) {
				$this->opCodes[] = array(
					'equal',
					$ai,
					$i,
					$bj,
					$j
				);
			}
		}
		return $this->opCodes;
	}

	/**
	 * Return a series of nested arrays containing different groups of generated
	 * opcodes for the differences between the strings with up to $context lines
	 * of surrounding content.
	 *
	 * Essentially what happens here is any big equal blocks of strings are stripped
	 * out, the smaller subsets of changes are then arranged in to their groups.
	 * This means that the sequence matcher and diffs do not need to include the full
	 * content of the different files but can still provide context as to where the
	 * changes are.
	 *
	 * @param int $context The number of lines of context to provide around the groups.
	 * @return array Nested array of all of the grouped opcodes.
	 */
	public function getGroupedOpcodes($context=3)
	{
		$opCodes = $this->getOpCodes();
		if(empty($opCodes)) {
			$opCodes = array(
				array(
					'equal',
					0,
					1,
					0,
					1
				)
			);
		}

		if($opCodes[0][0] == 'equal') {
			$opCodes[0] = array(
				$opCodes[0][0],
				max($opCodes[0][1], $opCodes[0][2] - $context),
				$opCodes[0][2],
				max($opCodes[0][3], $opCodes[0][4] - $context),
				$opCodes[0][4]
			);
		}

		$lastItem = count($opCodes) - 1;
		if($opCodes[$lastItem][0] == 'equal') {
			list($tag, $i1, $i2, $j1, $j2) = $opCodes[$lastItem];
			$opCodes[$lastItem] = array(
				$tag,
				$i1,
				min($i2, $i1 + $context),
				$j1,
				min($j2, $j1 + $context)
			);
		}

		$maxRange = $context * 2;
		$groups = array();
		$group = array();
		foreach($opCodes as $code) {
			list($tag, $i1, $i2, $j1, $j2) = $code;
			if($tag == 'equal' && $i2 - $i1 > $maxRange) {
				$group[] = array(
					$tag,
					$i1,
					min($i2, $i1 + $context),
					$j1,
					min($j2, $j1 + $context)
				);
				$groups[] = $group;
				$group = array();
				$i1 = max($i1, $i2 - $context);
				$j1 = max($j1, $j2 - $context);
			}
			$group[] = array(
				$tag,
				$i1,
				$i2,
				$j1,
				$j2
			);
		}

		if(!empty($group) && !(count($group) == 1 && $group[0][0] == 'equal')) {
			$groups[] = $group;
		}

		return $groups;
	}

	/**
	 * Return a measure of the similarity between the two sequences.
	 * This will be a float value between 0 and 1.
	 *
	 * Out of all of the ratio calculation functions, this is the most
	 * expensive to call if getMatchingBlocks or getOpCodes is yet to be
	 * called. The other calculation methods (quickRatio and realquickRatio)
	 * can be used to perform quicker calculations but may be less accurate.
	 *
	 * The ratio is calculated as (2 * number of matches) / total number of
	 * elements in both sequences.
	 *
	 * @return float The calculated ratio.
	 */
	public function Ratio()
	{
		$matches = array_reduce($this->getMatchingBlocks(), array($this, 'ratioReduce'), 0);
		return $this->calculateRatio($matches, count ($this->a) + count ($this->b));
	}

	/**
	 * Helper function to calculate the number of matches for Ratio().
	 *
	 * @param int $sum The running total for the number of matches.
	 * @param array $triple Array containing the matching block triple to add to the running total.
	 * @return int The new running total for the number of matches.
	 */
	private function ratioReduce($sum, $triple)
	{
		return $sum + ($triple[count($triple) - 1]);
	}

	/**
	 * Quickly return an upper bound ratio for the similarity of the strings.
	 * This is quicker to compute than Ratio().
	 *
	 * @return float The calculated ratio.
	 */
	private function quickRatio()
	{
		if($this->fullBCount === null) {
			$this->fullBCount = array();
			$bLength = count ($this->b);
			for($i = 0; $i < $bLength; ++$i) {
				$char = $this->b[$i];
				$this->fullBCount[$char] = $this->arrayGetDefault($this->fullBCount, $char, 0) + 1;
			}
		}

		$avail = array();
		$matches = 0;
		$aLength = count ($this->a);
		for($i = 0; $i < $aLength; ++$i) {
			$char = $this->a[$i];
			if(isset($avail[$char])) {
				$numb = $avail[$char];
			}
			else {
				$numb = $this->arrayGetDefault($this->fullBCount, $char, 0);
			}
			$avail[$char] = $numb - 1;
			if($numb > 0) {
				++$matches;
			}
		}

		$this->calculateRatio($matches, count ($this->a) + count ($this->b));
	}

	/**
	 * Return an upper bound ratio really quickly for the similarity of the strings.
	 * This is quicker to compute than Ratio() and quickRatio().
	 *
	 * @return float The calculated ratio.
	 */
	private function realquickRatio()
	{
		$aLength = count ($this->a);
		$bLength = count ($this->b);

		return $this->calculateRatio(min($aLength, $bLength), $aLength + $bLength);
	}

	/**
	 * Helper function for calculating the ratio to measure similarity for the strings.
	 * The ratio is defined as being 2 * (number of matches / total length)
	 *
	 * @param int $matches The number of matches in the two strings.
	 * @param int $length The length of the two strings.
	 * @return float The calculated ratio.
	 */
	private function calculateRatio($matches, $length=0)
	{
		if($length) {
			return 2 * ($matches / $length);
		}
		else {
			return 1;
		}
	}

	/**
	 * Helper function that provides the ability to return the value for a key
	 * in an array of it exists, or if it doesn't then return a default value.
	 * Essentially cleaner than doing a series of if(isset()) {} else {} calls.
	 *
	 * @param array $array The array to search.
	 * @param string $key The key to check that exists.
	 * @param mixed $default The value to return as the default value if the key doesn't exist.
	 * @return mixed The value from the array if the key exists or otherwise the default.
	 */
	private function arrayGetDefault($array, $key, $default)
	{
		if(isset($array[$key])) {
			return $array[$key];
		}
		else {
			return $default;
		}
	}

	/**
	 * Sort an array by the nested arrays it contains. Helper function for getMatchingBlocks
	 *
	 * @param array $a First array to compare.
	 * @param array $b Second array to compare.
	 * @return int -1, 0 or 1, as expected by the usort function.
	 */
	private function tupleSort($a, $b)
	{
		$max = max(count($a), count($b));
		for($i = 0; $i < $max; ++$i) {
			if($a[$i] < $b[$i]) {
				return -1;
			}
			else if($a[$i] > $b[$i]) {
				return 1;
			}
		}

		if(count($a) == count($b)) {
			return 0;
		}
		else if(count($a) < count($b)) {
			return -1;
		}
		else {
			return 1;
		}
	}
}


text:
module AdminHelper

  def future_records?
    @date > 0.months.ago
  end

  def beyond_earliest_records?
    earliest = Month.get_earliest_months() ; return true if earliest.nil?
    earliest = earliest.first
    return true if earliest.year.nil? or earliest.month.nil?
    earliest.year > @date.year or (earliest.year == @date.year and earliest.month > @date.month)
  end

  def no_records?
    @user_months.is_a?(Hash) and @user_months.values.all? { |m| m.nil? }
  end

  def get_record_as_date(day_num)
    Date.parse(day_num.to_s + "-" + @records.month.to_s + "-" + @records.year.to_s)
  end

end


text:
set -o errexit
set -o xtrace

# Keep track of the current directory
TOOLS_DIR=$(cd $(dirname "$0") && pwd)
TOP_DIR=`cd $TOOLS_DIR/..; pwd`

# Change dir to top of devstack
cd $TOP_DIR

# Import common functions
source $TOP_DIR/functions

FILES=$TOP_DIR/files

PIP_GET_PIP_URL=https://bootstrap.pypa.io/get-pip.py
LOCAL_PIP="$FILES/$(basename $PIP_GET_PIP_URL)"

GetDistro
echo "Distro: $DISTRO"

function get_versions {
    PIP=$(which pip 2>/dev/null || which pip-python 2>/dev/null || true)
    if [[ -n $PIP ]]; then
        PIP_VERSION=$($PIP --version | awk '{ print $2}')
        echo "pip: $PIP_VERSION"
    else
        echo "pip: Not Installed"
    fi
}

function install_get_pip {
    if [[ ! -r $LOCAL_PIP ]]; then
        curl -o $LOCAL_PIP $PIP_GET_PIP_URL || \
            die $LINENO "Download of get-pip.py failed"
    fi
    sudo -E python $LOCAL_PIP
}

function configure_pypi_alternative_url {
    PIP_ROOT_FOLDER="$HOME/.pip"
    PIP_CONFIG_FILE="$PIP_ROOT_FOLDER/pip.conf"
    if [[ ! -d $PIP_ROOT_FOLDER ]]; then
        echo "Creating $PIP_ROOT_FOLDER"
        mkdir $PIP_ROOT_FOLDER
    fi
    if [[ ! -f $PIP_CONFIG_FILE ]]; then
        echo "Creating $PIP_CONFIG_FILE"
        touch $PIP_CONFIG_FILE
    fi
    if ! ini_has_option "$PIP_CONFIG_FILE" "global" "index-url"; then
        #it means that the index-url does not exist
        iniset "$PIP_CONFIG_FILE" "global" "index-url" "$PYPI_OVERRIDE"
    fi

}

# Show starting versions
get_versions

# Do pip

# Eradicate any and all system packages
uninstall_package python-pip

install_get_pip

if [[ -n $PYPI_ALTERNATIVE_URL ]]; then
    configure_pypi_alternative_url
fi

pip_install -U setuptools

get_versions


text:
set -e
set -x

skip_zeroing_disk=0
if [ -e "$HOME/skip_zeroing_disk" ]; then
    echo "NOTE: will not zero disk at the end due to VMWare Fusion bug"
    echo "See: https://communities.vmware.com/t5/VMware-Fusion-Discussions/VMWare-Fusion-Pro-11-15-6-16696540-causes-macOS-crash-during/m-p/2284011#M139190"
    skip_zeroing_disk=1
fi

sudo apt update
sudo apt install -y build-essential
sudo apt-get --purge remove modemmanager  # required to access serial ports.

# Zephyr
wget --no-verbose https://apt.kitware.com/keys/kitware-archive-latest.asc
sudo apt-key add kitware-archive-latest.asc
sudo apt-add-repository 'deb https://apt.kitware.com/ubuntu/ bionic main'
sudo apt update
# NOTE: latest cmake cannot be installed due to
# https://github.com/zephyrproject-rtos/zephyr/issues/30232
sudo apt install -y --no-install-recommends git \
     cmake=3.22.2-0kitware1ubuntu18.04.1 cmake-data=3.22.2-0kitware1ubuntu18.04.1 \
     ninja-build gperf ccache dfu-util device-tree-compiler wget \
     python3-dev python3-pip python3-setuptools python3-tk python3-wheel xz-utils file \
     make gcc gcc-multilib g++-multilib libsdl2-dev

# Avahi, so that ssh microtvm works.
# apt install -y avahi-daemon

OLD_HOSTNAME=$(hostname)
sudo hostnamectl set-hostname microtvm
sudo sed -i.bak "s/${OLD_HOSTNAME}/microtvm.localdomain/g" /etc/hosts

# Poetry deps
sudo apt install -y python3-venv

# TVM deps
sudo apt install -y llvm

# ONNX deps
sudo apt install -y protobuf-compiler libprotoc-dev

# nrfjprog
NRF_COMMANDLINE_TOOLS_FILE=nRFCommandLineToolsLinuxamd64.tar.gz
NRF_COMMANDLINE_TOOLS_URL=https://www.nordicsemi.com/-/media/Software-and-other-downloads/Desktop-software/nRF-command-line-tools/sw/Versions-10-x-x/10-12-1/nRFCommandLineTools10121Linuxamd64.tar.gz
NRF_COMMANDLINE_TOOLS_INSTALLER=nRF-Command-Line-Tools_10_12_1_Linux-amd64.deb
JLINK_LINUX_INSTALLER=JLink_Linux_V688a_x86_64.deb

cd ~
mkdir -p nrfjprog
wget --no-verbose -O $NRF_COMMANDLINE_TOOLS_FILE $NRF_COMMANDLINE_TOOLS_URL
cd nrfjprog
tar -xzvf "../${NRF_COMMANDLINE_TOOLS_FILE}"
sudo apt install -y "./${JLINK_LINUX_INSTALLER}"
sudo apt install -y "./${NRF_COMMANDLINE_TOOLS_INSTALLER}"
source ~/.profile
nrfjprog --help
cd ..
rm -rf nrfjprog "${NRF_COMMANDLINE_TOOLS_FILE}"

# Zephyr
pip3 install --user -U west
echo 'export PATH=$HOME/.local/bin:"$PATH"' >> ~/.profile
source ~/.profile
echo PATH=$PATH

cd ~
echo "Downloading zephyr SDK..."
~/ubuntu_install_zephyr_sdk.sh ~/zephyr-sdk
rm -f ubuntu_install_zephyr_sdk.sh

# GDB for Zephyr SDK depends on python3.8
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt install -y python3.8-dev

sudo find ~/zephyr-sdk -name '*.rules' -exec cp {} /etc/udev/rules.d \;
sudo udevadm control --reload

# Poetry
curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python3
sed -i "/^# If not running interactively,/ i source \$HOME/.poetry/env" ~/.bashrc
sed -i "/^# If not running interactively,/ i export ZEPHYR_BASE=$HOME/zephyr/zephyr" ~/.bashrc
sed -i "/^# If not running interactively,/ i\\ " ~/.bashrc

# Clean box for packaging as a base box
sudo apt-get clean
if [ $skip_zeroing_disk -eq 0 ]; then
    echo "Zeroing disk..."
    EMPTY_FILE="$HOME/EMPTY"
    dd if=/dev/zero "of=${EMPTY_FILE}" bs=1M || /bin/true
    if [ ! -e "${EMPTY_FILE}" ]; then
        echo "failed to zero empty sectors on disk"
        exit 2
    fi
    rm -f "${EMPTY_FILE}"
else
    echo "NOTE: skipping zeroing disk due to command-line argument."
fi