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

/** @addtogroup STM32H7xx_HAL_Driver
  * @{
  */

/** @defgroup FLASHEx  FLASHEx
  * @brief FLASH HAL Extension module driver
  * @{
  */

#ifdef HAL_FLASH_MODULE_ENABLED

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @addtogroup FLASHEx_Private_Constants
  * @{
  */
#define FLASH_TIMEOUT_VALUE       50000U/* 50 s */
/**
  * @}
  */
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
extern FLASH_ProcessTypeDef pFlash;

/* Private function prototypes -----------------------------------------------*/

static void FLASH_MassErase(uint32_t VoltageRange, uint32_t Banks);
void FLASH_Erase_Sector(uint32_t Sector, uint32_t Bank, uint32_t VoltageRange);
static HAL_StatusTypeDef FLASH_OB_EnableWRP(uint32_t WRPSector, uint32_t Banks);
static HAL_StatusTypeDef FLASH_OB_DisableWRP(uint32_t WRPSector, uint32_t Bank);
static void FLASH_OB_GetWRP(uint32_t *WRPState, uint32_t *WRPSector, uint32_t Bank);
static HAL_StatusTypeDef FLASH_OB_RDPConfig(uint32_t RDPLevel);
static uint32_t FLASH_OB_GetRDP(void);
static HAL_StatusTypeDef FLASH_OB_PCROPConfig(uint32_t PCROConfigRDP, uint32_t PCROPStartAddr, uint32_t PCROPEndAddr, uint32_t Banks);
static void FLASH_OB_GetPCROP(uint32_t *PCROPConfig, uint32_t *PCROPStartAddr,uint32_t *PCROPEndAddr, uint32_t Bank);
static HAL_StatusTypeDef FLASH_OB_BOR_LevelConfig(uint8_t Level);
static uint32_t FLASH_OB_GetBOR(void);
static HAL_StatusTypeDef FLASH_OB_UserConfig(uint32_t UserType, uint32_t UserConfig);
static uint32_t FLASH_OB_GetUser(void);
static HAL_StatusTypeDef FLASH_OB_BootAddConfig(uint32_t BootOption, uint32_t BootAddress0, uint32_t BootAddress1);
static void FLASH_OB_GetBootAdd(uint32_t *BootAddress0, uint32_t *BootAddress1);
static HAL_StatusTypeDef FLASH_OB_SecureAreaConfig(uint32_t SecureAreaConfig, uint32_t SecureAreaStartAddr, uint32_t SecureAreaEndAddr, uint32_t Banks);
static void FLASH_OB_GetSecureArea(uint32_t *SecureAreaConfig, uint32_t *SecureAreaStartAddr, uint32_t *SecureAreaEndAddr, uint32_t Bank);

/* Private functions ---------------------------------------------------------*/

/** @defgroup FLASHEx_Private_Functions Extended FLASH Private functions
  * @{
  */

/** @defgroup FLASHEx_Group1 Extended IO operation functions
 *  @brief   Extended IO operation functions
 *
@verbatim
 ===============================================================================
                ##### Extended programming operation functions #####
 ===============================================================================
    [..]
    This subsection provides a set of functions allowing to manage the Extension FLASH
    programming operations Operations.

@endverbatim
  * @{
  */
/**
  * @brief  Perform a mass erase or erase the specified FLASH memory sectors
  * @param[in]  pEraseInit pointer to an FLASH_EraseInitTypeDef structure that
  *         contains the configuration information for the erasing.
  *
  * @param[out]  SectorError pointer to variable  that
  *         contains the configuration information on faulty sector in case of error
  *         (0xFFFFFFFF means that all the sectors have been correctly erased)
  *
  * @retval HAL Status
  */
HAL_StatusTypeDef HAL_FLASHEx_Erase(FLASH_EraseInitTypeDef *pEraseInit, uint32_t *SectorError)
{
  HAL_StatusTypeDef status = HAL_OK;
  uint32_t index = 0;

  /* Process Locked */
  __HAL_LOCK(&pFlash);

  /* Check the parameters */
  assert_param(IS_FLASH_TYPEERASE(pEraseInit->TypeErase));
  assert_param(IS_VOLTAGERANGE(pEraseInit->VoltageRange));
  assert_param(IS_FLASH_BANK(pEraseInit->Banks));

  /* Wait for last operation to be completed */
  if((pEraseInit->Banks & FLASH_BANK_1) == FLASH_BANK_1)
  {
    status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_1);
  }

  if((pEraseInit->Banks & FLASH_BANK_2) == FLASH_BANK_2)
  {
    status |= FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_2);
  }

  if(status == HAL_OK)
  {
    /*Initialization of SectorError variable*/
    *SectorError = 0xFFFFFFFF;

    if(pEraseInit->TypeErase == FLASH_TYPEERASE_MASSERASE)
    {
      /*Mass erase to be done*/
      FLASH_MassErase(pEraseInit->VoltageRange, pEraseInit->Banks);

      /* Wait for last operation to be completed */
      if((pEraseInit->Banks & FLASH_BANK_1) == FLASH_BANK_1)
      {
        status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_1);
        /* if the erase operation is completed, disable the Bank1 BER Bit */
        FLASH->CR1 &= (~FLASH_CR_BER);
      }
      if((pEraseInit->Banks & FLASH_BANK_2) == FLASH_BANK_2)
      {
        status |= FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_2);
        /* if the erase operation is completed, disable the Bank2 BER Bit */
        FLASH->CR2 &= (~FLASH_CR_BER);
      }
    }
    else
    {
      /* Check the parameters */
      assert_param(IS_FLASH_BANK_EXCLUSIVE(pEraseInit->Banks));
      assert_param(IS_FLASH_NBSECTORS(pEraseInit->NbSectors + pEraseInit->Sector));

      /* Erase by sector by sector to be done*/
      for(index = pEraseInit->Sector; index < (pEraseInit->NbSectors + pEraseInit->Sector); index++)
      {
        FLASH_Erase_Sector(index, pEraseInit->Banks, pEraseInit->VoltageRange);

        if((pEraseInit->Banks & FLASH_BANK_1) == FLASH_BANK_1)
        {
          /* Wait for last operation to be completed */
          status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_1);

          /* If the erase operation is completed, disable the SER Bit */
          FLASH->CR1 &= (~(FLASH_CR_SER | FLASH_CR_SNB));
        }
        if((pEraseInit->Banks & FLASH_BANK_2) == FLASH_BANK_2)
        {
          /* Wait for last operation to be completed */
          status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_2);

          /* If the erase operation is completed, disable the SER Bit */
          FLASH->CR2 &= (~(FLASH_CR_SER | FLASH_CR_SNB));
        }

        if(status != HAL_OK)
        {
          /* In case of error, stop erase procedure and return the faulty sector*/
          *SectorError = index;
          break;
        }
      }
    }
  }

  /* Process Unlocked */
  __HAL_UNLOCK(&pFlash);

  return status;
}

/**
  * @brief  Perform a mass erase or erase the specified FLASH memory sectors with interrupt enabled
  * @param  pEraseInit pointer to an FLASH_EraseInitTypeDef structure that
  *         contains the configuration information for the erasing.
  *
  * @retval HAL Status
  */
HAL_StatusTypeDef HAL_FLASHEx_Erase_IT(FLASH_EraseInitTypeDef *pEraseInit)
{
  HAL_StatusTypeDef status = HAL_OK;

  /* Process Locked */
  __HAL_LOCK(&pFlash);

  /* Check the parameters */
  assert_param(IS_FLASH_TYPEERASE(pEraseInit->TypeErase));
  assert_param(IS_VOLTAGERANGE(pEraseInit->VoltageRange));
  assert_param(IS_FLASH_BANK(pEraseInit->Banks));

  if((pEraseInit->Banks & FLASH_BANK_1) == FLASH_BANK_1)
  {
    /* Clear bank 1 pending flags (if any) */
    __HAL_FLASH_CLEAR_FLAG_BANK1(FLASH_FLAG_EOP_BANK1 | FLASH_FLAG_ALL_ERRORS_BANK1);

    /* Enable End of Operation and Error interrupts for Bank 1 */
    __HAL_FLASH_ENABLE_IT_BANK1(FLASH_IT_EOP_BANK1    | FLASH_IT_WRPERR_BANK1 | FLASH_IT_PGSERR_BANK1 | \
                                FLASH_IT_STRBERR_BANK1 | FLASH_IT_INCERR_BANK1 | FLASH_IT_OPERR_BANK1);
  }
  if((pEraseInit->Banks & FLASH_BANK_2) == FLASH_BANK_2)
  {
    /* Clear bank 2 pending flags (if any) */
    __HAL_FLASH_CLEAR_FLAG_BANK2(FLASH_FLAG_EOP_BANK2 | FLASH_FLAG_ALL_ERRORS_BANK2);

    /* Enable End of Operation and Error interrupts for Bank 2 */
    __HAL_FLASH_ENABLE_IT_BANK2(FLASH_IT_EOP_BANK2    | FLASH_IT_WRPERR_BANK2 | FLASH_IT_PGSERR_BANK2 | \
                                FLASH_IT_STRBERR_BANK2 | FLASH_IT_INCERR_BANK2 | FLASH_IT_OPERR_BANK2);
  }

  if(pEraseInit->TypeErase == FLASH_TYPEERASE_MASSERASE)
  {
    /*Mass erase to be done*/
    if(pEraseInit->Banks == FLASH_BANK_1)
    {
      pFlash.ProcedureOnGoing = FLASH_PROC_MASSERASE_BANK1;
    }
    else if(pEraseInit->Banks == FLASH_BANK_2)
    {
      pFlash.ProcedureOnGoing = FLASH_PROC_MASSERASE_BANK2;
    }
    else
    {
      pFlash.ProcedureOnGoing = FLASH_PROC_ALLBANK_MASSERASE;
    }

    FLASH_MassErase(pEraseInit->VoltageRange, pEraseInit->Banks);
  }
  else
  {
    /* Erase by sector to be done*/

    /* Check the parameters */
    assert_param(IS_FLASH_BANK_EXCLUSIVE(pEraseInit->Banks));
    assert_param(IS_FLASH_NBSECTORS(pEraseInit->NbSectors + pEraseInit->Sector));

    if(pEraseInit->Banks == FLASH_BANK_1)
    {
      pFlash.ProcedureOnGoing = FLASH_PROC_SECTERASE_BANK1;
    }
    else
    {
      pFlash.ProcedureOnGoing = FLASH_PROC_SECTERASE_BANK2;
    }

    pFlash.NbSectorsToErase = pEraseInit->NbSectors;
    pFlash.Sector = pEraseInit->Sector;
    pFlash.VoltageForErase = pEraseInit->VoltageRange;

    /*Erase 1st sector and wait for IT*/
    FLASH_Erase_Sector(pEraseInit->Sector, pEraseInit->Banks, pEraseInit->VoltageRange);
  }

  return status;
}

/**
  * @brief  Program option bytes
  * @param  pOBInit pointer to an FLASH_OBInitStruct structure that
  *         contains the configuration information for the programming.
  *
  * @retval HAL Status
  */
HAL_StatusTypeDef HAL_FLASHEx_OBProgram(FLASH_OBProgramInitTypeDef *pOBInit)
{
  HAL_StatusTypeDef status = HAL_OK;

  /* Process Locked */
  __HAL_LOCK(&pFlash);

  /* Check the parameters */
  assert_param(IS_OPTIONBYTE(pOBInit->OptionType));

  pFlash.ErrorCode = HAL_FLASH_ERROR_NONE;

  /*Write protection configuration*/
  if((pOBInit->OptionType & OPTIONBYTE_WRP) == OPTIONBYTE_WRP)
  {
    assert_param(IS_WRPSTATE(pOBInit->WRPState));
    assert_param(IS_FLASH_BANK(pOBInit->Banks));

    if(pOBInit->WRPState == OB_WRPSTATE_ENABLE)
    {
      /*Enable of Write protection on the selected Sector*/
      status = FLASH_OB_EnableWRP(pOBInit->WRPSector,pOBInit->Banks);
    }
    else
    {
      /*Disable of Write protection on the selected Sector*/
      status = FLASH_OB_DisableWRP(pOBInit->WRPSector, pOBInit->Banks);
    }
    if(status != HAL_OK)
    {
      /* Process Unlocked */
      __HAL_UNLOCK(&pFlash);
      return status;
    }
  }

  /* Read protection configuration */
  if((pOBInit->OptionType & OPTIONBYTE_RDP) != RESET)
  {
    /* Configure the Read protection level */
    status = FLASH_OB_RDPConfig(pOBInit->RDPLevel);
    if(status != HAL_OK)
    {
      /* Process Unlocked */
      __HAL_UNLOCK(&pFlash);
      return status;
    }
  }

  /* User Configuration */
  if((pOBInit->OptionType & OPTIONBYTE_USER) != RESET)
  {
    /* Configure the user option bytes */
    status = FLASH_OB_UserConfig(pOBInit->USERType, pOBInit->USERConfig);
    if(status != HAL_OK)
    {
      /* Process Unlocked */
      __HAL_UNLOCK(&pFlash);
      return status;
    }
  }

  /* PCROP Configuration */
  if((pOBInit->OptionType & OPTIONBYTE_PCROP) != RESET)
  {
    assert_param(IS_FLASH_BANK(pOBInit->Banks));

    /*Configure the Proprietary code readout protection */
    status = FLASH_OB_PCROPConfig(pOBInit->PCROPConfig, pOBInit->PCROPStartAddr, pOBInit->PCROPEndAddr, pOBInit->Banks);
    if(status != HAL_OK)
    {
      /* Process Unlocked */
      __HAL_UNLOCK(&pFlash);
      return status;
    }

  }

  /*BOR Level  configuration*/
  if((pOBInit->OptionType & OPTIONBYTE_BOR) == OPTIONBYTE_BOR)
  {
    status = FLASH_OB_BOR_LevelConfig(pOBInit->BORLevel);
    if(status != HAL_OK)
    {
      /* Process Unlocked */
      __HAL_UNLOCK(&pFlash);
      return status;
    }
  }

  /*Boot Address  configuration*/
  if((pOBInit->OptionType & OPTIONBYTE_BOOTADD) == OPTIONBYTE_BOOTADD)
  {
    status = FLASH_OB_BootAddConfig(pOBInit->BootConfig, pOBInit->BootAddr0, pOBInit->BootAddr1);
    if(status != HAL_OK)
    {
      /* Process Unlocked */
      __HAL_UNLOCK(&pFlash);
      return status;
    }
  }
  /*Bank1 secure area  configuration*/
  if((pOBInit->OptionType & OPTIONBYTE_SECURE_AREA) == OPTIONBYTE_SECURE_AREA)
  {
    status = FLASH_OB_SecureAreaConfig(pOBInit->SecureAreaConfig, pOBInit->SecureAreaStartAddr, pOBInit->SecureAreaEndAddr,pOBInit->Banks);
    if(status != HAL_OK)
    {
      /* Process Unlocked */
      __HAL_UNLOCK(&pFlash);
      return status;
    }
  }

  /* Process Unlocked */
  __HAL_UNLOCK(&pFlash);

  return status;
}

/**
  * @brief Get the Option byte configuration
  * @note  The parameter Banks of the pOBInit structure must be exclusively FLASH_BANK_1 or FLASH_BANK_2
           as this parameter is use to get the given Bank WRP, PCROP and secured area.
  * @param  pOBInit pointer to an FLASH_OBInitStruct structure that
  *         contains the configuration information for the programming.
  *
  * @retval None
  */
void HAL_FLASHEx_OBGetConfig(FLASH_OBProgramInitTypeDef *pOBInit)
{
  /* Check the parameters */
  assert_param(IS_FLASH_BANK_EXCLUSIVE(pOBInit->Banks));
  pOBInit->OptionType = (OPTIONBYTE_WRP  | OPTIONBYTE_RDP         | \
                         OPTIONBYTE_USER | OPTIONBYTE_PCROP       | \
                         OPTIONBYTE_BOR  | OPTIONBYTE_BOOTADD | \
                         OPTIONBYTE_SECURE_AREA);

  /* Get write protection on the selected area */
  FLASH_OB_GetWRP(&(pOBInit->WRPState), &(pOBInit->WRPSector), pOBInit->Banks);

  /* Get Read protection level */
  pOBInit->RDPLevel = FLASH_OB_GetRDP();

  /* Get the user option bytes */
  pOBInit->USERConfig = FLASH_OB_GetUser();

  /* Get the Proprietary code readout protection */
  FLASH_OB_GetPCROP(&(pOBInit->PCROPConfig), &(pOBInit->PCROPStartAddr), &(pOBInit->PCROPEndAddr), pOBInit->Banks);

  /*Get BOR Level*/
  pOBInit->BORLevel = FLASH_OB_GetBOR();

  /*Get Boot Address*/
  FLASH_OB_GetBootAdd(&(pOBInit->BootAddr0), &(pOBInit->BootAddr1));
  /*Get Bank Secure area*/
  FLASH_OB_GetSecureArea(&(pOBInit->SecureAreaConfig), &(pOBInit->SecureAreaStartAddr), &(pOBInit->SecureAreaEndAddr), pOBInit->Banks);
}

/**
  * @brief  Unlock the FLASH Bank1 control registers access
  * @retval HAL Status
  */
HAL_StatusTypeDef HAL_FLASHEx_Unlock_Bank1(void)
{
  if(READ_BIT(FLASH->CR1, FLASH_CR_LOCK) != RESET)
  {
    /* Authorize the FLASH A Registers access */
    WRITE_REG(FLASH->KEYR1, FLASH_KEY1);
    WRITE_REG(FLASH->KEYR1, FLASH_KEY2);
  }
  else
  {
    return HAL_ERROR;
  }

  return HAL_OK;
}

/**
  * @brief  Locks the FLASH Bank1 control registers access
  * @retval HAL Status
  */
HAL_StatusTypeDef HAL_FLASHEx_Lock_Bank1(void)
{
  /* Set the LOCK Bit to lock the FLASH A Registers access */
  SET_BIT(FLASH->CR1, FLASH_CR_LOCK);
  return HAL_OK;
}

/**
  * @brief  Unlock the FLASH Bank2 control registers access
  * @retval HAL Status
  */
HAL_StatusTypeDef HAL_FLASHEx_Unlock_Bank2(void)
{
  if(READ_BIT(FLASH->CR2, FLASH_CR_LOCK) != RESET)
  {
    /* Authorize the FLASH A Registers access */
    WRITE_REG(FLASH->KEYR2, FLASH_KEY1);
    WRITE_REG(FLASH->KEYR2, FLASH_KEY2);
  }
  else
  {
    return HAL_ERROR;
  }

  return HAL_OK;
}

/**
  * @brief  Locks the FLASH Bank2 control registers access
  * @retval HAL Status
  */
HAL_StatusTypeDef HAL_FLASHEx_Lock_Bank2(void)
{
  /* Set the LOCK Bit to lock the FLASH A Registers access */
  SET_BIT(FLASH->CR2, FLASH_CR_LOCK);
  return HAL_OK;
}

/**
  * @brief  Full erase of FLASH memory sectors
  * @param  VoltageRange The device program/erase parallelism.
  *          This parameter can be one of the following values:
  *            @arg FLASH_VOLTAGE_RANGE_1 : Flash program/erase by 8 bits
  *            @arg FLASH_VOLTAGE_RANGE_2 : Flash program/erase by 16 bits
  *            @arg FLASH_VOLTAGE_RANGE_3 : Flash program/erase by 32 bits
  *            @arg FLASH_VOLTAGE_RANGE_4 : Flash program/erase by 64 bits
  *
  * @param  Banks Banks to be erased
  *          This parameter can be one of the following values:
  *            @arg FLASH_BANK_1: Bank1 to be erased
  *            @arg FLASH_BANK_2: Bank2 to be erased
  *            @arg FLASH_BANK_BOTH: Bank1 and Bank2 to be erased
  *
  * @retval HAL Status
  */
static void FLASH_MassErase(uint32_t VoltageRange, uint32_t Banks)
{
  /* Check the parameters */
  assert_param(IS_FLASH_BANK(Banks));
  assert_param(IS_VOLTAGERANGE(VoltageRange));

  /* Flash Mass Erase */
  if((Banks & FLASH_BANK_BOTH) == FLASH_BANK_BOTH)
  {
    /* reset Program/erase VoltageRange for Bank1 */
    FLASH->CR1 &= (~FLASH_CR_PSIZE);
    /* Bank1 will be erased, and set voltage range*/
    FLASH->CR1 |= FLASH_CR_BER | VoltageRange;

    FLASH->OPTCR |= FLASH_OPTCR_MER;

  }
  else
  {
    /* Proceed to erase Flash Bank  */
    if((Banks & FLASH_BANK_1) == FLASH_BANK_1)
    {
      /* reset Program/erase VoltageRange for Bank1 */
      FLASH->CR1 &= (~FLASH_CR_PSIZE);

      /* Bank1 will be erased, and set voltage range*/
      FLASH->CR1 |= FLASH_CR_BER | VoltageRange;
      FLASH->CR1 |= FLASH_CR_START;
    }
    if((Banks & FLASH_BANK_2) == FLASH_BANK_2)
    {
      /* reset Program/erase VoltageRange for Bank2 */
      FLASH->CR2 &= (~FLASH_CR_PSIZE);

      /* Bank2 will be erased, and set voltage range*/
      FLASH->CR2 |= FLASH_CR_BER | VoltageRange;
      FLASH->CR2 |= FLASH_CR_START;
    }
  }
}

/**
  * @brief  Erase the specified FLASH memory sector
  * @param  Sector FLASH sector to erase
  * @param  Banks Banks to be erased
  *          This parameter can be one of the following values:
  *            @arg FLASH_BANK_1: Bank1 to be erased
  *            @arg FLASH_BANK_2: Bank2 to be erased
  *            @arg FLASH_BANK_BOTH: Bank1 and Bank2 to be erased
  * @param  VoltageRange The device program/erase parallelism.
  *          This parameter can be one of the following values:
  *            @arg FLASH_VOLTAGE_RANGE_1 : Flash program/erase by 8 bits
  *            @arg FLASH_VOLTAGE_RANGE_2 : Flash program/erase by 16 bits
  *            @arg FLASH_VOLTAGE_RANGE_3 : Flash program/erase by 32 bits
  *            @arg FLASH_VOLTAGE_RANGE_4 : Flash program/erase by 62 bits
  *
  * @retval None
  */
void FLASH_Erase_Sector(uint32_t Sector, uint32_t Banks, uint32_t VoltageRange)
{
  assert_param(IS_FLASH_BANK_EXCLUSIVE(Banks));
  assert_param(IS_VOLTAGERANGE(VoltageRange));
  assert_param(IS_FLASH_SECTOR(Sector));

  if((Banks & FLASH_BANK_1) == FLASH_BANK_1)
  {
    /* reset Program/erase VoltageRange for Bank1 */
    FLASH->CR1 &= ~(FLASH_CR_PSIZE | FLASH_CR_SNB);

    FLASH->CR1 |= (FLASH_CR_SER | VoltageRange | (Sector << POSITION_VAL(FLASH_CR_SNB)));

    FLASH->CR1 |= FLASH_CR_START;
  }

  if((Banks & FLASH_BANK_2) == FLASH_BANK_2)
  {
    /* reset Program/erase VoltageRange for Bank2 */
    FLASH->CR2 &= ~(FLASH_CR_PSIZE | FLASH_CR_SNB);

    FLASH->CR2 |= (FLASH_CR_SER | VoltageRange  | (Sector << POSITION_VAL(FLASH_CR_SNB)));

    FLASH->CR2 |= FLASH_CR_START;
  }
}

/**
  * @brief  Enable the write protection of the desired bank1 or bank 2 sectors
  * @param  WRPSector specifies the sector(s) to be write protected.
  *          This parameter can be one of the following values:
  *            @arg WRPSector:  A combination of OB_WRP_SECTOR_0 to OB_WRP_SECTOR_0 or OB_WRP_SECTOR_All
  *
  * @param  Banks the specific bank to apply WRP sectors
  *          This parameter can be one of the following values:
  *            @arg FLASH_BANK_1: WRP enable on specified bank1 sectors
  *            @arg FLASH_BANK_2: WRP enable on specified bank2 sectors
  *            @arg FLASH_BANK_BOTH: WRP enable bank1 and bank2 specified sectors
  *
  * @retval HAL FLASH State
  */
static HAL_StatusTypeDef FLASH_OB_EnableWRP(uint32_t WRPSector, uint32_t Banks)
{
  HAL_StatusTypeDef status = HAL_OK;

  /* Check the parameters */
  assert_param(IS_FLASH_BANK(Banks));

  if((Banks & FLASH_BANK_1) == FLASH_BANK_1)
  {
    assert_param(IS_OB_WRP_SECTOR(WRPSector));

    /* Wait for last operation to be completed */
    status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_1);

    if(status == HAL_OK)
    {
      FLASH->WPSN_PRG1 &= (~(WRPSector & FLASH_WPSN_WRPSN));
    }
  }

  if((Banks & FLASH_BANK_2) == FLASH_BANK_2)
  {
    assert_param(IS_OB_WRP_SECTOR(WRPSector));

    /* Wait for last operation to be completed */
    status |= FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_2);

    if(status == HAL_OK)
    {
      FLASH->WPSN_PRG2 &= (~(WRPSector & FLASH_WPSN_WRPSN));
    }
  }

  if((Banks & FLASH_BANK_1) == FLASH_BANK_1)
  {
    /* Wait for last operation to be completed */
    status |= FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_1);
  }

  if((Banks & FLASH_BANK_2) == FLASH_BANK_2)
  {
    /* Wait for last operation to be completed */
    status |= FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_2);
  }

  return status;
}

/**
  * @brief  Disable the write protection of the desired bank1 or bank 2 sectors
  * @param  WRPSector specifies the sector(s) to disable write protection.
  *          This parameter can be one of the following values:
  *            @arg WRPSector:  A combination of FLASH_OB_WRP_SECTOR_0 to FLASH_OB_WRP_SECTOR_7 or FLASH_OB_WRP_SECTOR_All
  *
  * @param  Banks the specific bank to apply WRP sectors
  *          This parameter can be one of the following values:
  *            @arg FLASH_BANK_1: WRP disable on specified bank1 sectors
  *            @arg FLASH_BANK_2: WRP disable on specified bank2 sectors
  *            @arg FLASH_BANK_BOTH: WRP disable bank1 and bank2 specified sectors
  *
  * @retval HAL FLASH State
  */
static HAL_StatusTypeDef FLASH_OB_DisableWRP(uint32_t WRPSector, uint32_t Banks)
{
  HAL_StatusTypeDef status = HAL_OK;

  /* Check the parameters */
  assert_param(IS_FLASH_BANK(Banks));
  assert_param(IS_OB_WRP_SECTOR(WRPSector));

  if((Banks & FLASH_BANK_1) == FLASH_BANK_1)
  {
    /* Wait for last operation to be completed */
    status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_1);

    if(status == HAL_OK)
    {
      FLASH->WPSN_PRG1 |= (WRPSector & FLASH_WPSN_WRPSN);
    }
  }

  if((Banks & FLASH_BANK_2) == FLASH_BANK_2)
  {
    /* Wait for last operation to be completed */
    status |= FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_2);

    if(status == HAL_OK)
    {
      FLASH->WPSN_PRG2 |= (WRPSector & FLASH_WPSN_WRPSN);
    }
  }

  if((Banks & FLASH_BANK_1) == FLASH_BANK_1)
  {
    /* Wait for last operation to be completed */
    status |= FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_1);
  }

  if((Banks & FLASH_BANK_2) == FLASH_BANK_2)
  {
    /* Wait for last operation to be completed */
    status |= FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_2);
  }

  return status;
}

/**
  * @brief  Get the write protection of the given bank1 or bank 2 sectors
  * @param  WRPState gives the write protection state on the given bank .
  *          This parameter can be one of the following values:
  *          @arg WRPState: OB_WRPSTATE_DISABLE or OB_WRPSTATE_ENABLE

  * @param  WRPSector gives the write protected sector(s) on the given bank .
  *          This parameter can be one of the following values:
  *          @arg WRPSector:  A combination of FLASH_OB_WRP_SECTOR_0 to FLASH_OB_WRP_SECTOR_7 or FLASH_OB_WRP_SECTOR_All
  *
  * @param  Bank the specific bank to apply WRP sectors
  *          This parameter can be exclusively one of the following values:
  *            @arg FLASH_BANK_1: Get bank1 WRP sectors
  *            @arg FLASH_BANK_2: Get bank2 WRP sectors
  *            @arg FLASH_BANK_BOTH: note allowed in this functions
  *
  * @retval HAL FLASH State
  */
static void FLASH_OB_GetWRP(uint32_t *WRPState, uint32_t *WRPSector, uint32_t Bank)
{
  uint32_t regvalue = 0;
  /* Check the parameters */
  assert_param(IS_FLASH_BANK_EXCLUSIVE(Bank));

  if((Bank & FLASH_BANK_BOTH) == FLASH_BANK_1)
  {
    regvalue = FLASH->WPSN_CUR1;
  }

  if((Bank & FLASH_BANK_BOTH) == FLASH_BANK_2)
  {
    regvalue = FLASH->WPSN_CUR2;
  }

  (*WRPSector) = (~(regvalue & FLASH_WPSN_WRPSN)) & FLASH_WPSN_WRPSN;
  if(*WRPSector == 0)
  {
    (*WRPState) = OB_WRPSTATE_DISABLE;
  }
  else
  {
    (*WRPState) = OB_WRPSTATE_ENABLE;
  }
}

/**
  * @brief  Set the read protection level.
  *
  * @note   To configure the RDP level, the option lock bit OPTLOCK must be
  *         cleared with the call of the HAL_FLASH_OB_Unlock() function.
  * @note   To validate the RDP level, the option bytes must be reloaded
  *         through the call of the HAL_FLASH_OB_Launch() function.
  * @note   !!! Warning : When enabling OB_RDP level 2 it's no more possible
  *         to go back to level 1 or 0 !!!
  *
  * @param  RDPLevel specifies the read protection level.
  *         This parameter can be one of the following values:
  *            @arg OB_RDP_LEVEL_0: No protection
  *            @arg OB_RDP_LEVEL_1: Read protection of the memory
  *            @arg OB_RDP_LEVEL_2: Full chip protection
  *
  * @retval HAL status
  */
static HAL_StatusTypeDef FLASH_OB_RDPConfig(uint32_t RDPLevel)
{
  HAL_StatusTypeDef status = HAL_OK;

  /* Check the parameters */
  assert_param(IS_OB_RDP_LEVEL(RDPLevel));

  /* Wait for last operation to be completed */
  status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_1);
  status |= FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_2);

  if(status == HAL_OK)
  {
    /* Configure the RDP level in the option bytes register */
    MODIFY_REG(FLASH->OPTSR_PRG, FLASH_OPTSR_RDP, RDPLevel);

    /* Wait for last operation to be completed */
    status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_1);
    status |= FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_2);
  }

  return status;
}

/**
  * @brief  Get the read protection level.
  * @retval RDPLevel specifies the read protection level.
  *         This parameter can be one of the following values:
  *            @arg OB_RDP_LEVEL_0: No protection
  *            @arg OB_RDP_LEVEL_1: Read protection of the memory
  *            @arg OB_RDP_LEVEL_2: Full chip protection
  */
static uint32_t FLASH_OB_GetRDP(void)
{
  return (FLASH->OPTSR_CUR & FLASH_OPTSR_RDP);
}

/**
  * @brief  Program the FLASH User Option Byte.
  *
  * @note   To configure the user option bytes, the option lock bit OPTLOCK must
  *         be cleared with the call of the HAL_FLASH_OB_Unlock() function.
  *
  * @note   To validate the user option bytes, the option bytes must be reloaded
  *         through the call of the HAL_FLASH_OB_Launch() function.
  *
  * @param  UserType The FLASH User Option Bytes to be modified :
  *                   a combination of @arg FLASH_OB_USER_Type
  *
  * @param  UserConfig The FLASH User Option Bytes values:
  *         IWDG_SW(Bit4), WWDG_SW(Bit 5), nRST_STOP(Bit 6), nRST_STDY(Bit 7),
  *         FZ_IWDG_STOP(Bit 17), FZ_IWDG_SDBY(Bit 18), ST_RAM_SIZE(Bit[19:20]),
  *         ePcROP_EN(Bit 21), SWAP_BANK_OPT(Bit 31) .
  *
  * @retval HAL status
  */
static HAL_StatusTypeDef FLASH_OB_UserConfig(uint32_t UserType, uint32_t UserConfig)
{
  uint32_t optr_reg_val = 0;
  uint32_t optr_reg_mask = 0;
  HAL_StatusTypeDef status = HAL_OK;

  /* Check the parameters */
  assert_param(IS_OB_USER_TYPE(UserType));

  /* Wait for OB change operation to be completed */
  status = FLASH_OB_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE);

  if(status == HAL_OK)
  {
    if((UserType & OB_USER_IWDG1_SW) != RESET)
    {
      /* IWDG_HW option byte should be modified */
      assert_param(IS_OB_IWDG1_SOURCE(UserConfig & FLASH_OPTSR_IWDG1_SW));

      /* Set value and mask for IWDG_HW option byte */
      optr_reg_val |= (UserConfig & FLASH_OPTSR_IWDG1_SW);
      optr_reg_mask |= FLASH_OPTSR_IWDG1_SW;
    }
    if((UserType & OB_USER_NRST_STOP_D1) != RESET)
    {
      /* NRST_STOP option byte should be modified */
      assert_param(IS_OB_STOP_D1_RESET(UserConfig & FLASH_OPTSR_NRST_STOP_D1));

      /* Set value and mask for NRST_STOP option byte */
      optr_reg_val |= (UserConfig & FLASH_OPTSR_NRST_STOP_D1);
      optr_reg_mask |= FLASH_OPTSR_NRST_STOP_D1;
    }

    if((UserType & OB_USER_NRST_STDBY_D1) != RESET)
    {
      /* NRST_STDBY option byte should be modified */
      assert_param(IS_OB_STDBY_D1_RESET(UserConfig & FLASH_OPTSR_NRST_STBY_D1));

      /* Set value and mask for NRST_STDBY option byte */
      optr_reg_val |= (UserConfig & FLASH_OPTSR_NRST_STBY_D1);
      optr_reg_mask |= FLASH_OPTSR_NRST_STBY_D1;
    }

    if((UserType & OB_USER_IWDG_STOP) != RESET)
    {
      /* IWDG_STOP option byte should be modified */
      assert_param(IS_OB_USER_IWDG_STOP(UserConfig & FLASH_OPTSR_FZ_IWDG_STOP));

      /* Set value and mask for IWDG_STOP option byte */
      optr_reg_val |= (UserConfig & FLASH_OPTSR_FZ_IWDG_STOP);
      optr_reg_mask |= FLASH_OPTSR_FZ_IWDG_STOP;
    }

    if((UserType & OB_USER_IWDG_STDBY) != RESET)
    {
      /* IWDG_STDBY option byte should be modified */
      assert_param(IS_OB_USER_IWDG_STDBY(UserConfig & FLASH_OPTSR_FZ_IWDG_SDBY));

      /* Set value and mask for IWDG_STDBY option byte */
      optr_reg_val |= (UserConfig & FLASH_OPTSR_FZ_IWDG_SDBY);
      optr_reg_mask |= FLASH_OPTSR_FZ_IWDG_SDBY;
    }

    if((UserType & OB_USER_SECURITY) != RESET)
    {
      /* SECURITY option byte should be modified */
      assert_param(IS_OB_USER_SECURITY(UserConfig & FLASH_OPTSR_SECURITY));

      /* Set value and mask for ePcROP_EN option byte */
      optr_reg_val |= (UserConfig & FLASH_OPTSR_SECURITY);
      optr_reg_mask |= FLASH_OPTSR_SECURITY;
    }
    if((UserType & OB_USER_SWAP_BANK) != RESET)
    {
      /* SWAP_BANK_OPT option byte should be modified */
      assert_param(IS_OB_USER_SWAP_BANK(UserConfig & FLASH_OPTSR_SWAP_BANK_OPT));

      /* Set value and mask for SWAP_BANK_OPT option byte */
      optr_reg_val |= (UserConfig & FLASH_OPTSR_SWAP_BANK_OPT);
      optr_reg_mask |= FLASH_OPTSR_SWAP_BANK_OPT;
    }

    if((UserType & OB_USER_IOHSLV) != RESET)
    {
      /* IOHSLV_OPT option byte should be modified */
      assert_param(IS_OB_USER_IOHSLV(UserConfig & FLASH_OPTSR_IO_HSLV));

      /* Set value and mask for IOHSLV_OPT option byte */
      optr_reg_val |= (UserConfig & FLASH_OPTSR_IO_HSLV);
      optr_reg_mask |= FLASH_OPTSR_IO_HSLV;
    }

    /* Configure the option bytes register */
    MODIFY_REG(FLASH->OPTSR_PRG, optr_reg_mask, optr_reg_val);
  }

  return status;
}
/**
  * @brief  Return the FLASH User Option Byte value.
  * @retval The FLASH User Option Bytes values
  *         IWDG_SW(Bit4), WWDG_SW(Bit 5), nRST_STOP(Bit 6), nRST_STDY(Bit 7),
  *         FZ_IWDG_STOP(Bit 17), FZ_IWDG_SDBY(Bit 18), ST_RAM_SIZE(Bit[19:20]),
  *         ePcROP_EN(Bit 21), SWAP_BANK_OPT(Bit 31) .
  */
static uint32_t FLASH_OB_GetUser(void)
{
  uint32_t userConfig = READ_REG(FLASH->OPTSR_CUR);
  userConfig &= (~(FLASH_OPTSR_BOR_LEV | FLASH_OPTSR_RDP));

  return userConfig;
}

/**
  * @brief  Configure the Proprietary code readout protection of the desired addresses
  *
  * @note   To configure the PCROP options, the option lock bit OPTLOCK must be
  *         cleared with the call of the HAL_FLASH_OB_Unlock() function.
  * @note   To validate the PCROP options, the option bytes must be reloaded
  *         through the call of the HAL_FLASH_OB_Launch() function.
  *
  * @param  PCROPConfig specifies if the PCROP area for the given Bank shall be erased or not
  *                        when RDP level  decreased from Level 1 to Level 0.
  *                        This parameter must be a value of @arg FLASH_OB_PCROP_RDP enumeration
  *
  * @param  PCROPStartAddr specifies the start address of the Proprietary code readout protection
  *          This parameter can be an address between begin and end of the bank
  *
  * @param  PCROPEndAddr specifies the end address of the Proprietary code readout protection
  *          This parameter can be an address between PCROPStartAddr and end of the bank
  *
  * @param  Banks the specific bank to apply PCROP sectors
  *          This parameter can be one of the following values:
  *            @arg FLASH_BANK_1: PCROP on specified bank1 area
  *            @arg FLASH_BANK_2: PCROP on specified bank2 area
  *            @arg FLASH_BANK_BOTH: PCROP on specified bank1 and bank2 area (same config will be applied on both banks)
  *
  * @retval HAL Status
  */
static HAL_StatusTypeDef FLASH_OB_PCROPConfig(uint32_t PCROPConfig, uint32_t PCROPStartAddr, uint32_t PCROPEndAddr, uint32_t Banks)
{
  HAL_StatusTypeDef status = HAL_OK;

  /* Check the parameters */
  assert_param(IS_FLASH_BANK(Banks));
  assert_param(IS_OB_PCROP_RDP(PCROPConfig));
  assert_param(IS_FLASH_PROGRAM_ADDRESS(PCROPStartAddr));
  assert_param(IS_FLASH_PROGRAM_ADDRESS(PCROPEndAddr));

  if((Banks & FLASH_BANK_1) == FLASH_BANK_1)
  {
    assert_param(IS_FLASH_PROGRAM_ADDRESS_BANK1(PCROPStartAddr));
    assert_param(IS_FLASH_PROGRAM_ADDRESS_BANK1(PCROPEndAddr));

    /* Wait for last operation to be completed */
    status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE,FLASH_BANK_1);

    if(status == HAL_OK)
    {
      /* Configure the Proprietary code readout protection */
      FLASH->PRAR_PRG1 = ((PCROPStartAddr - FLASH_BANK1_BASE) >> 8);

      FLASH->PRAR_PRG1 |= (((PCROPEndAddr - FLASH_BANK1_BASE) >> 8) << POSITION_VAL(FLASH_PRAR_PROT_AREA_END)) ;

      FLASH->PRAR_PRG1 |= PCROPConfig;

      /* Wait for last operation to be completed */
      status |= FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_1);
    }
  }
  if((Banks & FLASH_BANK_2) == FLASH_BANK_2)
  {
    assert_param(IS_FLASH_PROGRAM_ADDRESS_BANK2(PCROPStartAddr));
    assert_param(IS_FLASH_PROGRAM_ADDRESS_BANK2(PCROPEndAddr));

    /* Wait for last operation to be completed */
    status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE,FLASH_BANK_2);

    if(status == HAL_OK)
    {
      FLASH->PRAR_PRG2 = ((PCROPStartAddr - FLASH_BANK2_BASE) >> 8);

      FLASH->PRAR_PRG2 |= (((PCROPEndAddr - FLASH_BANK2_BASE) >> 8) << POSITION_VAL(FLASH_PRAR_PROT_AREA_END)) ;

      FLASH->PRAR_PRG2 |= PCROPConfig;

      /* Wait for last operation to be completed */
      status |= FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_2);
    }
  }

  return status;
}

/**
  * @brief  Get the Proprietary code readout protection configuration on a given Bank
  *
  * @param  PCROPConfig gives if the PCROP area for the given Bank shall be erased or not
  *                        when RDP level decreased from Level 1 to Level 0 or during a mass erase.
  *
  * @param  PCROPStartAddr gives the start address of the Proprietary code readout protection of the bank
  *
  * @param  PCROPEndAddr gives the end address of the Proprietary code readout protection of the bank
  *
  * @param  Bank the specific bank to apply PCROP sectors
  *          This parameter can be exclusively one of the following values:
  *            @arg FLASH_BANK_1: PCROP on specified bank1 area
  *            @arg FLASH_BANK_2: PCROP on specified bank2 area
  *            @arg FLASH_BANK_BOTH: is  not allowed here
  *
  * @retval HAL Status
  */
static void FLASH_OB_GetPCROP(uint32_t *PCROPConfig, uint32_t *PCROPStartAddr,uint32_t *PCROPEndAddr, uint32_t Bank)
{
  uint32_t regvalue = 0;
  uint32_t bankBase = 0;

  /* Check the parameters */
  assert_param(IS_FLASH_BANK_EXCLUSIVE(Bank));

  if((Bank & FLASH_BANK_BOTH) == FLASH_BANK_1)
  {
    regvalue = FLASH->PRAR_CUR1;
    bankBase = FLASH_BANK1_BASE;
  }

  if((Bank & FLASH_BANK_BOTH) == FLASH_BANK_2)
  {
    regvalue = FLASH->PRAR_CUR2;
    bankBase = FLASH_BANK2_BASE;
  }

  (*PCROPConfig) =  (regvalue & FLASH_PRAR_DMEP);

  (*PCROPStartAddr) = ((regvalue & FLASH_PRAR_PROT_AREA_START) << 8) + bankBase;
  (*PCROPEndAddr) = (regvalue & FLASH_PRAR_PROT_AREA_END) >> POSITION_VAL(FLASH_PRAR_PROT_AREA_END) ;
  (*PCROPEndAddr) = ((*PCROPEndAddr) << 8) + bankBase;
}

/**
  * @brief  Set the BOR Level.
  * @param  Level specifies the Option Bytes BOR Reset Level.
  *          This parameter can be one of the following values:
  *            @arg OB_BOR_LEVEL1: Supply voltage ranges from 1.69V - 1.8V
  *            @arg OB_BOR_LEVEL2: Supply voltage ranges from 1.94V - 2.1V
  *            @arg OB_BOR_LEVEL3: Supply voltage ranges from 2.30V - 2.49V
  * @retval HAL Status
  */
static HAL_StatusTypeDef FLASH_OB_BOR_LevelConfig(uint8_t Level)
{
  HAL_StatusTypeDef status = HAL_OK;

  assert_param(IS_OB_BOR_LEVEL(Level));

  /* Wait for last operation to be completed */
  status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_1);
  status |= FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_2);

  if(status == HAL_OK)
  {
    /* Configure BOR_LEV option byte */
    MODIFY_REG(FLASH->OPTSR_PRG, FLASH_OPTSR_BOR_LEV, Level );

    /* Wait for last operation to be completed */
    status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_1);
    status |= FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_2);
  }

  return status;
}

/**
  * @brief  Get the BOR Level.
  * @retval The Option Bytes BOR Reset Level.
  *            This parameter can be one of the following values:
  *            @arg OB_BOR_LEVEL1: Supply voltage ranges from 1.69V - 1.8V
  *            @arg OB_BOR_LEVEL2: Supply voltage ranges from 1.94V - 2.1V
  *            @arg OB_BOR_LEVEL3: Supply voltage ranges from 2.30V - 2.49V
  */
static uint32_t FLASH_OB_GetBOR(void)
{
  return (FLASH->OPTSR_CUR & FLASH_OPTSR_BOR_LEV);
}

/**
  * @brief  Set Boot address
  * @param  BootOption Boot address option byte to be programmed,
  *                     This parameter must be a value of @ref FLASHEx_OB_BOOT_OPTION
                        (OB_BOOT_ADD0, OB_BOOT_ADD1 or OB_BOOT_ADD_BOTH)
  *
  * @param  BootAddress0 Specifies the Boot Address 0
  * @param  BootAddress1 Specifies the Boot Address 1
  * @retval HAL Status
  */
static HAL_StatusTypeDef FLASH_OB_BootAddConfig(uint32_t BootOption, uint32_t BootAddress0, uint32_t BootAddress1)
{
  HAL_StatusTypeDef status = HAL_OK;

  /* Check the parameters */
  assert_param(IS_OB_BOOT_ADD_OPTION(BootOption));

  /* Wait for last operation to be completed */
  status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_1);
  status |= FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_2);

  if(status == HAL_OK)
  {
    if((BootOption & OB_BOOT_ADD0) == OB_BOOT_ADD0)
    {
      /* Check the parameters */
      assert_param(IS_BOOT_ADDRESS(BootAddress0));

      /* Configure BOOT ADD0 */
      MODIFY_REG(FLASH->BOOT_PRG, FLASH_BOOT_ADD0, (BootAddress0 >> 16));
    }

    if((BootOption & OB_BOOT_ADD1) == OB_BOOT_ADD1)
    {
      /* Check the parameters */
      assert_param(IS_BOOT_ADDRESS(BootAddress1));

      /* Configure BOOT ADD1 */
      MODIFY_REG(FLASH->BOOT_PRG, FLASH_BOOT_ADD1, BootAddress1 );
    }

    /* Wait for last operation to be completed */
    status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_1);
    status |= FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_2);
  }

  return status;
}

/**
  * @brief  Get Boot address
  * @param  BootAddress0 Specifies the Boot Address 0.
  * @param  BootAddress1 Specifies the Boot Address 1.
  * @retval HAL Status
  */
static void FLASH_OB_GetBootAdd(uint32_t *BootAddress0, uint32_t *BootAddress1)
{
  uint32_t regvalue = 0;

  regvalue = FLASH->BOOT_CUR;

  (*BootAddress0) = (regvalue & FLASH_BOOT_ADD0) << 16;

  (*BootAddress1) = (regvalue & FLASH_BOOT_ADD1);

}

/**
  * @brief  Set secure area configuration
  * @param  SecureAreaConfig specify if the secure area will be deleted or not during next mass-erase,
  *
  * @param  SecureAreaStartAddr Specifies the secure area start address
  * @param  SecureAreaEndAddr Specifies the secure area end address
  * @param  Banks Specifies the Bank
  * @retval HAL Status
  */
static HAL_StatusTypeDef FLASH_OB_SecureAreaConfig(uint32_t SecureAreaConfig, uint32_t SecureAreaStartAddr, uint32_t SecureAreaEndAddr, uint32_t Banks)
{
  HAL_StatusTypeDef status = HAL_OK;

  /* Check the parameters */
  assert_param(IS_FLASH_BANK_EXCLUSIVE(Banks));
  assert_param(IS_OB_SECURE_RDP(SecureAreaConfig));

  if((Banks & FLASH_BANK_1) == FLASH_BANK_1)
  {
    /* Check the parameters */
    assert_param(IS_FLASH_PROGRAM_ADDRESS_BANK1(SecureAreaStartAddr));
    assert_param(IS_FLASH_PROGRAM_ADDRESS_BANK1(SecureAreaEndAddr));

    /* Wait for last operation to be completed */
    status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_1);

    if(status == HAL_OK)
    {
      /* Configure the secure area */
      FLASH->SCAR_PRG1 = ((SecureAreaStartAddr - FLASH_BANK1_BASE) >> 8);

      FLASH->SCAR_PRG1 |= (((SecureAreaEndAddr - FLASH_BANK1_BASE) >> 8) << POSITION_VAL(FLASH_SCAR_SEC_AREA_END)) ;

      FLASH->SCAR_PRG1 |= (SecureAreaConfig & FLASH_SCAR_DMES);

      status |= FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_1);

    }
  }
  if((Banks & FLASH_BANK_2) == FLASH_BANK_2)
  {
    /* Check the parameters */
    assert_param(IS_FLASH_PROGRAM_ADDRESS_BANK2(SecureAreaStartAddr));
    assert_param(IS_FLASH_PROGRAM_ADDRESS_BANK2(SecureAreaEndAddr));

    /* Wait for last operation to be completed */
    status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_2);

    if(status == HAL_OK)
    {
      /* Configure the secure area */
      FLASH->SCAR_PRG2 = ((SecureAreaStartAddr - FLASH_BANK2_BASE) >> 8);

      FLASH->SCAR_PRG2 |= (((SecureAreaEndAddr - FLASH_BANK2_BASE) >> 8) << POSITION_VAL(FLASH_SCAR_SEC_AREA_END)) ;

      FLASH->SCAR_PRG2 |= (SecureAreaConfig & FLASH_SCAR_DMES);

      status |= FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE, FLASH_BANK_2);
    }
  }

  return status;
}

/**
  * @brief  Set secure area configuration
  * @param  SecureAreaConfig specify if the secure area will be deleted or not during next mass-erase,
  *
  * @param  SecureAreaStartAddr Specifies the secure area start address
  * @param  SecureAreaEndAddr Specifies the secure area end address
  * @param  Bank Specifies the Bank
  * @retval HAL Status
  */
static void FLASH_OB_GetSecureArea(uint32_t *SecureAreaConfig, uint32_t *SecureAreaStartAddr, uint32_t *SecureAreaEndAddr, uint32_t Bank)
{
  uint32_t regvalue = 0;
  uint32_t bankBase = 0;

  /* Check the parameters */
  assert_param(IS_FLASH_BANK_EXCLUSIVE(Bank));

  if((Bank & FLASH_BANK_BOTH) == FLASH_BANK_1)
  {
    regvalue = FLASH->SCAR_CUR1;
    bankBase = FLASH_BANK1_BASE;
  }

  if((Bank & FLASH_BANK_BOTH) == FLASH_BANK_2)
  {
    regvalue = FLASH->SCAR_CUR2;
    bankBase = FLASH_BANK2_BASE;
  }

  (*SecureAreaConfig) = (regvalue & FLASH_SCAR_DMES);
  (*SecureAreaStartAddr) = ((regvalue & FLASH_SCAR_SEC_AREA_START) << 8) + bankBase;
  (*SecureAreaEndAddr) = (regvalue & FLASH_SCAR_SEC_AREA_END) >> POSITION_VAL(FLASH_SCAR_SEC_AREA_END) ;
  (*SecureAreaEndAddr) = ((*SecureAreaEndAddr) << 8) + bankBase;

}
/**
  * @}
  */

/**
  * @}
  */
#endif /* HAL_FLASH_MODULE_ENABLED */
/**
  * @}
  */
/**
  * @}
  */

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


text:
using System;

namespace ASC.Web.Community.News
{
    public partial class _default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Redirect(string.Format("?{0}", Request.QueryString));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/lytAdvanceSearchRoot"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white">

    <LinearLayout
        android:id="@+id/lytSearchHeader"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingBottom="8dp"
        android:paddingLeft="15dp"
        android:paddingRight="15dp"
        android:paddingTop="8dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:weightSum="1.0">

            <LinearLayout
                android:id="@+id/lytSortingData"
                android:layout_width="@dimen/height_width_0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_weight=".85"
                android:orientation="horizontal">

                <com.tungnui.abccomputer.view.RobotoTextView
                    android:id="@+id/tvSortingName"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:gravity="center_vertical"
                    android:text="@string/order_by"
                    android:textColor="@color/title_color"
                    android:textSize="15sp" />

                <ImageView
                    android:layout_width="30dp"
                    android:layout_height="wrap_content"
                    android:padding="@dimen/pad_margin_10dp"
                    android:src="@drawable/ic_drop_down_blue" />

            </LinearLayout>

            <ImageView
                android:id="@+id/ivListTypeIcon"
                android:layout_width="@dimen/height_width_0dp"
                android:layout_height="20dp"
                android:layout_gravity="center_vertical"
                android:layout_marginRight="@dimen/pad_margin_15dp"
                android:layout_weight=".08"
                android:src="@drawable/ic_grid" />

            <ToggleButton
                android:id="@+id/btnToggleExpand"
                android:layout_width="@dimen/height_width_0dp"
                android:layout_height="20dp"
                android:layout_gravity="center_vertical"
                android:layout_weight=".06"
                android:background="@drawable/ic_filter_arrow_down"
                android:checked="false"
                android:text=""
                android:textOff=""
                android:textOn="" />

        </LinearLayout>

    </LinearLayout>

    <View
        android:id="@+id/lineView"
        android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:layout_below="@+id/lytSearchHeader"
        android:background="@color/toolbar_boarder" />

    <RelativeLayout
        android:id="@+id/lytSearchAttribute"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/lineView"
        android:paddingBottom="8dp"
        android:paddingLeft="15dp"
        android:paddingRight="15dp"
        android:paddingTop="8dp"
        android:visibility="gone">

        <LinearLayout
            android:id="@+id/lytSearchCategory"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:paddingBottom="@dimen/pad_margin_10dp"
            android:paddingTop="@dimen/pad_margin_10dp"
            android:weightSum="1">

            <com.tungnui.abccomputer.view.RobotoTextView
                android:id="@+id/searchQueryInput"
                android:layout_width="@dimen/height_width_0dp"
                android:layout_height="match_parent"
                android:layout_weight=".50"
                android:gravity="center_vertical"
                android:text="@string/category"
                android:textColor="@color/title_color"
                android:textSize="15sp" />

            <LinearLayout
                android:id="@+id/categoryChooser"
                android:layout_width="@dimen/height_width_0dp"
                android:layout_height="30dp"
                android:layout_weight=".50"
                android:background="@drawable/attribute_spinner"
                android:weightSum="1">

                <com.tungnui.abccomputer.view.RobotoTextView
                    android:id="@+id/selectedCat"
                    android:layout_width="@dimen/height_width_0dp"
                    android:layout_height="match_parent"
                    android:layout_weight=".80"
                    android:ellipsize="end"
                    android:gravity="center_vertical"
                    android:maxLines="1"
                    android:paddingLeft="@dimen/pad_margin_10dp"
                    android:text="@string/all"
                    android:textColor="@color/white"
                    android:textSize="15sp" />

                <ImageView
                    android:layout_width="@dimen/height_width_0dp"
                    android:layout_height="match_parent"
                    android:layout_weight=".20"
                    android:padding="@dimen/pad_margin_10dp"
                    android:src="@drawable/ic_lil_down_arrow" />

            </LinearLayout>

        </LinearLayout>

        <LinearLayout
            android:id="@+id/lytSearchPrice"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/lytSearchCategory"
            android:orientation="horizontal"
            android:paddingBottom="@dimen/pad_margin_10dp"
            android:paddingTop="@dimen/pad_margin_10dp"
            android:weightSum="1">

            <com.tungnui.abccomputer.view.RobotoTextView
                android:id="@+id/searchQueryInputdf"
                android:layout_width="@dimen/height_width_0dp"
                android:layout_height="wrap_content"
                android:layout_weight=".50"
                android:gravity="center_vertical"
                android:text="@string/price"
                android:textColor="@color/title_color"
                android:textSize="15sp" />

            <LinearLayout
                android:layout_width="@dimen/height_width_0dp"
                android:layout_height="wrap_content"
                android:layout_weight=".50"
                android:orientation="horizontal"
                android:weightSum="1">

                <EditText
                    android:id="@+id/edtMinPrice"
                    android:layout_width="0dp"
                    android:layout_height="30dp"
                    android:layout_weight=".40"
                    android:background="@drawable/edt_back_border"
                    android:gravity="center"
                    android:hint="@string/min"
                    android:inputType="number"
                    android:maxLines="1"
                    android:textSize="@dimen/txt_size_14sp" />

                <TextView
                    android:id="@+id/tvPriceText"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight=".20"
                    android:gravity="center"
                    android:text="@string/to"
                    android:textColor="@color/blue"
                    android:textSize="15sp" />

                <EditText
                    android:id="@+id/edtMaxPrice"
                    android:layout_width="0dp"
                    android:layout_height="30dp"
                    android:layout_weight=".40"
                    android:background="@drawable/edt_back_border"
                    android:gravity="center"
                    android:hint="@string/max"
                    android:imeOptions="actionSearch"
                    android:inputType="number"
                    android:maxLines="1"
                    android:textSize="@dimen/txt_size_14sp" />

            </LinearLayout>

        </LinearLayout>

    </RelativeLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:layout_below="@+id/lytSearchAttribute"
        android:background="@color/toolbar_boarder" />

</RelativeLayout>


text:
![Broadcastery Logo](http://censoredsoftware.com/projects/broadcastery/broadcastery_logo_full.png)

Overview
========

Broadcastery is a very straight forward and minimal message broadcasting plugin for Bukkit/Spigot-based Minecraft servers.

Installation
============

To install, simply place the Broadcastery.jar in to your plugins folder and reload your server. A configuration file will be generated which you can use to customize the plugin to your liking.


text:
using System.Collections.Generic;

namespace Talifun.Crusher.Crusher
{
    public class CssFileToWatchEqualityComparer : IEqualityComparer<CssFileToWatch>
    {
        public bool Equals(CssFileToWatch x, CssFileToWatch y)
        {
            return string.Equals(x.FilePath, y.FilePath);
        }

        public int GetHashCode(CssFileToWatch obj)
        {
            return obj.FilePath.GetHashCode();
        }
    }
}


text:
<?php
namespace MOC\V\TestSuite\Tests\Component\Document;

use MOC\V\Component\Document\Component\Parameter\Repository\FileParameter;
use MOC\V\Component\Document\Component\Parameter\Repository\PaperOrientationParameter;
use MOC\V\Component\Document\Component\Parameter\Repository\PaperSizeParameter;
use MOC\V\TestSuite\AbstractTestCase;

/**
 * Class ParameterTest
 *
 * @package MOC\V\TestSuite\Tests\Component\Document
 */
class ParameterTest extends AbstractTestCase
{

    public function testAbstractParameter()
    {

        /** @var \MOC\V\Component\Document\Component\Parameter\Parameter $MockParameter */
        $MockParameter = $this->getMockForAbstractClass('MOC\V\Component\Document\Component\Parameter\Parameter');

        $Parameter = new $MockParameter();
        $this->assertInstanceOf('MOC\V\Component\Document\Component\Parameter\Parameter', $Parameter);

    }

    public function testFileParameter()
    {

        try {
            new FileParameter(null);
        } catch (\Exception $E) {
            $this->assertInstanceOf('MOC\V\Component\Document\Component\Exception\Repository\EmptyFileException', $E);
        }

        $Parameter = new FileParameter(__FILE__);
        $this->assertEquals(__FILE__, $Parameter->getFile());

        try {
            $Parameter->setFile(__DIR__);
        } catch (\Exception $E) {
            $this->assertInstanceOf('MOC\V\Component\Document\Component\Exception\Repository\TypeFileException', $E);
        }

    }

    public function testPaperOrientationParameter()
    {

        try {
            new PaperOrientationParameter(null);
        } catch (\Exception $E) {
            $this->assertInstanceOf('MOC\V\Component\Document\Component\Exception\ComponentException', $E);
        }

        $Parameter = new PaperOrientationParameter();
        $this->assertEquals('PORTRAIT', $Parameter->getOrientation());
    }

    public function testPaperSizeParameter()
    {

        try {
            new PaperSizeParameter(null);
        } catch (\Exception $E) {
            $this->assertInstanceOf('MOC\V\Component\Document\Component\Exception\ComponentException', $E);
        }

        $Parameter = new PaperSizeParameter();
        $this->assertEquals('A4', $Parameter->getSize());
    }
}


text:
using System;
using UIKit;
using Xamarin.iOS.FileExplorer.Extensions;

namespace Xamarin.iOS.FileExplorer.ViewControllers
{
    public interface IActionsViewControllerDelegate
    {
        void ActionsViewControllerDidRequestRemoval(ActionsViewController controller);
        void ActionsViewControllerDidRequestShare(ActionsViewController controller);
    }

public class ActionsViewController : UIViewController
	{
		private readonly UIViewController _contentViewController;
		private readonly UIToolbar _toolbar = new UIToolbar();

		public ActionsViewController(UIViewController contentViewController)
		{
			_contentViewController = contentViewController;
		}

		public ActionsViewController(IntPtr handle) : base(handle)
		{
		}

		public override void ViewDidLoad()
		{
			base.ViewDidLoad();

			View.BackgroundColor = UIColor.White;

			ExtendedLayoutIncludesOpaqueBars = false;
			EdgesForExtendedLayout = UIRectEdge.None;

			Add(_toolbar);
			_toolbar.TranslatesAutoresizingMaskIntoConstraints = false;
			_toolbar.SizeToFit();
			_toolbar.PinToBottom(View);
			_toolbar.Items = new[]
			{
				new UIBarButtonItem(UIBarButtonSystemItem.Action, (e, a) => { OnShareButtonTapped(); }),
				new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace, (e, a) => { }),
				new UIBarButtonItem(UIBarButtonSystemItem.Trash, (e, a) => { OnTrashButtonTapped(); })
			};

			this.AddContentChildViewController(_contentViewController, new UIEdgeInsets(top: 0, left: 0, bottom: _toolbar.Bounds.Height, right: 0));
			NavigationItem.Title = _contentViewController.NavigationItem.Title;
		}

        public IActionsViewControllerDelegate ActionsViewControllerDelegate { get; set; }

		protected virtual void OnShareButtonTapped()
		{
		    ActionsViewControllerDelegate?.ActionsViewControllerDidRequestShare(this);
		}

		protected virtual void OnTrashButtonTapped()
		{
            ActionsViewControllerDelegate?.ActionsViewControllerDidRequestRemoval(this);
        }
    }
}


text:
package master

import (
	"encoding/json"
	"fmt"
	"time"

	apierrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	utilruntime "k8s.io/apimachinery/pkg/util/runtime"
	"k8s.io/apimachinery/pkg/util/wait"
	genericapiserver "k8s.io/apiserver/pkg/server"
	"k8s.io/kubernetes/pkg/api"
	coreclient "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion"
)

type ClientCARegistrationHook struct {
	ClientCA []byte

	RequestHeaderUsernameHeaders     []string
	RequestHeaderGroupHeaders        []string
	RequestHeaderExtraHeaderPrefixes []string
	RequestHeaderCA                  []byte
	RequestHeaderAllowedNames        []string
}

func (h ClientCARegistrationHook) PostStartHook(hookContext genericapiserver.PostStartHookContext) error {
	// no work to do
	if len(h.ClientCA) == 0 && len(h.RequestHeaderCA) == 0 {
		return nil
	}

	// initializing CAs is important so that aggregated API servers can come up with "normal" config.
	// We've seen lagging etcd before, so we want to retry this a few times before we decide to crashloop
	// the API server on it.
	err := wait.Poll(1*time.Second, 30*time.Second, func() (done bool, err error) {
		// retry building the config since sometimes the server can be in an inbetween state which caused
		// some kind of auto detection failure as I recall from other post start hooks.
		// TODO see if this is still true and fix the RBAC one too if it isn't.
		client, err := coreclient.NewForConfig(hookContext.LoopbackClientConfig)
		if err != nil {
			utilruntime.HandleError(err)
			return false, nil
		}

		return h.tryToWriteClientCAs(client)
	})

	// if we're never able to make it through initialization, kill the API server
	if err != nil {
		return fmt.Errorf("unable to initialize client CA configmap: %v", err)
	}

	return nil

}

// tryToWriteClientCAs is here for unit testing with a fake client.  This is a wait.ConditionFunc so the bool
// indicates if the condition was met.  True when its finished, false when it should retry.
func (h ClientCARegistrationHook) tryToWriteClientCAs(client coreclient.CoreInterface) (bool, error) {
	if _, err := client.Namespaces().Create(&api.Namespace{ObjectMeta: metav1.ObjectMeta{Name: metav1.NamespaceSystem}}); err != nil && !apierrors.IsAlreadyExists(err) {
		utilruntime.HandleError(err)
		return false, nil
	}

	data := map[string]string{}
	if len(h.ClientCA) > 0 {
		data["client-ca-file"] = string(h.ClientCA)
	}

	if len(h.RequestHeaderCA) > 0 {
		var err error

		// encoding errors aren't going to get better, so just fail on them.
		data["requestheader-username-headers"], err = jsonSerializeStringSlice(h.RequestHeaderUsernameHeaders)
		if err != nil {
			return false, err
		}
		data["requestheader-group-headers"], err = jsonSerializeStringSlice(h.RequestHeaderGroupHeaders)
		if err != nil {
			return false, err
		}
		data["requestheader-extra-headers-prefix"], err = jsonSerializeStringSlice(h.RequestHeaderExtraHeaderPrefixes)
		if err != nil {
			return false, err
		}
		data["requestheader-client-ca-file"] = string(h.RequestHeaderCA)
		data["requestheader-allowed-names"], err = jsonSerializeStringSlice(h.RequestHeaderAllowedNames)
		if err != nil {
			return false, err
		}
	}

	// write errors may work next time if we retry, so queue for retry
	if err := writeConfigMap(client, "extension-apiserver-authentication", data); err != nil {
		utilruntime.HandleError(err)
		return false, nil
	}

	return true, nil
}

func jsonSerializeStringSlice(in []string) (string, error) {
	out, err := json.Marshal(in)
	if err != nil {
		return "", err
	}
	return string(out), err
}

func writeConfigMap(client coreclient.ConfigMapsGetter, name string, data map[string]string) error {
	existing, err := client.ConfigMaps(metav1.NamespaceSystem).Get(name, metav1.GetOptions{})
	if apierrors.IsNotFound(err) {
		_, err := client.ConfigMaps(metav1.NamespaceSystem).Create(&api.ConfigMap{
			ObjectMeta: metav1.ObjectMeta{Namespace: metav1.NamespaceSystem, Name: name},
			Data:       data,
		})
		return err
	}
	if err != nil {
		return err
	}

	existing.Data = data
	_, err = client.ConfigMaps(metav1.NamespaceSystem).Update(existing)
	return err
}


text:
id: 5900f4241000cf542c50ff37
title: 'Problema 184: Triângulos contendo a origem'
challengeType: 5
forumTopicId: 301820
dashedName: problem-184-triangles-containing-the-origin
---

# --description--

Considere o conjunto $I_r$ de pontos $(x,y)$ com coordenadas inteiras no interior do círculo com raio $r$, centralizado na origem, ou seja, $x^2 + y^2 < r^2$.

Para um raio de 2, $I_2$ contém os nove pontos (0,0), (1,0), (1,1), (0,1), (-1,1), (-1,0), (-1,-1), (0,-1) e (1,-1). Há oito triângulos com todos os três vértices em $I_2$ que contêm a origem no interior. Dois deles são mostrados abaixo. Os outros são obtidos por rotação.

<img class="img-responsive center-block" alt="círculo com raio 2, centralizado na origem, com nove pontos marcados e dois triângulos - (-1,0), (0,1), (1,-1) e (-1,1), (0,-1), (1,1)" src="https://cdn.freecodecamp.org/curriculum/project-euler/triangles-containing-the-origin.gif" style="background-color: white; padding: 10px;" />

Para um raio de 3, há 360 triângulos contendo a origem no interior e tendo todos os vértices em $I_3$. Para $I_5$, o número é 10600.

Quantos triângulos há contendo a origem no interior e tendo todos os três vértices em $I_{105}$?

# --hints--

`trianglesConttainingOrigin()` deve retornar `1725323624056`.

```js
assert.strictEqual(trianglesConttainingOrigin(), 1725323624056);
```

# --seed--

## --seed-contents--

```js
function trianglesContainingOrigin() {

  return true;
}

trianglesContainingOrigin();
```

# --solutions--

```js
// solution required
```


text:
namespace app_list {

namespace {

// Waiter to ensure results for a query have been published by the search
// controller.
class ResultsWaiter : public SearchController::Observer {
 public:
  explicit ResultsWaiter(const std::u16string& query) : query_(query) {
    observer_.Observe(::test::GetAppListClient()->search_controller());
  }
  ~ResultsWaiter() override = default;

  void OnResultsAdded(
      const std::u16string& query,
      const std::vector<const ChromeSearchResult*>& results) override {
    if (query != query_)
      return;
    observer_.Reset();
    run_loop_.Quit();
  }

  void Wait() { run_loop_.Run(); }

 private:
  const std::u16string query_;
  base::RunLoop run_loop_;
  base::ScopedObservation<SearchController, SearchController::Observer>
      observer_{this};
};

}  // namespace

AppListSearchBrowserTest::AppListSearchBrowserTest() {
  scoped_feature_list_.InitWithFeatures(
      {chromeos::features::kHelpAppLauncherSearch,
       chromeos::features::kHelpAppDiscoverTab},
      {});
}

void AppListSearchBrowserTest::SetUpOnMainThread() {
  InProcessBrowserTest::SetUpOnMainThread();
}

// The AppListClient is in charge of communication from ash to chrome, so can
// be used to mimic UI actions. Examples include starting a search, launching
// a result, or possibly activating a particular view.
AppListClientImpl* AppListSearchBrowserTest::GetClient() {
  auto* client = ::test::GetAppListClient();
  CHECK(client);
  return client;
}

void AppListSearchBrowserTest::StartSearch(const std::string& query) {
  GetClient()->StartSearch(base::ASCIIToUTF16(query));
}

void AppListSearchBrowserTest::SearchAndWaitForProviders(
    const std::string& query,
    const std::set<ResultType> providers) {
  base::RunLoop run_loop;
  base::RepeatingClosure quit_closure = run_loop.QuitClosure();
  std::set<ResultType> finished_providers;
  const SearchController::ResultsChangedCallback callback =
      base::BindLambdaForTesting([&](ResultType provider) {
        finished_providers.insert(provider);

        // Quit the run loop if all |providers| are finished.
        for (const auto& type : providers) {
          if (finished_providers.find(type) == finished_providers.end())
            return;
        }
        quit_closure.Run();
      });

  // The ordering of this logic is important. The results changed callback
  // must be set before the call to StartSearch, to avoid a race between a
  // provider returning and the callback being set, which could lead to the
  // run loop timing out.
  GetClient()->search_controller()->set_results_changed_callback_for_test(
      std::move(callback));
  ResultsWaiter results_waiter(base::ASCIIToUTF16(query));
  GetClient()->StartSearch(base::ASCIIToUTF16(query));
  run_loop.Run();
  // Once the run loop is finished, we have to remove the callback because the
  // referenced variables are about to go out of scope.
  GetClient()->search_controller()->set_results_changed_callback_for_test(
      base::DoNothing());
  // Wait for some results to get published for the query - result publishing
  // may get delayed due to a burn in period.
  results_waiter.Wait();
}

std::vector<ChromeSearchResult*> AppListSearchBrowserTest::PublishedResults() {
  return GetClient()
      ->GetModelUpdaterForTest()
      ->GetPublishedSearchResultsForTest();
}

std::vector<ChromeSearchResult*>
AppListSearchBrowserTest::PublishedResultsForProvider(
    const ResultType provider) {
  std::vector<ChromeSearchResult*> results;
  for (auto* result : PublishedResults()) {
    if (result->result_type() == provider)
      results.push_back(result);
  }
  return results;
}

// Returns a search result for the given |id|, or nullptr if no matching
// search result exists.
ChromeSearchResult* AppListSearchBrowserTest::FindResult(
    const std::string& id) {
  for (auto* result : PublishedResults()) {
    if (result->id() == id)
      return result;
  }
  return nullptr;
}

Profile* AppListSearchBrowserTest::GetProfile() {
  return browser()->profile();
}

}  // namespace app_list


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
    <meta name="description" content="Point Cloud Attenuation and Eye Dome Lighting example.">
    <meta name="cesium-sandcastle-labels" content="3D Tiles">
    <title>Cesium Demo</title>

Loading...

    <select data-bind="options: exampleTypes, value: currentExampleType"></select>

        Maximum Screen Space Error

            <input type="range" min="0.0" max="64.0" step="0.1" data-bind="value: maximumScreenSpaceError, valueUpdate: 'input'">
            <input type="text" size="5" data-bind="value: maximumScreenSpaceError">

Attenuation

        Geometric Error Scale

            <input type="range" min="0.0" max="2.0" step="0.1" data-bind="value: geometricErrorScale, valueUpdate: 'input'">
            <input type="text" size="5" data-bind="value: geometricErrorScale">

        Maximum Attenuation

            <input type="range" min="0.0" max="32.0" step="1.0" data-bind="value: maximumAttenuation, valueUpdate: 'input'">
            <input type="text" size="5" data-bind="value: maximumAttenuation">

        Base Resolution

            <input type="range" min="0.0" max="10.0" step="0.01" data-bind="value: baseResolution, valueUpdate: 'input'">
            <input type="text" size="5" data-bind="value: baseResolution">

Eye Dome Lighting

        Eye Dome Lighting Strength

            <input type="range" min="0.0" max="10.0" step="0.1" data-bind="value: eyeDomeLightingStrength, valueUpdate: 'input'">
            <input type="text" size="5" data-bind="value: eyeDomeLightingStrength">

        Eye Dome Lighting Radius

            <input type="range" min="0.0" max="10.0" step="0.1" data-bind="value: eyeDomeLightingRadius, valueUpdate: 'input'">
            <input type="text" size="5" data-bind="value: eyeDomeLightingRadius">


text:
package org.apache.spark.streaming.dds

import dds.prelude._
import dds._
import dds.config.DefaultEntities.{defaultDomainParticipant, defaultPolicyFactory}
import org.apache.spark.storage.StorageLevel
import org.omg.dds.sub.DataReaderQos
import scala.collection.JavaConversions._
import org.apache.spark.streaming.receiver.Receiver

object DDSReceiver {

  def createDataReader[T: Manifest](topicName: String, sub: org.omg.dds.sub.Subscriber, qos: org.omg.dds.sub.DataReaderQos) = {
    val topic = Topic[T](topicName)
    implicit val s = sub
    val dr = DataReader[T](topic, qos)
    dr
  }

  def apply[T: Manifest](topicName: String, storageLevel: StorageLevel) = {
    val sub = dds.config.DefaultEntities.defaultSub
    val dr: org.omg.dds.sub.DataReader[T] = createDataReader(topicName, sub, sub.getDefaultDataReaderQos())
    new DDSReceiver[T](dr, storageLevel)
  }

  def apply[T: Manifest](topicName: String, qos: org.omg.dds.sub.DataReaderQos, storageLevel: StorageLevel) = {
    val sub = dds.config.DefaultEntities.defaultSub
    val dr: org.omg.dds.sub.DataReader[T] = createDataReader(topicName, sub, qos)
    new DDSReceiver[T](dr, storageLevel)
  }

  def apply[T: Manifest](topicName: String, partition: String, qos: org.omg.dds.sub.DataReaderQos, storageLevel: StorageLevel) = {
    val subQos = SubscriberQos().withPolicy(Partition(partition))
    implicit val sub = Subscriber(subQos)
    val dr: org.omg.dds.sub.DataReader[T] = createDataReader(topicName, sub, qos)
    new DDSReceiver[T](dr, storageLevel)
  }

  def apply[T: Manifest](topicName: String, partitions: List[String], qos: org.omg.dds.sub.DataReaderQos, storageLevel: StorageLevel) = {
    val subQos = SubscriberQos().withPolicy(Partition(partitions))
    implicit val sub = Subscriber(subQos)
    val dr: org.omg.dds.sub.DataReader[T] = createDataReader(topicName, sub, qos)
    new DDSReceiver[T](dr, storageLevel)
  }
}

class DDSReceiver[T](dr: org.omg.dds.sub.DataReader[T], storageLevel: StorageLevel ) extends Receiver[T](storageLevel) {

  private var lid: Int = 0

  /**
   * store samples store the received values as a reliable or unreliable receiver
   * depending on the DataReader Reliability QoS
   */
  val storeSamples = if (dr.getQos.getReliability.getKind == Reliability.Reliable.getKind) {
    (i: Iterator[T]) => this.store(i)
  }
  else {
    (i: Iterator[T]) => i.foreach(this.store(_))
  }

  def onStart(): Unit = {
    lid = dr listen {
      case DataAvailable(_) => {
        val data = dr.take().filter(_.getData != null).map(_.getData)
        storeSamples(data)
      }
    }
  }

  def onStop(): Unit = {
    dr.deaf(lid)
    dr.close()
  }
}


text:
set -e

################### ENVIRONMENT ###################
# CI w/o D by default or local tests
if [ -z $DC ]; then
    DC=dmd
fi;

# cover result destination and cleanup
if [[ ! -d temp ]]; then
    mkdir temp
else
    rm temp/*.lst -rf || true
fi;

###################### TESTS ######################
# grammar
cd grammar && dub run --config=generate && dub run --config=test
cd ..

# in-source unit tests + cover main application
dub build --build=unittest-cov --config=compiler --compiler=${DC}
bin/styx -v -p -a -t <<< "unit a;"
bin/styx

# release build
dub build --build=release --config=compiler --compiler=${DC}
dub build --build=release --config=library --compiler=${DC}

# file-based tests
rm bin/styx -rf || true
dub build --build=cov --config=compiler --compiler=${DC}
cd tests
$DC test.d
./test


text:
package com.baidu.hsb.manager;

import java.io.EOFException;
import java.nio.channels.SocketChannel;

import org.apache.log4j.Logger;

import com.baidu.hsb.HeisenbergServer;
import com.baidu.hsb.config.ErrorCode;
import com.baidu.hsb.net.FrontendConnection;
import com.baidu.hsb.util.TimeUtil;

/**
 * @author xiongzhao@baidu.com 2011-4-22 下午02:23:55
 */
public class ManagerConnection extends FrontendConnection {
    private static final Logger LOGGER = Logger.getLogger(ManagerConnection.class);
    private static final long AUTH_TIMEOUT = 15 * 1000L;

    public ManagerConnection(SocketChannel channel) {
        super(channel);
    }

    @Override
    public boolean isIdleTimeout() {
        if (isAuthenticated) {
            return super.isIdleTimeout();
        } else {
            return TimeUtil.currentTimeMillis() > Math.max(lastWriteTime, lastReadTime) + AUTH_TIMEOUT;
        }
    }

    @Override
    public void handle(final byte[] data) {
        HeisenbergServer.getInstance().getManagerExecutor().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    handler.handle(data);
                } catch (Throwable t) {
                    error(ErrorCode.ERR_HANDLE_DATA, t);
                }
            }
        });
    }

    @Override
    public void error(int errCode, Throwable t) {
        // 根据异常类型和信息,选择日志输出级别。
        if (t instanceof EOFException) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(toString(), t);
            }
        } else if (isConnectionReset(t)) {
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info(toString(), t);
            }
        } else {
            LOGGER.warn(toString(), t);
        }

        // 异常返回码处理
        switch (errCode) {
        case ErrorCode.ERR_HANDLE_DATA:
            String msg = t.getMessage();
            writeErrMessage(ErrorCode.ER_YES, msg == null ? t.getClass().getSimpleName() : msg);
            break;
        default:
            close();
        }
    }

}


text:
require('express');
exports.google = function(request, response) {
   response.render('googlefccefaef8d3f96fe');

}


text:
import unittest
from default_model import *

# Force the cache
data_store.resource_cache.change_cache_region(make_region().configure('dogpile.cache.memory_pickle'))

class CacheTest(unittest.TestCase):
    def tearDown(self):
        tear_down()

    def test_direct_cache(self):
        alice1 = lp_model.new(name=alice_name, mboxes={alice_mail}, short_bio_en=alice_bio_en)
        #For test ONLY. Do not do that yourself
        alice_store1 = alice1.model_manager.convert_client_resource(alice1)
        data_store.resource_cache.set_resource(alice_store1)
        alice2 = data_store.resource_cache.get_resource(alice1.id)
        self.assertFalse(alice1 is alice2)
        self.assertEquals(alice1.name, alice2.name)
        self.assertEquals(alice1.id, alice2.id)
        self.assertEquals(alice1.short_bio_en, alice2.short_bio_en)
        self.assertEquals(set(alice1.mboxes), set(alice2.mboxes))

        data_store.resource_cache.remove_resource(alice1)
        self.assertFalse(data_store.resource_cache.get_resource(alice1.id))

    def test_simple_get(self):
        alice1 = create_alice()
        alice2 = client_manager.get(id=alice1.id)
        self.assertFalse(alice1 is alice2)
        self.assertEquals(alice1.name, alice2.name)
        self.assertEquals(alice1.id, alice2.id)
        self.assertEquals(alice1.short_bio_en, alice2.short_bio_en)
        self.assertEquals(set(alice1.mboxes), set(alice2.mboxes))

    def test_get_friend(self):
        alice1 = create_alice()
        bob1 = create_bob()
        alice1.friends = {bob1}
        alice1.save()

        alice2 = client_manager.get(id=alice1.id)
        self.assertEquals(alice1.id, alice2.id)

        bob2 = list(alice2.friends)[0]
        self.assertFalse(bob1 is bob2)
        self.assertEquals(bob1.name, bob2.name)
        self.assertEquals(bob1.id, bob2.id)
        self.assertEquals(bob1.short_bio_en, bob2.short_bio_en)
        self.assertEquals(set(bob1.mboxes), set(bob2.mboxes))

    def test_modification(self):
        req_name = """ASK { ?x foaf:name "%s"^^xsd:string }"""
        self.assertFalse(bool(data_graph.query(req_name % alice_name)))

        alice1 = create_alice()
        self.assertTrue(bool(data_graph.query(req_name % alice_name)))
        #Not saved modification
        new_name = "New Alice"
        alice1.name = new_name

        alice2 = client_manager.get(id=alice1.id)
        self.assertFalse(alice1 is alice2)
        self.assertEquals(alice1.id, alice2.id)
        self.assertNotEquals(alice1.name, alice2.name)
        self.assertEquals(alice2.name, alice_name)

        # Save the modification
        alice1.save()
        self.assertFalse(bool(data_graph.query(req_name % alice_name)))
        self.assertTrue(bool(data_graph.query(req_name % new_name)))

        alice3 = client_manager.get(id=alice1.id)
        self.assertFalse(alice1 is alice3)
        self.assertEquals(alice1.id, alice3.id)
        self.assertEquals(alice1.name, alice3.name)
        self.assertEquals(alice3.name, new_name)

        name3 = "Third Alice"
        alice3.name = name3
        alice3.save()
        self.assertFalse(bool(data_graph.query(req_name % new_name)))
        self.assertTrue(bool(data_graph.query(req_name % name3)))

        alice4 = client_manager.get(id=alice1.id)
        self.assertFalse(alice3 is alice4)
        self.assertEquals(alice3.id, alice4.id)
        self.assertEquals(alice3.name, alice4.name)
        self.assertEquals(alice4.name, name3)

    def test_basic_deletion(self):
        alice1 = create_alice()
        alice_iri = alice1.id
        alice1.delete()

        alice2 = client_manager.get(id=alice_iri)
        self.assertEquals(alice2.types, [])

    def test_delete_from_cache(self):
        alice1 = create_alice()
        alice_iri = alice1.id

        alice2 = client_manager.get(id=alice_iri)
        alice2.delete()

        alice3 = client_manager.get(id=alice_iri)
        self.assertEquals(alice3.types, [])
        self.assertFalse(bool(data_graph.query("ASK { <%s> ?p ?o }" % alice_iri)))


text:
extern NSString * const WLXBluetoothDeviceServiceErrorDomain;
typedef enum : NSUInteger {
    WLXBluetoothDeviceServiceErrorServicesDiscoveryAlreadyStarted,
} WLXBluetoothDeviceServiceError;

@import CoreBluetooth;

@interface WLXServicesManager : NSObject<CBPeripheralDelegate>

@property (nonatomic, readonly) NSArray * services;
@property (nonatomic, readonly) BOOL discovering;
@property (nonatomic, readonly) BOOL servicesDiscovered;
@property (nonatomic, readonly) BOOL invalidated;

- (instancetype)initWithPeripheral:(CBPeripheral *)peripheral notificationCenter:(NSNotificationCenter *)notificationCenter;

- (BOOL)discoverServicesUsingBlock:(void(^)(NSError *))block;

- (CBService *)serviceFromUUID:(CBUUID *)serviceUUID;

- (WLXServiceManager *)managerForService:(CBUUID *)serviceUUID;

@end


text:
package com.demo.demorules;

import com.google.gson.annotations.SerializedName;

public class BrmsInsertElement {
	@SerializedName("out-identifier")
	private String outidentifier="result";
	//private PsiData object=new PsiData();
	private PsiDataWrapper object=new PsiDataWrapper();
	@SerializedName("return-object")
	private boolean returnObject=true;
	@SerializedName("entry-point")
	private String entryPoint="DEFAULT";
	public String getOutidentifier() {
		return outidentifier;
	}
	public void setOutidentifier(String outidentifier) {
		this.outidentifier = outidentifier;
	}
	public PsiDataWrapper getObject() {
		return object;
	}
	public void setObject(PsiDataWrapper object) {
		this.object = object;
	}
	public String getEntryPoint() {
		return entryPoint;
	}
	public void setEntryPoint(String entryPoint) {
		this.entryPoint = entryPoint;
	}

}


text:
<?php
/**
 * @namespace
 */
namespace Vein\Core\Cache\Backend;

use Phalcon\Cache\Backend\Memcache as MemcacheBase,
	Phalcon\Cache\BackendInterface,
	Phalcon\Cache\Exception;

/**
 * Memcache
 *
 * This backend uses memcache as cache backend
 */
class Memcache extends MemcacheBase implements BackendInterface
{
	/**
	 * Add an item to the memcache server
	 *
	 * @param string $key
	 * @param string $var
	 * @param bool $flag
	 * @param integer $expire
	 *
	 * @return bool
	 */
	public function add($key, $var, $flag, $expire)
	{
		if (!$this->_memcache) {
			$this->_connect();
		}
		return $this->_memcache->add($key, $var, $flag, $expire);
	}

}


text:
package org.apache.kafka.streams.state.internals;

import org.apache.kafka.streams.processor.internals.ProcessorRecordContext;

import java.util.Arrays;
import java.util.Objects;

public class ContextualRecord {
    private final byte[] value;
    private final ProcessorRecordContext recordContext;

    public ContextualRecord(final byte[] value, final ProcessorRecordContext recordContext) {
        this.value = value;
        this.recordContext = recordContext;
    }

    public ProcessorRecordContext recordContext() {
        return recordContext;
    }

    public byte[] value() {
        return value;
    }

    long sizeBytes() {
        return (value == null ? 0 : value.length) + recordContext.sizeBytes();
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        final ContextualRecord that = (ContextualRecord) o;
        return Arrays.equals(value, that.value) &&
            Objects.equals(recordContext, that.recordContext);
    }

    @Override
    public int hashCode() {
        return Objects.hash(value, recordContext);
    }
}


text:
package api.web.gw2.mapping.v2.guild.upgrades;

import api.web.gw2.mapping.core.CoinAmount;
import api.web.gw2.mapping.core.CoinValue;
import api.web.gw2.mapping.core.DurationValue;
import api.web.gw2.mapping.core.IdValue;
import api.web.gw2.mapping.core.LevelValue;
import api.web.gw2.mapping.core.LocalizedResource;
import api.web.gw2.mapping.core.OptionalValue;
import api.web.gw2.mapping.core.QuantityValue;
import api.web.gw2.mapping.core.SetValue;
import api.web.gw2.mapping.core.URLReference;
import api.web.gw2.mapping.core.URLValue;
import api.web.gw2.mapping.v2.APIv2;
import java.time.Duration;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.Set;

/**
 * Defines a guild upgrade.
 * @author Fabrice Bouyé
 */
@APIv2(endpoint = "v2/guild/upgrades") // NOI18N.
public interface GuildUpgrade {

    /**
     * Gets the id of this upgrade.
     * @return An {@code int}.
     */
    @IdValue
    int getId();

    /**
     * Gets the type of this upgrade.
     * @return An {@code GuildUpgradeType} instance, never {@code null}.
     */
    GuildUpgradeType getType();

    /**
     * Gets the i18n name of this upgrade.
     * @return A {@code String} instance, never {@code null}.
     */
    @LocalizedResource
    String getName();

    /**
     * Gets the i18n description of this upgrade.
     * @return A {@code String} instance, never {@code null}.
     */
    @LocalizedResource
    String getDescription();

    /**
     * Gets the icon of this upgrade.
     * @return A {@code URLReference} instance, never {@code null}.
     */
    @URLValue
    URLReference getIcon();

    /**
     * Gets the build time of this upgrade in seconds.
     * @return A {@code Duration} instance, never {@code null}.
     */
    @DurationValue
    Duration getBuildTime();

    /**
     * Gets the required guild level to build this upgrade.
     * @return An {@code int} > 0.
     */
    // @todo create @GuildLevelValue?
    @LevelValue
    int getRequiredLevel();

    /**
     * Gets the amount of experience gained from building this upgrade.
     * @return An {@code int} > 0.
     */
    @QuantityValue
    int getExperience();

    /**
     * Gets a set of all upgrade ids required to be built before allowed to build this upgrade.
     * @return A non-modifiable {@code Set<Integer>}, never {@code null}.
     */
    @IdValue
    @SetValue
    Set<Integer> getPrerequisites();

    /**
     * Gets a set of costs required before allowed to build this upgrade.
     * @return A non-modifiable {@code Set<GuildUpgradeCost>}, never {@code null}.
     */
    @SetValue
    Set<GuildUpgradeCost> getCosts();

    // @todo Not sure about the need to split into a sub itnerface for those 2 fields.
    /**
     * Gets the maximum number item slots for this bank tab.
     * @return An {@code OptionalInt}, never {@code null}.
     */
    @OptionalValue
    @QuantityValue
    OptionalInt getBagMaxItems();

    /**
     * Gets the maximum number of coins for this bank tab.
     * @return An {@code Optional<CoinAmount>}, never {@code null}.
     */
    @OptionalValue
    @CoinValue
    Optional<CoinAmount> getBagMaxCoins();
}