text:
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F7xx_HAL_LTDC_H
#define __STM32F7xx_HAL_LTDC_H

#ifdef __cplusplus
 extern "C" {
#endif

#if defined (STM32F746xx) || defined (STM32F756xx) || defined (STM32F767xx) || defined (STM32F769xx) || defined (STM32F777xx) || defined (STM32F779xx)

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

/** @addtogroup STM32F7xx_HAL_Driver
  * @{
  */

/** @defgroup LTDC LTDC
  * @brief LTDC HAL module driver
  * @{
  */

/* Exported types ------------------------------------------------------------*/
/** @defgroup LTDC_Exported_Types LTDC Exported Types
  * @{
  */
#define MAX_LAYER  2

/**
  * @brief  LTDC color structure definition
  */
typedef struct
{
  uint8_t Blue;                    /*!< Configures the blue value.
                                        This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */

  uint8_t Green;                   /*!< Configures the green value.
                                        This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */

  uint8_t Red;                     /*!< Configures the red value.
                                        This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */

  uint8_t Reserved;                /*!< Reserved 0xFF */
} LTDC_ColorTypeDef;

/**
  * @brief  LTDC Init structure definition
  */
typedef struct
{
  uint32_t            HSPolarity;                /*!< configures the horizontal synchronization polarity.
                                                      This parameter can be one value of @ref LTDC_HS_POLARITY */

  uint32_t            VSPolarity;                /*!< configures the vertical synchronization polarity.
                                                      This parameter can be one value of @ref LTDC_VS_POLARITY */

  uint32_t            DEPolarity;                /*!< configures the data enable polarity.
                                                      This parameter can be one of value of @ref LTDC_DE_POLARITY */

  uint32_t            PCPolarity;                /*!< configures the pixel clock polarity.
                                                      This parameter can be one of value of @ref LTDC_PC_POLARITY */

  uint32_t            HorizontalSync;            /*!< configures the number of Horizontal synchronization width.
                                                      This parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF. */

  uint32_t            VerticalSync;              /*!< configures the number of Vertical synchronization height.
                                                      This parameter must be a number between Min_Data = 0x000 and Max_Data = 0x7FF. */

  uint32_t            AccumulatedHBP;            /*!< configures the accumulated horizontal back porch width.
                                                      This parameter must be a number between Min_Data = LTDC_HorizontalSync and Max_Data = 0xFFF. */

  uint32_t            AccumulatedVBP;            /*!< configures the accumulated vertical back porch height.
                                                      This parameter must be a number between Min_Data = LTDC_VerticalSync and Max_Data = 0x7FF. */

  uint32_t            AccumulatedActiveW;        /*!< configures the accumulated active width.
                                                      This parameter must be a number between Min_Data = LTDC_AccumulatedHBP and Max_Data = 0xFFF. */

  uint32_t            AccumulatedActiveH;        /*!< configures the accumulated active height.
                                                      This parameter must be a number between Min_Data = LTDC_AccumulatedVBP and Max_Data = 0x7FF. */

  uint32_t            TotalWidth;                /*!< configures the total width.
                                                      This parameter must be a number between Min_Data = LTDC_AccumulatedActiveW and Max_Data = 0xFFF. */

  uint32_t            TotalHeigh;                /*!< configures the total height.
                                                      This parameter must be a number between Min_Data = LTDC_AccumulatedActiveH and Max_Data = 0x7FF. */

  LTDC_ColorTypeDef   Backcolor;                 /*!< Configures the background color. */
} LTDC_InitTypeDef;

/**
  * @brief  LTDC Layer structure definition
  */
typedef struct
{
  uint32_t WindowX0;                   /*!< Configures the Window Horizontal Start Position.
                                            This parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF. */

  uint32_t WindowX1;                   /*!< Configures the Window Horizontal Stop Position.
                                            This parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF. */

  uint32_t WindowY0;                   /*!< Configures the Window vertical Start Position.
                                            This parameter must be a number between Min_Data = 0x000 and Max_Data = 0x7FF. */

  uint32_t WindowY1;                   /*!< Configures the Window vertical Stop Position.
                                            This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0x7FF. */

  uint32_t PixelFormat;                /*!< Specifies the pixel format.
                                            This parameter can be one of value of @ref LTDC_Pixelformat */

  uint32_t Alpha;                      /*!< Specifies the constant alpha used for blending.
                                            This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */

  uint32_t Alpha0;                     /*!< Configures the default alpha value.
                                            This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */

  uint32_t BlendingFactor1;            /*!< Select the blending factor 1.
                                            This parameter can be one of value of @ref LTDC_BlendingFactor1 */

  uint32_t BlendingFactor2;            /*!< Select the blending factor 2.
                                            This parameter can be one of value of @ref LTDC_BlendingFactor2 */

  uint32_t FBStartAdress;              /*!< Configures the color frame buffer address */

  uint32_t ImageWidth;                 /*!< Configures the color frame buffer line length.
                                            This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0x1FFF. */

  uint32_t ImageHeight;                /*!< Specifies the number of line in frame buffer.
                                            This parameter must be a number between Min_Data = 0x000 and Max_Data = 0x7FF. */

  LTDC_ColorTypeDef   Backcolor;       /*!< Configures the layer background color. */
} LTDC_LayerCfgTypeDef;

/**
  * @brief  HAL LTDC State structures definition
  */
typedef enum
{
  HAL_LTDC_STATE_RESET             = 0x00U,    /*!< LTDC not yet initialized or disabled */
  HAL_LTDC_STATE_READY             = 0x01U,    /*!< LTDC initialized and ready for use   */
  HAL_LTDC_STATE_BUSY              = 0x02U,    /*!< LTDC internal process is ongoing     */
  HAL_LTDC_STATE_TIMEOUT           = 0x03U,    /*!< LTDC Timeout state                   */
  HAL_LTDC_STATE_ERROR             = 0x04U     /*!< LTDC state error                     */
}HAL_LTDC_StateTypeDef;

/**
  * @brief  LTDC handle Structure definition
  */
typedef struct
{
  LTDC_TypeDef                *Instance;                /*!< LTDC Register base address                */

  LTDC_InitTypeDef            Init;                     /*!< LTDC parameters                           */

  LTDC_LayerCfgTypeDef        LayerCfg[MAX_LAYER];      /*!< LTDC Layers parameters                    */

  HAL_LockTypeDef             Lock;                     /*!< LTDC Lock                                 */

  __IO HAL_LTDC_StateTypeDef  State;                    /*!< LTDC state                                */

  __IO uint32_t               ErrorCode;                /*!< LTDC Error code                           */

} LTDC_HandleTypeDef;
/**
  * @}
  */

/* Exported constants --------------------------------------------------------*/
/** @defgroup LTDC_Exported_Constants LTDC Exported Constants
  * @{
  */

/** @defgroup LTDC_Error_Code LTDC Error Code
  * @{
  */
#define HAL_LTDC_ERROR_NONE      ((uint32_t)0x00000000U)    /*!< LTDC No error             */
#define HAL_LTDC_ERROR_TE        ((uint32_t)0x00000001U)    /*!< LTDC Transfer error       */
#define HAL_LTDC_ERROR_FU        ((uint32_t)0x00000002U)    /*!< LTDC FIFO Underrun        */
#define HAL_LTDC_ERROR_TIMEOUT   ((uint32_t)0x00000020U)    /*!< LTDC Timeout error        */
/**
  * @}
  */

/** @defgroup LTDC_HS_POLARITY LTDC HS POLARITY
  * @{
  */
#define LTDC_HSPOLARITY_AL                ((uint32_t)0x00000000U)                /*!< Horizontal Synchronization is active low. */
#define LTDC_HSPOLARITY_AH                LTDC_GCR_HSPOL                        /*!< Horizontal Synchronization is active high. */
/**
  * @}
  */

/** @defgroup LTDC_VS_POLARITY LTDC VS POLARITY
  * @{
  */
#define LTDC_VSPOLARITY_AL                ((uint32_t)0x00000000U)                /*!< Vertical Synchronization is active low. */
#define LTDC_VSPOLARITY_AH                LTDC_GCR_VSPOL                        /*!< Vertical Synchronization is active high. */
/**
  * @}
  */

/** @defgroup LTDC_DE_POLARITY LTDC DE POLARITY
  * @{
  */
#define LTDC_DEPOLARITY_AL                ((uint32_t)0x00000000U)                /*!< Data Enable, is active low. */
#define LTDC_DEPOLARITY_AH                LTDC_GCR_DEPOL                        /*!< Data Enable, is active high. */
/**
  * @}
  */

/** @defgroup LTDC_PC_POLARITY LTDC PC POLARITY
  * @{
  */
#define LTDC_PCPOLARITY_IPC               ((uint32_t)0x00000000U)                /*!< input pixel clock. */
#define LTDC_PCPOLARITY_IIPC              LTDC_GCR_PCPOL                        /*!< inverted input pixel clock. */
/**
  * @}
  */

/** @defgroup LTDC_SYNC LTDC SYNC
  * @{
  */
#define LTDC_HORIZONTALSYNC               (LTDC_SSCR_HSW >> 16)                 /*!< Horizontal synchronization width. */
#define LTDC_VERTICALSYNC                 LTDC_SSCR_VSH                         /*!< Vertical synchronization height. */
/**
  * @}
  */

/** @defgroup LTDC_BACK_COLOR LTDC BACK COLOR
  * @{
  */
#define LTDC_COLOR                   ((uint32_t)0x000000FFU)                     /*!< Color mask */
/**
  * @}
  */

/** @defgroup LTDC_BlendingFactor1 LTDC Blending Factor1
  * @{
  */
#define LTDC_BLENDING_FACTOR1_CA                       ((uint32_t)0x00000400U)   /*!< Blending factor : Cte Alpha */
#define LTDC_BLENDING_FACTOR1_PAxCA                    ((uint32_t)0x00000600U)   /*!< Blending factor : Cte Alpha x Pixel Alpha*/
/**
  * @}
  */

/** @defgroup LTDC_BlendingFactor2 LTDC Blending Factor2
  * @{
  */
#define LTDC_BLENDING_FACTOR2_CA                       ((uint32_t)0x00000005U)   /*!< Blending factor : Cte Alpha */
#define LTDC_BLENDING_FACTOR2_PAxCA                    ((uint32_t)0x00000007U)   /*!< Blending factor : Cte Alpha x Pixel Alpha*/
/**
  * @}
  */

/** @defgroup LTDC_Pixelformat LTDC Pixel format
  * @{
  */
#define LTDC_PIXEL_FORMAT_ARGB8888                  ((uint32_t)0x00000000U)      /*!< ARGB8888 LTDC pixel format */
#define LTDC_PIXEL_FORMAT_RGB888                    ((uint32_t)0x00000001U)      /*!< RGB888 LTDC pixel format   */
#define LTDC_PIXEL_FORMAT_RGB565                    ((uint32_t)0x00000002U)      /*!< RGB565 LTDC pixel format   */
#define LTDC_PIXEL_FORMAT_ARGB1555                  ((uint32_t)0x00000003U)      /*!< ARGB1555 LTDC pixel format */
#define LTDC_PIXEL_FORMAT_ARGB4444                  ((uint32_t)0x00000004U)      /*!< ARGB4444 LTDC pixel format */
#define LTDC_PIXEL_FORMAT_L8                        ((uint32_t)0x00000005U)      /*!< L8 LTDC pixel format       */
#define LTDC_PIXEL_FORMAT_AL44                      ((uint32_t)0x00000006U)      /*!< AL44 LTDC pixel format     */
#define LTDC_PIXEL_FORMAT_AL88                      ((uint32_t)0x00000007U)      /*!< AL88 LTDC pixel format     */
/**
  * @}
  */

/** @defgroup LTDC_Alpha LTDC Alpha
  * @{
  */
#define LTDC_ALPHA               LTDC_LxCACR_CONSTA                             /*!< LTDC Cte Alpha mask */
/**
  * @}
  */

/** @defgroup LTDC_LAYER_Config LTDC LAYER Config
  * @{
  */
#define LTDC_STOPPOSITION                 (LTDC_LxWHPCR_WHSPPOS >> 16)          /*!< LTDC Layer stop position  */
#define LTDC_STARTPOSITION                LTDC_LxWHPCR_WHSTPOS                  /*!< LTDC Layer start position */

#define LTDC_COLOR_FRAME_BUFFER           LTDC_LxCFBLR_CFBLL                    /*!< LTDC Layer Line length    */
#define LTDC_LINE_NUMBER                  LTDC_LxCFBLNR_CFBLNBR                 /*!< LTDC Layer Line number    */
/**
  * @}
  */

/** @defgroup LTDC_Interrupts LTDC Interrupts
  * @{
  */
#define LTDC_IT_LI                      LTDC_IER_LIE
#define LTDC_IT_FU                      LTDC_IER_FUIE
#define LTDC_IT_TE                      LTDC_IER_TERRIE
#define LTDC_IT_RR                      LTDC_IER_RRIE
/**
  * @}
  */

/** @defgroup LTDC_Flag LTDC Flag
  * @{
  */
#define LTDC_FLAG_LI                     LTDC_ISR_LIF
#define LTDC_FLAG_FU                     LTDC_ISR_FUIF
#define LTDC_FLAG_TE                     LTDC_ISR_TERRIF
#define LTDC_FLAG_RR                     LTDC_ISR_RRIF
/**
  * @}
  */

/** @defgroup LTDC_Reload_Type LTDC Reload Type
  * @{
  */
#define LTDC_RELOAD_IMMEDIATE            LTDC_SRCR_IMR       /*!< Immediate Reload */
#define LTDC_RELOAD_VERTICAL_BLANKING    LTDC_SRCR_VBR       /*!< Vertical Blanking Reload */
/**
  * @}
  */

/**
  * @}
  */

/* Exported macro ------------------------------------------------------------*/
/** @defgroup LTDC_Exported_Macros LTDC Exported Macros
  * @{
  */

/** @brief Reset LTDC handle state
  * @param  __HANDLE__: specifies the LTDC handle.
  * @retval None
  */
#define __HAL_LTDC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_LTDC_STATE_RESET)

/**
  * @brief  Enable the LTDC.
  * @param  __HANDLE__: LTDC handle
  * @retval None.
  */
#define __HAL_LTDC_ENABLE(__HANDLE__)    ((__HANDLE__)->Instance->GCR |= LTDC_GCR_LTDCEN)

/**
  * @brief  Disable the LTDC.
  * @param  __HANDLE__: LTDC handle
  * @retval None.
  */
#define __HAL_LTDC_DISABLE(__HANDLE__)   ((__HANDLE__)->Instance->GCR &= ~(LTDC_GCR_LTDCEN))

/**
  * @brief  Enable the LTDC Layer.
  * @param  __HANDLE__: LTDC handle
  * @param  __LAYER__: Specify the layer to be enabled
  *                     This parameter can be 0 or 1
  * @retval None.
  */
#define __HAL_LTDC_LAYER_ENABLE(__HANDLE__, __LAYER__)  ((LTDC_LAYER((__HANDLE__), (__LAYER__)))->CR |= (uint32_t)LTDC_LxCR_LEN)

/**
  * @brief  Disable the LTDC Layer.
  * @param  __HANDLE__: LTDC handle
  * @param  __LAYER__: Specify the layer to be disabled
  *                     This parameter can be 0 or 1
  * @retval None.
  */
#define __HAL_LTDC_LAYER_DISABLE(__HANDLE__, __LAYER__) ((LTDC_LAYER((__HANDLE__), (__LAYER__)))->CR &= ~(uint32_t)LTDC_LxCR_LEN)

/**
  * @brief  Reload  Layer Configuration.
  * @param  __HANDLE__: LTDC handle
  * @retval None.
  */
#define __HAL_LTDC_RELOAD_CONFIG(__HANDLE__)   ((__HANDLE__)->Instance->SRCR |= LTDC_SRCR_IMR)

/* Interrupt & Flag management */
/**
  * @brief  Get the LTDC pending flags.
  * @param  __HANDLE__: LTDC handle
  * @param  __FLAG__: Get the specified flag.
  *          This parameter can be any combination of the following values:
  *            @arg LTDC_FLAG_LI: Line Interrupt flag
  *            @arg LTDC_FLAG_FU: FIFO Underrun Interrupt flag
  *            @arg LTDC_FLAG_TE: Transfer Error interrupt flag
  *            @arg LTDC_FLAG_RR: Register Reload Interrupt Flag
  * @retval The state of FLAG (SET or RESET).
  */
#define __HAL_LTDC_GET_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR & (__FLAG__))

/**
  * @brief  Clears the LTDC pending flags.
  * @param  __HANDLE__: LTDC handle
  * @param  __FLAG__: specifies the flag to clear.
  *          This parameter can be any combination of the following values:
  *            @arg LTDC_FLAG_LI: Line Interrupt flag
  *            @arg LTDC_FLAG_FU: FIFO Underrun Interrupt flag
  *            @arg LTDC_FLAG_TE: Transfer Error interrupt flag
  *            @arg LTDC_FLAG_RR: Register Reload Interrupt Flag
  * @retval None
  */
#define __HAL_LTDC_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ICR = (__FLAG__))

/**
  * @brief  Enables the specified LTDC interrupts.
  * @param  __HANDLE__: LTDC handle
  * @param __INTERRUPT__: specifies the LTDC interrupt sources to be enabled.
  *          This parameter can be any combination of the following values:
  *            @arg LTDC_IT_LI: Line Interrupt flag
  *            @arg LTDC_IT_FU: FIFO Underrun Interrupt flag
  *            @arg LTDC_IT_TE: Transfer Error interrupt flag
  *            @arg LTDC_IT_RR: Register Reload Interrupt Flag
  * @retval None
  */
#define __HAL_LTDC_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER |= (__INTERRUPT__))

/**
  * @brief  Disables the specified LTDC interrupts.
  * @param  __HANDLE__: LTDC handle
  * @param __INTERRUPT__: specifies the LTDC interrupt sources to be disabled.
  *          This parameter can be any combination of the following values:
  *            @arg LTDC_IT_LI: Line Interrupt flag
  *            @arg LTDC_IT_FU: FIFO Underrun Interrupt flag
  *            @arg LTDC_IT_TE: Transfer Error interrupt flag
  *            @arg LTDC_IT_RR: Register Reload Interrupt Flag
  * @retval None
  */
#define __HAL_LTDC_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER &= ~(__INTERRUPT__))

/**
  * @brief  Checks whether the specified LTDC interrupt has occurred or not.
  * @param  __HANDLE__: LTDC handle
  * @param  __INTERRUPT__: specifies the LTDC interrupt source to check.
  *          This parameter can be one of the following values:
  *            @arg LTDC_IT_LI: Line Interrupt flag
  *            @arg LTDC_IT_FU: FIFO Underrun Interrupt flag
  *            @arg LTDC_IT_TE: Transfer Error interrupt flag
  *            @arg LTDC_IT_RR: Register Reload Interrupt Flag
  * @retval The state of INTERRUPT (SET or RESET).
  */
#define __HAL_LTDC_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->ISR & (__INTERRUPT__))
/**
  * @}
  */

#if defined (STM32F769xx) || defined (STM32F779xx)
/* Include LTDC HAL Extension module */
#include "stm32f7xx_hal_ltdc_ex.h"
#endif /* STM32F769xx) | STM32F779xx */

/* Exported functions --------------------------------------------------------*/
/** @addtogroup LTDC_Exported_Functions
  * @{
  */
/** @addtogroup LTDC_Exported_Functions_Group1
  * @{
  */
/* Initialization and de-initialization functions *****************************/
HAL_StatusTypeDef HAL_LTDC_Init(LTDC_HandleTypeDef *hltdc);
HAL_StatusTypeDef HAL_LTDC_DeInit(LTDC_HandleTypeDef *hltdc);
void HAL_LTDC_MspInit(LTDC_HandleTypeDef* hltdc);
void HAL_LTDC_MspDeInit(LTDC_HandleTypeDef* hltdc);
void HAL_LTDC_ErrorCallback(LTDC_HandleTypeDef *hltdc);
void HAL_LTDC_LineEvenCallback(LTDC_HandleTypeDef *hltdc);
void HAL_LTDC_ReloadEventCallback(LTDC_HandleTypeDef *hltdc);
/**
  * @}
  */

/** @addtogroup LTDC_Exported_Functions_Group2
  * @{
  */
/* IO operation functions *****************************************************/
void  HAL_LTDC_IRQHandler(LTDC_HandleTypeDef *hltdc);
/**
  * @}
  */

/** @addtogroup LTDC_Exported_Functions_Group3
  * @{
  */
/* Peripheral Control functions ***********************************************/
HAL_StatusTypeDef HAL_LTDC_ConfigLayer(LTDC_HandleTypeDef *hltdc, LTDC_LayerCfgTypeDef *pLayerCfg, uint32_t LayerIdx);
HAL_StatusTypeDef HAL_LTDC_SetWindowSize(LTDC_HandleTypeDef *hltdc, uint32_t XSize, uint32_t YSize, uint32_t LayerIdx);
HAL_StatusTypeDef HAL_LTDC_SetWindowPosition(LTDC_HandleTypeDef *hltdc, uint32_t X0, uint32_t Y0, uint32_t LayerIdx);
HAL_StatusTypeDef HAL_LTDC_SetPixelFormat(LTDC_HandleTypeDef *hltdc, uint32_t Pixelformat, uint32_t LayerIdx);
HAL_StatusTypeDef HAL_LTDC_SetAlpha(LTDC_HandleTypeDef *hltdc, uint32_t Alpha, uint32_t LayerIdx);
HAL_StatusTypeDef HAL_LTDC_SetAddress(LTDC_HandleTypeDef *hltdc, uint32_t Address, uint32_t LayerIdx);
HAL_StatusTypeDef HAL_LTDC_SetPitch(LTDC_HandleTypeDef *hltdc, uint32_t LinePitchInPixels, uint32_t LayerIdx);
HAL_StatusTypeDef HAL_LTDC_ConfigColorKeying(LTDC_HandleTypeDef *hltdc, uint32_t RGBValue, uint32_t LayerIdx);
HAL_StatusTypeDef HAL_LTDC_ConfigCLUT(LTDC_HandleTypeDef *hltdc, uint32_t *pCLUT, uint32_t CLUTSize, uint32_t LayerIdx);
HAL_StatusTypeDef HAL_LTDC_EnableColorKeying(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx);
HAL_StatusTypeDef HAL_LTDC_DisableColorKeying(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx);
HAL_StatusTypeDef HAL_LTDC_EnableCLUT(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx);
HAL_StatusTypeDef HAL_LTDC_DisableCLUT(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx);
HAL_StatusTypeDef HAL_LTDC_ProgramLineEvent(LTDC_HandleTypeDef *hltdc, uint32_t Line);
HAL_StatusTypeDef HAL_LTDC_EnableDither(LTDC_HandleTypeDef *hltdc);
HAL_StatusTypeDef HAL_LTDC_DisableDither(LTDC_HandleTypeDef *hltdc);
HAL_StatusTypeDef HAL_LTDC_Reload(LTDC_HandleTypeDef *hltdc, uint32_t ReloadType);
HAL_StatusTypeDef HAL_LTDC_ConfigLayer_NoReload(LTDC_HandleTypeDef *hltdc, LTDC_LayerCfgTypeDef *pLayerCfg, uint32_t LayerIdx);
HAL_StatusTypeDef HAL_LTDC_SetWindowSize_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t XSize, uint32_t YSize, uint32_t LayerIdx);
HAL_StatusTypeDef HAL_LTDC_SetWindowPosition_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t X0, uint32_t Y0, uint32_t LayerIdx);
HAL_StatusTypeDef HAL_LTDC_SetPixelFormat_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t Pixelformat, uint32_t LayerIdx);
HAL_StatusTypeDef HAL_LTDC_SetAlpha_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t Alpha, uint32_t LayerIdx);
HAL_StatusTypeDef HAL_LTDC_SetAddress_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t Address, uint32_t LayerIdx);
HAL_StatusTypeDef HAL_LTDC_SetPitch_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t LinePitchInPixels, uint32_t LayerIdx);
HAL_StatusTypeDef HAL_LTDC_ConfigColorKeying_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t RGBValue, uint32_t LayerIdx);
HAL_StatusTypeDef HAL_LTDC_EnableColorKeying_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx);
HAL_StatusTypeDef HAL_LTDC_DisableColorKeying_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx);
HAL_StatusTypeDef HAL_LTDC_EnableCLUT_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx);
HAL_StatusTypeDef HAL_LTDC_DisableCLUT_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx);

/**
  * @}
  */

/** @addtogroup LTDC_Exported_Functions_Group4
  * @{
  */
/* Peripheral State functions *************************************************/
HAL_LTDC_StateTypeDef HAL_LTDC_GetState(LTDC_HandleTypeDef *hltdc);
uint32_t              HAL_LTDC_GetError(LTDC_HandleTypeDef *hltdc);
/**
  * @}
  */

/**
  * @}
  */
/* Private types -------------------------------------------------------------*/
/** @defgroup LTDC_Private_Types LTDC Private Types
  * @{
  */

/**
  * @}
  */

/* Private variables ---------------------------------------------------------*/
/** @defgroup LTDC_Private_Variables LTDC Private Variables
  * @{
  */

/**
  * @}
  */

/* Private constants ---------------------------------------------------------*/
/** @defgroup LTDC_Private_Constants LTDC Private Constants
  * @{
  */

/**
  * @}
  */

/* Private macros ------------------------------------------------------------*/
/** @defgroup LTDC_Private_Macros LTDC Private Macros
  * @{
  */
#define LTDC_LAYER(__HANDLE__, __LAYER__)         ((LTDC_Layer_TypeDef *)((uint32_t)(((uint32_t)((__HANDLE__)->Instance)) + 0x84 + (0x80*(__LAYER__)))))
#define IS_LTDC_LAYER(LAYER)                      ((LAYER) <= MAX_LAYER)
#define IS_LTDC_HSPOL(HSPOL)                      (((HSPOL) == LTDC_HSPOLARITY_AL) || \
                                                   ((HSPOL) == LTDC_HSPOLARITY_AH))
#define IS_LTDC_VSPOL(VSPOL)                      (((VSPOL) == LTDC_VSPOLARITY_AL) || \
                                                   ((VSPOL) == LTDC_VSPOLARITY_AH))
#define IS_LTDC_DEPOL(DEPOL)                      (((DEPOL) ==  LTDC_DEPOLARITY_AL) || \
                                                   ((DEPOL) ==  LTDC_DEPOLARITY_AH))
#define IS_LTDC_PCPOL(PCPOL)                      (((PCPOL) ==  LTDC_PCPOLARITY_IPC) || \
                                                   ((PCPOL) ==  LTDC_PCPOLARITY_IIPC))
#define IS_LTDC_HSYNC(HSYNC)                      ((HSYNC)  <= LTDC_HORIZONTALSYNC)
#define IS_LTDC_VSYNC(VSYNC)                      ((VSYNC)  <= LTDC_VERTICALSYNC)
#define IS_LTDC_AHBP(AHBP)                        ((AHBP)   <= LTDC_HORIZONTALSYNC)
#define IS_LTDC_AVBP(AVBP)                        ((AVBP)   <= LTDC_VERTICALSYNC)
#define IS_LTDC_AAW(AAW)                          ((AAW)    <= LTDC_HORIZONTALSYNC)
#define IS_LTDC_AAH(AAH)                          ((AAH)    <= LTDC_VERTICALSYNC)
#define IS_LTDC_TOTALW(TOTALW)                    ((TOTALW) <= LTDC_HORIZONTALSYNC)
#define IS_LTDC_TOTALH(TOTALH)                    ((TOTALH) <= LTDC_VERTICALSYNC)
#define IS_LTDC_BLUEVALUE(BBLUE)                  ((BBLUE)  <= LTDC_COLOR)
#define IS_LTDC_GREENVALUE(BGREEN)                ((BGREEN) <= LTDC_COLOR)
#define IS_LTDC_REDVALUE(BRED)                    ((BRED)   <= LTDC_COLOR)
#define IS_LTDC_BLENDING_FACTOR1(BlendingFactor1) (((BlendingFactor1) == LTDC_BLENDING_FACTOR1_CA) || \
                                                   ((BlendingFactor1) == LTDC_BLENDING_FACTOR1_PAxCA))
#define IS_LTDC_BLENDING_FACTOR2(BlendingFactor2) (((BlendingFactor2) == LTDC_BLENDING_FACTOR2_CA) || \
                                                   ((BlendingFactor2) == LTDC_BLENDING_FACTOR2_PAxCA))
#define IS_LTDC_PIXEL_FORMAT(Pixelformat)         (((Pixelformat) == LTDC_PIXEL_FORMAT_ARGB8888) || ((Pixelformat) == LTDC_PIXEL_FORMAT_RGB888)   || \
                                                   ((Pixelformat) == LTDC_PIXEL_FORMAT_RGB565)   || ((Pixelformat) == LTDC_PIXEL_FORMAT_ARGB1555) || \
                                                   ((Pixelformat) == LTDC_PIXEL_FORMAT_ARGB4444) || ((Pixelformat) == LTDC_PIXEL_FORMAT_L8)       || \
                                                   ((Pixelformat) == LTDC_PIXEL_FORMAT_AL44)     || ((Pixelformat) == LTDC_PIXEL_FORMAT_AL88))
#define IS_LTDC_ALPHA(ALPHA)                      ((ALPHA) <= LTDC_ALPHA)
#define IS_LTDC_HCONFIGST(HCONFIGST)              ((HCONFIGST) <= LTDC_STARTPOSITION)
#define IS_LTDC_HCONFIGSP(HCONFIGSP)              ((HCONFIGSP) <= LTDC_STOPPOSITION)
#define IS_LTDC_VCONFIGST(VCONFIGST)              ((VCONFIGST) <= LTDC_STARTPOSITION)
#define IS_LTDC_VCONFIGSP(VCONFIGSP)              ((VCONFIGSP) <= LTDC_STOPPOSITION)
#define IS_LTDC_CFBP(CFBP)                        ((CFBP) <= LTDC_COLOR_FRAME_BUFFER)
#define IS_LTDC_CFBLL(CFBLL)                      ((CFBLL) <= LTDC_COLOR_FRAME_BUFFER)
#define IS_LTDC_CFBLNBR(CFBLNBR)                  ((CFBLNBR) <= LTDC_LINE_NUMBER)
#define IS_LTDC_LIPOS(LIPOS)                      ((LIPOS) <= 0x7FF)
#define IS_LTDC_RELAOD(RELOADTYPE)                (((RELOADTYPE) == LTDC_RELOAD_IMMEDIATE) || ((RELOADTYPE) == LTDC_SRCR_VBR))
/**
  * @}
  */

/* Private functions ---------------------------------------------------------*/
/** @defgroup LTDC_Private_Functions LTDC Private Functions
  * @{
  */

/**
  * @}
  */

/**
  * @}
  */
#endif /* STM32F746xx || STM32F756xx || STM32F767xx || STM32F769xx || STM32F777xx || STM32F779xx */
/**
  * @}
  */

#ifdef __cplusplus
}
#endif

#endif /* __STM32F7xx_HAL_LTDC_H */

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


text:
import * as assert from 'assert'
import { after } from 'mocha'

// You can import and use all API from the 'vscode' module
// as well as import your extension to test it
import * as vscode from 'vscode'
// import * as myExtension from '../extension';

suite('Extension Test Suite', () => {
    after(() => {
        vscode.window.showInformationMessage('All tests done!')
    })

    test('Sample test', () => {
        assert.equal(-1, [1, 2, 3].indexOf(5))
        assert.equal(-1, [1, 2, 3].indexOf(0))
    })
})

redpajama_set_name: RedPajamaGithub


text:
package org.apache.ignite.internal.commandline.defragmentation;

import org.apache.ignite.internal.visor.defragmentation.VisorDefragmentationOperation;
import org.jetbrains.annotations.Nullable;

/** */
public enum DefragmentationSubcommands {
    /** */
    SCHEDULE("schedule", VisorDefragmentationOperation.SCHEDULE),

    /** */
    STATUS("status", VisorDefragmentationOperation.STATUS),

    /** */
    CANCEL("cancel", VisorDefragmentationOperation.CANCEL);

    /** */
    private final String name;

    /** */
    private final VisorDefragmentationOperation visorOperation;

    /** */
    DefragmentationSubcommands(String name, VisorDefragmentationOperation visorOperation) {
        this.name = name;
        this.visorOperation = visorOperation;
    }

    /**
     * @param strRep String representation of subcommand.
     * @return Subcommand for its string representation.
     */
    public static @Nullable DefragmentationSubcommands of(String strRep) {
        for (DefragmentationSubcommands cmd : values()) {
            if (cmd.text().equalsIgnoreCase(strRep))
                return cmd;
        }

        return null;
    }

    /** */
    public String text() {
        return name;
    }

    /** */
    public VisorDefragmentationOperation operation() {
        return visorOperation;
    }
}


text:
"""opencache-client.py: simple command-line client to make requests to an OpenCache controller."""

import json
import optparse
import random
import urllib

def do_opencache_call(method, host, port, node, expr, call_id=None):
    """Make a JSON-RPC call to an OpenCache controller. Print and return the result."""
    if call_id == None:
        call_id = random.randint(1, 999)
    params = {'node' : str(node), 'expr' : str(expr)}
    url =  "http://%s:%s" % (host, port)
    try:
        post_data = json.dumps({"id":call_id, "method":str(method), "params":params, "jsonrpc":"2.0"})
    except Exception as exception:
        print "[ERROR] Could not encode JSON: %s" % exception
    try:
        response_data = urllib.urlopen(url, post_data).read()
        print "[INFO] Sent request: %s" %post_data
        try:
            response_json = json.loads(response_data)
            if response_json['id'] == str(call_id):
                print "[INFO] Received response: %s" %response_json
                return response_json
            else:
                print "[ERROR] Mismatched call ID for response: %s" %response_json
                raise IOError("Mismatched call ID for response: %s" %response_json)
        except Exception as exception:
            print "[ERROR] Could not decode JSON from OpenCache node response: %s" % exception
    except IOError as exception:
        print "[ERROR] Could not connect to OpenCache instance: %s" % exception

if __name__ == '__main__':
    """Read command line arguments."""
    parser = optparse.OptionParser()
    parser.add_option("-m", "--method", dest="method",
        help="method to call on OpenCache controller: start/stop/pause/stat/refresh")
    parser.add_option("-i", "--hostname", dest="host", default='127.0.0.1',
        help="hostname of OpenCache controller")
    parser.add_option("-p", "--port", dest="port", default='49001',
        help="port number of the OpenCache JSON-RPC interface listening for requests")
    parser.add_option("-n", "--node", dest="node", default='*',
        help="list of nodes to execute given OpenCache command on")
    parser.add_option("-e", "--expression", dest="expr", default='*',
        help="list of expressions to execute with given OpenCache command")
    (options, args) = parser.parse_args()
    do_opencache_call(options.method, options.host, options.port, options.node, options.expr)


text:
using namespace Glyph3;
//--------------------------------------------------------------------------------
extern LRESULT CALLBACK WindowProc( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam );
//--------------------------------------------------------------------------------
Win32RenderWindow::Win32RenderWindow( )
{
	m_hWnd = 0;

	// Specify the window style
	m_dStyle = (WS_OVERLAPPEDWINDOW | WS_VISIBLE);
}
//--------------------------------------------------------------------------------
Win32RenderWindow::~Win32RenderWindow()
{
	Shutdown();
}
//--------------------------------------------------------------------------------
// This free function is used as a hook into the window's messaging system.  When
// the window is initialized, the owner passes a pointer to a IWindowProc
// implementation.  When Windows sends a message to this window, we call this
// handler function - which will either call the default processor (when no valid
// pointer is there) or call the IWindowProc method (when a valid one is
// available).
//--------------------------------------------------------------------------------
LRESULT CALLBACK InternalWindowProc( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam )
{
	LONG_PTR ObjPtr = GetWindowLongPtr(hwnd, 0);

	if (ObjPtr == 0) {
        return( DefWindowProc( hwnd, msg, wparam, lparam ) );
	} else {
	    return( ((IWindowProc*)ObjPtr)->WindowProc(hwnd, msg, wparam, lparam) );
	}
}
//--------------------------------------------------------------------------------
void Win32RenderWindow::Initialize(IWindowProc* WindowProcObj)
{
	WNDCLASSEX wc;

	// Setup the window class
	memset(&wc,0, sizeof(wc));
	wc.cbSize			= sizeof(WNDCLASSEX);
	wc.style			= CS_HREDRAW | CS_VREDRAW;
	wc.lpfnWndProc		= InternalWindowProc;
	wc.cbClsExtra		= 0;
	wc.cbWndExtra		= sizeof(WindowProcObj);
	wc.hInstance		= 0;
	wc.hIcon			= LoadIcon(NULL, IDI_APPLICATION);
	wc.hCursor			= LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground	= (HBRUSH)GetStockObject(BLACK_BRUSH);
	wc.lpszMenuName		= NULL;
	wc.lpszClassName	= L"HieroglyphWin32";
	wc.hIconSm			= LoadIcon(NULL, IDI_APPLICATION);

	if ( WindowProcObj != nullptr ) {
		WindowProcObj->BeforeRegisterWindowClass(wc);
	}

	// Register the window class
	RegisterClassEx(&wc);

	// Record the desired device size
	RECT rc;
	rc.top = rc.left = 0;
	rc.right = m_iWidth;
	rc.bottom = m_iHeight;

	// Adjust the window size for correct device size
	AdjustWindowRectEx(&rc, m_dStyle, false, 0);

	long lwidth = rc.right - rc.left;
	long lheight = rc.bottom - rc.top;

	long lleft = (long)m_iLeft;
	long ltop = (long)m_iTop;

	// Create an instance of the window
	m_hWnd = CreateWindowEx(
		NULL,							// extended style
		wc.lpszClassName, 				// class name
		m_sCaption.c_str(),				// instance title
		m_dStyle,						// window style
		lleft, ltop,					// initial x, y
		lwidth,							// initial width
		lheight,						// initial height
		NULL,							// handle to parent
		NULL,							// handle to menu
		NULL,							// instance of this application
		NULL );							// extra creation parms

	// Update the size of the window according to the client area that was
	// created.  Due to limitations about the desktop size, this can cause some
	// situations where the created window is smaller than requested.

	RECT rect;
	GetClientRect( m_hWnd, &rect );
	m_iWidth = rect.right - rect.left;
	m_iHeight = rect.bottom - rect.top;

	if (m_hWnd) {
		// Set in the "extra" bytes the pointer to the IWindowProc object
		// which handles messages for the window
        SetWindowLongPtr(m_hWnd, 0, (LONG_PTR)WindowProcObj);
    	// Initially display the window
		ShowWindow( m_hWnd, SW_SHOWNORMAL );
		UpdateWindow( m_hWnd );
	}
}
//--------------------------------------------------------------------------------
void Win32RenderWindow::Shutdown()
{
	if ( m_hWnd )
		DestroyWindow( m_hWnd );

	m_hWnd = 0;
}
//--------------------------------------------------------------------------------
void Win32RenderWindow::Paint()
{

}
//--------------------------------------------------------------------------------
Vector2f Win32RenderWindow::GetCursorPosition()
{
	POINT p;
	GetCursorPos( &p );
	ScreenToClient( m_hWnd, &p );

	return( Vector2f( static_cast<float>(p.x), static_cast<float>(p.y) ) );
}
//--------------------------------------------------------------------------------


text:
'use strict';

/**
 * Load required plugins
 */
var gulp = require('gulp'),
  $ = require('gulp-load-plugins')(),
  autoprefixer = require('gulp-autoprefixer'),
  concat = require('gulp-concat'),
  cleanCss = require('gulp-clean-css'),
  ghPages = require('gulp-gh-pages'),
  jshint = require('gulp-jshint'),
  rename = require('gulp-rename'),
  rsync = require('gulp-rsync'),
  sass = require('gulp-sass'),
  sourcemaps = require('gulp-sourcemaps'),
  twig = require('gulp-twig'),
  uglify = require('gulp-uglify'),

  browserSync = require('browser-sync'),
  reload = browserSync.reload,
  runSequence = require('run-sequence'),
  argv = require('yargs').argv,
  rimraf = require('rimraf'),
  assemble = require('fabricator-assemble'),
  yaml = require('js-yaml'),
  fs = require('fs'),
  globby = require('globby'),
  path = require('path'),
  markdown = require('markdown-it')({
    html: true
  });

/**
 * Configuration
 */
var config = {
  dev: $.util.env.dev,
  src: {
    styles: {
      fabricator: 'src/assets/fabricator/styles/fabricator.scss'
    },
    javascript: {
      fabricator: [
        'node_modules/prismjs/prism.js',
        'src/assets/fabricator/scripts/*.js'
      ]
    }
  },
  styleguide: {
    dest: 'styleguide'
  },
  framework: {
    dest: 'build'
  },
  locales: yaml.safeLoad(fs.readFileSync('src/data/locales.yml', 'utf-8')),
  autoprefixer: ['last 2 versions', 'safari 8', 'ie 9', 'ff 28']
};

/**
 * Build vendors dependencies
 */
gulp.task('vendors', function() {

  // CSS VENDORS
  gulp.src([
    'node_modules/Yamm/yamm/yamm.css',
    'node_modules/bootstrap-accessibility-plugin/plugins/css/bootstrap-accessibility.css',
    'node_modules/blueimp-gallery/css/blueimp-gallery.min.css',
    'node_modules/blueimp-bootstrap-image-gallery/css/bootstrap-image-gallery.min.css',
    'node_modules/pikaday/css/pikaday.css'
  ])
    .pipe(concat('vendors.css'))
    .pipe(cleanCss())
    .pipe(gulp.dest(config.framework.dest + '/css'));

  // JS VENDORS
  // (with jQuery and Bootstrap dependencies first)
  gulp.src([
    'node_modules/jquery/dist/jquery.js',
    'node_modules/drmonty-chosen/js/chosen.jquery.js',
    'node_modules/typeahead.js/dist/typeahead.bundle.js',
    'node_modules/bootstrap-sass/assets/javascripts/bootstrap/affix.js',
    'node_modules/bootstrap-sass/assets/javascripts/bootstrap/alert.js',
    'node_modules/bootstrap-sass/assets/javascripts/bootstrap/button.js',
    'node_modules/bootstrap-sass/assets/javascripts/bootstrap/carousel.js',
    'node_modules/bootstrap-sass/assets/javascripts/bootstrap/collapse.js',
    'node_modules/bootstrap-sass/assets/javascripts/bootstrap/dropdown.js',
    'node_modules/bootstrap-sass/assets/javascripts/bootstrap/modal.js',
    'node_modules/bootstrap-sass/assets/javascripts/bootstrap/tooltip.js',
    'node_modules/bootstrap-sass/assets/javascripts/bootstrap/popover.js',
    'node_modules/bootstrap-sass/assets/javascripts/bootstrap/scrollspy.js',
    'node_modules/bootstrap-sass/assets/javascripts/bootstrap/tab.js',
    'node_modules/bootstrap-sass/assets/javascripts/bootstrap/transition.js',
    'node_modules/bootstrap-accessibility-plugin/plugins/js/bootstrap-accessibility.js',
    'node_modules/tablesorter/dist/js/jquery.tablesorter.js',
    'node_modules/jquery-drilldown/dist/jquery.drilldown.js',
    'node_modules/Placeholdr/placeholdr.js',
    'node_modules/blueimp-gallery/js/jquery.blueimp-gallery.min.js',
    'node_modules/blueimp-bootstrap-image-gallery/js/bootstrap-image-gallery.min.js',
    'node_modules/moment/moment.js',
    'node_modules/pikaday/pikaday.js',
    'node_modules/twitter-timeline/index.js'
  ])
    .pipe(concat('vendors.js'))
    .pipe(gulp.dest(config.framework.dest + '/js'))
    .pipe(concat('vendors.min.js'))
    .pipe(uglify())
    .pipe(gulp.dest(config.framework.dest + '/js'));

  // FONTS SOURCES
  // Important to add the bootstrap fonts to avoid issues with the fonts include path
  gulp.src([
    'node_modules/bootstrap-sass/assets/fonts/bootstrap/*',
    'assets/fonts/*'
  ])
    .pipe(gulp.dest(config.framework.dest + '/fonts'));
});

/**
 * Build styles from SCSS files
 * With error reporting on compiling (so that there's no crash)
 */
gulp.task('styles', function() {
  if (!argv.dev) { console.log('[styles] Outputting minified styles.' ); }
  else { console.log('[styles] Processing styles for dev env. No minifying here, for sourcemaps!') }

  return gulp.src('src/assets/sass/admin.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe($.if(argv.dev, sourcemaps.init()))
    .pipe(autoprefixer({
      browsers: config.autoprefixer
    }))
    .pipe($.if(argv.dev, sourcemaps.write()))
    .pipe($.if(!argv.dev, cleanCss()))
    .pipe(gulp.dest(config.framework.dest + '/css'));
});

gulp.task('print', function() {
  return gulp.src('src/assets/sass/print/print.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe($.if(argv.dev, sourcemaps.init()))
    .pipe(autoprefixer({
      browsers: config.autoprefixer
    }))
    .pipe($.if(argv.dev, sourcemaps.write()))
    .pipe($.if(!argv.dev, cleanCss()))
    .pipe(gulp.dest(config.framework.dest + '/css'));
});

gulp.task('twitter-inject', function() {
  return gulp.src('src/assets/sass/twitter-inject.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe($.if(argv.dev, sourcemaps.init()))
    .pipe(autoprefixer({
      browsers: config.autoprefixer
    }))
    .pipe($.if(argv.dev, sourcemaps.write()))
    .pipe($.if(!argv.dev, cleanCss()))
    .pipe(gulp.dest(config.framework.dest + '/css'));
});

/**
 * Build JS
 * With error reporting on compiling (so that there's no crash)
 */
gulp.task('scripts', function() {
  return gulp.src(['src/assets/js/*.js'])
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'))
    .pipe(concat('main.js'))
    .pipe(gulp.dest(config.framework.dest + '/js'))
    .pipe(rename({ suffix: '.min' }))
    .pipe(uglify())
    .pipe(gulp.dest(config.framework.dest + '/js'));
});

/**
 * Copy images to build
 */
gulp.task('build-images', function() {
  return gulp.src(['src/assets/img/**', 'node_modules/blueimp-gallery/img/**'])
    .pipe(gulp.dest(config.framework.dest + '/img'));
});

/**
 * Copy fonts to build
 */
gulp.task('build-fonts', function() {
  return gulp.src(['src/assets/fonts/**'])
    .pipe(gulp.dest(config.framework.dest + '/fonts'));
});

/**
 * Compile TWIG example pages
 */
gulp.task('clean-twig', function(cb) {
  rimraf('src/views/pages', cb);
});

gulp.task('twig', ['clean-twig'], function() {
  return gulp.src(['src/example-pages/*.twig', '!src/example-pages/layout.twig'])
    .pipe(twig())
    .pipe(gulp.dest('src/views/pages'));
});

/**
 * FABRICATOR
 */
// Build the style guide
gulp.task('assemble-everything', function(cb) {
  runSequence('clean', 'assemble', 'copy', 'styles:fabricator', 'scripts:fabricator', cb);
});

gulp.task('assemble', function(done) {
  // Build style guide for every language
  for (var localeCode in config.locales) {
    if (config.locales.hasOwnProperty(localeCode)) {
      var locale = config.locales[localeCode];

      // Do not build disabled locales
      if (locale.disabled) continue;

      var dest = config.styleguide.dest + '/' + locale.code,
        data = {
          locale: locale.code,
          version: fs.readFileSync('VERSION', 'utf-8')
        },
        dictionary = {};

      // Get all translation files for the current locale
      var translations = globby.sync('src/locales/' + locale.code + '/*.yml');

      // Build a dictionary using the filename as the main key
      translations.forEach(function (file) {
        var id = path.basename(file, path.extname(file));
        dictionary[id] = yaml.safeLoad(fs.readFileSync(file, 'utf-8'));
      });

      // Assemble the style guide
      assemble({
        dest: dest,
        logErrors: config.dev,
        helpers: {
          // Register the translation helper
          t: function () {
            // Build an array out of fn arguments
            var args = Array.prototype.slice.call(arguments);
            // Remove the last entry which is an object given by Handlebars
            var obj = args.pop();

            // Build a full translation key with all arguments
            args = args.join('.');

            // Remove any digits coming from the component key prefix
            args = args.replace(/(\d+[\-\.]?)/g, '');

            // Look for the translation in the dictionnary
            var value = args.trim().split('.').reduce(function (dict, key) {
              if (!dict) {
                return null;
              }
              return dict[key];
            }, dictionary);

            // Parse content for Markdown if required
            if (value && obj.hash && obj.hash.markdown) {
              var value = markdown.render(value);
            }

            return value || '[Missing translation: ' + args + ']';
          },
          // Return true if the language given match with the current locale
          isCurrentLocale: function (lang, options) {
            if (lang === locale.code) {
              return options.fn(this);
            }
            return options.inverse(this);
          },
          // Return the corresponding data value
          data: function (value) {
            return data[value] || '';
          },
          toUpperCase: function (value) {
            return value.toUpperCase();
          },
          renderFile: function (path, file) {
            var fileName = 'src/materials-data/' + path + file,
              exists = fs.existsSync(fileName);

            if (!exists) return '[File "' + fileName + '" doesn't exist.]';

            return fs.readFileSync(fileName, 'utf-8');
          },
          replace: function (regex, newSubstr, str) {
            return str.replace(new RegExp(regex, 'g'), newSubstr);
          },
          modulo: function (index, divider, block) {
            if ((parseInt(index, 10) + 1) % divider === 0) {
              return block.fn(this);
            }
          },
          // Remove number prefixes (01- or 01.02-)
          prefixless: function (value) {
            return value.replace(/(\d+[\-\.]?)+/ig, '');
          }
        }
      })
    }
  }
  done();
});

// Copy all the required files to the styleguide folder
gulp.task('copy', ['copy:framework', 'copy:assets', 'copy:landing', 'copy:files']);

gulp.task('copy:framework', function() {
  return gulp.src([config.framework.dest + '/**/*'])
    .pipe(gulp.dest(config.styleguide.dest));
});

gulp.task('copy:assets', function() {
  return gulp.src(['styleguide-img/**/*'])
    .pipe(gulp.dest(config.styleguide.dest + '/styleguide-img'));
});

gulp.task('copy:landing', function() {
  return gulp.src(['src/index.html'])
    .pipe(gulp.dest(config.styleguide.dest));
});

gulp.task('copy:files', function() {
  return gulp.src(['src/assets/files/*'])
    .pipe(gulp.dest(config.styleguide.dest + '/files'));
});

// Build Fabricator style
gulp.task('styles:fabricator', function() {
  gulp.src(config.src.styles.fabricator)
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError))
    .pipe(autoprefixer({
      browsers: config.autoprefixer
    }))
    .pipe($.if(!config.dev, cleanCss()))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(config.styleguide.dest + '/css'))
    .pipe($.if(config.dev, reload({stream:true})));
});

// Build Fabricator scripts
gulp.task('scripts:fabricator', function() {
  return gulp.src(config.src.javascript.fabricator)
    .pipe(concat('fabricator.min.js'))
    .pipe(uglify())
    .pipe(gulp.dest(config.styleguide.dest + '/js'));
});

/**
 * Clean output directories
 */
gulp.task('clean', function(cb) {
  rimraf(config.styleguide.dest, cb);
});

/**
 * Serve
 */
gulp.task('serve', ['assemble-everything'], function () {
  browserSync({
    server: {
      baseDir: config.styleguide.dest
    },
    notify: false,
    open: false
  });

  gulp.task('assemble:watch', ['assemble-everything'], reload);
  gulp.watch(['src/**/*.{html,md,json,yml}'], ['assemble:watch']);

  gulp.watch(['src/assets/sass/**/*.scss', 'src/assets/fabricator/styles/**/*.scss'], function() {
    runSequence('styles', 'print', 'twitter-inject', 'assemble:watch');
  });
  gulp.watch(['src/assets/js/*.js', 'src/assets/fabricator/scripts/**/*.js'], function() {
    runSequence('scripts', 'assemble:watch');
  });
  gulp.watch(['src/assets/img/**/*.{jpg,png,gif,svg}'], function() {
    runSequence('build-images', 'assemble:watch');
  });
  gulp.watch(['src/assets/fonts/**/*.{eot,woff,woff2,ttf}'], function() {
    runSequence('build-fonts', 'assemble:watch');
  });
  gulp.watch(['src/example-pages/*.twig'], function() {
    runSequence('twig', 'assemble:watch');
  });
});

/**
 * Deploy to GH pages
 */
gulp.task('deploy', function () {
  if (argv.github) {
    return gulp.src(config.styleguide.dest + '/**/*')
      .pipe(ghPages());
  }
  else {
    return gulp.src(config.styleguide.dest + '/**/*')
      .pipe(rsync({
        root: 'styleguide',
        hostname: 'swg',
        destination: '/var/www/swg',
        progress: true,
        recursive: true,
        clean: true
      }));
  }
});

/**
 * Default task build the style guide
 */
gulp.task('default', ['clean'], function(cb) {
  runSequence(
    'vendors',
    'styles',
    'print',
    'twitter-inject',
    'scripts',
    'twig',
    'build-images',
    'build-fonts',
    'styles:fabricator',
    'scripts:fabricator',
    'assemble',
    'copy',
    cb
  );
});


text:
#pragma once

#include "js_value_fwd.h"
#include "v8.h"
#include "mldb/arch/exception.h"

namespace MLDB {

namespace JS {

template<typename T>
v8::Local<T> toLocalChecked(const v8::MaybeLocal<T> & val)
{
    v8::Local<T> result;
    if (!val.ToLocal(&result)) {
        // TODO: throw JS exception instead?
        throw MLDB::Exception("JS Expected value was not returned; JS exception in process");
    }
    return result;
}

template<typename T>
T check(const v8::Maybe<T> & val)
{
    if (val.IsNothing()) {
        // TODO: throw JS exception instead?
        throw MLDB::Exception("JS expected check did not pass; JS exception in process");
    }
    return val.ToChecked();
}

// Some API methods change from X to Maybe<X>; this allows us to operate on them
// over the different versions of the API
template<typename T>
T check(const T & val)
{
    return val;
}

/*****************************************************************************/
/* JSVALUE                                                                   */
/*****************************************************************************/

/** Opaque type used to represent a Javascript value
*/

struct JSValue : public v8::Handle<v8::Value> {
    JSValue()
    {
    }

    template<typename T>
    JSValue(const v8::Handle<T> & val)
        : v8::Handle<v8::Value>(val)
    {
    }

    template<typename T>
    JSValue(const v8::MaybeLocal<T> & val)
        : v8::Handle<v8::Value>(toLocalChecked(val))
    {
    }

    operator v8::Handle<v8::Object>() const;
};

/*****************************************************************************/
/* JSVALUE                                                                   */
/*****************************************************************************/

/** Opaque type used to represent a Javascript object.  Convertible to a
    Javscript value.
*/

struct JSObject : public v8::Handle<v8::Object> {
    JSObject()
    {
    }

    template<typename T>
    JSObject(const v8::Handle<T> & val)
        : v8::Handle<v8::Object>(val)
    {
    }

    void initialize();

    void add(const std::string & key, const std::string & value);
    void add(const std::string & key, const JSValue & value);
};

} // namespace JS

} // namespace MLDB


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Unix Permissions 101</title>
<meta name="generator" content="Org mode" />
<meta name="author" content="Anurag Peshne" />

<link rel="stylesheet" type="text/css" href="../css/style.css" />

<link rel="canonical" href="https://anuragpeshne.github.io/essays/permissions101.html" />

Unix Permissions 101

Table of Contents

1. Multiple servers, multiple configs

1.1. Debugging

1.2. Analysis

2. sudo

2.1. sudo justExecuteThis

2.2. sudo mode

3. Unix Permissions 101

DRAFT

1 Multiple servers, multiple configs

Couple of days ago we discovered a nasty bug in one of our systems. Before
getting to the bug let me explain the setup very briefly:

We have a master node which wakes up several AWS instances, delegates series of jobs, from a queue, to them and after all of the jobs are completed switches them off. Each slave node, after completing a job, stores the result in a common database.

Each of the event is logged in the same common database.

The system was working as expected until we found that the results calculated
by the slave nodes are being stored in a development database and not in the
production database.
Initially it looked like we plugged in wrong configuration file, which of course
wasn't the case. I checked the code that talked to the database to see if
someone hard coded the Dev DB configuration and later forgot to revert. Nothing
helped.

I even considered the possibility of multiple configuration files and
tried grepping the whole repository for Dev DB credential. Nothing was
mentioned anywhere about the Dev DB.

1.1 Debugging

The master node packs the Python scripts, configuration files and other data
files nicely in an egg (zip file) and deploys it to the slave nodes. I sshed
into one of the slaves and to my horror saw that the job did have configuration
of the Dev DB! This was surprising since while the master node didn't have a
trace of the incorrect configuration, the egg contained it.

My job was now a bit easier, I just needed to figure out how the unwanted
configuration slipped into the egg. I went over the code and double checked the
path of configuration declared for making the egg. Ultimately, I manually executed
the script that does the zipping of code and deployment. I found that the zipping
operation failed due to insufficient permissions. ls -l revealed that the
build folder was owned by the root and was readonly for others. The script
couldn't clean the temporary files and failed. Since this operation was done
using Python subprocess and the exception was handled in a way that didn't
stop the script, the script went on failing to deploy to each slave.

When the slaves were ordered to execute the job, they executed the last available
version of the egg, which happened to be a job which was being tested on development
server and thus contained development configuration.

1.2 Analysis

After the file permissions were fixed, it was time for examining what went wrong.
And what could have been done so that finding the cause would have been easier.
The fatal mistake was to handle the subprocess exception and not stop. This
is exactly opposite of the Unix Philosophy1:

Rule of Repair: Repair what you can — but when you must fail, fail noisily and as soon as possible.

Instead of silently consuming the exception, the script should have failed and
log it. Still this isn't the root cause of the bug. The root cause is setting
up of incorrect file permissions.

2 sudo

2.1 sudo justExecuteThis

The main problem is not technical but, like most of the other problems in software
development, a social one. We want to get things working, fast. Unable to save
a file? - use sudo. Unable to install package? - use sudo. I can bet most of
the engineer would repeat the last command, if it failed, prefixing it with sudo
without giving it a thought. For most of us, sudo means:

I don't really understand (or want to know) why you failed but I don't want you to fail.

Here, I give you the power of sudo

Again, the problem is not technical. Fixing the permission is not very difficult.
But why would one get into the trouble of actually reading up the commands and
doing it the right way, when one can just sudo.

2.2 sudo mode

After one has successfully executed couple of commands using sudo, which were
failing earlier, it is very tempting to get into sudo mode – su. Switch
to superuser and one never have to type in sudo again.

Using su (login as superuser) we can go anywhere and do anything we wish,
there is no one to stop us. But whenever we create a new file, other ordinary
users may only be able to read it and not write it.

Most of the code we write is executed by non privileged users.

3 Unix Permissions 101

There are just 3 commands one needs to know to avoid 90% of the unnecessary
use of sudo.

ls -l (list directory with a long listing format2):

This is the usual ls with -l flag which outputs extra information about
the files in the directory.

-rw-r--r--  1 anuragpeshne  staff  1080 Feb  2 20:52 LICENSE
-rw-r--r--  1 anuragpeshne  staff    51 Feb  2 20:52 README.md
drwxr-xr-x  7 anuragpeshne  staff   238 May  1 20:57 assets
drwxr-xr-x  3 anuragpeshne  staff   102 May 21 16:15 css
drwxr-xr-x  9 anuragpeshne  staff   306 Jun  5 13:45 essays
-rw-r--r--@ 1 anuragpeshne  staff    53 Feb 28 20:41 googleb7e54271b39d6266.html
-rw-r--r--  1 anuragpeshne  staff  8556 Apr  2 00:11 index.html
drwxr-xr-x  3 anuragpeshne  staff   102 Apr  1 22:32 js
-rw-r--r--  1 anuragpeshne  staff  6565 Feb 20 23:08 now.html
drwxr-xr-x  8 anuragpeshne  staff   272 Apr  2 00:11 org-files
drwxr-xr-x  4 anuragpeshne  staff   136 Feb 21 23:02 quotes
drwxr-xr-x  3 anuragpeshne  staff   102 Feb 16 20:09 todo

The first 10 characters denote file permissions. The first character denotes
whether the file is regular file or directory3. 3 Sets of 3 characters
follow that. Each character in the set denotes whether it is [w]ritable,
e[x]ecutable or [r]eadble. The sets represents permission of Owner, Group and
Other. The third, fourth column gives the information about owner and group.

Thus in the above example, only anuragpeshne can write to file README.md
while users in group staff and others can just read it.

chown (change owner4):

If you are working in some folder above your home folder, most probably it
won't be owned by you; It will be owned by root. If you are editing files
in your repository and going to edit those many times in a day, it would be
a good idea to own the repository folder.

sudo chown -R $(whoami) ./

chmod (change mode5):

There are couple of ways to change file permissions, but I'm going to mention
just one way. chmod ugo file, where ugo are octal values representing permission
for user, group and others. For calculating these octal value, just add
up the number corresponding to the permission you want to give.

<colgroup>
<col  class="org-left" />

<col  class="org-right" />
</colgroup>

read
4

write
2

execute
1

Examples:

chmod 600 d.txt will give permission to read and write only to the user
(owner).

chmod 755 app will give permission to read and execute to everyone but only
the user can write to it.

And that's it! From now on whenever you are tempted to use sudo, give yourself
a moment to think if you are going to edit the file often, if so, change the
ownership to you or add yourself to the owner group.

Footnotes:

1

: Rule of Repair

2

: ls

3

: The first character can denote much more than directories, symlinks, regular files, but that's out of scope of this article.

4

: chown

5

: chmod

Please enable JavaScript to view the comments powered by Disqus.

Date: 2016-05-19

Author: Anurag Peshne

Emacs 25.2.2 (Org mode 9.1.14)

Validate


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Caching;
using Bardock.Utils.Sync;
using Sixeyed.Caching.Caches;
using Sixeyed.Caching.Configuration;
using Sixeyed.Caching.Cryptography;
using Sixeyed.Caching.Logging;
using Sixeyed.Caching.Serialization;

namespace Sixeyed.Caching
{
    /// <summary>
    /// Base class for <see cref="ICache"/> implementations, also implements <see cref="OutputCacheProvider"/>
    /// </summary>
    public abstract class CacheBase : OutputCacheProvider, ICache
    {
        private static readonly StringLocker _locker = new StringLocker();
        private static NullCache _nullCache = new NullCache();

        private CacheBase _current;
        private bool _initialised;

        protected const string _NULL_VALUE = "?#_NULL_#?";

        protected CacheBase Current
        {
            get
            {
                if (!CacheConfiguration.Current.Enabled)
                {
                    return _nullCache;
                }
                if (!_initialised)
                {
                    Initialise();
                    _initialised = true;
                }
                return this;
            }
        }

        protected Serializer _serializer = new Serializer();

        public Serializer Serializer
        {
            get { return _serializer; }
            set { _serializer = value;  }
        }

        public abstract CacheType CacheType { get; }
        protected abstract void InitialiseInternal();
        protected abstract void SetInternal(string key, object value);
        protected abstract void SetInternal(string key, object value, DateTime expiresAt);
        protected abstract void SetInternal(string key, object value, TimeSpan validFor);
        protected abstract object GetInternal(string key);
        protected abstract void RemoveInternal(string key);
        protected abstract bool ExistsInternal(string key);

        protected virtual bool ItemsNeedSerializing
        {
            get { return false; ; }
        }

        public void Initialise()
        {
            try
            {
                InitialiseInternal();
            }
            catch (Exception ex)
            {
                Log.Error("CacheBase.Initialise - failed, NullCache will be used. CacheName: {0}, Message: {1}", CacheConfiguration.Current.DefaultCacheName, ex.Message);
                _current = _nullCache;
            }
        }

        public void Set(string key, object value, SerializationFormat serializationFormat = SerializationFormat.None)
        {
            try
            {
                value = PreProcess(value, serializationFormat);
                Current.SetInternal(key, value);
            }
            catch (Exception ex)
            {
                Log.Warn("CacheBase.Set - failed, item not cached. Message: {0}", ex.Message);
            }
        }

        void ICache.Set(string key, object value, DateTime expiresAt, SerializationFormat serializationFormat = SerializationFormat.Null)
        {
            try
            {
                value = PreProcess(value, serializationFormat);
                Current.SetInternal(key, value, expiresAt);
            }
            catch (Exception ex)
            {
                Log.Warn("CacheBase.Set - failed, item not cached. Message: {0}", ex.Message);
            }
        }

        public void Set(string key, object value, TimeSpan validFor, SerializationFormat serializationFormat = SerializationFormat.Null)
        {
            try
            {
                value = PreProcess(value, serializationFormat);
                Current.SetInternal(key, value, validFor);
            }
            catch (Exception ex)
            {
                Log.Warn("CacheBase.Set - failed, item not cached. Message: {0}", ex.Message);
            }
        }

        public T Get<T>(string key, SerializationFormat serializationFormat = SerializationFormat.Null)
        {
            var value = Get(typeof(T), key, serializationFormat);;

            if(value == null)
                return default(T);

            return (T)value;
        }

        public object Get(Type type, string key, SerializationFormat serializationFormat = SerializationFormat.Null)
        {
            object item = Current.GetInternal(key);
            return PostProcess(type, key, item, serializationFormat);
        }

        protected abstract List<string> GetAllKeys();

        public Dictionary<string, object> GetAll(Type type, SerializationFormat serializationFormat = SerializationFormat.Null)
        {
            return this.GetAllKeys()
                .ToDictionary(
                    key => key,
                    key => this.Get(type, key, serializationFormat));
        }

        public Dictionary<string, T> GetAll<T>(SerializationFormat serializationFormat = SerializationFormat.Null)
        {
            return this.GetAllKeys()
                .ToDictionary(
                    key => key,
                    key => this.Get<T>(key, serializationFormat));
        }

        public override void Remove(string key)
        {
            try
            {
                Current.RemoveInternal(key);
            }
            catch (Exception ex)
            {
                Log.Warn("CacheBase.Remove - failed, item not cached. Message: {0}", ex.Message);
            }
        }

        public void RemoveAll()
        {
            this.RemoveAll(keyPrefix: null);
        }

        public void RemoveAll(string keyPrefix)
        {
            // Lock by prefix. If prefix is NULL, lock globally
            lock (keyPrefix != null ? (object)_locker.GetLockObject(keyPrefix) : _locker)
            {
                foreach (var key in this.GetAllKeys())
                {
                    if (keyPrefix == null || key.StartsWith(keyPrefix))
                        this.Remove(key);
                }
            }
        }

        public bool Exists(string key)
        {
            var exists = false;
            try
            {
                exists = Current.ExistsInternal(key);
            }
            catch (Exception ex)
            {
                Log.Warn("CacheBase.Exists - failed, item not cached. Message: {0}", ex.Message);
            }
            return exists;
        }

        private object PreProcess(object value, SerializationFormat requestedFormat)
        {
            object processed = value;
            var doEncryption = CacheConfiguration.Current.Encryption.Enabled;

            if (processed == null)
            {
                processed = _NULL_VALUE;
            }
            else
            {
                var serializer = GetSerializer(requestedFormat, doEncryption);
                processed = serializer.Serialize(value);
            }
            if (doEncryption)
            {
                processed = Encryption.Encrypt((string)processed);
            }
            return processed;
        }

        private object PostProcess(Type type, string key, object value, SerializationFormat requestedFormat)
        {
            if (value == null)
                throw new CacheKeyNotFoundException();

            var processed = value;
            var doEncryption = CacheConfiguration.Current.Encryption.Enabled;
            if (doEncryption)
            {
                processed = Encryption.Decrypt((string)processed);
            }

            processed = PostProcessNullValue(type, key, processed);
            if (processed == null)
                return null;

            var serializer = GetSerializer(requestedFormat, doEncryption);
            return serializer.Deserialize(type, processed);
        }

        private object PostProcessNullValue(Type type, string key, object value)
        {
            if (!_NULL_VALUE.Equals(value))
                return value;

            if (!IsNullable(type))
                throw new CacheValueCastException(
                    string.Format("Cache item with key '{0}' has NULL as value but specified type '{1}' is not nullable", key, type.FullName));

            return null;
        }

        private static bool IsNullable(Type type)
        {
            if (!type.IsValueType) return true; // ref-type
            if (Nullable.GetUnderlyingType(type) != null) return true; // Nullable<T>
            return false; // value-type
        }

        private ISerializer GetSerializer(SerializationFormat requestedFormat, bool doEncryption)
        {
            var serializer = Serializer.Null;
            //if we're encrypting, we need to use a known serializer;
            //otherwise use requested or configured setting
            if (doEncryption)
            {
                serializer = Serializer.Json;
            }
            else if (requestedFormat != SerializationFormat.Null)
            {
                serializer = Serializer.Get(requestedFormat);
            }
            else if (ItemsNeedSerializing)
            {
                serializer = Serializer.Get(CacheConfiguration.Current.DefaultSerializationFormat);
            }
            return serializer;
        }

        #region OutputCacheProvider implementation

        public override object Add(string key, object entry, DateTime utcExpiry)
        {
            Set(key, entry, utcExpiry);
            return entry;
        }

        public override void Set(string key, object value, DateTime expiresAt)
        {
            try
            {
                var itemBytes = Serializer.Binary.Serialize(value) as byte[];
                var item = new CacheItem() { ItemBytes = itemBytes };
                var serializedItem = Serializer.Json.Serialize(item);
                var cacheKey = CacheKeyBuilder.GetCacheKey(key);
                Current.SetInternal(cacheKey, serializedItem, expiresAt);
            }
            catch (Exception ex)
            {
                Log.Warn("CacheBase.Set - failed, item not cached. Message: {0}", ex.Message);
            }
        }

        public override object Get(string key)
        {
            var cacheKey = CacheKeyBuilder.GetCacheKey(key);
            object item = null;
            try
            {
                var serializedItem = Current.GetInternal(cacheKey);
                if (serializedItem != null)
                {
                    var cacheItem = Serializer.Json.Deserialize(typeof(CacheItem), serializedItem) as CacheItem;
                    item = Serializer.Binary.Deserialize(null, cacheItem.ItemBytes);
                }
            }
            catch (Exception ex)
            {
                Log.Warn("CacheBase.Get - failed, item not cached. Message: {0}", ex.Message);
            }
            return item;
        }

        #endregion

    }
}


text:
"""Generates subset font.

1. Corrects characters from .svg files in given directory.
  Only text nodes in <text> element are taken into account.
2. Make subset font which contains only the characters corrected above.
"""

import logging
import optparse
import os
import shutil
import subprocess
import sys
import tempfile
from xml.etree import cElementTree as ElementTree

from build_tools import util

def ExtractCharactersFromSvgFile(svg_file):
  result = set()
  for text in ElementTree.parse(svg_file).findall(
      './/{http://www.w3.org/2000/svg}text'):
    if text.text:
      result.update(tuple(text.text))  # Split into characters.
  logging.debug('%s: %s', svg_file, result)
  return result

def ExtractCharactersFromDirectory(svg_paths):
  result = set()
  for dirpath, _, filenames in util.WalkFileContainers(svg_paths):
    for filename in filenames:
      if os.path.splitext(filename)[1] != '.svg':
        # Do nothing for files other than svg.
        continue
      result.update(ExtractCharactersFromSvgFile(
          os.path.join(dirpath, filename)))
  return list(result)

def MakeSubsetFont(fonttools_path, unicodes, input_font, output_font):
  """Makes subset font using fontTools toolchain.

  Args:
    fonttools_path: Path to fontTools library.
    unicodes: A list of unicode characters of which glyph should be in
              the output.
    input_font: Path to input font.
    output_font: Path to output font.
  """
  if not unicodes:
    # subset.py requires at least one unicode character.
    logging.debug('No unicode character is specified. Use "A" as stub.')
    unicodes = [u'A']

  tempdir = tempfile.mkdtemp()
  try:
    # fontTools's output file name is fixed (input file path + '.subset').
    # To get result with specified file name, copy the input font
    # to temporary directory and copy the result with renaming.
    shutil.copy(input_font, tempdir)
    temp_input_font = os.path.join(tempdir, os.path.basename(input_font))
    commands = ['python', os.path.join(fonttools_path, 'subset.py'),
                temp_input_font]
    commands.extend(['U+%08x' % ord(char) for char in unicodes])
    env = os.environ.copy()
    # In fontTools toolchain, "from fontTools import XXXX" is executed.
    # In order for successfull import, add parent directory of the toolchain
    # into PYTHONPATH.
    env['PYTHONPATH'] += ':%s' % os.path.join(fonttools_path, '..')
    if subprocess.call(commands, env=env) != 0:
      sys.exit(1)
    shutil.copyfile('%s.subset' % temp_input_font, output_font)
  finally:
    shutil.rmtree(tempdir)

def ParseOptions():
  """Parses options."""
  parser = optparse.OptionParser()
  parser.add_option('--svg_paths', dest='svg_paths',
                    help='Comma separated paths to a directory or'
                    ' a .zip file containing .svg files.')
  parser.add_option('--input_font', dest='input_font',
                    help='Path to the input font.')
  parser.add_option('--output_font', dest='output_font',
                    help='Path to the output font.')
  parser.add_option('--fonttools_path', dest='fonttools_path',
                    help='Path to fontTools toolchain.')
  parser.add_option('--verbose', dest='verbose',
                    help='Verbosity')
  return parser.parse_args()[0]

def main():
  logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')

  options = ParseOptions()
  if options.verbose:
    logging.getLogger().setLevel(logging.DEBUG)
  unicodes = ExtractCharactersFromDirectory(options.svg_paths)
  MakeSubsetFont(options.fonttools_path, unicodes,
                 options.input_font, options.output_font)

if __name__ == '__main__':
  main()


text:
SoftapHookup::SoftapHookup(char *defaultssid, char *password, ESP8266WebServer *inServer) {
    softapssid = defaultssid;
    softappassword = password;
    server = inServer;
    clearNetworkFromEepromPin = -1;
    init();
}

SoftapHookup::SoftapHookup(char *defaultssid, char *password, ESP8266WebServer *inServer,
                           int inClearNetworkFromEepromPin) {
    softapssid = defaultssid;
    softappassword = password;
    server = inServer;
    clearNetworkFromEepromPin = inClearNetworkFromEepromPin;
    init();
}

void SoftapHookup::init() {
    currentMode = SH_MODE_RESET_CHECK;
    numberOfFoundNetworks = 0;
    timeoutMillis = 10000;
    lastConnectAttemptFailed = false;  //load this from eeprom
    eepromStartingByte = 0;
    shouldWriteToEeprom = true;
    hideSsid = 0;
    ssidChannel = 6;
}

void SoftapHookup::start() {
  while(currentMode != SH_MODE_CONNECTED){
    looper();
  }
}

void SoftapHookup::looper() {
  switch (currentMode) {
        case SH_MODE_RESET_CHECK:
            checkForReset();
            break;
        case SH_MODE_EEPROM_CONNECT:
            readFromEeprom();
            break;
        case SH_MODE_SCAN:
            scanForNetworks();
            break;
        case SH_MODE_SOFTAPSETUP:
            setupSoftAp();
            break;
        case SH_MODE_SOFTAPSERVER:
            softapServer();
            break;
        case SH_MODE_CONNECTING:
            connectToRemoteWifi();
            break;
        case SH_MODE_CONNECTED:
            break;
        default:
            Serial.println("Idle");
    }
}

void SoftapHookup::checkForReset() {
    Serial.println("Checking eeprom reset pin");
    currentMode = SH_MODE_EEPROM_CONNECT;

    if (clearNetworkFromEepromPin == -1) {
        Serial.println("No reset pin specified.  Skipping eeprom reset");
        return;
    }

    pinMode(clearNetworkFromEepromPin, INPUT);

    if (digitalRead(clearNetworkFromEepromPin) == HIGH) {
        Serial.println("Pin detected.  Clearing eeprom");
        clearEeprom();
    } else {
        Serial.println("Skipping eeprom clearing.  Pin not detected.");
    }
}

void SoftapHookup::connectToRemoteWifi() {
    Serial.print("Connecting to network ");
    Serial.print(String(remoteSsid));
    Serial.print(" with password ");
    Serial.print(String(remotePassword));
    Serial.println(".");

    if (strlen(remotePassword) > 0) {
        WiFi.begin(remoteSsid, remotePassword);
    } else {
        WiFi.begin(remoteSsid);
    }

    unsigned long previousMillis = millis();
    unsigned long currentMillis;

    while (WiFi.status() != WL_CONNECTED) {
        currentMillis = millis();
        if ((currentMillis - previousMillis) >= timeoutMillis) {
            Serial.println("Connection Timeout");
            currentMode = SH_MODE_SCAN;
            lastConnectAttemptFailed = true;
            return;
        }
        delay(500);
        Serial.print(".");
    }

    Serial.println("");
    Serial.print("Connected! IP address: ");
    Serial.println(WiFi.localIP());
    saveToEeprom();
    currentMode = SH_MODE_CONNECTED;

    Serial.println("Stopping server and shutting down SoftAP");
    server->stop();
    server->close();
    WiFi.enableAP(false);
}

void SoftapHookup::readFromEeprom() {
    Serial.println("Checking Eeprom");
    if (shouldIgnoreEeprom) {
        currentMode = SH_MODE_SCAN;
        return;
    }
    EEPROM.begin(512);

    for (int i = 0; i < sizeof(remoteSsid); ++i) {
        remoteSsid[i] = char(EEPROM.read(eepromStartingByte + i));
    }
    Serial.print("SSID: ");
    Serial.println(remoteSsid);

    Serial.println("Reading EEPROM pass");

    for (int i = 0; i < sizeof(remotePassword); ++i) {
        remotePassword[i] = char(EEPROM.read(eepromStartingByte + sizeof(remoteSsid) + i));
    }

    Serial.print("Password: ");
    Serial.println(remotePassword);

    if (strlen(remoteSsid) > 0) {
        shouldWriteToEeprom = false;
        currentMode = SH_MODE_CONNECTING;
    } else {
        currentMode = SH_MODE_SCAN;
    }
}

void SoftapHookup::saveToEeprom() {
    if (!shouldWriteToEeprom || shouldIgnoreEeprom) {
        Serial.println("Skipping write to Eeprom");
        return;
    }
    Serial.println("Writing to Eeprom");

    EEPROM.begin(512);

    clearEeprom();

    for (int i = 0; i < sizeof(remoteSsid); ++i) {
        EEPROM.write(eepromStartingByte + i, remoteSsid[i]);
    }
    Serial.print("Wrote: ");
    Serial.println(remoteSsid);

    for (int i = 0; i < sizeof(remotePassword); ++i) {
        EEPROM.write(eepromStartingByte + sizeof(remoteSsid) + i, remotePassword[i]);
    }
    EEPROM.commit();
    Serial.print("Wrote: ");
    Serial.println(remotePassword);

}

void SoftapHookup::clearEeprom() {
    if (shouldIgnoreEeprom) {
        Serial.println("Skipping clear Eeprom");
        return;
    }
    Serial.println("Clearing Eeprom");

    int length = getEepromSizeUsed();

    EEPROM.begin(512);

    for (int i = 0; i < length; ++i) {
        EEPROM.write(eepromStartingByte + i, 0);
    }
    EEPROM.commit();
}

void SoftapHookup::softapServer() {
    server->handleClient();
}

void SoftapHookup::setupSoftAp() {
    Serial.println("Starting SoftAP");
    String AP_NameString = String(softapssid);

    char AP_NameChar[AP_NameString.length() + 1];
    memset(AP_NameChar, 0, AP_NameString.length() + 1);

    for (int i = 0; i < AP_NameString.length(); i++) {
        AP_NameChar[i] = AP_NameString.charAt(i);
    }
    WiFi.softAP(AP_NameChar, softappassword, ssidChannel, hideSsid);
    currentMode = SH_MODE_SOFTAPSERVER;

    server->on("/", HTTP_GET, std::bind(&SoftapHookup::showNetworks, this));
    server->on("/refresh", HTTP_GET, std::bind(&SoftapHookup::refresh, this));
    server->on("/select", HTTP_POST, std::bind(&SoftapHookup::selectSsid, this));

    server->begin();

    IPAddress myIP = WiFi.softAPIP();
    Serial.print("SoftAP IP address: ");
    Serial.println(myIP);
    Serial.print("SoftAP SSID: ");
    Serial.println(AP_NameChar);
    Serial.print("SoftAP password: ");
    Serial.println(softappassword);
}

void SoftapHookup::refresh() {
    scanForNetworks();
    showNetworks();
}

String SoftapHookup::getHTMLHeader() {
    return "<!DOCTYPE HTML>\r\n\r\n";
}

String SoftapHookup::getHTMLFooter() {
    return "\n";
}

void SoftapHookup::selectSsid() {
    Serial.println("User selection detected");
    String hiddenPassword = server->arg("hiddenpassword");
    String hiddenSsid = server->arg("hiddenssid");
    int ssidNum = server->arg("ssid").toInt();
    String password = server->arg("password");
    boolean useHiddenNetwork = false;
    String s = "";

    s += getHTMLHeader();

    if (hiddenSsid.length() > 0) {
        useHiddenNetwork = true;
    }

    s += "Connecting to network
";
    s += (useHiddenNetwork ? hiddenSsid : WiFi.SSID(ssidNum));

    s += "
";

    s += getHTMLFooter();

    server->send(200, "text/html", s);
    if (useHiddenNetwork) {
        hiddenSsid.toCharArray(remoteSsid, sizeof(remoteSsid));
        hiddenPassword.toCharArray(remotePassword, sizeof(remotePassword));
    } else {
        WiFi.SSID(ssidNum).toCharArray(remoteSsid, sizeof(remoteSsid));
        password.toCharArray(remotePassword, sizeof(remotePassword));
    }
    currentMode = SH_MODE_CONNECTING;
}

void SoftapHookup::showNetworks() {
    String s = "";
    s += getHTMLHeader();
    if (numberOfFoundNetworks == 0) {
        s += "no networks found";
    } else {
        if (lastConnectAttemptFailed == true) {
            s += "Last connection failed
";
        }

        s += "Select a network for " +
             String(softapssid) +
             " to connect.  * denotes password protected network

<form action=\"/select\" method=\"post\">";
        s += "<select name=\"ssid\">";
        for (int i = 0; i < numberOfFoundNetworks; ++i) {
            s += "<option value=\"" + String(i) + "\">";
            s += i + 1;
            s += ": ";
            s += WiFi.SSID(i);
            s += " (";
            s += WiFi.RSSI(i);
            s += ")";
            s += (WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : " *";
            s += "</option>";
        }
        s += "</select>

";
        s += "Network Password: <input type=\"text\" name=\"password\">
";
        s += "
or

";
        s += "Hidden network SSID: <input type=\"text\" name=\"hiddenssid\">
";
        s += "Network Password: <input type=\"text\" name=\"hiddenpassword\">
";
        s += "
";
        s += "<input type=\"submit\" value=\"Select\">";
        s += "</form>";
    }
    s += "Refresh";

    s += getHTMLFooter();

    server->send(200, "text/html", s);
    Serial.println("in index");
}

void SoftapHookup::scanForNetworks() {
    Serial.println("scan start");
    WiFi.disconnect();
    delay(100);

    numberOfFoundNetworks = WiFi.scanNetworks();
    Serial.println("scan done");
    if (numberOfFoundNetworks == 0) {
        Serial.println("no networks found");
    } else {
        Serial.print(numberOfFoundNetworks);
        Serial.println(" networks found");
        for (int i = 0; i < numberOfFoundNetworks; ++i) {
            Serial.print(i + 1);
            Serial.print(": ");
            Serial.print(WiFi.SSID(i));
            Serial.print(" (");
            Serial.print(WiFi.RSSI(i));
            Serial.print(")");
            Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : "*");
            delay(10);
        }
    }
    Serial.println("");
    currentMode = SH_MODE_SOFTAPSETUP;
}

int SoftapHookup::getEepromSizeUsed() {
    return sizeof(remoteSsid) + sizeof(remotePassword);
}

void SoftapHookup::setEepromStartingByte(int startByte) {
    eepromStartingByte = startByte;
}

void SoftapHookup::setShouldWriteEeprom(boolean shouldWrite) {
    shouldWriteToEeprom = shouldWrite;
}

void SoftapHookup::ignoreEeprom(boolean shouldIgnore) {
    shouldIgnoreEeprom = shouldIgnore;
}

void SoftapHookup::setTimeoutMilliseconds(unsigned long milliseconds) {
    timeoutMillis = milliseconds;
}

void SoftapHookup::hideSoftapSsid(boolean shouldHideSSID) {
    hideSsid = (shouldHideSSID == true)? 1:0;
}

void SoftapHookup::setSsidChannel(int idChannel) {
    ssidChannel = idChannel;
}


text:
typedef int integer_t;

#include "message.h"
#include "vm_statistics.h"

#define HOST_VM_INFO    1

typedef void *host_info_t;

#ifdef __cplusplus
extern "C" {
#endif
extern int vm_page_size;
mach_port_t mach_host_self(void);
int host_page_size(mach_port_t port, vm_size_t *sizeOut);
int host_statistics(mach_port_t port, int type, host_info_t dataOut, mach_msg_type_number_t *dataOutSize);
#ifdef __cplusplus
}
#endif


text:
<?php

// Load this file before loading "system/core/Common.php"

/**
 * Class registry
 *
 * @staticvar array $_classes
 * @param string $class
 * @param string $directory
 * @param array $param
 * @param bool $reset
 * @param object $obj
 * @return object
 */
function &load_class(
	$class,
	$directory = 'libraries',
	$param = NULL,
	$reset = FALSE,
	$obj = NULL
)
{
	static $_classes = array();

	if ($reset)
	{
		// If Utf8 is instantiated twice,
		// error "Constant UTF8_ENABLED already defined" occurs
		$UTF8 = $_classes['Utf8'];
		$_classes = array(
			'Utf8' => $UTF8
		);
		$obj = new stdClass();
		return $obj;
	}

	// Register object directly
	if ($obj)
	{
		is_loaded($class);

		$_classes[$class] = $obj;
		return $_classes[$class];
	}

	// Does the class exist? If so, we're done...
	if (isset($_classes[$class]))
	{
		return $_classes[$class];
	}

	$name = FALSE;

	// Look for the class first in the local application/libraries folder
	// then in the native system/libraries folder
	foreach (array(APPPATH, BASEPATH) as $path)
	{
		if (file_exists($path.$directory.'/'.$class.'.php'))
		{
			$name = 'CI_'.$class;

			if (class_exists($name, FALSE) === FALSE)
			{
				require_once($path.$directory.'/'.$class.'.php');
			}

			break;
		}
	}

	// Is the request a class extension? If so we load it too
	if (file_exists(APPPATH.$directory.'/'.config_item('subclass_prefix').$class.'.php'))
	{
		$name = config_item('subclass_prefix').$class;

		if (class_exists($name, FALSE) === FALSE)
		{
			require_once(APPPATH.$directory.'/'.$name.'.php');
		}
	}

	// Did we find the class?
	if ($name === FALSE)
	{
		// Note: We use exit() rather then show_error() in order to avoid a
		// self-referencing loop with the Exceptions class
		set_status_header(503);
		echo 'Unable to locate the specified class: '.$class.'.php';
		exit(5); // EXIT_UNK_CLASS
	}

	// Keep track of what we just loaded
	is_loaded($class);

	$_classes[$class] = isset($param)
		? new $name($param)
		: new $name();
	return $_classes[$class];
}

/**
 * Keeps track of which libraries have been loaded.
 *
 * @staticvar array $_is_loaded
 * @param string $class
 * @param bool $reset
 * @return array
 */
function &is_loaded($class = '', $reset = FALSE)
{
	static $_is_loaded = array();

	if ($reset)
	{
		$_is_loaded = array();
		return $_is_loaded;
	}

	if ($class !== '')
	{
		$_is_loaded[strtolower($class)] = $class;
	}

	return $_is_loaded;
}

function is_cli($return = null)
{
	static $_return = TRUE;

	if ($return !== null)
	{
		$_return = $return;
	}

	return $_return;
}

function show_error($message, $status_code = 500, $heading = 'An Error Was Encountered')
{
	$status_code = abs($status_code);
	if ($status_code < 100)
	{
		$exit_status = $status_code + 9; // 9 is EXIT__AUTO_MIN
		if ($exit_status > 125) // 125 is EXIT__AUTO_MAX
		{
			$exit_status = 1; // EXIT_ERROR
		}

		$status_code = 500;
	}
	else
	{
		$exit_status = 1; // EXIT_ERROR
	}

	while (ob_get_level() > 1)
	{
		ob_end_clean();
	}

	throw new CIPHPUnitTestShowErrorException($message, $status_code);
}

function show_404($page = '', $log_error = TRUE)
{
	while (ob_get_level() > 1)
	{
		ob_end_clean();
	}

	throw new CIPHPUnitTestShow404Exception($page, 404);
}

function set_status_header($code = 200, $text = '')
{
//	if (is_cli())
//	{
//		return;
//	}

	if (empty($code) OR ! is_numeric($code))
	{
		show_error('Status codes must be numeric', 500);
	}

	if (empty($text))
	{
		is_int($code) OR $code = (int) $code;
		$stati = array(
			100	=> 'Continue',
			101	=> 'Switching Protocols',

			200	=> 'OK',
			201	=> 'Created',
			202	=> 'Accepted',
			203	=> 'Non-Authoritative Information',
			204	=> 'No Content',
			205	=> 'Reset Content',
			206	=> 'Partial Content',

			300	=> 'Multiple Choices',
			301	=> 'Moved Permanently',
			302	=> 'Found',
			303	=> 'See Other',
			304	=> 'Not Modified',
			305	=> 'Use Proxy',
			307	=> 'Temporary Redirect',

			400	=> 'Bad Request',
			401	=> 'Unauthorized',
			402	=> 'Payment Required',
			403	=> 'Forbidden',
			404	=> 'Not Found',
			405	=> 'Method Not Allowed',
			406	=> 'Not Acceptable',
			407	=> 'Proxy Authentication Required',
			408	=> 'Request Timeout',
			409	=> 'Conflict',
			410	=> 'Gone',
			411	=> 'Length Required',
			412	=> 'Precondition Failed',
			413	=> 'Request Entity Too Large',
			414	=> 'Request-URI Too Long',
			415	=> 'Unsupported Media Type',
			416	=> 'Requested Range Not Satisfiable',
			417	=> 'Expectation Failed',
			422	=> 'Unprocessable Entity',

			500	=> 'Internal Server Error',
			501	=> 'Not Implemented',
			502	=> 'Bad Gateway',
			503	=> 'Service Unavailable',
			504	=> 'Gateway Timeout',
			505	=> 'HTTP Version Not Supported'
		);

		if (isset($stati[$code]))
		{
			$text = $stati[$code];
		}
		else
		{
			show_error('No status text available. Please check your status code number or supply your own message text.', 500);
		}
	}

	// Save status code in Output object
	// added by ci-phpunit-test
	$CI =& get_instance();
	$output = $CI->output;
	$output->_status = [
		'code'     => $code,
		'text'     => $text,
		'redirect' => null,
	];

	// Everything is done, so return
	// added by ci-phpunit-test
	if (ENVIRONMENT === 'testing')
	{
		return;
	}

	if (strpos(PHP_SAPI, 'cgi') === 0)
	{
		header('Status: '.$code.' '.$text, TRUE);
	}
	else
	{
		$server_protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1';
		header($server_protocol.' '.$code.' '.$text, TRUE, $code);
	}
}


text:
const EventEmitter	= require('events').EventEmitter;
const Logger		= require("./Logger");
//Get Semantic SDP objects
const SemanticSDP	= require("semantic-sdp");
const SDPInfo		= SemanticSDP.SDPInfo;
const MediaInfo		= SemanticSDP.MediaInfo;
const CandidateInfo	= SemanticSDP.CandidateInfo;
const DTLSInfo		= SemanticSDP.DTLSInfo;
const ICEInfo		= SemanticSDP.ICEInfo;
const StreamInfo	= SemanticSDP.StreamInfo;
const TrackInfo		= SemanticSDP.TrackInfo;
const Direction		= SemanticSDP.Direction;
const CodecInfo		= SemanticSDP.CodecInfo;

//Get the Medooze Media Server interface
const MediaServer  = require("medooze-media-server");

const Participant = require("./Participant");

class Room
{
	constructor(id,ip)
	{
		//Store id
		this.id = id;

		//Create UDP server endpoint
		this.endpoint = MediaServer.createEndpoint(ip);

		//The comentarist set
		this.participants = new Map();

		//Create the room media capabilities
		this.capabilities = {
			audio : {
				codecs		: ["opus"],
				extensions	: ["urn:ietf:params:rtp-hdrext:ssrc-audio-level"]
			},
			video : {
				codecs		: ["vp9"],
				rtx		: true,
				rtcpfbs		:  [
					{ "id": "transport-cc"},
					{ "id": "ccm", "params": ["fir"]},
					{ "id": "nack"},
					{ "id": "nack", "params": ["pli"]},
				],
				extensions	: [ "http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01", "urn:3gpp:video-orientation"]
			}
		};

		//No participants
		this.max = 0;

		//Create event emitter
		this.emitter = new EventEmitter();

		//Active speaker detection
		this.activeSpeakerDetector = MediaServer.createActiveSpeakerDetector();

		//When new speaker detected
		this.activeSpeakerDetector.on("activespeakerchanged",(track)=>{
			//Get active speaker id
			const speakerId = track.participant.getId();
			//Check if it is the same as current one
			if (this.speakerId===speakerId)
				//Do nothing
				return;
			//Update speaker
			this.speakerId = speakerId;

			//Log
			this.logger.debug("activespeakerchanged speakerId=%d",speakerId);

			//Relaunch event
			this.emitter.emit("activespeakerchanged",track.participant,track);
		});
		//Create uri
		this.uri = ["rooms",id];

		//Create logger
		this.logger = new Logger("rooms["+this.id+"]");

		//Log
		this.logger.info("created()");
	}

	getId()
	{
		return this.id;
	}

	getSpeakerId()
	{
		return this.speakerId;
	}

	getEndpoint()
	{
		return this.endpoint;
	}

	getCapabilities() {
		return this.capabilities;
	}

	createParticipant(name)
	{
		this.logger.info("createParticipant() "+ name);

		//Create participant
		const participant = new Participant(
			this.max++,
			name,
			this.endpoint.createSDPManager("unified-plan",this.capabilities),
			this
		);

		//Listener for any new publisher stream
		participant.on('stream',(stream)=>{
			//Send it to the other participants
			for (let other of this.participants.values())
				//Check it is not the event source
				if (participant.getId()!=other.getId())
					//Add stream to participant
					other.addStream(stream);
			//Get audio tracks
			const audioTracks = stream.getAudioTracks();
			//If there are any
			if (audioTracks.length)
			{
				//Get participant id
				const participantId = participant.getId();
				//And firsst audio track
				const audioTrack = audioTracks[0];
				//Only log for now
				this.logger.debug("addSpeaker() [participant:%s]",participantId);
				//Store participant
				audioTrack.participant = participant;
				audioTrack.stream	   = stream;
				//Add to detecotr
				this.activeSpeakerDetector.addSpeaker(audioTrack);
			}

			//Get video tracks
			const videoTracks = stream.getVideoTracks();
			//For each video track
			for (let i=0; i<videoTracks.length; ++i)
				//Request an iframe so playback can start even if no other participant has subscribed
				videoTracks[i].refresh();
		});

		//Wait for stopped event
		participant.on('stopped', () => {
			//Delete comentarist
			this.participants.delete(participant.id);
			//emir participant change
			this.emitter.emit("participants",this.participants.values());
		});

		//Add to the participant to list
		this.participants.set(participant.id,participant);

		//emit participant change
		this.emitter.emit("participants",this.getInfo().participants);

		//Done
		return participant;
	}

	getStreams() {
		const streams = [];

		//For each participant
		for (let participant of this.participants.values())
			//For each stream
			for (let stream of participant.getIncomingStreams())
				//Add participant streams
				streams.push(stream);
		//return them
		return streams;
	}

	getInfo()
	{
		//Create info
		const info = {
			id : this.id,
			participants : []
		};

		//For each participant
		for (let participant of this.participants.values())
			//Append it
			info.participants.push(participant.getInfo());

		//Return it
		return info;
	}

	/**
	 * Add event listener
	 * @param {String} event	- Event name
	 * @param {function} listeener	- Event listener
	 * @returns {Transport}
	 */
	on()
	{
		//Delegate event listeners to event emitter
		this.emitter.on.apply(this.emitter, arguments);
		//Return object so it can be chained
		return this;
	}

	/**
	 * Remove event listener
	 * @param {String} event	- Event name
	 * @param {function} listener	- Event listener
	 * @returns {Transport}
	 */
	off()
	{
		//Delegate event listeners to event emitter
		this.emitter.removeListener.apply(this.emitter, arguments);
		//Return object so it can be chained
		return this;
	}

	stop()
	{
		if (!this.endpoint)
			return;

		//Log
		this.logger.info("stop()");

		//Stop vad
		this.activeSpeakerDetector.stop();

		//For each participant
		for (const [id,participant] of this.participants)
			//Stop it with reason
			participant.stop("destroyed");

		//Stop endpoint
		this.endpoint.stop();

		//Emit event
		this.logger.info("stopped");
		this.emitter.emit("stopped");

		//Null things
		this.activeSpeakerDetector = null;
		this.participants = null;
		this.endpoint = null;
		this.emitter = null;
	}

};

module.exports = Room;


text:
<?php

namespace Entities;

/**
 * Estadosseguimiento
 *
 * @Table(name="estadosSeguimiento")
 * @Entity
 */
class Estadosseguimiento
{
    /**
     * @var integer
     *
     * @Column(name="id", type="integer", precision=0, scale=0, nullable=false, unique=false)
     * @Id
     * @GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string
     *
     * @Column(name="nombre", type="string", length=250, precision=0, scale=0, nullable=true, unique=false)
     */
    private $nombre;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set nombre
     *
     * @param string $nombre
     *
     * @return Estadosseguimiento
     */
    public function setNombre($nombre)
    {
        $this->nombre = $nombre;

        return $this;
    }

    /**
     * Get nombre
     *
     * @return string
     */
    public function getNombre()
    {
        return $this->nombre;
    }
}


text:
REST API - Datasets
===================

.. automodule:: iceprod.server.rest.datasets