text:
/*==============================================================================================================================
                                             User NOTES
1. How To use this driver:
--------------------------
   - This driver supports STM32F4xx devices on STM324x7I-EVAL (MB786) Evaluation boards.

   - Configure the options in file STM324x7I_eval_audio_codec.h in the section CONFIGURATION.
      Refer to the sections 2 and 3 to have more details on the possible configurations.

   - Call the function EVAL_AUDIO_Init(
                                    OutputDevice: physical output mode (OUTPUT_DEVICE_SPEAKER,
                                                 OUTPUT_DEVICE_HEADPHONE, OUTPUT_DEVICE_AUTO or
                                                 OUTPUT_DEVICE_BOTH)
                                    Volume: initial volume to be set (0 is min (mute), 100 is max (100%)
                                    AudioFreq: Audio frequency in Hz (8000, 16000, 22500, 32000 ...)
                                     this parameter is relative to the audio file/stream type.
                                   )
      This function configures all the hardware required for the audio application (codec, I2C, I2S,
      GPIOs, DMA and interrupt if needed). This function returns 0 if configuration is OK.
      if the returned value is different from 0 or the function is stuck then the communication with
      the codec or the IOExpander has failed (try to un-plug the power or reset device in this case).
      + OUTPUT_DEVICE_SPEAKER: only speaker will be set as output for the audio stream.
      + OUTPUT_DEVICE_HEADPHONE: only headphones will be set as output for the audio stream.
      + OUTPUT_DEVICE_AUTO: Selection of output device is made through external switch (implemented
         into the audio jack on the evaluation board). When the Headphone is connected it is used
         as output. When the headphone is disconnected from the audio jack, the output is
         automatically switched to Speaker.
      + OUTPUT_DEVICE_BOTH: both Speaker and Headphone are used as outputs for the audio stream
         at the same time.

   - Call the function EVAL_AUDIO_Play(
                                  pBuffer: pointer to the audio data file address
                                  Size: size of the buffer to be sent in Bytes
                                 )
      to start playing (for the first time) from the audio file/stream.

   - Call the function EVAL_AUDIO_PauseResume(
                                         Cmd: AUDIO_PAUSE (or 0) to pause playing or AUDIO_RESUME (or
                                               any value different from 0) to resume playing.
                                         )
       Note. After calling EVAL_AUDIO_PauseResume() function for pause, only EVAL_AUDIO_PauseResume() should be called
          for resume (it is not allowed to call EVAL_AUDIO_Play() in this case).
       Note. This function should be called only when the audio file is played or paused (not stopped).

   - For each mode, you may need to implement the relative callback functions into your code.
      The Callback functions are named EVAL_AUDIO_XXX_CallBack() and only their prototypes are declared in
      the STM324x7I_eval_audio_codec.h file. (refer to the example for more details on the callbacks implementations)

   - To Stop playing, to modify the volume level or to mute, use the functions
       EVAL_AUDIO_Stop(), EVAL_AUDIO_VolumeCtl() and EVAL_AUDIO_Mute().

   - The driver API and the callback functions are at the end of the STM324x7I_eval_audio_codec.h file.

 Driver architecture:
 --------------------
 This driver is composed of three main layers:
   o High Audio Layer: consists of the function API exported in the STM324x7I_eval_audio_codec.h file
     (EVAL_AUDIO_Init(), EVAL_AUDIO_Play() ...)
   o Codec Control layer: consists of the functions API controlling the audio codec (CS43L22) and
     included as local functions in file STM324x7I_eval_audio_codec.c (Codec_Init(), Codec_Play() ...)
   o Media Access Layer (MAL): which consists of functions allowing to access the media containing/
     providing the audio file/stream. These functions are also included as local functions into
     the STM324x7I_eval_audio_codec.c file (Audio_MAL_Init(), Audio_MAL_Play() ...)
  Each set of functions (layer) may be implemented independently of the others and customized when
  needed.

2. Modes description:
---------------------
     + AUDIO_MAL_MODE_NORMAL : is suitable when the audio file is in a memory location.
     + AUDIO_MAL_MODE_CIRCULAR: is suitable when the audio data are read either from a
        memory location or from a device at real time (double buffer could be used).

3. DMA interrupts description:
------------------------------
     + EVAL_AUDIO_IT_TC_ENABLE: Enable this define to use the DMA end of transfer interrupt.
        then, a callback should be implemented by user to perform specific actions
        when the DMA has finished the transfer.
     + EVAL_AUDIO_IT_HT_ENABLE: Enable this define to use the DMA end of half transfer interrupt.
        then, a callback should be implemented by user to perform specific actions
        when the DMA has reached the half of the buffer transfer (generally, it is useful
        to load the first half of buffer while DMA is loading from the second half).
     + EVAL_AUDIO_IT_ER_ENABLE: Enable this define to manage the cases of error on DMA transfer.

4. Known Limitations:
---------------------
   1- When using the Speaker, if the audio file quality is not high enough, the speaker output
      may produce high and uncomfortable noise level. To avoid this issue, to use speaker
      output properly, try to increase audio file sampling rate (typically higher than 48KHz).
      This operation will lead to larger file size.
   2- Communication with the audio codec (through I2C) may be corrupted if it is interrupted by some
      user interrupt routines (in this case, interrupts could be disabled just before the start of
      communication then re-enabled when it is over). Note that this communication is only done at
      the configuration phase (EVAL_AUDIO_Init() or EVAL_AUDIO_Stop()) and when Volume control modification is
      performed (EVAL_AUDIO_VolumeCtl() or EVAL_AUDIO_Mute()). When the audio data is played, no communication is
      required with the audio codec.
  3- Parsing of audio file is not implemented (in order to determine audio file properties: Mono/Stereo, Data size,
     File size, Audio Frequency, Audio Data header size ...). The configuration is fixed for the given audio file.
  4- Mono audio streaming is not supported (in order to play mono audio streams, each data should be sent twice
     on the I2S or should be duplicated on the source buffer. Or convert the stream in stereo before playing).
  5- Supports only 16-bit audio data size.
===============================================================================================================================*/

/* Includes ------------------------------------------------------------------*/
#include "STM324x7i_eval_audio_codec.h"

/** @addtogroup Utilities
  * @{
  */

/** @addtogroup STM32_EVAL
  * @{
  */

/** @addtogroup STM324x7I_EVAL
  * @{
  */

/** @addtogroup STM324x7I_EVAL_AUDIO_CODEC
  * @brief       This file includes the low layer driver for CS43L22 Audio Codec
  *              available on STM324x7I-EVAL evaluation board(MB786).
  * @{
  */

/** @defgroup STM324x7I_EVAL_AUDIO_CODEC_Private_Types
  * @{
  */
/**
  * @}
  */

/** @defgroup STM324x7I_EVAL_AUDIO_CODEC_Private_Defines
  * @{
  */

/* Mask for the bit EN of the I2S CFGR register */
#define I2S_ENABLE_MASK                 0x0400

/* Delay for the Codec to be correctly reset */
#define CODEC_RESET_DELAY               0x4FFF

/* Codec audio Standards */
#ifdef I2S_STANDARD_PHILLIPS
 #define  CODEC_STANDARD                0x04
 #define I2S_STANDARD                   I2S_Standard_Phillips
#elif defined(I2S_STANDARD_MSB)
 #define  CODEC_STANDARD                0x00
 #define I2S_STANDARD                   I2S_Standard_MSB
#elif defined(I2S_STANDARD_LSB)
 #define  CODEC_STANDARD                0x08
 #define I2S_STANDARD                   I2S_Standard_LSB
#else
 #error "Error: No audio communication standard selected !"
#endif /* I2S_STANDARD */

/* The 7 bits Codec address (sent through I2C interface) */
#define CODEC_ADDRESS                   0x94  /* b00100111 */
/**
  * @}
  */

/** @defgroup STM324x7I_EVAL_AUDIO_CODEC_Private_Macros
  * @{
  */
/**
  * @}
  */

/** @defgroup STM324x7I_EVAL_AUDIO_CODEC_Private_Variables
  * @{
  */
/* This structure is declared global because it is handled by two different functions */
static DMA_InitTypeDef DMA_InitStructure;
DMA_InitTypeDef AUDIO_MAL_DMA_InitStructure;

uint32_t AudioTotalSize = 0xFFFF; /* This variable holds the total size of the audio file */
uint32_t AudioRemSize   = 0xFFFF; /* This variable holds the remaining data in audio file */
uint16_t *CurrentPos;             /* This variable holds the current position of audio pointer */

__IO uint32_t  CODECTimeout = CODEC_LONG_TIMEOUT;
__IO uint8_t OutputDev = 0;

/**
  * @}
  */

/** @defgroup STM324x7I_EVAL_AUDIO_CODEC_Private_Function_Prototypes
  * @{
  */
/**
  * @}
  */

/** @defgroup STM324x7I_EVAL_AUDIO_CODEC_Private_Functions
  * @{
  */

/*-----------------------------------
                           Audio Codec functions
                                    ------------------------------------------*/
/* High Layer codec functions */
static uint32_t Codec_Init(uint16_t OutputDevice, uint8_t Volume, uint32_t AudioFreq);
static uint32_t Codec_DeInit(void);
static uint32_t Codec_Play(void);
static uint32_t Codec_PauseResume(uint32_t Cmd);
static uint32_t Codec_Stop(uint32_t Cmd);
static uint32_t Codec_VolumeCtrl(uint8_t Volume);
static uint32_t Codec_Mute(uint32_t Cmd);
/* Low layer codec functions */
static void     Codec_CtrlInterface_Init(void);
static void     Codec_CtrlInterface_DeInit(void);
static void     Codec_AudioInterface_Init(uint32_t AudioFreq);
static void     Codec_AudioInterface_DeInit(void);
static void     Codec_Reset(void);
static uint32_t Codec_WriteRegister(uint8_t RegisterAddr, uint8_t RegisterValue);
static uint32_t Codec_ReadRegister(uint8_t RegisterAddr);
static void     Codec_GPIO_Init(void);
static void     Codec_GPIO_DeInit(void);
static void     Delay(__IO uint32_t nCount);
/*----------------------------------------------------------------------------*/

/*-----------------------------------
                   MAL (Media Access Layer) functions
                                    ------------------------------------------*/
/* Peripherals configuration functions */
static void     Audio_MAL_Init(void);
static void     Audio_MAL_DeInit(void);
static void     Audio_MAL_Play(uint32_t Addr, uint32_t Size);
static void     Audio_MAL_PauseResume(uint32_t Cmd, uint32_t Addr);
static void     Audio_MAL_Stop(void);
/*----------------------------------------------------------------------------*/

/**
  * @brief  Configure the audio peripherals.
  * @param  OutputDevice: OUTPUT_DEVICE_SPEAKER, OUTPUT_DEVICE_HEADPHONE,
  *                       OUTPUT_DEVICE_BOTH or OUTPUT_DEVICE_AUTO .
  * @param  Volume: Initial volume level (from 0 (Mute) to 100 (Max))
  * @param  AudioFreq: Audio frequency used to play the audio stream.
  * @retval 0 if correct communication, else wrong communication
  */
uint32_t EVAL_AUDIO_Init(uint16_t OutputDevice, uint8_t Volume, uint32_t AudioFreq)
{
  /* Perform low layer Codec initialization */
  if (Codec_Init(OutputDevice, VOLUME_CONVERT(Volume), AudioFreq) != 0)
  {
    return 1;
  }
  else
  {
    /* I2S data transfer preparation:
    Prepare the Media to be used for the audio transfer from memory to I2S peripheral */
    Audio_MAL_Init();

    /* Return 0 when all operations are OK */
    return 0;
  }
}

/**
  * @brief  Deinitializes all the resources used by the codec (those initialized
  *         by EVAL_AUDIO_Init() function) EXCEPT the I2C resources since they are
  *         used by the IOExpander as well (and eventually other modules).
  * @param  None
  * @retval 0 if correct communication, else wrong communication
  */
uint32_t EVAL_AUDIO_DeInit(void)
{
  /* DeInitialize the Media layer */
  Audio_MAL_DeInit();

  /* DeInitialize Codec */
  Codec_DeInit();

  return 0;
}

/**
  * @brief  Starts playing audio stream from a data buffer for a determined size.
  * @param  pBuffer: Pointer to the buffer
  * @param  Size: Number of audio data BYTES.
  * @retval 0 if correct communication, else wrong communication
  */
uint32_t EVAL_AUDIO_Play(uint16_t* pBuffer, uint32_t Size)
{
  /* Set the total number of data to be played (count in half-word) */
  AudioTotalSize = Size/2;

  /* Call the audio Codec Play function */
  Codec_Play();

  /* Update the Media layer and enable it for play */
  Audio_MAL_Play((uint32_t)pBuffer, (uint32_t)(DMA_MAX(AudioTotalSize / 2)));

  /* Update the remaining number of data to be played */
  AudioRemSize = (Size/2) - DMA_MAX(AudioTotalSize);

  /* Update the current audio pointer position */
  CurrentPos = pBuffer + DMA_MAX(AudioTotalSize);

  return 0;
}

/**
  * @brief  This function Pauses or Resumes the audio file stream. In case
  *         of using DMA, the DMA Pause feature is used. In all cases the I2S
  *         peripheral is disabled.
  *
  * @WARNING When calling EVAL_AUDIO_PauseResume() function for pause, only
  *          this function should be called for resume (use of EVAL_AUDIO_Play()
  *          function for resume could lead to unexpected behavior).
  *
  * @param  Cmd: AUDIO_PAUSE (or 0) to pause, AUDIO_RESUME (or any value different
  *         from 0) to resume.
  * @retval 0 if correct communication, else wrong communication
  */
uint32_t EVAL_AUDIO_PauseResume(uint32_t Cmd)
{
  /* Call the Audio Codec Pause/Resume function */
  if (Codec_PauseResume(Cmd) != 0)
  {
    return 1;
  }
  else
  {
    /* Call the Media layer pause/resume function */
    Audio_MAL_PauseResume(Cmd, 0);

    /* Return 0 if all operations are OK */
    return 0;
  }
}

/**
  * @brief  Stops audio playing and Power down the Audio Codec.
  * @param  Option: could be one of the following parameters
  *           - CODEC_PDWN_SW: for software power off (by writing registers).
  *                            Then no need to reconfigure the Codec after power on.
  *           - CODEC_PDWN_HW: completely shut down the codec (physically).
  *                            Then need to reconfigure the Codec after power on.
  * @retval 0 if correct communication, else wrong communication
  */
uint32_t EVAL_AUDIO_Stop(uint32_t Option)
{
  /* Call Audio Codec Stop function */
  if (Codec_Stop(Option) != 0)
  {
    return 1;
  }
  else
  {
    /* Call Media layer Stop function */
    Audio_MAL_Stop();

    /* Update the remaining data number */
    AudioRemSize = AudioTotalSize;

    /* Return 0 when all operations are correctly done */
    return 0;
  }
}

/**
  * @brief  Controls the current audio volume level.
  * @param  Volume: Volume level to be set in percentage from 0% to 100% (0 for
  *         Mute and 100 for Max volume level).
  * @retval 0 if correct communication, else wrong communication
  */
uint32_t EVAL_AUDIO_VolumeCtl(uint8_t Volume)
{
  /* Call the codec volume control function with converted volume value */
  return (Codec_VolumeCtrl(VOLUME_CONVERT(Volume)));
}

/**
  * @brief  Enables or disables the MUTE mode by software
  * @param  Command: could be AUDIO_MUTE_ON to mute sound or AUDIO_MUTE_OFF to
  *         unmute the codec and restore previous volume level.
  * @retval 0 if correct communication, else wrong communication
  */
uint32_t EVAL_AUDIO_Mute(uint32_t Cmd)
{
  /* Call the Codec Mute function */
  return (Codec_Mute(Cmd));
}

/**
  * @brief  This function handles main Media layer interrupt.
  * @param  None
  * @retval 0 if correct communication, else wrong communication
  */
void Audio_MAL_IRQHandler(void)
{
#ifndef AUDIO_MAL_MODE_NORMAL
  uint16_t *pAddr = (uint16_t *)CurrentPos;
  uint32_t Size = AudioRemSize;
#endif /* AUDIO_MAL_MODE_NORMAL */

#ifdef AUDIO_MAL_DMA_IT_TC_EN
  /* Transfer complete interrupt */
  if (DMA_GetFlagStatus(AUDIO_MAL_DMA_STREAM, AUDIO_MAL_DMA_FLAG_TC) != RESET)
  {
 #ifdef AUDIO_MAL_MODE_NORMAL
    /* Check if the end of file has been reached */
    if (AudioRemSize > 0)
    {
      /* Wait the DMA Stream to be effectively disabled */
      while (DMA_GetCmdStatus(AUDIO_MAL_DMA_STREAM) != DISABLE)
      {}

      /* Clear the Interrupt flag */
      DMA_ClearFlag(AUDIO_MAL_DMA_STREAM, AUDIO_MAL_DMA_FLAG_TC);

      /* Re-Configure the buffer address and size */
      DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t) CurrentPos;
      DMA_InitStructure.DMA_BufferSize = (uint32_t) (DMA_MAX(AudioRemSize));

      /* Configure the DMA Stream with the new parameters */
      DMA_Init(AUDIO_MAL_DMA_STREAM, &DMA_InitStructure);

      /* Enable the I2S DMA Stream*/
      DMA_Cmd(AUDIO_MAL_DMA_STREAM, ENABLE);

      /* Update the current pointer position */
      CurrentPos += DMA_MAX(AudioRemSize);

      /* Update the remaining number of data to be played */
      AudioRemSize -= DMA_MAX(AudioRemSize);
    }
    else
    {
      /* Disable the I2S DMA Stream*/
      DMA_Cmd(AUDIO_MAL_DMA_STREAM, DISABLE);

      /* Clear the Interrupt flag */
      DMA_ClearFlag(AUDIO_MAL_DMA_STREAM, AUDIO_MAL_DMA_FLAG_TC);

      /* Manage the remaining file size and new address offset: This function
      should be coded by user (its prototype is already declared in stm32_eval_audio_codec.h) */
      EVAL_AUDIO_TransferComplete_CallBack((uint32_t)CurrentPos, 0);
    }

 #elif defined(AUDIO_MAL_MODE_CIRCULAR)
    /* Manage the remaining file size and new address offset: This function
       should be coded by user (its prototype is already declared in stm32_eval_audio_codec.h) */
    EVAL_AUDIO_TransferComplete_CallBack(pAddr, Size);

    /* Clear the Interrupt flag */
    DMA_ClearFlag(AUDIO_MAL_DMA_STREAM, AUDIO_MAL_DMA_FLAG_TC);
 #endif /* AUDIO_MAL_MODE_NORMAL */
  }
#endif /* AUDIO_MAL_DMA_IT_TC_EN */

#ifdef AUDIO_MAL_DMA_IT_HT_EN
  /* Half Transfer complete interrupt */
  if (DMA_GetFlagStatus(AUDIO_MAL_DMA_STREAM, AUDIO_MAL_DMA_FLAG_HT) != RESET)
  {
    /* Manage the remaining file size and new address offset: This function
       should be coded by user (its prototype is already declared in stm32_eval_audio_codec.h) */
    EVAL_AUDIO_HalfTransfer_CallBack((uint32_t)pAddr, Size);

    /* Clear the Interrupt flag */
    DMA_ClearFlag(AUDIO_MAL_DMA_STREAM, AUDIO_MAL_DMA_FLAG_HT);
  }
#endif /* AUDIO_MAL_DMA_IT_HT_EN */

#ifdef AUDIO_MAL_DMA_IT_TE_EN
  /* FIFO Error interrupt */
  if ((DMA_GetFlagStatus(AUDIO_MAL_DMA_STREAM, AUDIO_MAL_DMA_FLAG_TE) != RESET) || \
     (DMA_GetFlagStatus(AUDIO_MAL_DMA_STREAM, AUDIO_MAL_DMA_FLAG_FE) != RESET) || \
     (DMA_GetFlagStatus(AUDIO_MAL_DMA_STREAM, AUDIO_MAL_DMA_FLAG_DME) != RESET))

  {
    /* Manage the error generated on DMA FIFO: This function
       should be coded by user (its prototype is already declared in stm32_eval_audio_codec.h) */
    EVAL_AUDIO_Error_CallBack((uint32_t*)&pAddr);

    /* Clear the Interrupt flag */
    DMA_ClearFlag(AUDIO_MAL_DMA_STREAM, AUDIO_MAL_DMA_FLAG_TE | AUDIO_MAL_DMA_FLAG_FE | \
                                        AUDIO_MAL_DMA_FLAG_DME);
  }
#endif /* AUDIO_MAL_DMA_IT_TE_EN */
}

/*========================

                CS43L22 Audio Codec Control Functions
                                                ==============================*/
/**
  * @brief  Initializes the audio codec and all related interfaces (control
  *         interface: I2C and audio interface: I2S)
  * @param  OutputDevice: can be OUTPUT_DEVICE_SPEAKER, OUTPUT_DEVICE_HEADPHONE,
  *                       OUTPUT_DEVICE_BOTH or OUTPUT_DEVICE_AUTO .
  * @param  Volume: Initial volume level (from 0 (Mute) to 100 (Max))
  * @param  AudioFreq: Audio frequency used to play the audio stream.
  * @retval 0 if correct communication, else wrong communication
  */
static uint32_t Codec_Init(uint16_t OutputDevice, uint8_t Volume, uint32_t AudioFreq)
{
  uint32_t counter = 0;

  /* Configure the Codec related IOs */
  Codec_GPIO_Init();

  /* Reset the Codec Registers */
  Codec_Reset();

  /* Initialize the Control interface of the Audio Codec */
  Codec_CtrlInterface_Init();

  /* Keep Codec powered OFF */
  counter += Codec_WriteRegister(0x02, 0x01);

  switch (OutputDevice)
  {
    case OUTPUT_DEVICE_SPEAKER:
      counter += Codec_WriteRegister(0x04, 0xFA); /* SPK always ON & HP always OFF */
      OutputDev = 0xFA;
      break;

    case OUTPUT_DEVICE_HEADPHONE:
      counter += Codec_WriteRegister(0x04, 0xAF); /* SPK always OFF & HP always ON */
      OutputDev = 0xAF;
      break;

    case OUTPUT_DEVICE_BOTH:
      counter += Codec_WriteRegister(0x04, 0xAA); /* SPK always ON & HP always ON */
      OutputDev = 0xAA;
      break;

    case OUTPUT_DEVICE_AUTO:
      counter += Codec_WriteRegister(0x04, 0x05); /* Detect the HP or the SPK automatically */
      OutputDev = 0x05;
      break;

    default:
      counter += Codec_WriteRegister(0x04, 0x05); /* Detect the HP or the SPK automatically */
      OutputDev = 0x05;
      break;
  }

  /* Clock configuration: Auto detection */
  counter += Codec_WriteRegister(0x05, 0x81);

  /* Set the Slave Mode and the audio Standard */
  counter += Codec_WriteRegister(0x06, CODEC_STANDARD);

  /* Set the Master volume */
  Codec_VolumeCtrl(Volume);

  /* If the Speaker is enabled, set the Mono mode and volume attenuation level */
  if (OutputDevice != OUTPUT_DEVICE_HEADPHONE)
  {
    /* Set the Speaker Mono mode */
    counter += Codec_WriteRegister(0x0F , 0x06);

    /* Set the Speaker attenuation level */
    counter += Codec_WriteRegister(0x24, 0x00);
    counter += Codec_WriteRegister(0x25, 0x00);
  }

  /* Power on the Codec */
  counter += Codec_WriteRegister(0x02, 0x9E);

  /* Additional configuration for the CODEC. These configurations are done to reduce
      the time needed for the Codec to power off. If these configurations are removed,
      then a long delay should be added between powering off the Codec and switching
      off the I2S peripheral MCLK clock (which is the operating clock for Codec).
      If this delay is not inserted, then the codec will not shut down properly and
      it results in high noise after shut down. */

  /* Disable the analog soft ramp */
  counter += Codec_WriteRegister(0x0A, 0x00);
  /* Disable the digital soft ramp */
  counter += Codec_WriteRegister(0x0E, 0x04);
  /* Disable the limiter attack level */
  counter += Codec_WriteRegister(0x27, 0x00);
  /* Adjust Bass and Treble levels */
  counter += Codec_WriteRegister(0x1F, 0x0F);
  /* Adjust PCM volume level */
  counter += Codec_WriteRegister(0x1A, 0x0A);
  counter += Codec_WriteRegister(0x1B, 0x0A);

  /* Configure the I2S peripheral */
  Codec_AudioInterface_Init(AudioFreq);

  /* Return communication control value */
  return counter;
}

/**
  * @brief  Restore the audio codec state to default state and free all used
  *         resources.
  * @param  None
  * @retval 0 if correct communication, else wrong communication
  */
static uint32_t Codec_DeInit(void)
{
  uint32_t counter = 0;

  /* Reset the Codec Registers */
  Codec_Reset();

  /* Keep Codec powered OFF */
  counter += Codec_WriteRegister(0x02, 0x01);

  /* Deinitialize all use GPIOs */
  Codec_GPIO_DeInit();

  /* Disable the Codec control interface */
  Codec_CtrlInterface_DeInit();

  /* Deinitialize the Codec audio interface (I2S) */
  Codec_AudioInterface_DeInit();

  /* Return communication control value */
  return counter;
}

/**
  * @brief  Start the audio Codec play feature.
  * @note   For this codec no Play options are required.
  * @param  None
  * @retval 0 if correct communication, else wrong communication
  */
static uint32_t Codec_Play(void)
{
  /*
     No actions required on Codec level for play command
     */

  /* Return communication control value */
  return 0;
}

/**
  * @brief  Pauses and resumes playing on the audio codec.
  * @param  Cmd: AUDIO_PAUSE (or 0) to pause, AUDIO_RESUME (or any value different
  *         from 0) to resume.
  * @retval 0 if correct communication, else wrong communication
  */
static uint32_t Codec_PauseResume(uint32_t Cmd)
{
  uint32_t counter = 0;

  /* Pause the audio file playing */
  if (Cmd == AUDIO_PAUSE)
  {
    /* Mute the output first */
    counter += Codec_Mute(AUDIO_MUTE_ON);

    /* Put the Codec in Power save mode */
    counter += Codec_WriteRegister(0x02, 0x01);
  }
  else /* AUDIO_RESUME */
  {
    /* Unmute the output first */
    counter += Codec_Mute(AUDIO_MUTE_OFF);

    counter += Codec_WriteRegister(0x04, OutputDev);

    /* Exit the Power save mode */
    counter += Codec_WriteRegister(0x02, 0x9E);
  }

  return counter;
}

/**
  * @brief  Stops audio Codec playing. It powers down the codec.
  * @param  CodecPdwnMode: selects the  power down mode.
  *          - CODEC_PDWN_SW: only mutes the audio codec. When resuming from this
  *                           mode the codec keeps the previous initialization
  *                           (no need to re-Initialize the codec registers).
  *          - CODEC_PDWN_HW: Physically power down the codec. When resuming from this
  *                           mode, the codec is set to default configuration
  *                           (user should re-Initialize the codec in order to
  *                            play again the audio stream).
  * @retval 0 if correct communication, else wrong communication
  */
static uint32_t Codec_Stop(uint32_t CodecPdwnMode)
{
  uint32_t counter = 0;

  /* Mute the output first */
  Codec_Mute(AUDIO_MUTE_ON);

  if (CodecPdwnMode == CODEC_PDWN_SW)
  {
    /* Power down the DAC and the speaker (PMDAC and PMSPK bits)*/
    counter += Codec_WriteRegister(0x02, 0x9F);
  }
  else /* CODEC_PDWN_HW */
  {
    /* Power down the DAC components */
    counter += Codec_WriteRegister(0x02, 0x9F);

    /* Wait at least 100us */
    Delay(0xFFF);

    /* Reset The pin */
    IOE_WriteIOPin(AUDIO_RESET_PIN, BitReset);
  }

  return counter;
}

/**
  * @brief  Sets higher or lower the codec volume level.
  * @param  Volume: a byte value from 0 to 255 (refer to codec registers
  *         description for more details).
  * @retval 0 if correct communication, else wrong communication
  */
static uint32_t Codec_VolumeCtrl(uint8_t Volume)
{
  uint32_t counter = 0;

  if (Volume > 0xE6)
  {
    /* Set the Master volume */
    counter += Codec_WriteRegister(0x20, Volume - 0xE7);
    counter += Codec_WriteRegister(0x21, Volume - 0xE7);
  }
  else
  {
    /* Set the Master volume */
    counter += Codec_WriteRegister(0x20, Volume + 0x19);
    counter += Codec_WriteRegister(0x21, Volume + 0x19);
  }

  return counter;
}

/**
  * @brief  Enables or disables the mute feature on the audio codec.
  * @param  Cmd: AUDIO_MUTE_ON to enable the mute or AUDIO_MUTE_OFF to disable the
  *             mute mode.
  * @retval 0 if correct communication, else wrong communication
  */
static uint32_t Codec_Mute(uint32_t Cmd)
{
  uint32_t counter = 0;

  /* Set the Mute mode */
  if (Cmd == AUDIO_MUTE_ON)
  {
    counter += Codec_WriteRegister(0x04, 0xFF);
  }
  else /* AUDIO_MUTE_OFF Disable the Mute */
  {
    counter += Codec_WriteRegister(0x04, OutputDev);
  }

  return counter;
}

/**
  * @brief  Resets the audio codec. It restores the default configuration of the
  *         codec (this function shall be called before initializing the codec).
  * @note   This function calls an external driver function: The IO Expander driver.
  * @param  None
  * @retval None
  */
static void Codec_Reset(void)
{
  /* Configure the IO Expander (to use the Codec Reset pin mapped on the IOExpander) */
  IOE_Config();

  /* Power Down the codec */
  IOE_WriteIOPin(AUDIO_RESET_PIN, BitReset);

  /* wait for a delay to insure registers erasing */
  Delay(CODEC_RESET_DELAY);

  /* Power on the codec */
  IOE_WriteIOPin(AUDIO_RESET_PIN, BitSet);

  /* wait for a delay to insure wakeup */
  Delay(10);
}

/**
  * @brief  Switch dynamically (while audio file is played) the output target
  *         (speaker or headphone).
  * @note   This function modifies a global variable of the audio codec driver: OutputDev.
  * @param  Output: specifies the audio output target: OUTPUT_DEVICE_SPEAKER,
  *         OUTPUT_DEVICE_HEADPHONE, OUTPUT_DEVICE_BOTH or OUTPUT_DEVICE_AUTO
  * @retval 0 if correct communication, else wrong communication
  */
uint32_t Codec_SwitchOutput(uint8_t Output)
{
  uint8_t counter = 0;

  switch (Output)
  {
    case OUTPUT_DEVICE_SPEAKER:
      counter += Codec_WriteRegister(0x04, 0xFA); /* SPK always ON & HP always OFF */
      OutputDev = 0xFA;
      break;

    case OUTPUT_DEVICE_HEADPHONE:
      counter += Codec_WriteRegister(0x04, 0xAF); /* SPK always OFF & HP always ON */
      OutputDev = 0xAF;
      break;

    case OUTPUT_DEVICE_BOTH:
      counter += Codec_WriteRegister(0x04, 0xAA); /* SPK always ON & HP always ON */
      OutputDev = 0xAA;
      break;

    case OUTPUT_DEVICE_AUTO:
      counter += Codec_WriteRegister(0x04, 0x05); /* Detect the HP or the SPK automatically */
      OutputDev = 0x05;
      break;

    default:
      counter += Codec_WriteRegister(0x04, 0x05); /* Detect the HP or the SPK automatically */
      OutputDev = 0x05;
      break;
  }

  return counter;
}

/**
  * @brief  Writes a Byte to a given register into the audio codec through the
            control interface (I2C)
  * @param  RegisterAddr: The address (location) of the register to be written.
  * @param  RegisterValue: the Byte value to be written into destination register.
  * @retval 0 if correct communication, else wrong communication
  */
static uint32_t Codec_WriteRegister(uint8_t RegisterAddr, uint8_t RegisterValue)
{
  uint32_t result = 0;

  /*!< While the bus is busy */
  CODECTimeout = CODEC_LONG_TIMEOUT;
  while(I2C_GetFlagStatus(CODEC_I2C, I2C_FLAG_BUSY))
  {
    if((CODECTimeout--) == 0) return Codec_TIMEOUT_UserCallback();
  }

  /* Start the config sequence */
  I2C_GenerateSTART(CODEC_I2C, ENABLE);

  /* Test on EV5 and clear it */
  CODECTimeout = CODEC_FLAG_TIMEOUT;
  while (!I2C_CheckEvent(CODEC_I2C, I2C_EVENT_MASTER_MODE_SELECT))
  {
    if((CODECTimeout--) == 0) return Codec_TIMEOUT_UserCallback();
  }

  /* Transmit the slave address and enable writing operation */
  I2C_Send7bitAddress(CODEC_I2C, CODEC_ADDRESS, I2C_Direction_Transmitter);

  /* Test on EV6 and clear it */
  CODECTimeout = CODEC_FLAG_TIMEOUT;
  while (!I2C_CheckEvent(CODEC_I2C, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED))
  {
    if((CODECTimeout--) == 0) return Codec_TIMEOUT_UserCallback();
  }

  /* Transmit the first address for write operation */
  I2C_SendData(CODEC_I2C, RegisterAddr);

  /* Test on EV8 and clear it */
  CODECTimeout = CODEC_FLAG_TIMEOUT;
  while (!I2C_CheckEvent(CODEC_I2C, I2C_EVENT_MASTER_BYTE_TRANSMITTING))
  {
    if((CODECTimeout--) == 0) return Codec_TIMEOUT_UserCallback();
  }

  /* Prepare the register value to be sent */
  I2C_SendData(CODEC_I2C, RegisterValue);

  /*!< Wait till all data have been physically transferred on the bus */
  CODECTimeout = CODEC_LONG_TIMEOUT;
  while(!I2C_GetFlagStatus(CODEC_I2C, I2C_FLAG_BTF))
  {
    if((CODECTimeout--) == 0) Codec_TIMEOUT_UserCallback();
  }

  /* End the configuration sequence */
  I2C_GenerateSTOP(CODEC_I2C, ENABLE);

#ifdef VERIFY_WRITTENDATA
  /* Verify that the data has been correctly written */
  result = (Codec_ReadRegister(RegisterAddr) == RegisterValue)? 0:1;
#endif /* VERIFY_WRITTENDATA */

  /* Return the verifying value: 0 (Passed) or 1 (Failed) */
  return result;
}

/**
  * @brief  Reads and returns the value of an audio codec register through the
  *         control interface (I2C).
  * @param  RegisterAddr: Address of the register to be read.
  * @retval Value of the register to be read or dummy value if the communication
  *         fails.
  */
static uint32_t Codec_ReadRegister(uint8_t RegisterAddr)
{
  uint32_t result = 0;

  /*!< While the bus is busy */
  CODECTimeout = CODEC_LONG_TIMEOUT;
  while(I2C_GetFlagStatus(CODEC_I2C, I2C_FLAG_BUSY))
  {
    if((CODECTimeout--) == 0) return Codec_TIMEOUT_UserCallback();
  }

  /* Start the config sequence */
  I2C_GenerateSTART(CODEC_I2C, ENABLE);

  /* Test on EV5 and clear it */
  CODECTimeout = CODEC_FLAG_TIMEOUT;
  while (!I2C_CheckEvent(CODEC_I2C, I2C_EVENT_MASTER_MODE_SELECT))
  {
    if((CODECTimeout--) == 0) return Codec_TIMEOUT_UserCallback();
  }

  /* Transmit the slave address and enable writing operation */
  I2C_Send7bitAddress(CODEC_I2C, CODEC_ADDRESS, I2C_Direction_Transmitter);

  /* Test on EV6 and clear it */
  CODECTimeout = CODEC_FLAG_TIMEOUT;
  while (!I2C_CheckEvent(CODEC_I2C, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED))
  {
    if((CODECTimeout--) == 0) return Codec_TIMEOUT_UserCallback();
  }

  /* Transmit the register address to be read */
  I2C_SendData(CODEC_I2C, RegisterAddr);

  /* Test on EV8 and clear it */
  CODECTimeout = CODEC_FLAG_TIMEOUT;
  while (I2C_GetFlagStatus(CODEC_I2C, I2C_FLAG_BTF) == RESET)
  {
    if((CODECTimeout--) == 0) return Codec_TIMEOUT_UserCallback();
  }

  /*!< Send STRAT condition a second time */
  I2C_GenerateSTART(CODEC_I2C, ENABLE);

  /*!< Test on EV5 and clear it (cleared by reading SR1 then writing to DR) */
  CODECTimeout = CODEC_FLAG_TIMEOUT;
  while(!I2C_CheckEvent(CODEC_I2C, I2C_EVENT_MASTER_MODE_SELECT))
  {
    if((CODECTimeout--) == 0) return Codec_TIMEOUT_UserCallback();
  }

  /*!< Send Codec address for read */
  I2C_Send7bitAddress(CODEC_I2C, CODEC_ADDRESS, I2C_Direction_Receiver);

  /* Wait on ADDR flag to be set (ADDR is still not cleared at this level */
  CODECTimeout = CODEC_FLAG_TIMEOUT;
  while(I2C_GetFlagStatus(CODEC_I2C, I2C_FLAG_ADDR) == RESET)
  {
    if((CODECTimeout--) == 0) return Codec_TIMEOUT_UserCallback();
  }

  /*!< Disable Acknowledgment */
  I2C_AcknowledgeConfig(CODEC_I2C, DISABLE);

  /* Clear ADDR register by reading SR1 then SR2 register (SR1 has already been read) */
  (void)CODEC_I2C->SR2;

  /*!< Send STOP Condition */
  I2C_GenerateSTOP(CODEC_I2C, ENABLE);

  /* Wait for the byte to be received */
  CODECTimeout = CODEC_FLAG_TIMEOUT;
  while(I2C_GetFlagStatus(CODEC_I2C, I2C_FLAG_RXNE) == RESET)
  {
    if((CODECTimeout--) == 0) return Codec_TIMEOUT_UserCallback();
  }

  /*!< Read the byte received from the Codec */
  result = I2C_ReceiveData(CODEC_I2C);

  /* Wait to make sure that STOP flag has been cleared */
  CODECTimeout = CODEC_FLAG_TIMEOUT;
  while(CODEC_I2C->CR1 & I2C_CR1_STOP)
  {
    if((CODECTimeout--) == 0) return Codec_TIMEOUT_UserCallback();
  }

  /*!< Re-Enable Acknowledgment to be ready for another reception */
  I2C_AcknowledgeConfig(CODEC_I2C, ENABLE);

  /* Clear AF flag for next communication */
  I2C_ClearFlag(CODEC_I2C, I2C_FLAG_AF);

  /* Return the byte read from Codec */
  return result;
}

/**
  * @brief  Initializes the Audio Codec control interface (I2C).
  * @param  None
  * @retval None
  */
static void Codec_CtrlInterface_Init(void)
{
  I2C_InitTypeDef I2C_InitStructure;

  /* Enable the CODEC_I2C peripheral clock */
  RCC_APB1PeriphClockCmd(CODEC_I2C_CLK, ENABLE);

  /* If the I2C peripheral is already enabled, don't reconfigure it */
  if ((CODEC_I2C->CR1 & I2C_CR1_PE) != 0)
  {
    /* CODEC_I2C peripheral configuration */
    I2C_DeInit(CODEC_I2C);
    I2C_InitStructure.I2C_Mode = I2C_Mode_I2C;
    I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2;
    I2C_InitStructure.I2C_OwnAddress1 = 0x33;
    I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
    I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
    I2C_InitStructure.I2C_ClockSpeed = I2C_SPEED;

    /* Enable the I2C peripheral */
    I2C_Cmd(CODEC_I2C, ENABLE);

    /* Initialize the I2C peripheral */
    I2C_Init(CODEC_I2C, &I2C_InitStructure);
  }
}

/**
  * @brief  Restore the Audio Codec control interface to its default state.
  *         This function doesn't de-initialize the I2C because the I2C peripheral
  *         may be used by other modules.
  * @param  None
  * @retval None
  */
static void Codec_CtrlInterface_DeInit(void)
{
  /* Disable the I2C peripheral */ /* This step is not done here because
     the I2C interface can be used by other modules */
  /* I2C_DeInit(CODEC_I2C); */
}

/**
  * @brief  Initializes the Audio Codec audio interface (I2S)
  * @note   This function assumes that the I2S input clock (through PLL_R in
  *         Devices RevA/Z and through dedicated PLLI2S_R in Devices RevB/Y)
  *         is already configured and ready to be used.
  * @param  AudioFreq: Audio frequency to be configured for the I2S peripheral.
  * @retval None
  */
static void Codec_AudioInterface_Init(uint32_t AudioFreq)
{
  I2S_InitTypeDef I2S_InitStructure;

  /* Enable the CODEC_I2S peripheral clock */
  RCC_APB1PeriphClockCmd(CODEC_I2S_CLK, ENABLE);

  /* CODEC_I2S peripheral configuration */
  SPI_I2S_DeInit(CODEC_I2S);
  I2S_InitStructure.I2S_AudioFreq = AudioFreq;
  I2S_InitStructure.I2S_Standard = I2S_STANDARD;
  I2S_InitStructure.I2S_DataFormat = I2S_DataFormat_16b;
  I2S_InitStructure.I2S_CPOL = I2S_CPOL_Low;
  I2S_InitStructure.I2S_Mode = I2S_Mode_MasterTx;
#ifdef CODEC_MCLK_ENABLED
  I2S_InitStructure.I2S_MCLKOutput = I2S_MCLKOutput_Enable;
#elif defined(CODEC_MCLK_DISABLED)
  I2S_InitStructure.I2S_MCLKOutput = I2S_MCLKOutput_Disable;
#else
 #error "No selection for the MCLK output has been defined !"
#endif /* CODEC_MCLK_ENABLED */

  /* Initialize the I2S peripheral with the structure above */
  I2S_Init(CODEC_I2S, &I2S_InitStructure);

  /* The I2S peripheral will be enabled only in the EVAL_AUDIO_Play() function
       or by user functions if DMA mode not enabled */
}

/**
  * @brief  Restores the Audio Codec audio interface to its default state.
  * @param  None
  * @retval None
  */
static void Codec_AudioInterface_DeInit(void)
{
  /* Disable the CODEC_I2S peripheral (in case it hasn't already been disabled) */
  I2S_Cmd(CODEC_I2S, DISABLE);

  /* Deinitialize the CODEC_I2S peripheral */
  SPI_I2S_DeInit(CODEC_I2S);

  /* Disable the CODEC_I2S peripheral clock */
  RCC_APB1PeriphClockCmd(CODEC_I2S_CLK, DISABLE);
}

/**
  * @brief Initializes IOs used by the Audio Codec (on the control and audio
  *        interfaces).
  * @param  None
  * @retval None
  */
static void Codec_GPIO_Init(void)
{
   GPIO_InitTypeDef GPIO_InitStructure;

  /* Enable I2S and I2C GPIO clocks */
  RCC_AHB1PeriphClockCmd(CODEC_I2C_GPIO_CLOCK | CODEC_I2S_GPIO_CLOCK, ENABLE);

  /* CODEC_I2C SCL and SDA pins configuration -------------------------------------*/
  /* If the I2C peripheral is already enabled, don't reconfigure it */
  if ((CODEC_I2C->CR1 & I2C_CR1_PE) != 0)
  {
    GPIO_InitStructure.GPIO_Pin = CODEC_I2C_SCL_PIN | CODEC_I2C_SDA_PIN;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_OType = GPIO_OType_OD;
    GPIO_InitStructure.GPIO_PuPd  = GPIO_PuPd_NOPULL;
    GPIO_Init(CODEC_I2C_GPIO, &GPIO_InitStructure);
    /* Connect pins to Periph */
    GPIO_PinAFConfig(CODEC_I2C_GPIO, CODEC_I2S_SCL_PINSRC, CODEC_I2C_GPIO_AF);
    GPIO_PinAFConfig(CODEC_I2C_GPIO, CODEC_I2S_SDA_PINSRC, CODEC_I2C_GPIO_AF);
  }

  /* CODEC_I2S pins configuration: WS, SCK and SD pins -----------------------------*/
  GPIO_InitStructure.GPIO_Pin = CODEC_I2S_WS_PIN | CODEC_I2S_SCK_PIN | CODEC_I2S_SD_PIN;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
  GPIO_Init(CODEC_I2S_GPIO, &GPIO_InitStructure);
  /* Connect pins to I2S peripheral  */
  GPIO_PinAFConfig(CODEC_I2S_GPIO, CODEC_I2S_WS_PINSRC, CODEC_I2S_GPIO_AF);
  GPIO_PinAFConfig(CODEC_I2S_GPIO, CODEC_I2S_SCK_PINSRC, CODEC_I2S_GPIO_AF);
  GPIO_PinAFConfig(CODEC_I2S_GPIO, CODEC_I2S_SD_PINSRC, CODEC_I2S_GPIO_AF);

 #ifdef CODEC_MCLK_ENABLED
  /* CODEC_I2S pins configuration: MCK pin */
  GPIO_InitStructure.GPIO_Pin = CODEC_I2S_MCK_PIN;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
  GPIO_Init(CODEC_I2S_MCK_GPIO, &GPIO_InitStructure);
  /* Connect pins to I2S peripheral  */
  GPIO_PinAFConfig(CODEC_I2S_MCK_GPIO, CODEC_I2S_MCK_PINSRC, CODEC_I2S_GPIO_AF);
 #endif /* CODEC_MCLK_ENABLED */
}

/**
  * @brief  Restores the IOs used by the Audio Codec interface to their default state.
  * @param  None
  * @retval None
  */
static void Codec_GPIO_DeInit(void)
{
  GPIO_InitTypeDef GPIO_InitStructure;

  /* Deinitialize all the GPIOs used by the driver (EXCEPT the I2C IOs since
     they are used by the IOExpander as well) */
  GPIO_InitStructure.GPIO_Pin = CODEC_I2S_WS_PIN | CODEC_I2S_SCK_PIN | CODEC_I2S_SD_PIN;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_PuPd  = GPIO_PuPd_NOPULL;
  GPIO_Init(CODEC_I2S_GPIO, &GPIO_InitStructure);
  /* Disconnect pins from I2S peripheral  */
  GPIO_PinAFConfig(CODEC_I2S_GPIO, CODEC_I2S_WS_PIN, 0x00);
  GPIO_PinAFConfig(CODEC_I2S_GPIO, CODEC_I2S_SCK_PIN, 0x00);
  GPIO_PinAFConfig(CODEC_I2S_GPIO, CODEC_I2S_SD_PIN, 0x00);

#ifdef CODEC_MCLK_ENABLED
  /* CODEC_I2S pins deinitialization: MCK pin */
  GPIO_InitStructure.GPIO_Pin = CODEC_I2S_MCK_PIN;
  GPIO_Init(CODEC_I2S_MCK_GPIO, &GPIO_InitStructure);
  /* Disconnect pins from I2S peripheral  */
  GPIO_PinAFConfig(CODEC_I2S_MCK_GPIO, CODEC_I2S_MCK_PINSRC, CODEC_I2S_GPIO_AF);
#endif /* CODEC_MCLK_ENABLED */
}

/**
  * @brief  Inserts a delay time (not accurate timing).
  * @param  nCount: specifies the delay time length.
  * @retval None
  */
static void Delay( __IO uint32_t nCount)
{
  for (; nCount != 0; nCount--);
}

#ifdef USE_DEFAULT_TIMEOUT_CALLBACK
/**
  * @brief  Basic management of the timeout situation.
  * @param  None
  * @retval None
  */
uint32_t Codec_TIMEOUT_UserCallback(void)
{
  /* The following code allows I2C error recovery and return to normal communication
     if the error source doesn't still exist (ie. hardware issue..) */
  I2C_InitTypeDef I2C_InitStructure;

  /* LCD_ErrLog("> I2C Timeout error occurred\n"); */

  I2C_GenerateSTOP(CODEC_I2C, ENABLE);
  I2C_SoftwareResetCmd(CODEC_I2C, ENABLE);
  I2C_SoftwareResetCmd(CODEC_I2C, DISABLE);

  /* CODEC_I2C peripheral configuration */
  I2C_DeInit(CODEC_I2C);
  I2C_InitStructure.I2C_Mode = I2C_Mode_I2C;
  I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2;
  I2C_InitStructure.I2C_OwnAddress1 = 0x33;
  I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
  I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
  I2C_InitStructure.I2C_ClockSpeed = I2C_SPEED;
  /* Enable the I2C peripheral */
  I2C_Cmd(CODEC_I2C, ENABLE);
  I2C_Init(CODEC_I2C, &I2C_InitStructure);

  /* At this stage the I2C error should be recovered and device can communicate
     again (except if the error source still exist).
     User can implement mechanism (ex. test on max trial number) to manage situation
     when the I2C can't recover from current error. */

  /* LCD_UsrLog("> I2C error recovered.\n"); */

  return 0;
}
#endif /* USE_DEFAULT_TIMEOUT_CALLBACK */
/*========================

                Audio MAL Interface Control Functions

                                                ==============================*/

/**
  * @brief  Initializes and prepares the Media to perform audio data transfer
  *         from Media to the I2S peripheral.
  * @param  None
  * @retval None
  */
static void Audio_MAL_Init(void)
{
#if defined(AUDIO_MAL_DMA_IT_TC_EN) || defined(AUDIO_MAL_DMA_IT_HT_EN) || defined(AUDIO_MAL_DMA_IT_TE_EN)
  NVIC_InitTypeDef NVIC_InitStructure;
#endif

  /* Enable the DMA clock */
  RCC_AHB1PeriphClockCmd(AUDIO_MAL_DMA_CLOCK, ENABLE);

  /* Configure the DMA Stream */
  DMA_Cmd(AUDIO_MAL_DMA_STREAM, DISABLE);
  DMA_DeInit(AUDIO_MAL_DMA_STREAM);
  /* Set the parameters to be configured */
  DMA_InitStructure.DMA_Channel = AUDIO_MAL_DMA_CHANNEL;
  DMA_InitStructure.DMA_PeripheralBaseAddr = CODEC_I2S_ADDRESS;
  DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)0;      /* This field will be configured in play function */
  DMA_InitStructure.DMA_DIR = DMA_DIR_MemoryToPeripheral;
  DMA_InitStructure.DMA_BufferSize = (uint32_t)0xFFFE;      /* This field will be configured in play function */
  DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
  DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
  DMA_InitStructure.DMA_PeripheralDataSize = AUDIO_MAL_DMA_PERIPH_DATA_SIZE;
  DMA_InitStructure.DMA_MemoryDataSize = AUDIO_MAL_DMA_MEM_DATA_SIZE;
#ifdef AUDIO_MAL_MODE_NORMAL
  DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;
#elif defined(AUDIO_MAL_MODE_CIRCULAR)
  DMA_InitStructure.DMA_Mode = DMA_Mode_Circular;
#else
  #error "AUDIO_MAL_MODE_NORMAL or AUDIO_MAL_MODE_CIRCULAR should be selected !!"
#endif /* AUDIO_MAL_MODE_NORMAL */
  DMA_InitStructure.DMA_Priority = DMA_Priority_High;
  DMA_InitStructure.DMA_FIFOMode = DMA_FIFOMode_Enable;
  DMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_Full;
  DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_Single;
  DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single;
  DMA_Init(AUDIO_MAL_DMA_STREAM, &DMA_InitStructure);

  /* Enable the selected DMA interrupts (selected in "stm32_eval_audio_codec.h" defines) */
#ifdef AUDIO_MAL_DMA_IT_TC_EN
  DMA_ITConfig(AUDIO_MAL_DMA_STREAM, DMA_IT_TC, ENABLE);
#endif /* AUDIO_MAL_DMA_IT_TC_EN */
#ifdef AUDIO_MAL_DMA_IT_HT_EN
  DMA_ITConfig(AUDIO_MAL_DMA_STREAM, DMA_IT_HT, ENABLE);
#endif /* AUDIO_MAL_DMA_IT_HT_EN */
#ifdef AUDIO_MAL_DMA_IT_TE_EN
  DMA_ITConfig(AUDIO_MAL_DMA_STREAM, DMA_IT_TE | DMA_IT_FE | DMA_IT_DME, ENABLE);
#endif /* AUDIO_MAL_DMA_IT_TE_EN */

  /* Enable the I2S DMA request */
  SPI_I2S_DMACmd(CODEC_I2S, SPI_I2S_DMAReq_Tx, ENABLE);

#if defined(AUDIO_MAL_DMA_IT_TC_EN) || defined(AUDIO_MAL_DMA_IT_HT_EN) || defined(AUDIO_MAL_DMA_IT_TE_EN)
  /* I2S DMA IRQ Channel configuration */
  NVIC_InitStructure.NVIC_IRQChannel = AUDIO_MAL_DMA_IRQ;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = EVAL_AUDIO_IRQ_PREPRIO;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = EVAL_AUDIO_IRQ_SUBRIO;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);
#endif
}

/**
  * @brief  Restore default state of the used Media.
  * @param  None
  * @retval None
  */
static void Audio_MAL_DeInit(void)
{
#if defined(AUDIO_MAL_DMA_IT_TC_EN) || defined(AUDIO_MAL_DMA_IT_HT_EN) || defined(AUDIO_MAL_DMA_IT_TE_EN)
  NVIC_InitTypeDef NVIC_InitStructure;

  /* Deinitialize the NVIC interrupt for the I2S DMA Stream */
  NVIC_InitStructure.NVIC_IRQChannel = AUDIO_MAL_DMA_IRQ;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = EVAL_AUDIO_IRQ_PREPRIO;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = EVAL_AUDIO_IRQ_SUBRIO;
  NVIC_InitStructure.NVIC_IRQChannelCmd = DISABLE;
  NVIC_Init(&NVIC_InitStructure);
#endif

  /* Disable the DMA stream before the deinit */
  DMA_Cmd(AUDIO_MAL_DMA_STREAM, DISABLE);

  /* Dinitialize the DMA Stream */
  DMA_DeInit(AUDIO_MAL_DMA_STREAM);

  /*
     The DMA clock is not disabled, since it can be used by other streams
                                                                          */
}

/**
  * @brief  Starts playing audio stream from the audio Media.
  * @param  None
  * @retval None
  */
static void Audio_MAL_Play(uint32_t Addr, uint32_t Size)
{
  /* Configure the buffer address and size */
  DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)Addr;
  DMA_InitStructure.DMA_BufferSize = (uint32_t)Size;

  /* Configure the DMA Stream with the new parameters */
  DMA_Init(AUDIO_MAL_DMA_STREAM, &DMA_InitStructure);

  /* Enable the I2S DMA Stream*/
  DMA_Cmd(AUDIO_MAL_DMA_STREAM, ENABLE);

  /* If the I2S peripheral is still not enabled, enable it */
  if ((CODEC_I2S->I2SCFGR & I2S_ENABLE_MASK) == 0)
  {
    I2S_Cmd(CODEC_I2S, ENABLE);
  }
}

/**
  * @brief  Pauses or Resumes the audio stream playing from the Media.
  * @param  Cmd: AUDIO_PAUSE (or 0) to pause, AUDIO_RESUME (or any value different
  *              from 0) to resume.
  * @param  Addr: Address from/at which the audio stream should resume/pause.
  * @retval None
  */
static void Audio_MAL_PauseResume(uint32_t Cmd, uint32_t Addr)
{
  /* Pause the audio file playing */
  if (Cmd == AUDIO_PAUSE)
  {
    /* Disable the I2S DMA request */
    SPI_I2S_DMACmd(CODEC_I2S, SPI_I2S_DMAReq_Tx, DISABLE);

    /* Pause the I2S DMA Stream
        Note. For the STM32F4xx devices, the DMA implements a pause feature,
              by disabling the stream, all configuration is preserved and data
              transfer is paused till the next enable of the stream.*/
    DMA_Cmd(AUDIO_MAL_DMA_STREAM, DISABLE);
  }
  else /* AUDIO_RESUME */
  {
    /* Enable the I2S DMA request */
    SPI_I2S_DMACmd(CODEC_I2S, SPI_I2S_DMAReq_Tx, ENABLE);

    /* Resume the I2S DMA Stream
        Note. For the STM32F4xx devices, the DMA implements a pause feature,
              by disabling the stream, all configuration is preserved and data
              transfer is paused till the next enable of the stream.*/
    DMA_Cmd(AUDIO_MAL_DMA_STREAM, ENABLE);

    /* If the I2S peripheral is still not enabled, enable it */
    if ((CODEC_I2S->I2SCFGR & I2S_ENABLE_MASK) == 0)
    {
      I2S_Cmd(CODEC_I2S, ENABLE);
    }
  }
}

/**
  * @brief  Stops audio stream playing on the used Media.
  * @param  None
  * @retval None
  */
static void Audio_MAL_Stop(void)
{
  /* Stop the Transfer on the I2S side: Stop and disable the DMA stream */
  DMA_Cmd(AUDIO_MAL_DMA_STREAM, DISABLE);

  /* Clear all the DMA flags for the next transfer */
  DMA_ClearFlag(AUDIO_MAL_DMA_STREAM, AUDIO_MAL_DMA_FLAG_TC |AUDIO_MAL_DMA_FLAG_HT | \
                                  AUDIO_MAL_DMA_FLAG_FE | AUDIO_MAL_DMA_FLAG_TE);

  /*
           The I2S DMA requests are not disabled here.
                                                            */

  /* In all modes, disable the I2S peripheral */
  I2S_Cmd(CODEC_I2S, DISABLE);
}

/**
  * @}
  */

/**
  * @}
  */

/**
  * @}
  */

/**
  * @}
  */

/**
  * @}
  */

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


text:
package com.magento.idea.magento2plugin.xml.index;

import com.intellij.util.io.DataExternalizer;
import com.intellij.util.io.EnumeratorStringDescriptor;
import org.jetbrains.annotations.NotNull;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by dkvashnin on 11/10/15.
 */
public class StringSetDataExternalizer implements DataExternalizer<Set<String>> {

    private final EnumeratorStringDescriptor myStringEnumerator = new EnumeratorStringDescriptor();

    public synchronized void save(@NotNull DataOutput out, Set<String> values) throws IOException {

        out.writeInt(values.size());
        for(String value: values) {
            this.myStringEnumerator.save(out, value != null ? value : "");
        }

    }

    public synchronized Set<String> read(@NotNull DataInput in) throws IOException {
        Set<String> set = new HashSet<String>();
        int r = in.readInt();

        while (r > 0) {
            set.add(this.myStringEnumerator.read(in));
            r--;
        }

        return set;
    }
}

redpajama_set_name: RedPajamaGithub


text:
CLASS({
  name: 'HTMLGraph',
  package: 'foam.graphics',
  extendsModel: 'foam.ui.SimpleView',

  properties: [
    {
      model_: 'ColorProperty',
      name: 'graphColor',
      defaultValue: 'green'
    },
    {
      model_: 'ColorProperty',
      name: 'backgroundColor',
      defaultValue: 'transparent'
    },
    {
      model_: 'ArrayProperty',
      name:  'data',
      preSet: function(old, nu) {
        if ( old === nu ) return nu;
        if ( nu.length > this.width ) return nu.slice(-this.width);
        return nu;
      },
      lazyFactory: function() { return []; }
    },
    {
      model_: 'IntProperty',
      name: 'width',
      defaultValue: 40
    },
    {
      model_: 'IntProperty',
      name: 'height',
      defaultValue: 15
    },
    {
      model_: 'FloatProperty',
      name: 'min',
      defaultValueFn: function() {
        if ( this.data.length === 0 ) return 0;
        var min = Number.INFINITY;
        for ( var i = 0; i < this.data.length; ++i ) {
          min = Math.min(min, this.data[i]);
        }
        return Number.isNaN(min) ? 0 : min;
      }
    },
    {
      model_: 'FloatProperty',
      name: 'max',
      defaultValueFn: function() {
        if ( this.data.length === 0 ) return 100;
        var max = Number.NEGATIVE_INFINITY;
        for ( var i = 0; i < this.data.length; ++i ) {
          max = Math.max(max, this.data[i]);
        }
        return Number.isNaN(max) ? 100 : max;
      }
    }
  ],

  methods: [
    function addData(value, opt_maxNumValues) {
      var maxNumValues = opt_maxNumValues || this.width;

      if ( this.data.length === maxNumValues ) this.data.shift();
      this.data.push(value);
    }
  ],

  templates: [
    function toHTML() {/*
      <graph id="%%id">
        <% for ( var i = 0; i < this.data.length; ++i ) {
             var rowWidth = Math.round(10000 / this.data.length) / 100;
             var dataHeight = Math.min(100,
               Math.round(10000 * (this.data[i] - this.min) / this.max) / 100);
             var bgHeight = 100 - dataHeight; %>
          <graph-row style="width: {{rowWidth}}%">
            <graph-row-bg style="background: {{this.backgroundColor}}; flex-grow: {{bgHeight}}"></graph-row-bg>
            <graph-row-data style="background: {{this.graphColor}}; flex-grow: {{dataHeight}}"></graph-row-data>
          </graph-row>
        <% } %>
      </graph>
    */},
    function CSS() {/*
      graph {
        flex-grow: 1;
        display: flex;
        align-items: stretch;
        align-content: stretch;
      }
      graph-row {
        display: flex;
        flex-direction: column;
        align-items: stretch;
        align-content: stretch;
      }
      graph-row-bg {
        display: block;
        flex-grow: 1;
      }
      graph-row-data {
        display: block;
        min-height: 1px;
      }
    */}
  ]
});


text:
/* Automatically generated code, don't edit ! */

package org.urish.gwtit.titanium.ui.events;

/**
 *
 */
public interface TextAreaChangeHandler {

	public void onTextAreaChange(TextAreaChangeEvent event);

}


text:
layout: organization
category: national

title: Gift of Life Bone Marrow Foundation
impact_area: Health
keywords:
  - Adults in Need
  - Children in Need
  - Health and Wellness
location_services: Bronx,Brooklyn,Long Island,Manhattan,Queens,Staten Island,Greater New York
location_offices:
website: www.giftoflife.org

description: |
  Gift of Life helps children and adults suffering from life-threatening illnesses find their perfect matches for bone marrow transplants.
mission: |
  Headquartered in Boca Raton, Florida, Gift of Life is one of the nation's public bone marrow, blood stem cell and umbilical cord blood registries. Through its life-saving work, Gift of Life is a world leader facilitating transplants for children and adults suffering from many life-threatening diseases, among them leukemia and lymphoma.

   Gift of Life's vision for the future is simple: A match. Anytime. Anywhere. For anyone. Please join us in a global movement to save lives.

cash_grants: yes
grants:
  - |
    It costs $54 to process one donor test kit and enter them into the worldwide registry.  So $540 would add 10 new donors into the bone marrow registry.
service_opp: yes
services:
  - |
    Students have helped Gift of Life by educating their community about the importance of being a volunteer bone marrow donor, as well as helping to run bone marrow recruitment drives in their communities.

learn:
  - Make a presentation about our organization
  - Speak over the phone about our work
cont_relationship:
  - Help students develop a community service project with us
  - Attend an in-school Check Award Assembly if we receive a grant
  - Help students tell local newspapers and media about their grant and/or project with us
  - Educate the school by leading a workshop
  - Collect pennies during the Penny Harvest next fall

salutation: Mrs.
first_name: Marti
last_name: Freund
title_contact_person: Sr. Develop. Assoc.

city: Boca Raton
state: FL
address: |
  800 Yamato Road, Suite 101
  Boca Raton FL 33431
lat: 26.39471
lng: -80.077266
phone: 5619822900
ext: 2946
fax:
email: mfreund@giftoflife.org
preferred_contact: email,phone
contact_person_intro: |
  I was introduced to Gift of Life 5 years ago when one of my family members needed a bone marrow transplant.  The perfect match for my family member came from Gift of Life's registry.  I am forever grateful to the organization and want to help continue saving lives!
---
Gift of Life helps children and adults suffering from life-threatening illnesses find their perfect matches for bone marrow transplants.


text:
package org.apache.guacamole.net.auth;

import java.util.Collection;
import org.apache.guacamole.GuacamoleException;
import org.apache.guacamole.form.Form;

/**
 * UserContext implementation which simply delegates all function calls to
 * an underlying UserContext.
 */
public class DelegatingUserContext implements UserContext {

    /**
     * The wrapped UserContext.
     */
    private final UserContext userContext;

    /**
     * Wraps the given UserContext such that all function calls against this
     * DelegatingUserContext will be delegated to it.
     *
     * @param userContext
     *     The UserContext to wrap.
     */
    public DelegatingUserContext(UserContext userContext) {
        this.userContext = userContext;
    }

    /**
     * Returns the underlying UserContext wrapped by this
     * DelegatingUserContext.
     *
     * @return
     *     The UserContext wrapped by this DelegatingUserContext.
     */
    protected UserContext getDelegateUserContext() {
        return userContext;
    }

    @Override
    public User self() {
        return userContext.self();
    }

    @Override
    public Object getResource() throws GuacamoleException {
        return userContext.getResource();
    }

    @Override
    public AuthenticationProvider getAuthenticationProvider() {
        return userContext.getAuthenticationProvider();
    }

    @Override
    public Directory<User> getUserDirectory() throws GuacamoleException {
        return userContext.getUserDirectory();
    }

    @Override
    public Directory<UserGroup> getUserGroupDirectory() throws GuacamoleException {
        return userContext.getUserGroupDirectory();
    }

    @Override
    public Directory<Connection> getConnectionDirectory()
            throws GuacamoleException {
        return userContext.getConnectionDirectory();
    }

    @Override
    public Directory<ConnectionGroup> getConnectionGroupDirectory()
            throws GuacamoleException {
        return userContext.getConnectionGroupDirectory();
    }

    @Override
    public Directory<ActiveConnection> getActiveConnectionDirectory()
            throws GuacamoleException {
        return userContext.getActiveConnectionDirectory();
    }

    @Override
    public Directory<SharingProfile> getSharingProfileDirectory()
            throws GuacamoleException {
        return userContext.getSharingProfileDirectory();
    }

    @Override
    public ActivityRecordSet<ConnectionRecord> getConnectionHistory()
            throws GuacamoleException {
        return userContext.getConnectionHistory();
    }

    @Override
    public ActivityRecordSet<ActivityRecord> getUserHistory()
            throws GuacamoleException {
        return userContext.getUserHistory();
    }

    @Override
    public ConnectionGroup getRootConnectionGroup() throws GuacamoleException {
        return userContext.getRootConnectionGroup();
    }

    @Override
    public Collection<Form> getUserAttributes() {
        return userContext.getUserAttributes();
    }

    @Override
    public Collection<Form> getUserGroupAttributes() {
        return userContext.getUserGroupAttributes();
    }

    @Override
    public Collection<Form> getConnectionAttributes() {
        return userContext.getConnectionAttributes();
    }

    @Override
    public Collection<Form> getConnectionGroupAttributes() {
        return userContext.getConnectionGroupAttributes();
    }

    @Override
    public Collection<Form> getSharingProfileAttributes() {
        return userContext.getSharingProfileAttributes();
    }

    @Override
    public void invalidate() {
        userContext.invalidate();
    }

}


text:
package gr.iti.mklab.simmo.core;

/**
 *
 * @author amoumtzidou
 * @version 1.0.0
 * @since July 8, 2014
 */
public abstract class Segment extends Annotatable {

    /** The unique internal Item id */
    public String id = null;

	/** Types of frame blocks */
    public enum FRAMES_BLOCK_TYPE{SHOT, SCENE, UNDEFINED};

    /** The frame block type */
    FRAMES_BLOCK_TYPE framesBlockType = FRAMES_BLOCK_TYPE.UNDEFINED;

    /** Types of frame blocks */
    public enum SEGMENT_TYPE{LINEAR, SPATIAL, TEMPORAL, SPATIOTEMPORAL};

    /** The first frame of the segment */
    public int firstFrame = 0;

    /** The last frame of the segment */
    public int lastFrame = 0;

}


text:
/**
 * Created by easub on 2017/3/10.
 */

import React, { PropTypes } from 'react';
// import 'animate.css';
// import 'letteringjs';
// import 'textillate';

export default class PComponents extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function

  componentDidMount() {
    console.log('componentDidMount');
    const { title } = this.props;
    $(`.${title}`).textillate();
  }

  render() {
    const { title } = this.props;

    return (
      <p className={title} data-in-effect={'fadeIn'} data-loop={false}>
        {title}
      </p>
    );
  }
}

PComponents.propTypes = {
  title: PropTypes.string,
};


text:
package config

import (
	"os"
	"path/filepath"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestLoadConfig(t *testing.T) {
	key1 := "ae38315f6116585d64d82ec2455aa3ec61e02fee25d286f74ace9e4fea189217:Go"
	key2 := "bbbb315f6116585d64d82ec2455aa3ec61e02fee25d286f74ace9e4fea189217:Go"

	os.Setenv(envAppOpticsCollector, "example.com:12345")
	os.Setenv(envAppOpticsPrependDomain, "true")
	os.Setenv(envAppOpticsHistogramPrecision, "2")
	os.Setenv(envAppOpticsServiceKey, key1)

	c := NewConfig()
	assert.Equal(t, "example.com:12345", c.GetCollector())
	assert.Equal(t, true, c.PrependDomain)
	assert.Equal(t, 2, c.Precision)

	os.Setenv(envAppOpticsCollector, "test.abc:8080")
	c.RefreshConfig()
	assert.Equal(t, "test.abc:8080", c.GetCollector())

	c = NewConfig(
		WithCollector("hello.world"),
		WithServiceKey(key2))
	assert.Equal(t, "hello.world", c.GetCollector())
	assert.Equal(t, key2, c.GetServiceKey())

	os.Setenv(envAppOpticsServiceKey, key1)
	os.Setenv(envAppOpticsHostnameAlias, "test")
	os.Setenv(envAppOpticsInsecureSkipVerify, "false")
	os.Setenv(envAppOpticsTrustedPath, "test.crt")
	os.Setenv(envAppOpticsCollectorUDP, "hello.udp")

	c.RefreshConfig()
	assert.Equal(t, key1, c.GetServiceKey())
	assert.Equal(t, "test", c.GetHostAlias())
	assert.Equal(t, false, c.GetSkipVerify())
	assert.Equal(t, "test.crt", filepath.Base(c.GetTrustedPath()))
	assert.Equal(t, "hello.udp", c.GetCollectorUDP())
}


text:
module Azure::Network::Mgmt::V2019_09_01
  module Models
    #
    # ExpressRoute circuit peering identifier.
    #
    class ExpressRouteCircuitPeeringId

      include MsRestAzure

      # @return [String] The ID of the ExpressRoute circuit peering.
      attr_accessor :id

      #
      # Mapper for ExpressRouteCircuitPeeringId class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'ExpressRouteCircuitPeeringId',
          type: {
            name: 'Composite',
            class_name: 'ExpressRouteCircuitPeeringId',
            model_properties: {
              id: {
                client_side_validation: true,
                required: false,
                serialized_name: 'id',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
namespace drive {
namespace file_system {

typedef OperationTestBase CreateFileOperationTest;

TEST_F(CreateFileOperationTest, CreateFile) {
  CreateFileOperation operation(blocking_task_runner(),
                                observer(),
                                scheduler(),
                                metadata(),
                                cache());

  const base::FilePath kExistingFile(
      FILE_PATH_LITERAL("drive/root/File 1.txt"));
  const base::FilePath kExistingDirectory(
      FILE_PATH_LITERAL("drive/root/Directory 1"));
  const base::FilePath kNonExistingFile(
      FILE_PATH_LITERAL("drive/root/Directory 1/not exist.png"));
  const base::FilePath kFileInNonExistingDirectory(
      FILE_PATH_LITERAL("drive/root/not exist/not exist.png"));

  // Create fails if is_exclusive = true and a file exists.
  FileError error = FILE_ERROR_FAILED;
  operation.CreateFile(
      kExistingFile,
      true,  // is_exclusive
      google_apis::test_util::CreateCopyResultCallback(&error));
  test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_EXISTS, error);

  // Create succeeds if is_exclusive = false and a file exists.
  operation.CreateFile(
      kExistingFile,
      false,  // is_exclusive
      google_apis::test_util::CreateCopyResultCallback(&error));
  test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_OK, error);

  // Create fails if a directory existed even when is_exclusive = false.
  operation.CreateFile(
      kExistingDirectory,
      false,  // is_exclusive
      google_apis::test_util::CreateCopyResultCallback(&error));
  test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_EXISTS, error);

  // Create succeeds if no entry exists.
  operation.CreateFile(
      kNonExistingFile,
      true,   // is_exclusive
      google_apis::test_util::CreateCopyResultCallback(&error));
  test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_OK, error);

  // Create fails if the parent directory does not exist.
  operation.CreateFile(
      kFileInNonExistingDirectory,
      false,  // is_exclusive
      google_apis::test_util::CreateCopyResultCallback(&error));
  test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_NOT_A_DIRECTORY, error);
}

}  // namespace file_system
}  // namespace drive


text:
using System.Collections;

public class ElectricityData {

	public string timestamp { get; set; }
    public string phaseId { get; set; }
	public int activePower { get; set; }
	public int reactivePower { get; set; }

	public ElectricityData (string timestamp, string phaseId, int activePower, int reactivePower)
	{
		this.timestamp = timestamp;
		this.phaseId = phaseId;
		this.activePower = activePower;
		this.reactivePower = reactivePower;
	}

	public override string ToString ()
	{
		return string.Format ("[ElectricityData: Timestamp={0}, PhaseId={1},  ActivePower={2}, ItemId={3}]", timestamp, phaseId, activePower, reactivePower);
	}

	public string ToJson() {
		return "{\"Timestamp\":\""+timestamp+"\", \"PhaseId\":\""+phaseId+"\",  \"ActivePower\":\""+activePower+", \"ItemId\":\""+reactivePower+"\"}";
	}

	public string ToSend() {
		return "t:" + timestamp + ",p:" + phaseId + ",a:" + activePower + ",r:" + reactivePower;
	}

	public static string ArrayToSend(ArrayList items) {
		string toSend = "";
		if (items.Count > 0) {
			toSend = toSend + ((ElectricityData)items [0]).ToSend ();
		}
		if (items.Count > 1) {
			for (int i = 1; i < items.Count; i++) {
				toSend = toSend + ";" + ((ElectricityData)items [i]).ToSend ();
			}
		}
		return toSend;
	}

}


text:
package io.qubite.tomoko.util;

import io.qubite.tomoko.configuration.ConfigurationException;
import net.jodah.typetools.TypeResolver;

public class Preconditions {

    public static void checkNotNull(Object toCheck) {
        if (toCheck == null) {
            throw new NullPointerException();
        }
    }

    public static void checkNotNull(Object toCheck, String message) {
        if (toCheck == null) {
            throw new NullPointerException(message);
        }
    }

    public static void checkArgument(boolean test, String message) {
        if (!test) {
            throw new IllegalArgumentException(message);
        }
    }

    public static <T> void checkNonGeneric(Class<T> clazz) {
        if (clazz.getTypeParameters().length > 0) {
            throw new ConfigurationException("Class " + clazz.getSimpleName() + " is generic. Use value() to define the type explicitly.");
        }
    }

    public static <T> void checkNotUnknown(Class<T> clazz) {
        if (clazz.equals(TypeResolver.Unknown.class)) {
            throw new ConfigurationException("Could not extract type information. Specify it directly through value() methods.");
        }
    }

    public static <T> void checkNotUnknown(Class<T> clazz, String message) {
        if (clazz.equals(TypeResolver.Unknown.class)) {
            throw new ConfigurationException(message);
        }
    }

}


text:
<?php

namespace Sonata\AdminBundle\Builder;

use Sonata\AdminBundle\Admin\FieldDescriptionInterface;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormFactoryInterface;

/**
 * Interface FormContractorInterface
 *
 * @package Sonata\AdminBundle\Builder
 * @author  Thomas Rabaix <thomas.rabaix@sonata-project.org>
 */
interface FormContractorInterface extends BuilderInterface
{
    /**
     * @abstract
     *
     * @param \Symfony\Component\Form\FormFactoryInterface $formFactory
     */
    public function __construct(FormFactoryInterface $formFactory);

    /**
     * @abstract
     *
     * @param string $name
     * @param array  $options
     *
     * @return FormBuilder
     */
    public function getFormBuilder($name, array $options = array());

    /**
     * @abstract
     *
     * @param string                                              $type
     * @param \Sonata\AdminBundle\Admin\FieldDescriptionInterface $fieldDescription
     *
     * @return array
     */
    public function getDefaultOptions($type, FieldDescriptionInterface $fieldDescription);
}


text:
// TypeScript Version: 2.0

/**
* Returns an unsigned 32-bit integer corresponding to the IEEE 754 binary representation of a single-precision floating-point number.
*
* @param x - single-precision floating-point number
* @returns unsigned 32-bit integer
*
* @example
* var float64ToFloat32 = require( `@stdlib/number/float64/base/to-float32` );
*
* var f32 = float64ToFloat32( 1.337 );
* // returns 1.3370000123977661
*
* var w = toWordf( f32 ); // => 0 01111111 01010110010001011010001
* // returns 1068180177
*/
declare function toWordf( x: number ): number;

// EXPORTS //

export = toWordf;


text:
<?php

namespace yiiunit\framework\web\mocks;

use yii\web\Request;

class TestRequestComponent extends Request
{
    /**
     * @var bool|null override getIsAjax() method return value
     */
    public $getIssAjaxOverride;

    /**
     * @var string|null override getMethod() method return value
     */
    public $getMethodOverride;

    /**
     * @var string|null override getUserAgent() method return value
     */
    public $getUserAgentOverride;

    /**
     * @var bool|null override getIsPjax() method return value
     */
    public $getIsPjaxOverride;

    /**
     * @inheritDoc
     */
    public function getMethod()
    {
        if($this->getMethodOverride !== null) {
            return $this->getMethodOverride;
        }
        return parent::getMethod(); // TODO: Change the autogenerated stub
    }

    /**
     * @inheritDoc
     */
    public function getIsAjax()
    {
        if ($this->getIssAjaxOverride !== null) {
            return $this->getIssAjaxOverride;
        }
        return parent::getIsAjax();
    }

    /**
     * @inheritDoc
     */
    public function getIsPjax()
    {
        if ($this->getIsPjaxOverride !== null) {
            return $this->getIsPjaxOverride;
        }
        return parent::getIsPjax();
    }

    /**
     * @inheritDoc
     */
    public function getUserAgent()
    {
        if($this->getUserAgentOverride !== null) {
            return $this->getUserAgentOverride;
        }
        return parent::getUserAgent();
    }
}


text:
/* ###
 * IP: GHIDRA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ghidra.app.merge.util;

import java.awt.BorderLayout;

import javax.swing.*;
import javax.swing.text.*;

import generic.theme.GThemeDefaults.Colors.Messages;
import ghidra.app.merge.MergeConstants;
import ghidra.util.Msg;

/**
 * Panel that shows the current conflict number and the total number of
 * conflicts.
 *
 *
 */
public class ConflictCountPanel extends JPanel {

	private JTextPane textPane;
	private StyledDocument doc;
	private SimpleAttributeSet textAttrSet;
	private SimpleAttributeSet countAttrSet;

	/**
	 * Constructor
	 *
	 */
	public ConflictCountPanel() {
		super(new BorderLayout());
		create();
	}

	/**
	 * Update the counts, e.g., Conflict # 1 of 3.
	 * @param currentCount current
	 * @param totalCount total
	 */
	public void updateCount(int currentCount, int totalCount) {
		textPane.setText("");

		int offset = doc.getLength();
		try {
			doc.insertString(offset, "Conflict # ", textAttrSet);
			offset = doc.getLength();
			doc.insertString(offset, " " + currentCount + " ", countAttrSet);
			offset = doc.getLength();
			doc.insertString(offset, " of ", textAttrSet);
			offset = doc.getLength();
			doc.insertString(offset, " " + totalCount + " ", countAttrSet);
		}
		catch (BadLocationException e) {
			Msg.debug(this, "Exception updating text", e);
		}

	}

	private void create() {

		setBorder(BorderFactory.createTitledBorder("Current Conflict"));
		textPane = new JTextPane();
		textPane.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 0));
		textPane.setEditable(false);
		add(textPane);

		doc = textPane.getStyledDocument();

		textPane.setBackground(getBackground());

		SimpleAttributeSet set = new SimpleAttributeSet();
		set.addAttribute(StyleConstants.Bold, Boolean.TRUE);
		set.addAttribute(StyleConstants.Foreground, Messages.ERROR);

		textAttrSet = new SimpleAttributeSet();
		textAttrSet.addAttribute(StyleConstants.FontSize, 12);

		countAttrSet = new SimpleAttributeSet();
		countAttrSet.addAttribute(StyleConstants.Bold, Boolean.TRUE);
		countAttrSet.addAttribute(StyleConstants.Foreground, MergeConstants.CONFLICT_COLOR);
		updateCount(0, 10);
	}

}


text:
using System.IO;

namespace Hyperledger.Indy.Test
{
    class StorageUtils
    {
        private static void CleanDirectory(string path)
        {
            if (Directory.Exists(path))
            {
                Directory.Delete(path, true);
            }
        }

        public static void CleanupStorage()
        {
            var tmpDir = EnvironmentUtils.GetTmpPath();
            var homeDir = EnvironmentUtils.GetIndyHomePath();

            CleanDirectory(tmpDir);
            CleanDirectory(homeDir);
        }
    }
}


text:
{% extends "base.html"%}
{% block content %}

  {% include "includes/warning.html" %}
  {% include "market/includes/sell_steps.html" %}

EggZlist Post: Info

  <form method="post" class="post-form" action="">
    {{ form.hidden_tag() }}

Contact name: *

    {% if form.name.data %}
        {{ form.name(class_="post-input disabled", readonly=true) }}
    {% else %}
        {{ form.name(class_="post-input") }}
    {% endif %}
    {% for error in form.name.errors %}
        {{ error }}
    {% endfor %}

Email *

    {{ form.email(class_="post-input", placeholder="email@example.com") }}
    {% for error in form.email.errors %}
        {{ error }}
    {% endfor %}

Confirm email *

    {{ form.confirm(class_="post-input", placeholder="email@example.com")}}
    {% for error in form.confirm.errors %}
        {{ error }}
    {% endfor %}

Location:

viewable on map{{ form.viewable(class_="post-input") }}

Zip Code *

    {{ form.zipcode(class_="post-input zipcode") }}
    {% for error in form.zipcode.errors %}
        {{ error }}
    {% endfor %}

Address

    {{ form.address(class_="post-input") }}
    {% for error in form.address.errors %}
        {{ error }}
    {% endfor %}

City

    {{ form.city(class_="post-input") }}
    {% for error in form.city.errors %}
        {{ error }}
    {% endfor %}

State

    {{ form.state(class_="post-input state") }}
    {% for error in form.state.errors %}
        {{ error }}
    {% endfor %}

May users contact you by phone? :

Phone

    {{ form.phone(class_="post-input", placeholder="123-456-7890") }}
    {% for error in form.phone.errors %}
        {{ error }}
    {% endfor %}

        <button href="/market" type="button" name="button">

Cancel

        </button>

        <button type="submit" name="next">

Next

        </button>

  </form>

{% endblock %}


text:
{# ------------------------------------------------------- #}
{# INDIVIDUAL VIEW FOR EACH institutions #}
{# This page can use any data from http:localhost:2000/cms/#/form/institutions/ #}
{# Webhook uses the SWIG.js (like Djagno/Twig) templating system. Their documentation is here: #}
{# http://paularmstrong.github.io/swig/docs/tags/ #}
{# Learn about calling data into Webhook pages here: #}
{# http://www.webhook.com/docs/template-rules-and-filters/ #}
{# ------------------------------------------------------- #}
{# Confused what extends and blocks do? Watch a primer: #}
{# http://www.webhook.com/docs/template-inheritance-blocks/ #}
{% extends "templates/partials/base.html" %}
{# This sets our page <title>. It will append this institutions's name to the site title defined in base.html #}
{% block title %}{% parent %} - {{ item.name }}{% endblock %}
{% block content %}

View a list of all institutions

{{ item.name }}

        Name:
        {{ item.name }}

        Create Date:
        {# Format the date. You can use PHP's date function to format as needed. http://php.net/manual/en/function.date.php #}
        {{ item.create_date|date('F d Y') }}

        Last Updated:
        {# Format the date. You can use PHP's date function to format as needed. http://php.net/manual/en/function.date.php #}
        {{ item.last_updated|date('F d Y') }}

        Publish Date:
        {# Format the date. You can use PHP's date function to format as needed. http://php.net/manual/en/function.date.php #}
        {{ item.publish_date|date('F d Y') }}

        Address:
        <address>
          {{ item.address.street1 }}

          {% if item.address.street2 %}{{ item.address.street2 }}
{% endif %}
          {{ item.address.city }}, {{ item.address.state }}. {{ item.address.country }} {{ item.address.zip }}
        </address>

        Professional Experience (Institution):
        {# Relationship. Note that use the label you set for the relation, not the content-type name. #}
        {% for relation in item.professional_experience_institution %}
          {# You can ouput more than just the name. Feel free to output more fields from the CMS. #}
          {{ relation.name }}{% if not loop.last %},{% endif %}
        {% endfor %}

        Preview URL:
        {{ item.preview_url }}

        Slug:
        {{ item.slug }}

        Teaching Experience (Institution):
        {# Relationship. Note that use the label you set for the relation, not the content-type name. #}
        {% for relation in item.teaching_experience_institution %}
          {# You can ouput more than just the name. Feel free to output more fields from the CMS. #}
          {{ relation.name }}{% if not loop.last %},{% endif %}
        {% endfor %}

        Professional Affliations (Institution):
        {# Relationship. Note that use the label you set for the relation, not the content-type name. #}
        {% for relation in item.professional_affliations_institution %}
          {# You can ouput more than just the name. Feel free to output more fields from the CMS. #}
          {{ relation.name }}{% if not loop.last %},{% endif %}
        {% endfor %}

        Bio (Institution):
        {# Relationship. Note that use the label you set for the relation, not the content-type name. #}
        {% for relation in item.bio_institution %}
          {# You can ouput more than just the name. Feel free to output more fields from the CMS. #}
          {{ relation.name }}{% if not loop.last %},{% endif %}
        {% endfor %}

        References (Institution):
        {# Relationship. Note that use the label you set for the relation, not the content-type name. #}
        {% for relation in item.references_institution %}
          {# You can ouput more than just the name. Feel free to output more fields from the CMS. #}
          {{ relation.name }}{% if not loop.last %},{% endif %}
        {% endfor %}

        Grants and Fellowships (Institution):
        {# Relationship. Note that use the label you set for the relation, not the content-type name. #}
        {% for relation in item.grants_and_fellowships_institution %}
          {# You can ouput more than just the name. Feel free to output more fields from the CMS. #}
          {{ relation.name }}{% if not loop.last %},{% endif %}
        {% endfor %}

        University Service (Institution):
        {# Relationship. Note that use the label you set for the relation, not the content-type name. #}
        {% for relation in item.university_service_institution %}
          {# You can ouput more than just the name. Feel free to output more fields from the CMS. #}
          {{ relation.name }}{% if not loop.last %},{% endif %}
        {% endfor %}

        Research (chair institution):
        {# Relationship. Note that use the label you set for the relation, not the content-type name. #}
        {% for relation in item.research_chair_institution %}
          {# You can ouput more than just the name. Feel free to output more fields from the CMS. #}
          {{ relation.name }}{% if not loop.last %},{% endif %}
        {% endfor %}

{% endblock %}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?android:attr/listPreferredItemHeight"
    android:gravity="center_vertical">

    <LinearLayout
        android:id="@+id/profiles_pref"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center_vertical"
        android:clickable="true"
        android:focusable="true"
        android:background="?android:attr/selectableItemBackground">

        <LinearLayout
            android:id="@android:id/widget_frame"
            android:layout_width="68dip"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:orientation="vertical" />

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="6dip"
            android:layout_marginTop="6dip"
            android:layout_marginBottom="6dip"
            android:layout_weight="1">

            <TextView
                android:id="@+android:id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:singleLine="true"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:ellipsize="marquee"
                android:fadingEdge="horizontal"/>

            <TextView
                android:id="@android:id/summary"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@android:id/title"
                android:layout_alignLeft="@android:id/title"
                android:paddingBottom="3dip"
                android:visibility="gone"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textSize="13sp"
                android:textColor="?android:attr/textColorSecondary"
                android:focusable="false"
                android:maxLines="4" />

        </RelativeLayout>

    </LinearLayout>

    <View
        android:layout_width="2dip"
        android:layout_height="match_parent"
        android:layout_marginTop="5dip"
        android:layout_marginBottom="5dip"
        android:background="@android:drawable/divider_horizontal_dark" />

    <ImageView
        android:id="@+id/profiles_settings"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:paddingLeft="15dip"
        android:paddingRight="?android:attr/scrollbarSize"
        android:src="@drawable/ic_sysbar_quicksettings"
        android:contentDescription="Setting"
        android:layout_gravity="center"
        android:clickable="true"
        android:focusable="true"
        android:background="?android:attr/selectableItemBackground" />

</LinearLayout>


text:
package org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.allocationfile;

import org.apache.hadoop.util.Lists;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;

import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair
    .allocationfile.AllocationFileWriter.addIfPresent;

/**
 * DAO for Allocation File Queue.
 */
final public class AllocationFileQueue {
  private static final String DEFAULT_TAG_NAME = "queue";
  private static final String LEGACY_TAG_NAME = "pool";

  private final String queueName;
  private final String minResources;
  private final String maxResources;
  private final String aclAdministerApps;
  private final String aclSubmitApps;
  private final String aclSubmitReservations;
  private final String aclAdministerReservations;
  private final String aclListReservations;
  private final String schedulingPolicy;
  private final Integer maxRunningApps;
  private final Double maxAMShare;
  private final Boolean allowPreemptionFrom;
  private final Integer minSharePreemptionTimeout;
  private final String maxChildResources;
  private final Integer fairSharePreemptionTimeout;
  private final Double fairSharePreemptionThreshold;
  private final String maxContainerAllocation;
  private final List<AllocationFileQueue> subQueues;
  private final Float weight;
  private String tagName;

  private final boolean parent;
  private final boolean reservation;

  private AllocationFileQueue(Builder builder) {
    this.queueName = builder.name;
    this.parent = builder.parent;
    this.minResources = builder.minResources;
    this.maxResources = builder.maxResources;
    this.aclAdministerApps = builder.aclAdministerApps;
    this.aclSubmitApps = builder.aclSubmitApps;
    this.aclSubmitReservations = builder.aclSubmitReservations;
    this.aclAdministerReservations = builder.aclAdministerReservations;
    this.aclListReservations = builder.aclListReservations;
    this.schedulingPolicy = builder.schedulingPolicy;
    this.maxRunningApps = builder.maxRunningApps;
    this.maxAMShare = builder.maxAMShare;
    this.allowPreemptionFrom = builder.allowPreemptionFrom;
    this.minSharePreemptionTimeout = builder.minSharePreemptionTimeout;
    this.maxChildResources = builder.maxChildResources;
    this.fairSharePreemptionTimeout = builder.fairSharePreemptionTimeout;
    this.fairSharePreemptionThreshold = builder.fairSharePreemptionThreshold;
    this.maxContainerAllocation = builder.maxContainerAllocation;
    this.weight = builder.weight;
    this.reservation = builder.reservation;
    this.subQueues = builder.subQueues;
    this.tagName = DEFAULT_TAG_NAME;
  }

  String render() {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    printStartTag(pw);
    AllocationFileWriter.printQueues(pw, subQueues,
        tagName.equals(LEGACY_TAG_NAME));
    addIfPresent(pw, "minResources", minResources);
    addIfPresent(pw, "maxResources", maxResources);
    addIfPresent(pw, "aclAdministerApps", aclAdministerApps);
    addIfPresent(pw, "aclSubmitApps", aclSubmitApps);
    addIfPresent(pw, "aclSubmitReservations", aclSubmitReservations);
    addIfPresent(pw, "aclAdministerReservations", aclAdministerReservations);
    addIfPresent(pw, "aclListReservations", aclListReservations);
    addIfPresent(pw, "schedulingPolicy", schedulingPolicy);
    addIfPresent(pw, "maxRunningApps", maxRunningApps);
    addIfPresent(pw, "maxAMShare", maxAMShare);
    addIfPresent(pw, "allowPreemptionFrom", allowPreemptionFrom);
    addIfPresent(pw, "minSharePreemptionTimeout", minSharePreemptionTimeout);
    addIfPresent(pw, "maxChildResources", maxChildResources);
    addIfPresent(pw, "fairSharePreemptionTimeout", fairSharePreemptionTimeout);
    addIfPresent(pw, "fairSharePreemptionThreshold",
        fairSharePreemptionThreshold);
    addIfPresent(pw, "maxContainerAllocation", maxContainerAllocation);
    addIfPresent(pw, "weight", weight);
    if (reservation) {
      pw.println("<reservation></reservation>");
    }
    printEndTag(pw);
    pw.close();

    return sw.toString();
  }

  String renderWithLegacyTag() {
    this.tagName = LEGACY_TAG_NAME;
    return render();
  }

  private void printStartTag(PrintWriter pw) {
    String queueWithName = String.format("<%s name=\"%s\"", tagName, queueName);
    pw.print(queueWithName);
    if (parent) {
      pw.print(" type=\"parent\"");
    }
    pw.println(">");
  }

  private void printEndTag(PrintWriter pw) {
    pw.println("</" + tagName + ">");
  }

  /**
   * Class that can build queues (with subqueues) for testcases.
   * The intention of having this class to group the common properties of
   * simple queues and subqueues by methods delegating calls to a
   * queuePropertiesBuilder instance.
   */
  public static class Builder {
    private String name;
    private String minResources;
    private String maxResources;
    private String aclAdministerApps;
    private String aclSubmitApps;
    private String aclSubmitReservations;
    private String aclAdministerReservations;
    private String aclListReservations;
    private String schedulingPolicy;
    private Integer maxRunningApps;
    private Double maxAMShare;
    private Boolean allowPreemptionFrom;
    private Integer minSharePreemptionTimeout;
    private boolean parent;
    private String maxChildResources;
    private Integer fairSharePreemptionTimeout;
    private Double fairSharePreemptionThreshold;
    private String maxContainerAllocation;
    private boolean reservation;
    private final List<AllocationFileQueue> subQueues = Lists.newArrayList();
    private Float weight;

    public Builder(String name) {
      this.name = name;
    }

    public Builder parent(boolean value) {
      this.parent = value;
      return this;
    }

    public Builder minResources(String value) {
      this.minResources = value;
      return this;
    }

    public Builder maxResources(String value) {
      this.maxResources = value;
      return this;
    }

    public Builder aclAdministerApps(String value) {
      this.aclAdministerApps = value;
      return this;
    }

    public Builder aclSubmitApps(String value) {
      this.aclSubmitApps = value;
      return this;
    }

    public Builder aclSubmitReservations(String value) {
      this.aclSubmitReservations = value;
      return this;
    }

    public Builder aclAdministerReservations(String value) {
      this.aclAdministerReservations = value;
      return this;
    }

    public Builder aclListReservations(String value) {
      this.aclListReservations = value;
      return this;
    }

    public Builder schedulingPolicy(String value) {
      this.schedulingPolicy = value;
      return this;
    }

    public Builder maxRunningApps(int value) {
      this.maxRunningApps = value;
      return this;
    }

    public Builder maxAMShare(double value) {
      this.maxAMShare = value;
      return this;
    }

    public Builder allowPreemptionFrom(boolean value) {
      this.allowPreemptionFrom = value;
      return this;
    }

    public Builder minSharePreemptionTimeout(int value) {
      this.minSharePreemptionTimeout = value;
      return this;
    }

    public Builder maxChildResources(String value) {
      this.maxChildResources = value;
      return this;
    }

    public Builder fairSharePreemptionTimeout(Integer value) {
      this.fairSharePreemptionTimeout = value;
      return this;
    }

    public Builder fairSharePreemptionThreshold(
        double value) {
      this.fairSharePreemptionThreshold = value;
      return this;
    }

    public Builder maxContainerAllocation(String value) {
      this.maxContainerAllocation = value;
      return this;
    }

    public Builder weight(float value) {
      this.weight = value;
      return this;
    }

    public Builder reservation() {
      this.reservation = true;
      return this;
    }

    public Builder subQueue(AllocationFileQueue queue) {
      if (queue == null) {
        throw new IllegalArgumentException("Subqueue cannot be null!");
      }
      subQueues.add(queue);
      return this;
    }

    public AllocationFileQueue build() {
      return new AllocationFileQueue(this);
    }
  }
}


text:
DO $$
BEGIN

IF NOT EXISTS (
    SELECT 1
    FROM   pg_catalog.pg_class c
    JOIN   pg_catalog.pg_namespace n ON n.oid = c.relnamespace
    WHERE  c.relname = 'event_device_date_idx'
    AND    n.nspname = current_schema
    ) THEN
    CREATE INDEX event_device_date_idx ON event (device, date_time);
END IF;

IF NOT EXISTS (
    SELECT 1
    FROM   pg_catalog.pg_class c
    JOIN   pg_catalog.pg_namespace n ON n.oid = c.relnamespace
    WHERE  c.relname = 'event_date_time_idx'
    AND    n.nspname = current_schema
    ) THEN
    CREATE INDEX event_date_time_idx ON event (date_time);
END IF;

END;
$$


text:
BuilderShared = {
	makeBuilderShared : function(armyDescType)
	{
		var army = Army.makeArmy(armyDescType);
		var armyConfigOld = army._setArmyConfig;
		var refreshStatsOld = army.refreshStats;
		var loadOld = army.load;
		var dumpOld = army.dump;

		var out = {
			buildingMap : [],
			map : null,

			_setArmyConfig : function(config)
			{
				armyConfigOld.call(this, config);

				this.builds = 0;
				this.initBuilds = config.initBuilds;

				return config;
			},

			refreshStats : function()
			{
				refreshStatsOld.call(this);

				this.builds = this.initBuilds;
			},

			buildingPosition : function(building)
			{
				var config = ObjectDesc.getConfiguration(building);
				this.map = [];
				var map = [];

				if(this.builds == 0)
				{
					return map;
				}

				this.setSurrounding(this.position.x, this.position.y, map);

				this.map = map;

				for(var x = 0; x < map.length; x++)
				{
					var tiles = Field.getObject(map[x].x, map[x].y);

					var tile = tiles && tiles[0];

					if(tile)
					{
						if(!config.forbidenTiles)
						{
							break;
						}
						for(var i = 0; i < config.forbidenTiles.length; i++)
						{
							if(tile && tile.type == config.forbidenTiles[i])
							{
								map.splice(x, 1);
								x--;
								break;
							}
						}
					}
				}

				return map;
			},

			buildObject : function(building, x, y)
			{
				var map = this.buildingPosition(building);
				if(this.map && this.checkMapObject(map, {x : x, y : y}))
				{
					if(Field.getArmyObject(x, y) || Field.getBuildingObject(x, y))
					{
						return;
					}

					if(this.player && this.player.inTurn)
					{
						this.builds--;

						this.player.buildObject(building, x, y);
					}
				}
				this.map = null;
			},

			load : function(json)
			{
				loadOld.call(this, json);

				this.builds = json.builds;
			},

			dump : function()
			{
				var dump = dumpOld.call(this);

				console.log("builds ! ", this.builds);

				dump.builds = this.builds;

				return dump;
			}

		};

		return Object.assign(army, out);
	}
};


text:
package timeutil

import (
	"os"
	"testing"

	. "github.com/pingcap/check"
)

var _ = Suite(&testTimeSuite{})

func TestT(t *testing.T) {
	TestingT(t)
}

type testTimeSuite struct{}

func (s *testTimeSuite) TestgetTZNameFromFileName(c *C) {
	tz, err := inferTZNameFromFileName("/user/share/zoneinfo/Asia/Shanghai")

	c.Assert(err, IsNil)
	c.Assert(tz, Equals, "Asia/Shanghai")

	tz, err = inferTZNameFromFileName("/usr/share/zoneinfo.default/Asia/Shanghai")

	c.Assert(err, IsNil)
	c.Assert(tz, Equals, "Asia/Shanghai")
}

func (s *testTimeSuite) TestLocal(c *C) {
	os.Setenv("TZ", "Asia/Shanghai")
	systemTZ = InferSystemTZ()
	loc := SystemLocation()
	c.Assert(systemTZ, Equals, "Asia/Shanghai")
	c.Assert(loc.String(), Equals, "Asia/Shanghai")

	os.Setenv("TZ", "UTC")
	// reset systemTZ
	systemTZ = InferSystemTZ()
	loc = SystemLocation()
	c.Assert(loc.String(), Equals, "UTC")

	os.Setenv("TZ", "")
	// reset systemTZ
	systemTZ = InferSystemTZ()
	loc = SystemLocation()
	c.Assert(loc.String(), Equals, "UTC")
	os.Unsetenv("TZ")
}


text:
Location where default version of todeLoad.st is located.
Used by $GS_HOME/bin/createTodeImage and $GS_HOME/bin/updateTodeImage